| name | strategy-compact |
| description | Suggests manual context compaction at logical intervals to preserve context through task phases rather than arbitrary auto-compaction. |
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 enum | Yes | Nmap/gobuster output is massive. Findings are in Neo4j — you don't need raw output in context |
| Failed exploit chain (3+ attempts) | Yes | Dead-end reasoning pollutes context. Update attempts as failed in Neo4j first, then compact with fresh approach |
| Got initial shell + posted creds/shell | Yes | New user = fresh enumeration cycle. Prior exploitation context is noise now |
| Got new user (lateral movement) | Yes | Same as above — record creds/shell in Neo4j, compact, re-enumerate as new identity |
| Pivoting to completely different service | Yes | Web exploit context is useless for binary exploitation and vice versa |
Never Compact During
| Situation | Why |
|---|
| 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 progress | Intermediate state (tokens, session cookies, CSRF values) will vanish |
| Debugging a specific failure | Error context and hypothesis state are essential |
Pre-Compact Checklist
Before running /compact, verify all of these. Skipping any item means losing that state permanently:
- Neo4j graph updated — All findings (ports, creds, vulns, shells) written via
mcp__neo4j__write_cypher; all attempt outcomes current
- Failed approaches documented — Every failed or abandoned attempt updated in Neo4j with
outcome: 'failed' and output_summary
- Working exploits saved — Any exploit script saved to
/workspace/ (not just in conversation history)
- CVE payloads preserved — Payloads with special characters (null bytes, backticks, binary data) saved to file, not just in chat
- Credential chain documented — Which creds grant access to which services recorded as
credential nodes with AUTHENTICATES_TO relationships
- 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
| Persists | Lost |
|---|
| 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 instructions | Multi-step conversation context |
| Git state (commits, branches) | User-stated preferences from this session |
| TodoWrite task list | Nuanced failure analysis ("it failed because...") |
/compact summary message | Everything 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)
| Component | Tokens | % |
|---|
| System prompt | ~2.7K | 1.3% |
| Built-in tools | ~16.8K | 8.4% |
| MCP tool definitions (kali, neo4j, etc.) | ~10-20K | 5-10% |
| CLAUDE.md + memory files + skills | ~5-10K | 2.5-5% |
| Auto-compact buffer (reserved, unusable) | ~33K | 16.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):
export CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=70
{
"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:
- Queries Neo4j via HTTP API (batched — single POST, multiple statements)
- Writes
compact-state.md with: target, services, credentials, shells, flags, in-progress strategies, failed attempts, recent command history
- Creates a
compaction_event node in Neo4j for audit
- Warns on stderr about in-progress strategies (agent sees this in context)
- 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):
claude config set -g autoCompactEnabled false
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 % | Zone | Behavior |
|---|
| 0-50% | Green | Full precision, all details retained |
| 50-70% | Yellow | Minor precision loss, good time for proactive compact |
| 70-85% | Orange | Noticeable degradation, hallucination risk rises |
| 85-90% | Red | Unreliable — 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
| Situation | Action |
|---|
| Session feels sluggish, losing context | /compact with targeted summary |
| "Prompt is too long" error | claude --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 investigation | Use Agent tool with subagents (isolated 200K context each) |
Decision Heuristics
When approaching context limits, use these to decide:
- "Am I between phases?" — If yes, compact. If mid-exploit, ignore.
- "Is my context stale?" — If you're referencing findings from 100+ messages ago, compact.
- "Did I just fail hard?" — 3+ failed strategies = compact the dead reasoning.
- "Did I just succeed?" — Got a shell/flag/creds? Save to Neo4j + workspace, compact.
- "Am I about to pivot?" — Switching from web to binary? From Linux to AD? Compact.
Anti-Patterns
| Anti-Pattern | Why It Hurts | Instead |
|---|
| Disabling auto-compact without discipline | "Prompt is too long" kills the session permanently | Keep auto at 70% as safety net, manual compact at phase boundaries |
| Compacting without saving findings | Lose all discovered intel permanently | Always run pre-compact checklist, verify Neo4j has your data |
| Compacting mid-exploit | Payload bytes get mangled in summary | Finish the attempt first, even if it fails |
| Never compacting (riding auto-compact) | Auto fires mid-task, loses more than strategic compact would | Compact at phase boundaries proactively |
| Compacting with no summary message | Next phase has zero starting context | Write a specific summary of state + next steps |
| Saving payloads only in conversation | Markdown summarization strips special chars | Save to /workspace/ files before compact |
| Huge CLAUDE.md + many MCP servers | Eats 30%+ of context before you type anything | Keep CLAUDE.md under 200 lines, audit /mcp costs |