PRD 3 of 25

Context Management & Auto-Memory

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.

Install

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
Context Management architecture infographic
Architecture infographic — from bulletproof-context-guard/docs/media/
Context Management Architecture

1. Problem Statement

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.

2. Architecture Overview

Three layers of context management:

Layer 1: CLAUDE.md Hierarchy (Static)

LevelPathScope
Global~/.claude/CLAUDE.mdAll projects — universal rules, preferences, standards
Project~/.claude/projects/{path}/CLAUDE.mdPer-project — conventions, architecture notes
Repository{repo}/.claude/CLAUDE.mdGit-tracked — shared team configuration

Rules marked (ENFORCED) or (CRITICAL) survive compaction — reloaded from disk, not conversation.

Layer 2: Auto-Memory (File-Based Hot Context)

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

Layer 3: Context Guard Plugin (Active Monitoring)

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.

4-Tier Escalation

L1

Warning

≤30% left. Informational.

L2

Advisory

≤15% left. Save state.

L3

Yellow Alert

≤7% left. Force save.

L4

Critical

≤3% left. Emergency.

3. Key Components

3.1 Velocity Prediction

3-sample sliding window analyzes consumption rate. If consumption exceeds 5 percentage points per operation, escalation triggers earlier — before static thresholds would react.

3.2 Dynamic Thresholds

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.

3.3 Context Budget MCP Tool

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

3.4 State-Save Verification

PreCompact hook verifies all critical state persisted: plans, tasks, decisions, workflow state (conductor-state.json). Won't allow compression until verification passes.

4. Requirements

REQ-CTX-001 Token-precise context monitoring via PreToolUse hooks, self-registered from the plugin's own hooks.json so no settings.json wiring is required.
REQ-CTX-002 4-tier escalation at configurable distances from auto-compaction, measured as percentage of the context window remaining: Warning (≤30%), Advisory (≤15%), Yellow Alert (≤7%), Critical (≤3%).
REQ-CTX-003 3-sample velocity prediction, escalating early when consumption exceeds 5 percentage points per operation.
REQ-CTX-004 Dynamic thresholds from a rolling 10-measurement window, falling back to 16% remaining when history is insufficient.
REQ-CTX-005 PreCompact hook shall persist all critical state (plans, tasks, workflow) before allowing compression.
REQ-CTX-006 CLAUDE.md cascade: global → project → repository with (ENFORCED)/(CRITICAL) markers surviving compaction.
REQ-CTX-007 Auto-memory: MEMORY.md index + topic files organized by type (user, feedback, project, reference).
REQ-CTX-008 Two-layer memory: file-based hot (loaded every session) + vector deep (queried on demand via 74 MCP tools).
REQ-CTX-009 Context budget tool with 5 compartments: active_task, project_background, operator_preferences, safety_constraints, ambient_knowledge.
REQ-CTX-010 Session resumption from saved state including auto-memory, workflow checkpoints, and task progress.
REQ-CTX-011 Context health telemetry (level, velocity, predicted exhaustion) available to orchestrator for adaptive routing.
REQ-CTX-012 SessionEnd hook shall write session breadcrumb to Obsidian daily note for cross-session continuity.

5. Prompt to Build It

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.

6. Design Decisions

PreToolUse over PostToolUse

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.

Velocity over Static Thresholds

Static thresholds react after the fact. Velocity catches rapid consumption before it hits the threshold, enabling preemptive saves during fast-paced workflows.

File-Based + Vector Two-Layer

Files survive infrastructure failures. If Qdrant is down, MEMORY.md still loads. Vector provides deep semantic search. Complementary, not competing.

5-Compartment Budget

The context_budget MCP tool partitions the window into managed compartments with priorities. This prevents any single domain from crowding out others.

7. Hook Wiring

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

EventScriptTimeoutPurpose
SessionStartsession_start.sh10sClean per-session state, detect post-compaction resume, branch between good vs degraded recovery via state_saved verification file, auto-clean stale session dirs.
PreToolUsewarn.sh5s4-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.
PreCompactpre_compact.sh5sCapture 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.

Coordination with the memory plugin's PreCompact

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.

8. Integration Points

→ Memory System

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.

→ Multi-Agent Orchestration

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.

→ Agent Governance

Context pressure events are CONTEXT_PRESSURE audit events in the governance bus. Constitutional observer flags context-pressured decisions for review.

→ Plugin Ecosystem

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.