Skip to content

jlceaser/context-guard

Repository files navigation

Context Guard

Defense in depth for Claude Code context.
State preservation + security layer against prompt injection, leakage, and manipulation.

MIT License Zero Dependencies Shell: Bash Claude Code v0.5.0 Security Layer


The Problem

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..."

Quick Start

Plugin Install (recommended)

/plugin marketplace add jlceaser/context-guard
/plugin install context-guard@jlceaser

Restart Claude Code. That's it — hooks, skills, and agent are all active.

Manual Install

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)

One-liner

bash <(curl -sL https://raw.githubusercontent.com/jlceaser/context-guard/main/install.sh)

How It Works

                          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:

  1. systemMessage — critical metadata (project, branch, dirty files) is injected directly into the compaction summary. This survives compaction and is immediately available.

  2. 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):

  1. 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.

Context Security

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

4 Detection Engines

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>

3 Security Modes

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

Configuration

# 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 operation

Allowlist

Suppress 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

Skills

  • /cg-security-status — Security dashboard: events, config, hook registration
  • /cg-security-config — Manage mode, toggles, and allowlist

Architecture

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                │                        │
│          └──────────────────────────────────┘                        │
└──────────────────────────────────────────────────────────────────────┘

What Gets Captured

1. Git State

Branch, last commit, modified/staged/untracked files, diff statistics, recent commits (8), active branches, and domain classification.

2. Code Diffs (new in v3)

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.

3. Disk State

Recently modified files (catches non-git-tracked work), build directory status, artifact ages, project size.

4. Worktrees

Active worktree list, per-worktree dirty state, worktree detection (.git file vs directory).

5. Environment

Platform, shell, key env vars (VCPKG_ROOT, CMAKE_PREFIX_PATH, VIRTUAL_ENV, NODE_ENV, CARGO_HOME), git stashes.

6. Claude Ecosystem

Recently updated auto-memory files, session bookmarks, session chain number.

Domain Classification

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/*

Components

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

Configuration

# 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 for

SessionStart Integration

The 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"
fi

Option 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..."
  }]
}]

Comparison

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

Works great with context-mode

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.


Snapshot Example

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.

Uninstalling

bash uninstall.sh

Options:

  • --keep-snapshots — keep snapshot files
  • --skip-config — skip settings.json cleanup

Requirements

  • 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)

Philosophy

Context Guard protects both your work state and your context integrity:

  1. Capture everything — git + diffs + disk + worktrees + environment + Claude ecosystem
  2. Inject into the summary — systemMessage survives compaction
  3. Auto-recover — SessionStart detects and injects recovery context
  4. Guard the context — scan inputs/outputs for injection, leakage, and manipulation
  5. Multi-layer defense — hooks (auto) + skills (manual) + agent (intelligent) + security (active) + rules (protective)
  6. Session continuity — bookmarks and session chain across multiple sessions
  7. 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.


Contributing

See CONTRIBUTING.md for guidelines.

License

MIT


Context Guard — defense in depth for Claude Code context
Report Bug · Request Feature

Built by @jlceaser

About

Defense in depth for Claude Code context. Multi-layer preservation system: hooks + skills + agent + rules. Pure bash, zero dependencies.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages