agentsclimarketplace

Strategy compact

Skill d0gesec/pownie/skills/strategy-compact

Suggests manual context compaction at logical intervals to preserve context through task phases rather than arbitrary auto-compaction.From its SKILL.md

Install
npx -y skills add d0gesec/pownie --skill strategy-compact

Assembled from the repository path, not quoted from the project. Check it against their README if it does not work.

One thing to look at

  • 24 stars24 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.

SKILL.md

13.1 KB, as published. Nobody here has run it

Strategic Compact for Offensive Security

CTF and offsec sessions are long-form by nature — multi-hour engagements with heavy tool output, iterative exploitation, and chained attack paths. Auto-compaction is destructive in this context because it fires at arbitrary points and silently drops exploit state, payload bytes, and enumeration results. This skill teaches when and how to compact strategically so you keep attacking momentum without context rot.

When to Activate

  • Any CTF challenge, HTB machine, or pentest session
  • Session approaching context limits (responses getting shorter, losing track of prior findings)
  • After hitting a natural phase boundary (see below)
  • After 3+ failed strategies in the same category — compact the dead-end reasoning

Why This Matters for Offsec

Auto-compaction in a CTF session can:

  • Mangle CVE payloads — null bytes, backticks, escape sequences get stripped by markdown summarization
  • Lose enumeration context — which ports you already checked, which creds you already tried
  • Break multi-step exploit chains — partial state from stage 1 vanishes before stage 2
  • Repeat failed strategies — without the failure context, you try the same dead-end again

Strategic compaction at phase boundaries avoids all of this because Neo4j graph data and workspace files persist independently.

CTF Phase Model and Compact Points

Recon --> Enumeration --> Initial Access --> Post-Exploit Enum --> Lateral/Privesc --> Flag

Natural Compact Points

After this phase...Compact?Why
Full port scan + service enumYesNmap/gobuster output is massive. Findings are in Neo4j — you don't need raw output in context
Failed exploit chain (3+ attempts)YesDead-end reasoning pollutes context. Update attempts as failed in Neo4j first, then compact with fresh approach
Got initial shell + posted creds/shellYesNew user = fresh enumeration cycle. Prior exploitation context is noise now
Got new user (lateral movement)YesSame as above — record creds/shell in Neo4j, compact, re-enumerate as new identity
Pivoting to completely different serviceYesWeb exploit context is useless for binary exploitation and vice versa

Never Compact During

SituationWhy
Mid-exploit (payload assembled, not yet fired)Payload bytes will be mangled or lost
Active binary analysis (offsets, gadgets identified)ROP chains, canary values, libc offsets are hard to reconstruct
Multi-step CVE chain in progressIntermediate state (tokens, session cookies, CSRF values) will vanish
Debugging a specific failureError context and hypothesis state are essential

Pre-Compact Checklist

Before running /compact, verify all of these. Skipping any item means losing that state permanently:

  1. Neo4j graph updated — All findings (ports, creds, vulns, shells) written via mcp__neo4j__write_cypher; all attempt outcomes current
  2. Failed approaches documented — Every failed or abandoned attempt updated in Neo4j with outcome: 'failed' and output_summary
  3. Working exploits saved — Any exploit script saved to /workspace/ (not just in conversation history)
  4. CVE payloads preserved — Payloads with special characters (null bytes, backticks, binary data) saved to file, not just in chat
  5. Credential chain documented — Which creds grant access to which services recorded as credential nodes with AUTHENTICATES_TO relationships
  6. Current hypothesis noted — What you think the next step is — include in compact summary message

Post-Compact Recovery

After compacting, compact-state.md (auto-generated by PreCompact hook) provides orientation — target name, actual credential/service data, failed attempts, and recent command history. Run this sequence:

1. Read compact-state.md (if it exists)         <- target name + actual data snapshot
2. mcp__neo4j__read_cypher:                      <- full structured state
   MATCH (t:target)-[r*1..3]-(n)
   UNWIND r AS rel
   RETURN DISTINCT labels(n)[0] AS type, n.key AS key, properties(n) AS props
   ORDER BY type, key
