Defense in depth for Claude Code context.
State preservation + security layer against prompt injection, leakage, and manipulation.
When Claude Code hits ~95% context usage, it auto-compacts your conversation. You lose:
- Which files you were editing and why
- Your debugging trail, hypotheses, and decisions
- Build state, test results, error messages
- Uncommitted changes, stashes, and worktree state
- The overall narrative: "where were we?"
Context Guard captures your entire work environment β git state, actual code diffs, build health, worktrees, environment variables, and Claude's own memory β and automatically restores it after compaction.
Before: "Fix the auth bug in user-service.ts"
*edits 3 files, runs tests, debugging failing case*
--- COMPACTION ---
"I see we're working on a project. How can I help?"
After: --- COMPACTION ---
"Resuming: auth bug in user-service.ts, branch feat/auth-fix.
3 files modified (core:2, ui:1), tests failing on line 42.
Diff shows we added token validation but missed expiry check.
Continuing with the expiry logic..."
/plugin marketplace add jlceaser/context-guard
/plugin install context-guard@jlceaserRestart Claude Code. That's it β hooks, skills, and agent are all active.
git clone https://github.com/jlceaser/context-guard.git
cd context-guard
bash install.sh # auto-configures settings.json via jq
bash test.sh # verify (31 tests)bash <(curl -sL https://raw.githubusercontent.com/jlceaser/context-guard/main/install.sh) Context at 80%
β
ββββββββββββΌβββββββββββ
β PreCompact Hook β
β ββββββββββββββββββ β
β β Git state β β
β β Code diffs β β βββββββββββββββββββ
β β Build health β ββββββΆβ Snapshot .md β
β β Worktrees β β β + systemMessage β
β β Environment β β ββββββββββ¬βββββββββ
β β Claude memory β β β
β ββββββββββββββββββ β β
βββββββββββββββββββββββ β
βΌ
βββββββββββββββββββββββ ββββββββββββββββββ
β --- COMPACTION --- βββββΆβ systemMessage β
βββββββββββββββββββββββ β injected into β
β compacted state β
βββββββββββββββββββββββ ββββββββββ¬ββββββββ
β SessionStart Hook βββββββββββββββ
β Detects snapshot β
β Injects recovery ββββΆ Claude reads snapshot
βββββββββββββββββββββββ and resumes work
Two-phase defense:
-
systemMessage β critical metadata (project, branch, dirty files) is injected directly into the compaction summary. This survives compaction and is immediately available.
-
Snapshot file β full state with code diffs is saved to disk. Claude reads this on the next turn to restore complete context.
Annotation Layer (v4.0.0):
- Persistent annotations β topic-based notes that survive everything. Save key findings with
/cg-annotate <topic> "note", retrieve with/cg-recall <topic>. Stored in~/.claude/annotations/<project>/<topic>.md. Inspired by context-hub.
New in v0.5.0 β Context Guard now includes a security layer that protects against prompt injection, credential leakage, and context manipulation.
Tool Call βββΆ PreToolUse Hook βββΆ [Injection / File Guard] βββΆ BLOCK / WARN / PASS
β
Tool Executes βΌ
β
βΌ
PostToolUse Hook βββΆ [Injection / Leakage / Manipulation] βββΆ WARN / LOG
| Engine | What it detects | Example |
|---|---|---|
| Injection Scanner | Instruction override, identity reassignment, tag injection, jailbreak | "ignore previous instructions", <system>override</system> |
| Leakage Scanner | API keys, AWS credentials, private keys, JWT, tokens | AKIA..., -----BEGIN RSA PRIVATE KEY----- |
| File Guard | Sensitive file reads/writes | .env, .pem, id_rsa, credentials.json |
| Manipulation Scanner | Fake system tags, hidden instructions, zero-width chars | <system-reminder>fake</system-reminder> |
| Mode | PreToolUse | PostToolUse | Use case |
|---|---|---|---|
warn (default) |
Allow + systemMessage warning | systemMessage warning | Safe for daily use |
block |
Block dangerous calls | systemMessage warning | High-security environments |
log |
Silent logging | Silent logging | Audit/monitoring |
# Security config: ~/.claude/context-guard/security/config.sh
CG_SEC_ENABLED=true # Master switch
CG_SEC_MODE=warn # warn | block | log
CG_SEC_INJECTION_SCAN=true # Prompt injection detection
CG_SEC_LEAKAGE_SCAN=true # Credential leakage detection
CG_SEC_FILE_GUARD=true # Sensitive file protection
CG_SEC_MANIPULATION_SCAN=true # Context manipulation detection
CG_SEC_MAX_SCAN_BYTES=50000 # Max bytes to scan per operationSuppress known-safe patterns in ~/.claude/context-guard/security/allowlist.txt:
# Format: tool:pattern:reason
Read:.env.example:Example env file is safe
Bash:base64.*test:Test fixtures use base64
*:bearer_token:Project uses bearer tokens in tests
/cg-security-statusβ Security dashboard: events, config, hook registration/cg-security-configβ Manage mode, toggles, and allowlist
Context Guard is a 6-layer defense system:
ββββββββββββββββββββββββββββ Context Guard βββββββββββββββββββββββββββββ
β β
β LAYER 1: Hooks (automatic) β
β ββββββββββββββββ βββββββββββββββββ βββββββββββββββββββ β
β β PreCompact β β SessionStart β β Stop β β
β β Full snapshot β β Auto-detect β β Session β β
β β + code diffs β β + recovery β β bookmark β β
β β + systemMsg β β + resume β β + session chain β β
β βββββββββ¬βββββββ βββββββββ¬ββββββββ ββββββββββ¬βββββββββ β
β β β β β
β LAYER 2: Skills (manual control) β
β ββββββββββββββββ βββββββββββββββββ βββββββββββββββββββ β
β β /cg-snapshot β β /cg-restore β β /cg-context- β β
β β checkpoint β β manual load β β status β β
β ββββββββββββββββ βββββββββββββββββ βββββββββββββββββββ β
β β
β LAYER 2b: Annotation Layer (v4.0.0 β persistent knowledge) β
β ββββββββββββββββ βββββββββββββββββ β
β β /cg-annotate β β /cg-recall β β
β β save note to β β load topic β ~/.claude/annotations/ β
β β topic file β β list topics β <project>/<topic>.md β
β ββββββββββββββββ βββββββββββββββββ β
β β
β LAYER 3: Agent (intelligent) β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β context-keeper: reads snapshots + git + diffs β β
β β β multi-snapshot analysis + structured recovery briefing β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β
β LAYER 4: Guidance (passive) β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β CLAUDE.md template: auto-recovery instructions β β
β β β Claude reads snapshot without being told to β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β
β LAYER 5: Security (v0.5.0 β context content protection) β
β ββββββββββββββββ βββββββββββββββββ βββββββββββββββββββ β
β β PreToolUse β β PostToolUse β β Config + β β
β β Injection + β β Injection + β β Allowlist + β β
β β File Guard β β Leakage + β β Event Log β β
β β β block/warn β β Manipulation β β β audit trail β β
β ββββββββββββββββ βββββββββββββββββ βββββββββββββββββββ β
β β
β LAYER 6: Protection (rules) β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Hookify rules: protect snapshots + installed hooks β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β
β ββββββββββββββββββββββββββββββββββββ β
β β ~/.claude/compact-guard/ β β
β β snapshot-*.md latest.md β β
β β session-bookmark.md β β
β β .session-counter β β
β ββββββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Branch, last commit, modified/staged/untracked files, diff statistics, recent commits (8), active branches, and domain classification.
Actual git diff content β first 40 lines per file, up to 8 files. This is the most valuable data for recovery: Claude can see exactly what code was being changed.
Recently modified files (catches non-git-tracked work), build directory status, artifact ages, project size.
Active worktree list, per-worktree dirty state, worktree detection (.git file vs directory).
Platform, shell, key env vars (VCPKG_ROOT, CMAKE_PREFIX_PATH, VIRTUAL_ENV, NODE_ENV, CARGO_HOME), git stashes.
Recently updated auto-memory files, session bookmarks, session chain number.
Changes are automatically categorized:
| Domain | Patterns |
|---|---|
core |
core/*, */core/* |
src |
src/*, */src/* |
ui |
qml/*, *.qml, ui/*, components/* |
build |
CMake*, justfile, Makefile, *.cmake |
ci |
.github/*, .gitlab-ci* |
docs |
docs/*, *.md, CHANGELOG* |
scripts |
scripts/*, *.py, *.sh |
test |
test*/*, *_test.*, *_spec.* |
config |
*.json, *.yaml, *.yml, *.toml |
infra |
hooks/*, skills/*, agents/*, rules/* |
| Component | Type | Purpose |
|---|---|---|
compact-guard-pre.sh |
Hook (PreCompact) | Full state snapshot + code diffs + systemMessage |
compact-guard-post.sh |
Hook (SessionStart) | Auto-detect compaction + inject recovery |
compact-guard-stop.sh |
Hook (Stop) | Session bookmark for cross-session continuity |
compact-guard-lib.sh |
Library | Shared functions (git, worktree, domain, diff, JSON) |
security-pre-tool.sh |
Hook (PreToolUse) | Scan inputs for injection + sensitive file access |
security-post-tool.sh |
Hook (PostToolUse) | Scan outputs for injection + leakage + manipulation |
context-security-lib.sh |
Library | Security scanning functions (4 detection engines) |
/cg-snapshot |
Skill | Create manual checkpoint on demand |
/cg-restore |
Skill | Read and summarize latest snapshot |
/cg-context-status |
Skill | System health dashboard |
/cg-setup |
Skill | Initial setup and configuration |
/cg-security-status |
Skill | Security dashboard: events, config, hooks |
/cg-security-config |
Skill | Manage security mode, toggles, allowlist |
context-keeper |
Agent | Intelligent multi-snapshot recovery analysis |
context-health.sh |
Widget | StatusLine context health indicator |
compact-guard-rules.md |
Rules | Hookify protection for snapshots/hooks |
context-security-rules.md |
Rules | Hookify protection for security config/log |
test.sh |
Test Suite | Validate installation, hooks, and security layer |
# Trigger compaction at 80% instead of 95% (more room for recovery)
CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=80
# Environment variables (all optional, with defaults)
COMPACT_GUARD_DIR=~/.claude/compact-guard # Snapshot storage
COMPACT_GUARD_MAX_SNAPSHOTS=10 # Max snapshots to keep
COMPACT_GUARD_MAX_AGE=900 # Recovery detection window (seconds)
COMPACT_GUARD_DIFF_LINES=40 # Lines of diff per file
COMPACT_GUARD_DIFF_FILES=8 # Max files to capture diffs forThe post-hook can run as a standalone SessionStart hook or as an addon called from your existing session-start.sh:
Option A β Addon (recommended if you have a session-start.sh):
# In your session-start.sh:
COMPACT_RECOVERY=$("$HOME/.claude/hooks/compact-guard-post.sh" 2>/dev/null || true)
if [ -n "$COMPACT_RECOVERY" ]; then
CTX="$CTX | $COMPACT_RECOVERY"
fiOption B β Standalone hook in settings.json:
"SessionStart": [{
"matcher": "",
"hooks": [{
"type": "command",
"command": "bash \"$HOME/.claude/hooks/compact-guard-post.sh\"",
"statusMessage": "Checking for context recovery..."
}]
}]Context Guard focuses on state preservation β capturing your complete work environment (git + diffs + disk + build + worktrees + environment) and recovering it automatically after compaction.
| Capability | context-mode | context-cascade | context-engineer | Context Guard |
|---|---|---|---|---|
| Focus | Context reduction | Modular loading | Budget management | State preservation |
| Git state capture | - | - | - | Full |
| Code diff capture | - | - | - | Yes |
| Disk-level file tracking | - | - | - | Yes |
| Build health monitoring | - | - | - | Yes |
| Domain classification | - | - | - | Yes |
| Worktree awareness | - | - | - | Yes |
| Environment snapshot | - | - | - | Yes |
| systemMessage injection | - | - | - | Yes |
| Auto-recovery on compaction | Via SQLite | - | Via TASK.md | Via hooks |
| Session chain tracking | - | - | - | Yes |
| Manual checkpoints (skills) | - | Yes | - | Yes |
| Intelligent recovery (agent) | - | Yes | - | Yes |
| Visual indicator | CLI | - | Dashboard | StatusLine |
| Self-test suite | - | - | - | Yes |
| Auto-configure installer | - | - | One-liner | Auto (jq) |
| Zero external dependencies | No (Node.js) | No (MCP) | No (Node.js) | Yes |
| Pure bash | No | No | No | Yes |
context-mode (2,900+ stars) and Context Guard solve different halves of the context problem:
| context-mode | Context Guard | |
|---|---|---|
| Goal | Reduce context consumption | Preserve state across compaction |
| How | MCP sandbox (~98% context savings) | Multi-layer snapshot + recovery |
| Prevents compaction? | Delays it significantly | Handles it when it fires |
| Dependencies | Node.js, SQLite | None (pure bash) |
They are complementary. context-mode reduces context consumption so compaction happens less often. Context Guard preserves your full state when it does happen. Together: maximum longevity + zero loss.
Click to expand a sample snapshot
# Context Guard Snapshot
## Session Info
| Field | Value |
|-------|-------|
| Time | 2026-03-08 14:32:15 |
| Session | #3 |
| Trigger | auto |
| Working Dir | /home/user/myproject |
| Context Guard | v3.0.0 |
## 1. Git State
| Field | Value |
|-------|-------|
| Project | myproject |
| Branch | feat/auth-fix |
| Last Commit | a1b2c3d fix(core): handle empty config |
| Uncommitted | 3 files |
### Changes by Domain
| Domain | Files |
|--------|-------|
| core | 2 |
| ui | 1 |
### Modified Files (git)
core/src/auth_service.cpp
core/include/auth_service.h
qml/screens/LoginScreen.qml
### Diff Content (actual changes)
--- core/src/auth_service.cpp ---
@@ -42,6 +42,12 @@
bool AuthService::validateToken(const QString& token) {
+ // Check token expiry
+ auto expiry = extractExpiry(token);
+ if (expiry < QDateTime::currentDateTime()) {
+ return false;
+ }
+
return verifySignature(token);
}
## 2. Disk State
| Field | Value |
|-------|-------|
| Project Size | 156M |
| Build Dir | build/dev |
| Build State | exists |
| Last Build | 5min ago |
## 4. Environment
| Field | Value |
|-------|-------|
| Platform | Linux |
| Shell | /bin/bash |
| Key Vars | CMAKE_PREFIX_PATH=set VENV=active |
## Recovery
After compaction, this snapshot was automatically saved.
Read this file to restore working state.bash uninstall.shOptions:
--keep-snapshotsβ keep snapshot files--skip-configβ skip settings.json cleanup
- Claude Code with hooks support
- Bash (Linux, macOS, Windows Git Bash / MSYS2)
- Git (optional β gracefully degrades without it)
- jq (optional β enables auto-configuration, falls back to manual)
Context Guard protects both your work state and your context integrity:
- Capture everything β git + diffs + disk + worktrees + environment + Claude ecosystem
- Inject into the summary β systemMessage survives compaction
- Auto-recover β SessionStart detects and injects recovery context
- Guard the context β scan inputs/outputs for injection, leakage, and manipulation
- Multi-layer defense β hooks (auto) + skills (manual) + agent (intelligent) + security (active) + rules (protective)
- Session continuity β bookmarks and session chain across multiple sessions
- Zero dependencies β pure bash, works everywhere Claude Code runs
The result: compaction becomes a minor hiccup and malicious content gets flagged before it can cause harm.
See CONTRIBUTING.md for guidelines.
Context Guard β defense in depth for Claude Code context
Report Bug Β· Request Feature
Built by @jlceaser