Repository navigation
Description
Goal
Automate context-zone awareness: hooks that silently watch the plugin's own snapshot seam and inject routing guidance when a session crosses into a worse zone — plus rework zone bands so defaults are meaningful on 1M-class windows. Today the plugin is observability-only ("consumers decide what to do"); this adds the first shipped consumer.
Locked decisions (interview 2026-07-25/26; sweep-audited 2026-07-26)
- Ownership: context-guard owns the hooks (owns the data seam). Injected message carries a minimal generic continuation tree + presence-gated pointer to
session-flow:workflow's router (session-flow/workflow: end-of-phase continuation router (continue / clear / handoff / subagent / compact) #1476); plugin stays independently useful per PLUGIN-PHILOSOPHY.md. - Cadence: injection only on transition into a worse zone; silent otherwise; advisory by default.
- Posture: config
mode: advisory | blocking(renamed fromenforcingto match the repo's shipped gate-posture enum; the advisory-vs-blocking and fail-open axes are owned bydocs/conventions/hook-observability+docs/conventions/hook-precision— conform there or record divergence in those docs' terms). Blocking = PreToolUse gate active only on a fresh dumb-zone snapshot; fail-open onunknown; handoff-writing operations exempt (no deadlock); small grace budget. - PostCompact hook marks the session evidence-degraded — closes the reader contract's documented gap. VERIFIED against code.claude.com/docs/en/hooks (2026-07-26):
PostCompactexists,manual/automatchers, side-effect-only with no decision control — never gate on it.
Reopened by discipline sweep (2026-07-26) — design-stage inputs, not locked
- Event selection. The original pick (UserPromptSubmit + PostToolUse + a bespoke per-session dedupe state file) was made from recall; the live hooks doc lists ~30 events. Survey the field at design time. Leading candidates:
PostToolBatch(fires once per parallel tool batch, before the next model call — likely replaces PostToolUse AND dissolves the dedupe file),UserPromptSubmit,PreCompact(blocking-capable — the point-of-no-return intervention seam),SessionStart(the unknown-at-start state).PostToolUseFailureexists; note it.SubagentStart/SubagentStopevaluation belongs to context-guard: research non-interactive observability (headless + subagent context usage) #1478. - Hook config delivery. Bands stay in
zones.json(cross-plugin data seam). Hook enable/events/mode config: re-derive against the owner docs the interview missed —docs/conventions/hook-config-delivery/README.md(exec-form argv substitution reaches plugin hooks;CLAUDE_PLUGIN_OPTION_<KEY>env export; direct settings read) anddocs/conventions/config-cascade/README.md(the fleet's three-layer cascade dissolves — not defers — the per-project override tier).
Bands (amended by sweep)
- Window-class-aware absolute-token bands; resolver classifies from the snapshot's
context_window.context_window_size. - Occupancy definition first. Upstream
used_percentagecounts input tokens only (input_tokens + cache_creation_input_tokens + cache_read_input_tokens, no output — statusline doc). State ONE definition for token bands, including output-token treatment; never equate percentage and token shapes without normalizing (the interview's 50% ≙ 100k continuity argument compared unlike units). - Combination rule. Conservative-min across both shapes was the interview's pick, but what a consumer inlines and computes when the two shapes disagree must be an explicit acceptance criterion. Open design question, choose deliberately and record rationale in the reader contract: continuous measure (tokens + derived zone words as convenience view) vs enum-primitive.
- Version floor.
total_input_tokens/total_output_tokensmean current context occupancy only since CLI 2.1.132 (before that: cumulative session totals — bands would misfire badly). Design specified against 2.1.220; ship a minimum-version floor or runtime guard. - Defaults — declared judgment with named anchors, never presented as benchmark-derived:
| Class | smart | acceptable | dumb | Anchor |
|---|---|---|---|---|
| 1M | ≤ 200k | ≤ 400k | above | Thariq Shihipar range (sole named origin; see provenance) |
| 200k | ≤ 100k | ≤ 160k | above | Declared judgment below Chroma's confounded ~113k signal and Pocock's uncited 125k floor |
Numeric agreement of the 200k row with the shipped 50/75 percentage defaults is coincidence, not validation — those encode compaction headroom, not quality. Both rows carry equally low confidence.
- Local anchor: the producing machine's transcript history shows a session at 308k input tokens uncompacted on a 1M-class window (reader-contract observation). Bounds compaction behavior only — says nothing about quality; a testable prediction against future local sessions.
- Percentage keys retained only with (a) the recorded rationale in the reader contract — percentage answers distance to compaction, tokens answer distance to quality — and (b) a retirement trigger (e.g. removed once no shipped consumer inlines the percentage floor). Back-compat alone is how a second vocabulary becomes permanent.
Provenance (condensed claim table)
| Claim | Origin | Tier | Note |
|---|---|---|---|
| ~300–400k context rot | Thariq Shihipar (Anthropic CC team), x.com/trq212/status/2044548257058328723, 2026-04 | Named staff, informal | Self-hedged "highly task-dependent, not a fast rule"; sole origin |
CLAUDE_CODE_AUTO_COMPACT_WINDOW=400000 |
howborisusesclaudecode.com | Curation | Setting value invented by the site; absent from Thariq's article |
| "Use ≤40% of 1M" | Unlocatable | Folklore | Arithmetic on Thariq's number |
| Dumb zone at 125–150k | Pocock, aihero.dev smart-zone entry | Practitioner | Uncited |
| Official threshold | None exists | Official | Framing: "performance gradient, not hard cliff" |
| Degradation tracks absolute tokens, not window % | Chroma context-rot report; Anthropic system-card fixed-point evals | Primary research + official | High confidence |
| Sonnet 5 auto-compacts ~967k | code.claude.com/docs/en/model-config | Official | These bands are product opinion, not Anthropic-endorsed |
Generation drift is real (Mythos 5 markedly better than Opus 4.8 at 1M in same-table GraphWalks) — bands may already be conservative. No public benchmark measures agentic instruction-following decay, so onset numbers likely under-predict the practical dumb zone. Bands are meaningful against total occupancy including baseline overhead (system prompt, skills, MCP schemas). zones.json is the correction path.
Constraints
- Statusline single-slot contention (verified 2026-07-26): on the reference machine
~/.claude/context-guard/does not exist (setup never ran) and the statusline slot is owned by rate-limit-guard's tee — every session there resolvesunknowntoday, interactive included. Tee coexistence/chaining in the one statusline slot is a named design constraint; context-guard: research non-interactive observability (headless + subagent context usage) #1478 owns the observability survey. - Consumer-agnostic per PLUGIN-PHILOSOPHY.md.
Verify at implementation (never from memory)
- Chosen hook events' injection/blocking semantics vs the current hooks doc (
PostCompactalready verified 2026-07-26). - Whether subagent tool calls traverse parent-session hooks — undocumented upstream; needs an empirical test.
- Statusline snapshot refresh timing vs tool-side hook reads (staleness interplay).
- Anthropic auto-compact defaults (Sonnet 5 ~967k et al.) — recheck.
Acceptance criteria
- Crossing into a worse zone injects once per transition; silent while zone unchanged or
unknown. - Advisory default; blocking mode per spec — never blocks on
unknown, never blocks handoff writing. - PostCompact marks evidence-degraded per contract language.
- zones.json accepts the new band shape; malformed file falls back with visible notice (existing rule).
- Both known inliners migrate: plugin-quality audit's zones gate (currently rejects a token-shape zones.json and silently falls back to its inlined 50/75 table — the split-brain to prevent) and context-guard setup's seeder. Reader-contract inline floor updated with drift-check lane; the disagreement/combination rule consumers inline is stated verbatim in the contract.
- Version floor or runtime guard for pre-2.1.132 token-field semantics.
- Config delivered per the re-derived channel (see reopened section); consumer-agnostic.
Related
- Companion: session-flow/workflow: end-of-phase continuation router (continue / clear / handoff / subagent / compact) #1476 (router; likely one PR). Observability survey: context-guard: research non-interactive observability (headless + subagent context usage) #1478. Origin tree: x.com/mattpocockuk/status/2079879414297330146 (adapted; AFK-node polarity inverted in source — re-derivation recorded in session-flow/workflow: end-of-phase continuation router (continue / clear / handoff / subagent / compact) #1476).
Activity
kyle-sexton commentedon Jul 26, 2026
This was generated by AI during triage.
Triage
Classification
Feature(first shipped consumer of the plugin's snapshot seam; new hooks, new enforcement mode, reworked zone bands)priority: medium(left as-is — no blocking dependency or external deadline stated; assessed-default tier)C4— structural (work-class: structural). This is not a bounded small feature: it adds new hook wiring (UserPromptSubmit,PostToolUse,PostCompact) that runs in every consuming session, introduces aPreToolUseenforcing mode capable of blocking tool calls, and reworkszones.json's band schema (window-class-aware absolute-token bands, back-compat with existing percentage keys). Blast radius is cross-cutting (every session that installscontext-guard) and contract-shaped (hook behavior + config schema), matchingC4's "refactors, migrations, contract changes" bundle rather thanC3's bounded brief.Redundancy / rejected-concept check
docs/out-of-scope/ledger exists in this repo — skipped.plugins/context-guard/: nohooks/directory or hook registration exists today — onlyscripts/context-zone.sh,statusline-tee.sh,statusline-shim.sh, and thereference/reader-contract.md. The issue's framing ("today the plugin is observability-only") matches what's on disk. Not a duplicate.Cluster note
Routing: human-gated
Per
plugins/autonomy/reference/guardrails/admission-policy.md,C4ishuman-gatedalways under the shipped defaults — human review and human merge are mandatory for structural/contract changes regardless of brief completeness. This item is unambiguously in that bucket: it changes hook-triggered behavior across every consuming session and adds a mode that can block tool execution.Agent Brief
Type: Feature
Summary: Add zone-crossing hooks to
context-guard(advisory by default, optional enforcing mode) that inject continuation guidance on zone-transition events, plus a window-class-aware rework ofzones.json's token bands so defaults are meaningful on 1M-class context windows.Current behavior:
context-guardis observability-only: it exposes zone data via its snapshot seam but has no hooks and makes no behavioral decisions itself ("consumers decide what to do").zones.jsonbands are expressed as window percentages, which are not meaningful defaults on 1M-class windows.Desired behavior:
UserPromptSubmitandPostToolUsehooks (both default-on) inject routing guidance exactly on transition into a worse zone (smart→acceptable→dumb), deduped per session (~twice per session, silent otherwise);PostToolUsecoverage matters because an autonomous run may never emit a user prompt.PostCompacthook marks the session evidence-degraded, closing the documented reader-contract gap that the snapshot alone can't reveal a compaction happened.mode: advisory | enforcingconfig, defaultadvisory. Inenforcing, aPreToolUsegate activates only on a fresh dumb-zone snapshot, fails open onunknown(never blocks early-session null states or headless runs), exempts handoff-writing operations, and allows a small grace budget.zones.json, seeded/refreshed idempotently by the setup skill; a per-project override tier is explicitly deferred (trigger: a repo needing different tolerance than its operator).session-flow:workflow's router (companion session-flow/workflow: end-of-phase continuation router (continue / clear / handoff / subagent / compact) #1476) — the plugin stays independently useful without that companion installed.zones.jsonbands become window-class-aware absolute-token bands (resolver classifies window class from the snapshot'scontext_window_size); existing percentage keys are retained for back-compat; effective zone = conservative-min of applicable bands. Default bands and their provenance/anchors are specified in the issue body's table and must ship in the reader contract, including whether bands include baseline (system prompt/skills/MCP schema) overhead.Key interfaces:
UserPromptSubmit,PostToolUse,PostCompact, and (enforcing mode)PreToolUse— verify actual event names,additionalContextinjection shape, and deny semantics against current hooks docs before implementing, not from memoryzones.json's band schema — must accept both the existing percentage shape and the new window-class absolute-token shape; malformed file falls back with a visible notice (existing rule)plugins/context-guard/reference/reader-contract.md) — gains the evidence-degraded semantics and the inline-floor-value drift-check laneAcceptance criteria:
unknownadvisoryis the default posture;enforcingblocks per spec, never onunknown, never blocks handoff-writing operationsPostCompactmarks the session evidence-degraded per the reader contractzones.jsonaccepts both band shapes; a malformed file falls back with a visible noticePLUGIN-PHILOSOPHY.mdwith no companion installedOut of scope:
session-flow:workflow's router logic itself (companion session-flow/workflow: end-of-phase continuation router (continue / clear / handoff / subagent / compact) #1476, distinct brief)Why human-gated:
C4structural work class per admission policy — new hook wiring active in every consuming session plus a tool-blocking enforcement mode and a config-schema rework are exactly the "cross-cutting, hard to reverse" bundle that keeps human review and merge mandatory.feat(session-flow): adopt claim-provenance and constraint re-scan rul…
kyle-sexton commentedon Jul 26, 2026
Field evidence: the statusline single-slot constraint is resolved by chaining, observed working today
Surfaced incidentally while running the handoff-inbox queue on a Windows/Git Bash machine (CLI 2.1.220, 1M-class window). Posting because it partially contradicts a stated constraint that is currently shaping this issue's design.
What the Constraints section says
What is actually running on this machine
context-guardandrate-limit-guardare both enabled, and their tees coexist by nesting three deep in the single slot — each shim takes the next command as its argv tail, so the "one slot" is not exclusive:Both links are demonstrably live, not merely installed — checked within minutes of each other:
~/.claude/context-guard/bin/statusline-shim.sh+context/with 7 session snapshotsused_percentage: 15,context_window_size: 1000000context-zone.sh <session_id>smart— notunknown~/.claude/rate-limit-guard/rate-limits.json~/.claude/context-guard/zones.jsonused_percentage)So chaining is not a theoretical mitigation to be designed; it is in production on at least one machine, at depth 3, with the outer tee passing through byte-for-byte to an inner tee that keeps working. The reference-machine observation looks like setup never ran there, which is a different problem from the slot is exclusive.
Why this matters for the design
unknownis not the default state everywhere. A fail-open-on-unknownposture tested only against the reference machine would exercise the degraded path almost exclusively and could ship with the healthy path under-tested.rate-limit-guard's shim were outermost). Worth an explicit acceptance criterion, since setup will have to pick a side.Scope and limits of this evidence
setupskill produces this wiring.Unrelated observation, since it reproduced live
While gathering the above,
guardrails'block-hook-bypass.shfalse-fired on a read-only command: apython3 -cthat only didjson.load(open(path))and printed the result was blocked with "python3 -c file write bypasses Write/Edit hooks". No write was present — the soleopen()was a read. This matches the existing unanchored-substring false-positive class rather than anything in this issue; noting it here only because it happened during this check, and it belongs on aguardrailsissue if it is not already tracked.fix(session-flow): reground orchestrate's nested-subagent sources on …
feat(context-guard): zone-crossing hooks, token bands, and the workfl…
feat(context-guard): zone-crossing hooks, token bands, and the workfl…
Merge origin/main into feat/1475-1476-zone-hooks-and-router