Active context window monitoring with 4-tier escalation, velocity-based prediction, a two-layer memory architecture (file-based hot + vector deep), and automatic state preservation before compression.
Installs as a Claude Code plugin. The repositories are currently private, so the plugin fetch cannot resolve until they are published:
git clone https://github.com/bulletproofsoftware-ai/bulletproof-context-guard.git cd bulletproof-context-guard # point your Claude Code plugin config at this directory, or clone it into # your plugins directory. Hooks self-register via hooks/hooks.json: # SessionStart, PreToolUse, PreCompact # tunable thresholds live in plugin.json

bulletproof-context-guard/docs/media/
Claude Code operates within a finite context window. During long sessions — multi-file refactors, complex debugging, multi-agent workflows — the context fills. When it does, the system compresses conversation history, destroying in-progress plans, architectural decisions, and task state. This manifests as lost plans, repeated mistakes, broken workflows, and session amnesia.
The memory system's MCP tools provide the context_budget tool with 5 compartments (active_task, project_background, operator_preferences, safety_constraints, ambient_knowledge), but that manages what's in context — not when context is about to run out. The context guard monitors the window itself, predicting exhaustion and triggering graduated responses.
Three layers of context management:
| Level | Path | Scope |
|---|---|---|
| Global | ~/.claude/CLAUDE.md | All projects — universal rules, preferences, standards |
| Project | ~/.claude/projects/{path}/CLAUDE.md | Per-project — conventions, architecture notes |
| Repository | {repo}/.claude/CLAUDE.md | Git-tracked — shared team configuration |
Rules marked (ENFORCED) or (CRITICAL) survive compaction — reloaded from disk, not conversation.
MEMORY.md index (~200 lines, loaded every session) with individual topic files (user, feedback, project, reference types). Claude manages these automatically. Two-layer: file-based hot (loaded every session) + vector deep (queried via MCP tools on demand).
v3.0.0 plugin with PreToolUse hooks (self-registered via the plugin's own hooks/hooks.json) tracking token consumption. Velocity analysis predicts exhaustion. 4-tier escalation triggers graduated responses.
Warning
≤30% left. Informational.
Advisory
≤15% left. Save state.
Yellow Alert
≤7% left. Force save.
Critical
≤3% left. Emergency.
3-sample sliding window analyzes consumption rate. If consumption exceeds 5 percentage points per operation, escalation triggers earlier — before static thresholds would react.
Rolling window of last 10 measurements adapts alert levels to conversation patterns. Hard fallback: 16% remaining, used when there is not yet enough history to adapt.
The memory system's context_budget tool manages 5 compartments with pinning, eviction, and token estimation. This bridges the gap between what's in context (budget) and when context runs out (guard).
PreCompact hook verifies all critical state persisted: plans, tasks, decisions, workflow state (conductor-state.json). Won't allow compression until verification passes.
Build a context management system for Claude Code:
1. CONTEXT GUARD PLUGIN (v3.0.0):
- PreToolUse hook (self-registered via the plugin's hooks.json) tracking
token consumption
- 4-tier escalation on % of context remaining before auto-compaction:
Warning(≤30%), Advisory(≤15%), Yellow Alert(≤7%), Critical(≤3%)
- 3-sample velocity prediction, early trigger at >5 percentage points/op
- Dynamic thresholds from rolling 10-measurement window
- Fallback threshold: 16% remaining when history is insufficient
2. AUTO-MEMORY:
- MEMORY.md index (~200 lines) loaded every session
- Topic files with YAML frontmatter (name, description, type)
- Types: user, feedback, project, reference
- Two-layer: file-based hot + vector deep (via 74 MCP tools)
3. CLAUDE.MD HIERARCHY:
- Global → Project → Repository cascade
- (ENFORCED)/(CRITICAL) markers survive compaction
4. CONTEXT BUDGET (MCP tool):
- 5 compartments with pin/evict/estimate operations
- Bridges "what's in context" with "when it runs out"
5. STATE PRESERVATION:
- PreCompact hook saves plans, tasks, decisions, workflow state
- SessionEnd writes Obsidian daily note breadcrumb
Build as a Claude Code plugin whose hooks self-register via hooks/hooks.json.Warnings must reach the model before it commits to the next tool call, so the escalation notice fires on PreToolUse rather than after the fact. It also keeps the plugin self-contained: PreToolUse is one of the events Claude Code reads straight from a plugin's own hooks.json, so installing the plugin is the whole install — no settings.json edit.
Static thresholds react after the fact. Velocity catches rapid consumption before it hits the threshold, enabling preemptive saves during fast-paced workflows.
Files survive infrastructure failures. If Qdrant is down, MEMORY.md still loads. Vector provides deep semantic search. Complementary, not competing.
The context_budget MCP tool partitions the window into managed compartments with priorities. This prevents any single domain from crowding out others.
Context-Guard ships its hooks in ~/.claude/plugins/local/context-guard/hooks/hooks.json. Claude Code auto-discovers them when the plugin is installed — no wiring into settings.json required. Per-session state lives under state/sessions/<session_id>/.
| Event | Script | Timeout | Purpose |
|---|---|---|---|
| SessionStart | session_start.sh | 10s | Clean per-session state, detect post-compaction resume, branch between good vs degraded recovery via state_saved verification file, auto-clean stale session dirs. |
| PreToolUse | warn.sh | 5s | 4-tier actionable warnings calibrated to auto-compaction threshold. Tiers 3–4 get persistent reminders on every tool call. Fast-path exit <3ms when no flag file present so no observable latency cost. |
| PreCompact | pre_compact.sh | 5s | Capture last remaining_percentage from statusline JSON, log remaining=NN to compaction.log, clean per-session state. Coordinates with the memory plugin's PreCompact hook so context saves happen in order. |
Both plugins fire PreCompact hooks. Context-Guard records the compaction event (telemetry); the memory plugin's pre_compact.py performs the state save to Qdrant. They are non-overlapping concerns — order does not matter, but both must complete before Claude Code begins compression.
File-based auto-memory is the hot layer. Vector memory (74 MCP tools, Qdrant collections + cold-tier Postgres) is the deep layer. Context guard triggers saves before compaction. The context_budget tool manages what fills the window.
Context pressure signals feed the conductor. The 60% budget rule and max 3 specs/session constraint in the conductor's context-management skill directly depend on context guard telemetry.
Context pressure events are CONTEXT_PRESSURE audit events in the governance bus. Constitutional observer flags context-pressured decisions for review.
Context guard is a reference implementation of a monitoring plugin that lives entirely in the plugin hook layer — SessionStart, PreToolUse and PreCompact all self-register from its own hooks.json.