3. ls /workspace/                               <- saved exploit scripts and notes
4. Read MEMORY.md                               <- auto-loaded, check for target-specific notes

compact-state.md gives you the quick orientation (creds, shells, what failed, recent commands). The recovery Cypher gives the full structured data. Together = full continuity.

Compact Summary Messages

Always use /compact with a targeted summary. Generic summaries lose critical state.

Bad: /compact (no message) Bad: /compact Working on HTB machine Good: /compact Got shell as www-data via SQLi on port 80. Creds for mysql user in DB. Next: enumerate internal services for lateral movement to user tom. Exploit script at /workspace/sqli.py

The summary becomes your session's "load-bearing context" — everything else is rebuilt from Neo4j and files.

What Survives Compaction

PersistsLost
Neo4j graph (ports, creds, vulns, attempts, strategies, command_log)Raw tool output (nmap, gobuster, etc.)
Workspace files (/workspace/*.py, notes, exploits)Intermediate reasoning and analysis
Memory files (MEMORY.md, topic files)Payload bytes in conversation history
CLAUDE.md + skill instructionsMulti-step conversation context
Git state (commits, branches)User-stated preferences from this session
TodoWrite task listNuanced failure analysis ("it failed because...")
/compact summary messageEverything else

Controlling Auto-Compaction (Claude Code Internals)

Auto-compaction cannot be fully replaced — disabling it causes "prompt is too long" hard errors that permanently kill the session. The correct strategy is to tune auto-compact as a safety net and manually compact before it fires.

Token Budget Reality (200K Window)

ComponentTokens%
System prompt~2.7K1.3%
Built-in tools~16.8K8.4%
MCP tool definitions (kali, neo4j, etc.)~10-20K5-10%
CLAUDE.md + memory files + skills~5-10K2.5-5%
Auto-compact buffer (reserved, unusable)~33K16.5%
Available for conversation~120-133K~60-67%

With heavy MCP server load (kali + neo4j), usable context drops to ~120K. Auto-compact fires at ~83.5% usage (~167K tokens used).

Configuration

1. Tune auto-compact threshold (recommended: 70% for offsec):

# In shell profile (~/.zshrc or ~/.bashrc)
export CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=70

# Or in project settings (.claude/settings.local.json)
{
  "env": {
    "CLAUDE_AUTOCOMPACT_PCT_OVERRIDE": "70"
  }
}

Lower = fires earlier = preserves more context quality. At 70%, you get a larger buffer zone to manually compact before auto takes over.

2. Add Compact Instructions to CLAUDE.md (tells the summarizer what to keep):

## Compact Instructions

When compacting, always preserve:
- Target IP/hostname and current attack phase
- All discovered credentials and which services they access
- Current shell access (user, method, path)
- Active exploit chain state (what worked, what's next)
- File paths of saved exploit scripts in /workspace/
- Any CVE identifiers being exploited

These instructions survive compaction (they're in CLAUDE.md which reloads every turn) and guide the summarizer to keep attack-critical context.

3. PreCompact hook (pre-compact-save.sh — auto-saves Neo4j state):

The PreCompact hook fires before every compaction (auto or manual). It cannot block compaction, but it queries Neo4j and writes a rich compact-state.md so the post-compact agent can orient quickly.

What it does:

  1. Queries Neo4j via HTTP API (batched — single POST, multiple statements)
  2. Writes compact-state.md with: target, services, credentials, shells, flags, in-progress strategies, failed attempts, recent command history
  3. Creates a compaction_event node in Neo4j for audit
  4. Warns on stderr about in-progress strategies (agent sees this in context)
  5. Never writes intel TO Neo4j (beyond the compaction_event marker) — only reads

Config (already set in .claude/settings.json):

{
  "hooks": {
    "PreCompact": [{
      "matcher": "",
      "hooks": [{
        "type": "command",
        "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/skills/strategy-compact/pre-compact-save.sh"
      }]
    }]
  }
}

"matcher": "" catches ALL compactions (auto + manual).

Post-compact recovery flow:

Compaction fires
  -> pre-compact-save.sh queries Neo4j -> writes compact-state.md
  -> compaction runs (conversation context is summarized)
  -> post-compact agent sees compact summary + compact-state.md
  -> agent runs: mcp__neo4j__read_cypher with recovery Cypher
  -> full structured state rebuilt from Neo4j

compact-state.md is a data-rich orientation file — it carries actual credentials, services, failed attempts, and command history so the agent can act immediately. The recovery Cypher gives full structured detail.

4. Disable auto-compact entirely (NOT recommended — causes hard failures):

# Only if you are disciplined about manual /compact
claude config set -g autoCompactEnabled false
# Lives in ~/.claude.json (NOT settings.json)

If you disable auto-compact, you MUST manually /compact before context fills or the session dies with "prompt is too long" — an unrecoverable error.

Context Quality Degradation Zones

Usage %ZoneBehavior
0-50%GreenFull precision, all details retained
50-70%YellowMinor precision loss, good time for proactive compact
70-85%OrangeNoticeable degradation, hallucination risk rises
85-90%RedUnreliable — responses shorten, context references fail
90%+Critical"Prompt is too long" imminent — /compact NOW or lose session

"Prompt is Too Long" — What It Is and How to Avoid It

This error is different from auto-compaction. It means the total prompt (system + tools + CLAUDE.md + conversation) exceeded the model's hard limit. Once triggered, the session is permanently dead — every subsequent input returns the same error.

Causes:

  • Auto-compact disabled + no manual compaction -> context fills to hard limit
  • Very large CLAUDE.md + many MCP servers + conversation history
  • Resuming an old session that's already near capacity

Prevention:

  • Keep CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=70 as a safety net
  • Manually /compact at phase boundaries (the whole point of this skill)
  • Use /clear between completely unrelated tasks
  • Use subagents (Agent tool) for heavy exploration — their context is isolated
  • Run /mcp to audit MCP server token costs; disable servers you're not using

Session Recovery Strategies

SituationAction
Session feels sluggish, losing context/compact with targeted summary
"Prompt is too long" errorclaude --continue to resume in fresh session, or claude --resume to pick a session
Switching from one HTB box to another/clear (not compact — unrelated context is pure noise)
Multi-hour session, natural break/compact, close terminal, resume later with claude --continue
Need parallel investigationUse Agent tool with subagents (isolated 200K context each)

Decision Heuristics

When approaching context limits, use these to decide:

  1. "Am I between phases?" — If yes, compact. If mid-exploit, ignore.
  2. "Is my context stale?" — If you're referencing findings from 100+ messages ago, compact.
  3. "Did I just fail hard?" — 3+ failed strategies = compact the dead reasoning.
  4. "Did I just succeed?" — Got a shell/flag/creds? Save to Neo4j + workspace, compact.
  5. "Am I about to pivot?" — Switching from web to binary? From Linux to AD? Compact.

Anti-Patterns

Anti-PatternWhy It HurtsInstead
Disabling auto-compact without discipline"Prompt is too long" kills the session permanentlyKeep auto at 70% as safety net, manual compact at phase boundaries
Compacting without saving findingsLose all discovered intel permanentlyAlways run pre-compact checklist, verify Neo4j has your data
Compacting mid-exploitPayload bytes get mangled in summaryFinish the attempt first, even if it fails
Never compacting (riding auto-compact)Auto fires mid-task, loses more than strategic compact wouldCompact at phase boundaries proactively
Compacting with no summary messageNext phase has zero starting contextWrite a specific summary of state + next steps
Saving payloads only in conversationMarkdown summarization strips special charsSave to /workspace/ files before compact
Huge CLAUDE.md + many MCP serversEats 30%+ of context before you type anythingKeep CLAUDE.md under 200 lines, audit /mcp costs

Keep looking

Skills are one crate of 626,474. Ordering is by how many stacks a row turns up in, so the top of any crate is what has actually been picked rather than what has the most stars.