SLOPSHOPPER

context-guard

Per-session context-window observability. A mod writes each session's context-window figures to a snapshot file and shows the person a toast and a transcript…

bandguardcommandtoastprompttool
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · context-guard
› fix the failing auth test and add an audit log call ● context-guard: context-guard: next step: route it with /session-flow:workflow (if installed), or see https://code.claude.com/docs/en/context-window#when-your-context-fills-up · more: https://github.com/melodic-software/claude-code-plugins/blob/main/plugins/context-guard/README.md ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /context-guard ⎿ context-guard: zone unknown, 49% of a 200000-token window used (97400 tokens) ⎿ context-guard: Bands: smart up to 50%, acceptable up to 75%; approach margin 5 points ⎿ context-guard: This session: band row off, zone-change toast on ⎿ context-guard: Settings: /Users/dev/.claude/context-guard/zones.json (absent) ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

context-guard

A Claude Code plugin that makes each session's context-window usage observable to Claude itself and to any session or tool that needs it, so long-running workflows can route heavy work away from a degraded context before quality slips, instead of guessing. Four parts:

  • The module (hooks/register.tsx), a mod: a hooks module Claude Code runs in its own process. It shows the person a toast when the session crosses into a worse context zone, tells Claude the same when the operator turns on model_notices (off by default), answers /context-guard and the mcp__context-guard__status tool, draws an optional band row, and writes the snapshot file. It needs a Claude Code build that can run mods; older builds are unsupported. Pointer: when deciding which build that is, fetch mods overview: turn mods on or off live. As of: 2026-10-11. Recheck trigger: the terminal version that section names for mods changes. See The module.
  • Zone resolver (scripts/context-zone.sh). context-zone.sh <session_id> prints exactly one word: smart / acceptable / dumb / unknown. Two band shapes, combined conservatively (the worse computable zone wins): percentage bands over used_percentage (shipped defaults smart ≤ 50 < acceptable ≤ 75 < dumb) and window-class token bands over occupancy (total_input_tokens + total_output_tokens; shipped defaults 100k/150k on a 200k window, 128k/500k on a 1M window). Bands come from the machine-scope ~/.claude/context-guard/zones.json when present and valid, else from the shipped defaults. Zones say where you are; consumers decide what to do.
  • PostCompact marker hook (hooks/post-compact-mark.sh), a settings hook, so it runs where mods are off: it writes an evidence-degraded marker next to the session's snapshot, and the module honors it: a compacted session's effective zone is dumb regardless of its post-compaction numbers. Its row carries a 60-second timeout. The module is the only source of zone lines. No part of the plugin denies a tool call.
  • Reader contract (reference/reader-contract.md), the authoritative consumer contract: the snapshot path pattern, file shape, the 10-minute staleness rule, fail-open capability detection, the zones.json shape, session-id discovery via ${CLAUDE_SESSION_ID}, and the zone-is-not-a-compaction-indicator rule. Its companion reference/cloud-headless-capture.md is the writer-side channel inventory: why the module is the capture channel, which other channels were checked and rejected (with sources and dates), including the two that do carry live occupancy and still cannot supply a snapshot, and why unknown in a session where the module does not run is structural rather than a defect.

This plugin answers "how full is my context and what happens as it fills". For "what is my context made of" (the startup measurement and the live per-category breakdown), see the context-budget plugin.

The module

The module decides from the live session's figures in interactive, -p, --bg and /loop sessions alike, through a TypeScript copy of the resolver's band function over the same bands; a shared fixture (scripts/context-zone.fixtures.mjs) holds the two resolvers to the same answer. Tested with claude plugin test on Claude Code 2.1.288, and in live runs on 2.1.288: interactive, -p, --bg and /loop sessions, /compact, /branch and --resume on Linux, and -p on native Windows. The maintainer reviewed and accepted each place those runs differed from the retired statusline tee, such as an idle session's snapshot going stale where the tee kept rewriting it. No run was made in the Desktop app, VS Code, a cloud session, or under an organization's sign-in.

Lines to Claude

Lines go to Claude only with model_notices set to true; it is off by default, and then nothing from this plugin enters Claude's context. Claude can still read the zone from the status tool, and the person still gets the toast and transcript line below. With it on, a line goes to Claude only at a boundary, appended to the context of a main-thread tool result or of a prompt; a crossing seen when a turn ends reaches Claude with the next prompt. With the other options and zones.json at their defaults:

WhenLine
The session first reaches a worse zone this cycleonce per zone, "acceptable zone (2 of 3)."
The session comes within approach_margin points (5) of a zone edge or a zones.json threshold; where a token band edge decides the crossing, within that many points of the window in tokensonce per boundary, "acceptable zone (2 of 3), nearing dumb."
The session passes a zones.json thresholdonce per threshold, "past an operator threshold", with the threshold's action
After a compaction (not the precompute kind), and after /resume or /branchthe verdict, once, only when it is past smart; after a compaction it is dumb zone (3 of 3, compacted) once figures arrive, and until then a session with no figures gets "the context reading is unavailable after the compaction, until the next API response."
When the module loads into a session that already has turns (a --resume launch, a reload after an options change, a hooks-worker restart)the verdict, once, only when it is past smart
After /clearnothing: the new session starts in smart and a fresh cycle

A dip below a boundary sends nothing and starts no new cycle; only a return to smart does. An unknown reading sends nothing and changes nothing. Every line carries only the verdict: the zone word and its rank of three. Past smart, the verdict lines at a carrier are followed by one options line:

context-guard: options: record decisions and pending items in a durable file, then continue, /compact, or hand off with /session-flow:handoff, as you and the user choose. A zone never calls for terser output, fewer agents, or lower quality.

The verdict alone pushed Claude toward handoffs and terse delegation (#7118), so the line names the step that keeps state durable and leaves the rest to Claude and the user. A crossing or restatement inside the approach margin of the next zone adds ", nearing <zone>", and an approach line that would repeat it is not sent. Lines due at one carrier: a crossing or restatement recorded before a pending restatement merges into it; a crossing recorded after it is the newer verdict and replaces it. zone_line_data adds figures (percent, tokens, window); by default a line carries none, and it never carries a session id. A configured action's sentence (zones.json actions and thresholds, see the reader contract) appears at its crossing, never before. Subagents get no line. Each line sent to Claude is also written as sent to the debug log (claude --debug).

At a crossing the person gets the continuation menu (continue, /compact, /clear, /session-flow:handoff then /clear) as a 4-second toast, such as smart → acceptable · continue, /compact, /clear or handoff, and one transcript line Claude does not read, ending more: /context-guard. context_guard_toast turns the toast off; the transcript line stays. Both come right after the response, tool call, prompt or status read (/context-guard or the status tool) that showed the crossing, even when Claude's line waits for the next prompt. A turn operator mode holds gets neither, and neither does a session whose first reading is already past smart, which gets only Claude's line. A crossing already shown in an unattended turn is not offered again in the next typed turn; Claude gets it at that turn's first carrier. On every surface but the terminal (the Desktop app, VS Code, mobile), where a toast may not show, the line is also drawn as one notice row above the prompt until the next typed prompt. /context-guard writes the route through /session-flow:workflow and When your context fills up as a transcript line Claude does not read. The menu never reaches Claude: an exit menu in model context manufactures the model's own initiative to stop, summarize, or hand off, which the instruction-audit catalog flags as check I23. Claude's options line lists compaction and a handoff as choices beside continuing, never as a step to take; it is a deliberate exception to I23, decided by the owner in #7118.

Operator mode

With zone_report_mode set to operator, a turn a person started by typing (or through the Remote Control bridge) gets no line. When that turn ends, the line is offered as the prompt box's suggestion (Tab takes it) and shown as one notice row above the prompt, on every surface and never as a toast; with text in the box, only the notice shows, and the suggestion is offered again once the box is empty. Where nobody can take a suggestion, the line goes to Claude as in automatic mode: -p and SDK turns, /loop and scheduled turns, task notifications, a session with no drawing surface, and a suggestion the session reports it cannot show. A suggestion that was shown but not taken goes to Claude as the ordinary line at the next turn no person started (a --bg launch turn reads as typed, so its suggestion can go unseen); the next typed turn instead drops it unsent. Claude Code offers no way to withdraw a shown suggestion, so it stays in the box after that hand-off.

Which apps draw the band's site, AbovePrompt, is upstream's render-sites table to say. No probe of this plugin ran in the Desktop app or VS Code.

  • Pointer: mods reference: render sites.
  • As of: 2026-10-03, Claude Code 2.1.288.
  • Recheck trigger: the AbovePrompt row changes the apps it lists, or a Desktop run of this plugin is made.

The command, the band row and the status tool

/context-guard with no argument prints the verdict with its figures, the percent bands beside the token bands of the session's window class (the worse of the two decides the zone), approach margin, the band and toast state, and where zones.json lives and whether it is present. Claude reads that reply, as it reads any command's output, so the continuation route and this README's link go to a separate transcript line Claude does not read. /context-guard band on and band off set the band row for the session, and a bare band toggles it. The band row is off by default; context_guard_band turns it on. It shows context-guard: <zone> <n>% above the prompt, the zone first so a cut row still shows it, and context-guard: - before the first response. Claude can call mcp__context-guard__status for the exact figures from the last API response, the zone, whether a compaction degraded the evidence, and the bands. Where the session refuses the tool's registration (an organization policy can refuse a user mod's tools), the module logs one debug line saying so, and the lines, band and writes carry on.

Prompt-cache status-line segment (optional)

The main conversation's prompt-cache state reaches only a status line: a mod's $.session.usage() carries no cache expiry, so the band row cannot show it without guessing the lifetime, which depends on plan and usage-credit state a mod cannot read. scripts/cache-line.mjs reads the status line's prompt_cache object and prints one segment:

cache ● warm until 14:32 (1h) · hit 91%
cache ○ cold · next message re-caches ~82k · hit 88% · misses 2 (last: tools_changed)

It shows the expiry as a clock time, not a countdown, because Claude Code re-runs the status line when a warm cache expires; no refreshInterval is needed. It prints nothing before the first response, covers the main conversation only (subagents and workflows have their own, shorter lifetime the object leaves out), and does not appear in cloud or -p sessions, where a status line does not run. NO_COLOR turns its color off. A plugin cannot add a status-line segment, so /context-guard:setup apply cache-line copies the script to ~/.claude/context-guard/cache-line.mjs and prints the statusLine edit for you to paste, built by the script's --wire mode: your existing command runs first through --after, and your other statusLine keys stay. It never writes your settings. Pointer: for the object's fields, see Prompt cache fields. As of: 2026-10-10. Recheck trigger: that section renames a field the script reads.

The plugin sends no keep-warm requests: each one spends usage to save a rebuild that may never come. For the lifetime rules and the settings that change them, see Prompt caching.

Telemetry

With HOOK_TELEMETRY_SINK set, the module sends envelopes per the hook-telemetry convention to the sink, fire-and-forget, and only on fires that act:

  • zone-crossing-inject, status ok, for each fire that sends lines, with hook_event tool.call or prompt.submit and data zone, previous, armed and injected: true; and for each operator-mode suggestion shown, with hook_event turn.complete and data zone, previous, armed, injected: false and suggested: true.

A fire that sends nothing emits nothing, and no record carries a path field. A relative sink path is joined onto the session's project root. Unset, nothing is sent.

Snapshot writes

The module writes ~/.claude/context-guard/context/<session_id>.json in the reader contract's shape through lib/write-snapshot.mjs, run with node, which replaces it atomically, keeps the file and directory owner-only on POSIX, and at most hourly prunes files older than 14 days. A changed body is written at once; an unchanged one at most once per 60 seconds. Writes happen after every tool call, at each measurement after a response, from a 15-second timer that runs only while a turn runs, and at the session's end; an idle session writes nothing, so its file goes stale after 10 minutes. They follow the plugin's on/off switch only: context_guard_hooks_enabled and model_notices do not stop them, and a project that disables the plugin in enabledPlugins gets no snapshot or lines in its sessions. A session id outside [A-Za-z0-9_-] is never written. Where a process cannot start, the module writes nothing and logs that once to the debug log.

Published zone for status lines

A status line, or any other reader, can show the zone and its edges from the snapshot without importing plugin code. Read ~/.claude/context-guard/context/<session_id>.json, where <session_id> is the session_id the status line's own input carries. The file holds these keys beside context_window:

{
  "captured_at": "2026-10-11T18:00:00Z",
  "zone": "acceptable",
  "evidence_degraded": false,
  "bands": {
    "smart_max_used_percentage": 50,
    "acceptable_max_used_percentage": 75,
    "smart_max_tokens": 100000,
    "acceptable_max_tokens": 150000
  }
}
  • zone is smart, acceptable, dumb or unknown. It is computed from the bands below, and is dumb once the session was compacted.
  • bands are the edges after zones.json. The token edges are for the session's window class, and are null when the token shape is not computable.
  • Treat a captured_at older than 10 minutes as unknown.
  • With no file, or a file without these keys (an older plugin version), use your own fallback.

These keys are part of the reader contract: they change only with a major version and a changelog entry. They are written whatever model_notices says.

Where mods are off

Wherever mods are off for a session, whether the build is too old for mods or a setting, flag, policy or Claude Code itself turned them off, the module does not run: no lines, no band, no status tool, no module writes. The PostCompact marker, a settings hook, still runs wherever settings hooks do, and readers fall back as the reader contract says. /context-guard:check and /context-guard:setup check report "mods off" in that case. A hook that throws passes its event through unchanged.

Behavior

  • Per-session, atomic snapshots. One file per session id (no cross-session last-writer-wins); readers never see torn JSON (temp file + rename, with a brief retry for the Windows rename-over-open-target case). Stale sibling files are pruned with a 14-day cutoff, far above the staleness window, so live-but-idle sessions always survive.
  • Path containment. session_id becomes a filename, so the module writes only for an id of [A-Za-z0-9_-] and skips the snapshot for anything else.
  • Fail-open zone resolution. Absent, stale, or unparsable snapshots, null or out-of-range used_percentage, null current_usage, a non-ISO captured_at, a snapshot whose embedded session_id differs from the requested one, or missing jq all resolve unknown. Consumers take their conservative path on data they cannot trust, never a fabricated zone. The shipped bands are declared judgment defaults. zones.json is the tuning path. The reader contract records how the default auto-compact thresholds relate to the bands (relayed 2026-10-11; recheck when that section is renamed or stops relating them). Pointer: when deciding what those defaults are, fetch model config: default auto-compact thresholds live. As of: 2026-10-11. Recheck trigger: that table changes, or its section is renamed or removed. The trigger itself is operator-tunable, per model as well as globally; the reader contract's tunable table records which surfaces we rely on and where to read the rest. Bands belong below whatever it resolves to, normalized into the percentage shape, so the session reaches a boundary decision before the harness compacts for it. After the auto-compact window is lowered, we never read used_percentage as a forecast of when compaction will run. Pointer: when deciding what the percentage is measured against, fetch environment variables: variables live. As of: 2026-10-11. Recheck trigger: the CLAUDE_CODE_AUTO_COMPACT_WINDOW row changes what the percentage is measured against. The reader contract owns those surfaces, their verification dates, and the rationale.
  • Integrity boundary. The snapshot directory is owner-only where POSIX modes work; on Windows ACL volumes it keeps the inherited ACLs and other local users could forge snapshots. Zones are routing hints. Consumers must never attach security or egress decisions to a zone word. See the reader contract's untrusted-data section.

Process budget

The module's hooks run inside Claude Code and start two kinds of process. The snapshot write runs one node lib/write-snapshot.mjs, at most once per changed body or per 60 seconds for an unchanged one, which also runs the hourly prune. With HOOK_TELEMETRY_SINK set, each telemetry envelope starts one sink process, not awaited: one per fire that sends lines, per operator-mode suggestion shown. A tool call or prompt that writes nothing and sends no envelope starts no process and writes no file; the lines start none of their own beyond that envelope. The write is awaited inside the tool.call hook, so a slow write holds that one tool result, within Claude Code's own-time limit for a hook.

  • Pointer: mods reference: limits.
  • As of: 2026-10-03, Claude Code 2.1.288.
  • Recheck trigger: that section changes a hook's time limit or what happens when it is reached.

claude plugin test plugins/context-guard enforces it: the budget: case in hooks/context-guard.test.ts asserts, with no telemetry sink set, no process on calls that write nothing and one per write; the telemetry: cases assert one envelope per acting fire and none on other calls; and the floor: case asserts the 60-second floor. The tests the module replaced, and what holds their budget now:

Retired testWhat it heldHeld now by
The statusline tee's suiteThe snapshot body, atomic write, rename retry, prune and the processes per renderThe snapshot: cases and the budget: case in hooks/context-guard.test.ts; the helper's own suite, lib/write-snapshot.test.mjs, for the atomic write, rename retry, prune and temp files
The statusline shim's suiteThe shim finding the installed teeNothing: no shim ships
The wiring compose script's suiteComposing a statusLine around the shimNothing for the shim, which no longer ships. The optional cache segment composes its own statusLine with cache-line.mjs --wire, tested in scripts/cache-line.test.sh
The crossing hook's and the PreToolUse gate's suites, process counts includedThe crossing lines, the gate and the processes per fireThe line and budget: cases in hooks/context-guard.test.ts, for the lines and processes. The gate was removed, so nothing holds it
The hook-census ceiling on the crossing hook in .performance/ratchets.jsonProcesses per crossing-hook fireThe budget: case: 0 processes on a call that writes nothing

The PostCompact marker is the one settings hook left. Per docs/conventions/hook-budget/README.md it fires once per compaction. Measured on Windows 11 under Git Bash, twelve trials against an interleaved bash -c : floor, old and new interleaved in one loop (2026-09-02): 9 processes to 4, 9.4 spawn-equivalents before and 5.7 after (0.7.34), with date replaced by printf's clock (a date fallback below bash 4.2) and mkdir and rm behind existence guards. Its row keeps its 60-second timeout: an earlier measurement put a hook of this plugin at 22.0 s on Windows with Defender real-time protection, and a timeout caps a stalled hook without speeding a normal one.

Install

/plugin marketplace add melodic-software/claude-code-plugins
/plugin install context-guard@<marketplace>

Install at user scope (the default), so every session on the machine writes its snapshot. Nothing needs wiring. /context-guard:setup check reports whether the mod runs and what each option is set to; /context-guard:setup apply seeds ~/.claude/context-guard/zones.json from the shipped bands when you want a file to tune.

Requirements

The module needs a Claude Code build at or above the terminal version mods need (older builds are unsupported). prerequisites.json holds the floor as data, in detect.version.min of the entry with "id": "claude", which the check skill compares against (relayed 2026-10-11; recheck when that key moves); the pointer below is where to re-derive it. Its snapshot writes and the PostCompact marker row n

Source 2 files
hooks/register.tsx 896 lines
1import type { EngineInterface, PromptOrigin, Register, Timer } from 'claude-code'
2import { RANK, readBands, resolveZone, tokenShape, type Bands, type TokenShape, type Zone } from './zone.ts'
3
4const CONTRACT_DIR = 'context-guard'
5const PREFIX = 'context-guard: '
6const NEXT_ZONE: Partial<Record<Zone, Zone>> = { smart: 'acceptable', acceptable: 'dumb' }
7const SESSION_ID = /^[A-Za-z0-9_-]+$/
8const PERSON_ORIGINS = ['composer', 'bridge']
9const REOFFER_MS = 5_000
10const FLOOR_MS = 60_000
11// A tick lands a write once the floor has passed, so a write is never later than the floor plus one tick.
12const WRITE_TIMER_MS = 15_000
13const HELPER = 'lib/write-snapshot.mjs'
14const DATA_ITEMS = ['zone', 'percent', 'tokens', 'window']
15const ACTIONS = ['none', 'save-state', 'handoff'] as const
16const ACTION_TEXT: Record<Action, string> = {
17  none: '',
18  'save-state': 'save-state',
19  handoff: 'handoff',
20}
21
22type Action = (typeof ACTIONS)[number]
23type Rule = { action: Action; text?: string }
24type Threshold = Rule & { at: number }
25type Settings = { bands: Bands; margin: number; actions: Partial<Record<Zone, Rule>>; thresholds: Threshold[] }
26type Config = {
27  enabled: boolean
28  lines: boolean
29  operator: boolean
30  data: Set<string>
31  band: boolean
32  toast: boolean
33}
34// The snapshot body: reference/reader-contract.md "Snapshot file shape".
35type Snapshot = {
36  captured_at: string
37  session_id: string
38  cli_version?: string
39  context_window: {
40    total_input_tokens?: number
41    total_output_tokens?: number
42    context_window_size: number
43    used_percentage: number | null
44    remaining_percentage: number | null
45    current_usage: { input_tokens: number; output_tokens: number; cache_creation_input_tokens: number; cache_read_input_tokens: number } | null
46  }
47  // The published zone: what this body resolves to and the edges in force, for readers such as a status line.
48  zone?: Zone | 'unknown'
49  evidence_degraded?: boolean
50  bands?: { smart_max_used_percentage: number; acceptable_max_used_percentage: number; smart_max_tokens: number | null; acceptable_max_tokens: number | null }
51}
52type Reading = { zone: Zone | undefined; degraded: boolean; percent?: number; tokens?: number; window: number; token?: TokenShape }
53// shown: the person's channel has handled it: the batch's last crossing got the transcript line
54// (and the toast, when on), or it came from 'unobserved' and was deliberately skipped.
55type Crossing = { kind: 'crossing'; from: string; zone: Zone; degraded: boolean; handedOff?: boolean; shown?: boolean; armedBefore: number }
56type Event =
57  | Crossing
58  | { kind: 'restate'; zone: Zone; degraded: boolean; unavailable?: boolean }
59  | { kind: 'approach'; zone: Zone; toward: string }
60  // actionOnly: a restatement absorbed the verdict, so only the threshold's action sentence is sent.
61  | { kind: 'threshold'; zone: Zone; degraded: boolean; rule: Threshold; actionOnly?: boolean }
62type Session = {
63  armed: number
64  last: Zone | undefined
65  fired: Set<number>
66  approached: Set<string>
67  compacted: boolean
68  pending: Event[]
69  restate: boolean
70  // The unavailable line went out for a compaction and no figures have arrived since.
71  awaiting: boolean
72  reading: Reading | undefined
73  written: { sig: string; at: number } | undefined
74  body: Snapshot | undefined
75  offered: Event[]
76}
77// A crossing's notice is drawn only where a toast may not show (any surface but the terminal);
78// operator mode's held line is drawn on every surface.
79type Notice = { text: string; kind: 'crossing' | 'operator' }
80type State = {
81  origin: PromptOrigin | undefined
82  forceAutomatic: boolean
83  notice: Notice | undefined
84  bandShown: boolean
85  band: string | undefined
86  reading: Reading | undefined
87  recheckTool: boolean
88  reofferTimer: Timer | undefined
89  writeTimer: Timer | undefined
90  writing: Promise<void>
91  loggedOnce: Set<string>
92  sessions: Map<string, Session>
93  carry: boolean
94  settings: Settings
95  zonesText: string | null
96  zonesKey: string | undefined
97}
98
99// plugin.json declares no number bounds, because the engine refuses the whole module for a value
100// outside them; the module checks them here, uses the default and names each bad option once.
101const badOption = (name: string, kind: string, fallback: string) => `context-guard: option ${name} ${kind}; it reads as the default, ${fallback}`
102const quote = (s: string) => JSON.stringify(s.length > 40 ? `${s.slice(0, 40)}...` : s)
103
104export const parseConfig = (options: Record<string, unknown>): Config & { bad: string[] } => {
105  const bad: string[] = []
106  let items = String(options.zone_line_data ?? '')
107    .split(',')
108    .map(s => s.trim().toLowerCase())
109    .filter(s => s !== '')
110  const unknown = items.filter(s => !DATA_ITEMS.includes(s))
111  if (unknown.length > 0) {
112    bad.push(badOption('zone_line_data', `has an item that is not zone, percent, tokens or window (${quote(unknown.join(', '))})`, 'zone'))
113    items = []
114  }
115  return {
116    enabled: options.context_guard_hooks_enabled !== false,
117    lines: options.model_notices === true,
118    operator: options.zone_report_mode === 'operator',
119    data: new Set(['zone', ...items]),
120    band: options.context_guard_band === true,
121    toast: options.context_guard_toast !== false,
122    bad,
123  }
124}
125
126// C0 and C1 controls, DEL and the Unicode line and paragraph separators each break a line
127const breaksLine = (c: number): boolean => c < 0x20 || (c >= 0x7f && c <= 0x9f) || c === 0x2028 || c === 0x2029
128const oneLine = (s: string): string => {
129  let out = ''
130  let inRun = false
131  for (const ch of s) {
132    const brk = breaksLine(ch.charCodeAt(0))
133    if (!brk) out += ch
134    else if (!inRun) out += ' '
135    inRun = brk
136  }
137  return out.trim()
138}
139
140const asRule = (value: unknown): Rule | undefined => {
141  if (typeof value !== 'object' || value === null) return undefined
142  const v = value as Record<string, unknown>
143  // `block` armed the removed gate; it reads as `none`, text dropped, so its threshold keeps its lines.
144  if (v.action === 'block') return { action: 'none' }
145  if (!ACTIONS.includes(v.action as Action)) return undefined
146  // one line: a newline in the operator's text must not start a line that reads as the guard's own
147  const text = typeof v.text === 'string' ? oneLine(v.text) : ''
148  return { action: v.action as Action, ...(text !== '' ? { text } : {}) }
149}
150
151// zones.json: the bands as the resolver reads them, plus the mod's keys; an absent or invalid key
152// means its default, so a file written for the resolver alone keeps working.
153export const parseSettings = (zones: string | null): Settings => {
154  const { bands } = readBands(zones)
155  let z: Record<string, unknown> = {}
156  try {
157    const parsed: unknown = zones === null ? {} : JSON.parse(zones)
158    if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) z = parsed as Record<string, unknown>
159  } catch {
160    // malformed: every mod key takes its default
161  }
162  const margin = typeof z.approach_margin === 'number' ? z.approach_margin : NaN
163  const actionsIn = (typeof z.actions === 'object' && z.actions !== null ? z.actions : {}) as Record<string, unknown>
164  const actions: Partial<Record<Zone, Rule>> = {}
165  for (const zone of ['smart', 'acceptable', 'dumb'] as const) {
166    const rule = asRule(actionsIn[zone])
167    if (rule) actions[zone] = rule
168  }
169  const thresholds = (Array.isArray(z.thresholds) ? z.thresholds : [])
170    .map(t => {
171      const rule = asRule(t)
172      const at = (t as Record<string, unknown>)?.at_percent
173      return rule && typeof at === 'number' && at > 0 && at <= 100 ? { ...rule, at } : undefined
174    })
175    .filter((t): t is Threshold => t !== undefined)
176    .sort((a, b) => a.at - b.at)
177  return { bands, margin: Number.isFinite(margin) && margin >= 0 && margin < 100 ? margin : 5, actions, thresholds }
178}
179
180const newSession = (restate: Session['restate']): Session => ({
181  armed: 0,
182  last: undefined,
183  fired: new Set(),
184  approached: new Set(),
185  compacted: false,
186  pending: [],
187  restate,
188  awaiting: false,
189  reading: undefined,
190  written: undefined,
191  body: undefined,
192  offered: [],
193})
194
195// Records what the reading crossed since the last one as pending events. Each zone is reported once
196// per cycle: a zone's line fires when the session first reaches it, a dip below a boundary changes
197// nothing, and only a return to smart opens a new cycle.
198export const recordReading = (s: Session, reading: Reading, settings: Settings) => {
199  s.reading = reading
200  const { zone, percent } = reading
201  if (zone === undefined) return
202  if (s.restate) {
203    // A compacted session has no figures until the next API response, so its dumb zone is forced:
204    // the line says the reading is unavailable, and the restatement waits for the figures.
205    if (reading.degraded && percent === undefined && reading.tokens === undefined) {
206      if (!s.awaiting) s.pending.push({ kind: 'restate', zone, degraded: true, unavailable: true })
207      s.awaiting = true
208      return
209    }
210    s.awaiting = false
211    if (zone !== 'smart') s.pending.push({ kind: 'restate', zone, degraded: reading.degraded })
212    s.restate = false
213    s.armed = Math.max(s.armed, RANK[zone])
214    s.last = zone
215    for (const t of settings.thresholds) if (percent !== undefined && percent >= t.at) s.fired.add(t.at)
216    return
217  }
218  if (RANK[zone] > s.armed) {
219    s.pending.push({ kind: 'crossing', from: s.last ?? 'unobserved', zone, degraded: reading.degraded, armedBefore: s.armed })
220    s.armed = RANK[zone]
221  } else if (zone === 'smart' && s.armed > 0) {
222    s.armed = 0
223    s.fired.clear()
224    s.approached.clear()
225  }
226  s.last = zone
227  if (percent !== undefined) {
228    for (const t of settings.thresholds) {
229      if (!s.fired.has(t.at) && percent >= t.at) {
230        s.fired.add(t.at)
231        s.pending.push({ kind: 'threshold', zone, degraded: reading.degraded, rule: t })
232      }
233    }
234  }
235  // One approach line per boundary per cycle, in the shape that decides the boundary: the token
236  // shape when its edge sits below the percentage edge, else the percentage shape. The margin is in
237  // percentage points, of the window in the token shape.
238  if (settings.margin <= 0) return
239  const { smart, acceptable } = settings.bands
240  const tok = reading.token
241  const near = (edgePercent: number, edgeTokens: number | undefined) => {
242    if (tok !== undefined && edgeTokens !== undefined && (percent === undefined || edgeTokens < (edgePercent * tok.size) / 100)) {
243      return tok.used >= edgeTokens - (settings.margin * tok.size) / 100 && tok.used <= edgeTokens
244    }
245    return percent !== undefined && percent >= edgePercent - settings.margin && percent <= edgePercent
246  }
247  const boundaries = [
248    { key: 'acceptable', toward: 'acceptable', near: s.armed < 1 && near(smart, tok?.smart) },
249    { key: 'dumb', toward: 'dumb', near: s.armed < 2 && near(acceptable, tok?.acceptable) },
250    ...settings.thresholds.map(t => ({
251      key: `t${t.at}`,
252      toward: 'an operator threshold',
253      near: percent !== undefined && !s.fired.has(t.at) && percent >= t.at - settings.margin,
254    })),
255  ]
256  for (const b of boundaries) {
257    if (b.near && !s.approached.has(b.key)) {
258      s.approached.add(b.key)
259      s.pending.push({ kind: 'approach', zone, toward: b.toward })
260    }
261  }
262}
263
264// The verdict as Claude and the person read it: acceptable zone (2 of 3), dumb zone (3 of 3, compacted).
265const verdictText = (zone: Zone, degraded: boolean) => `${zone} zone (${RANK[zone] + 1} of 3${degraded && zone === 'dumb' ? ', compacted' : ''})`
266
267const dataText = (r: Reading | undefined, cfg: Config) => {
268  const items: string[] = []
269  if (cfg.data.has('percent') && r?.percent !== undefined) items.push(`${r.percent}% of the window used`)
270  if (cfg.data.has('tokens') && r?.tokens !== undefined) items.push(`${r.tokens} tokens in context`)
271  if (cfg.data.has('window') && r !== undefined) items.push(`a ${r.window}-token window`)
272  return items.length === 0 ? '' : `, ${items.join(', ')}`
273}
274
275const sentence = (source: string, rule: Rule) => {
276  const text = (rule.text ?? ACTION_TEXT[rule.action]).replace(/\.+$/, '')
277  return text === '' || rule.action === 'none' && rule.text === undefined ? '' : ` context-guard (${source}): ${text}.`
278}
279
280export const renderEvent = (e: Event, s: Session, cfg: Config, settings: Settings) => {
281  const data = dataText(s.reading, cfg)
282  // The sentence a zone's zones.json action adds, if any.
283  const action = (zone: Zone) => {
284    const rule = settings.actions[zone]
285    return rule ? sentence(`operator setting for the ${zone} zone`, rule) : ''
286  }
287  // A verdict line states facts only; the options line renderAll adds is the one that names choices.
288  const line = (zone: Zone, degraded: boolean, hint: string) => `context-guard: ${verdictText(zone, degraded)}${data}${hint}.`
289  // Within the approach margin of the next zone's boundary, the verdict says which zone is near.
290  const near = (zone: Zone) => {
291    const toward = NEXT_ZONE[zone]
292    return toward !== undefined && s.approached.has(toward) ? `, nearing ${toward}` : ''
293  }
294  switch (e.kind) {
295    case 'restate':
296    case 'crossing':
297      if (e.kind === 'restate' && e.unavailable) return 'context-guard: the context reading is unavailable after the compaction, until the next API response.'
298      return `${line(e.zone, e.degraded, near(e.zone))}${action(e.zone)}`
299    case 'approach':
300      return line(e.zone, false, `, nearing ${e.toward}`)
301    case 'threshold':
302      if (e.actionOnly) return sentence('operator setting for a threshold', e.rule).trimStart()
303      return `${line(e.zone, e.degraded, ', past an operator threshold')}${sentence('operator setting for a threshold', e.rule)}`
304  }
305}
306
307// Follows the verdict lines once per carrier past smart. The verdict alone pushed Claude toward
308// handoffs and terse delegation, so the line names the durable-state step and leaves the rest a choice.
309const OPTIONS =
310  'context-guard: options: record decisions and pending items in a durable file, then continue, /compact, or hand off with /session-flow:handoff, as you and the user choose. A zone never calls for terser output, fewer agents, or lower quality.'
311
312// The verdict lines due at one carrier: a line that another one already starts with (an approach
313// line its crossing repeats, with or without an action after it) is sent once.
314const renderAll = (events: Event[], s: Session, cfg: Config, settings: Settings) => {
315  const lines = [...new Set(events.map(e => renderEvent(e, s, cfg, settings)))]
316  const verdicts = lines.filter(l => !lines.some(o => o !== l && o.startsWith(l)))
317  return events.some(e => e.zone !== 'smart' && !(e.kind === 'restate' && e.unavailable)) ? [...verdicts, OPTIONS] : verdicts
318}
319
320// Appends lines to what Claude reads and writes each to the debug log, so the log holds what Claude was told.
321const withLines = <T extends { context?: readonly string[] }>($: EngineInterface, e: T, lines: readonly string[]): T => {
322  for (const line of lines) $.ui.log(line, { to: 'debug' })
323  return lines.length === 0 ? e : { ...e, context: [...(e.context ?? []), ...lines] }
324}
325
326const homeDir = async ($: EngineInterface) => (await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) || undefined
327
328// zones.json, re-read only when it appears, disappears or its mtime moves.
329async function loadSettings($: EngineInterface, st: State, home: string | undefined) {
330  if (home === undefined) return st.settings
331  const path = `${home}/.claude/${CONTRACT_DIR}/zones.json`
332  const stat = await $.fs.stat(path).catch(() => undefined)
333  const key = stat === undefined ? 'absent' : `${stat.mtimeMs}:${stat.size}`
334  if (key !== st.zonesKey) {
335    const text = stat === undefined ? null : await $.fs.read(path).then(String).catch(() => null)
336    st.settings = parseSettings(text)
337    st.zonesText = text
338    st.zonesKey = key
339  }
340  return st.settings
341}
342
343const isoSeconds = (ms: number) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z')
344
345// The session's state, created on first use: after /clear or a resume no session.start fires, so
346// every hook starts the new conversation's state lazily.
347const sessionFor = (st: State, sid: string) => {
348  let s = st.sessions.get(sid)
349  if (s === undefined) {
350    s = newSession(st.carry)
351    st.carry = false
352    st.sessions.set(sid, s)
353  }
354  return s
355}
356
357async function current($: EngineInterface, st: State) {
358  return sessionFor(st, await $.session.id())
359}
360
361async function refresh($: EngineInterface, st: State) {
362  const sid = await $.session.id()
363  const s = sessionFor(st, sid)
364  const home = await homeDir($)
365  const [usage, version, now, settings] = await Promise.all([
366    $.session.usage({ breakdown: 'summary' }),
367    $.session.version().catch(() => undefined),
368    $.clock.now(),
369    loadSettings($, st, home),
370  ])
371  const c = usage.context
372  const api = c.breakdown?.apiUsage ?? null
373  const body: Snapshot = {
374    captured_at: isoSeconds(now),
375    session_id: sid,
376    ...(version?.version ? { cli_version: version.version } : {}),
377    context_window: {
378      ...(c.tokens === undefined ? {} : { total_input_tokens: c.tokens }),
379      ...(api ? { total_output_tokens: api.output_tokens } : {}),
380      context_window_size: c.window,
381      used_percentage: c.percent ?? null,
382      remaining_percentage: c.percent === undefined ? null : 100 - c.percent,
383      current_usage: api
384        ? {
385            input_tokens: api.input_tokens,
386            output_tokens: api.output_tokens,
387            cache_creation_input_tokens: api.cache_creation_input_tokens,
388            cache_read_input_tokens: api.cache_read_input_tokens,
389          }
390        : null,
391    },
392  }
393  const { word } = resolveZone({ sid, snapshot: JSON.stringify(body), zones: st.zonesText, nowSec: Math.floor(now / 1000) })
394  if (!s.compacted && home !== undefined && SESSION_ID.test(sid)) {
395    s.compacted = await $.fs.exists(`${home}/.claude/${CONTRACT_DIR}/context/${sid}.compacted`).catch(() => false)
396  }
397  const zone = s.compacted ? 'dumb' : word === 'unknown' ? undefined : word
398  const token = tokenShape(body.context_window, body.cli_version, settings.bands)
399  body.zone = zone ?? 'unknown'
400  body.evidence_degraded = s.compacted
401  body.bands = {
402    smart_max_used_percentage: settings.bands.smart,
403    acceptable_max_used_percentage: settings.bands.acceptable,
404    smart_max_tokens: token?.smart ?? null,
405    acceptable_max_tokens: token?.acceptable ?? null,
406  }
407  const reading: Reading = { zone, degraded: s.compacted, percent: c.percent, tokens: c.tokens, window: c.window, token }
408  recordReading(s, reading, settings)
409  // A reading with no figures (usage gone at exit, or between responses) never replaces one that had them.
410  if (body.context_window.used_percentage !== null || s.body === undefined || s.body.context_window.used_percentage === null) s.body = body
411  // The kept figures still publish a compaction seen since: degraded, and dumb.
412  else if (s.compacted) s.body = { ...s.body, zone: 'dumb', evidence_degraded: true }
413  st.reading = reading
414  const band = bandText(reading)
415  if (band !== st.band) {
416    st.band = band
417    $.ui.invalidate('ui.render')
418  }
419  return { sid, s, body, settings }
420}
421
422const isPersonTurn = (st: State) => st.origin !== undefined && PERSON_ORIGINS.includes(st.origin.kind)
423
424// Operator mode holds the lines in a turn a person typed, where a suggestion can show.
425async function operatorHolds($: EngineInterface, st: State, cfg: Config) {
426  if (!cfg.operator || st.forceAutomatic || !isPersonTurn(st)) return false
427  return (await $.session.surfaces()).length > 0
428}
429
430// The continuation menu is the person's: a toast, and a transcript line Claude does not read. It
431// never goes into Claude's context. The engine titles the toast with the plugin's name.
432const toastText = (from: string, to: string) => `${from} → ${to} · continue, /compact, /clear or handoff`
433const menuLine = (from: string, to: string) =>
434  `context-guard: ${from} → ${to} · options: continue, /compact, /clear, or /session-flow:handoff then /clear · more: /context-guard`
435const menuZone = (zone: Zone, degraded: boolean) => (degraded && zone === 'dumb' ? 'dumb (compacted)' : zone)
436const noticeShows = (st: State, surface: string) => st.notice !== undefined && (st.notice.kind === 'operator' || surface !== 'terminal')
437
438// The lines a carrier attaches now, consumed; none when none is due or operator mode holds them.
439// One fire of a hook, for its telemetry envelope: the event, when it started, and the optional
440// correlation keys (docs/conventions/hook-telemetry, "Correlation keys").
441type Fire = { event: string; startMs: number; toolUseId?: unknown; agentId?: unknown }
442const PLAIN_ID = /^[A-Za-z0-9._-]+$/
443const RANK_WORD = ['smart', 'acceptable', 'dumb'] as const
444
445// Sends one envelope to HOOK_TELEMETRY_SINK, fire-and-forget; no sink set, nothing is sent. A
446// relative sink path is joined onto the session's project root, else skipped.
447async function emitTelemetry($: EngineInterface, hook: string, status: string, data: Record<string, unknown>, fire: Fire) {
448  const sink = await $.env.get('HOOK_TELEMETRY_SINK')
449  if (!sink) return
450  let path = sink
451  if (!/^(\/|[A-Za-z]:[\\/])/.test(sink)) {
452    const root = (await $.session.root().catch(() => undefined)) || (await $.env.get('CLAUDE_PROJECT_DIR'))
453    if (!root) return
454    path = `${root.replace(/[\\/]+$/, '')}/${sink}`
455  }
456  const [now, sid] = await Promise.all([$.clock.now(), $.session.id()])
457  const corr = Object.fromEntries(
458    [
459      ['session_id', sid],
460      ['tool_use_id', fire.toolUseId],
461      ['agent_id', fire.agentId],
462    ].filter(([, v]) => typeof v === 'string' && PLAIN_ID.test(v)),
463  )
464  const envelope = {
465    schema_version: '1.1',
466    timestamp: isoSeconds(now),
467    hook,
468    hook_event: fire.event,
469    status,
470    duration_ms: Math.max(0, Math.round(now - fire.startMs)),
471    ...corr,
472    data,
473  }
474  void $.process.run([path], { stdin: `${JSON.stringify(envelope)}\n`, timeoutMs: 10_000 }).catch(() => undefined)
475}
476
477// zone-crossing-inject's data for a fire that sent lines (data/zone-crossing-inject.schema.json).
478const crossingData = (s: Session, events: Event[], extra: Record<string, unknown>) => {
479  const crossed = events.filter(e => e.kind === 'crossing').at(-1)
480  const zone = s.reading?.zone ?? 'unknown'
481  return crossed?.kind === 'crossing'
482    ? { zone, previous: crossed.from === 'unobserved' ? '' : crossed.from, armed: RANK_WORD[crossed.armedBefore], ...extra }
483    : { zone, previous: s.last ?? '', armed: RANK_WORD[s.armed], ...extra }
484}
485
486// A restatement says the verdict as of when it was recorded, so a crossing, an approach or an
487// earlier restatement before it merges into it rather than reaching Claude twice. A threshold
488// before it keeps only its action sentence, which the restatement does not carry. A crossing
489// recorded after it is the newer verdict and replaces it.
490const mergeRestated = (pending: Event[]): Event[] => {
491  const lastRestate = pending.findLastIndex(e => e.kind === 'restate')
492  if (lastRestate < 0) return pending
493  const keep = pending.findLastIndex(e => e.kind === 'crossing') > lastRestate ? -1 : lastRestate
494  return pending.flatMap((e, i): Event[] => {
495    if (i > lastRestate || i === keep) return [e]
496    if (e.kind !== 'threshold' || sentence('operator setting for a threshold', e.rule) === '') return []
497    return [{ ...e, actionOnly: true }]
498  })
499}
500
501async function takeLines($: EngineInterface, st: State, cfg: Config, fire: Fire): Promise<string[]> {
502  const s = st.sessions.get(await $.session.id())
503  if (s === undefined) return []
504  if (!cfg.enabled) {
505    s.pending = []
506    return []
507  }
508  const holds = cfg.lines && (await operatorHolds($, st, cfg))
509  // No await from here until s.pending is replaced.
510  const merged = mergeRestated(s.pending)
511  // A hold keeps lines for the suggestion, except a crossing the person was already shown (read in an
512  // unattended turn): offering it again would repeat it, so it goes to Claude as in automatic mode.
513  const seen = (e: Event) => e.kind === 'crossing' && e.shown === true
514  const events = holds ? merged.filter(seen) : merged
515  s.pending = holds ? merged.filter(e => !seen(e)) : []
516  if (holds && events.length === 0) return []
517  st.forceAutomatic = false
518  let lines: string[] = []
519  if (cfg.lines && events.length > 0) {
520    await emitTelemetry($, 'zone-crossing-inject', 'ok', crossingData(s, events, { injected: true }), fire)
521    lines = renderAll(events, s, cfg, st.settings)
522  }
523  // The person's channel runs after Claude's lines are built, so a failing toast never drops one.
524  showCrossing($, st, cfg, events)
525  return lines
526}
527
528// Shows the person the last crossing among events not yet shown: a toast, a transcript line and the
529// crossing notice. Each crossing is shown once. A handed-off suggestion already reached the person,
530// and a crossing from 'unobserved' (a first reading already past smart) is never shown.
531function showCrossing($: EngineInterface, st: State, cfg: Config, events: Event[]) {
532  const due = events.filter((e): e is Crossing => e.kind === 'crossing' && !e.handedOff && !e.shown)
533  const crossed = due.at(-1)
534  const showable = crossed !== undefined && crossed.from !== 'unobserved'
535  const to = showable ? menuZone(crossed.zone, crossed.degraded) : ''
536  if (showable) {
537    st.notice = { text: menuLine(crossed.from, to), kind: 'crossing' }
538    $.ui.log(st.notice.text)
539  }
540  for (const e of due) e.shown = true
541  if (!showable) return
542  // The engine drops a failing toast itself; it never throws into the module.
543  if (cfg.toast) $.ui.toast(toastText(crossed.from, to))
544  $.ui.invalidate('ui.render')
545}
546
547// A crossing read with a turn's final answer has no carrier until the next prompt, so the person
548// sees it at the measurement; Claude's line still waits for that carrier. A turn operator mode
549// holds keeps it for the suggestion.
550async function showPending($: EngineInterface, st: State, cfg: Config) {
551  const s = st.sessions.get(await $.session.id())
552  if (s === undefined || !cfg.enabled) return
553  if (cfg.lines && (await operatorHolds($, st, cfg))) return
554  showCrossing($, st, cfg, s.pending)
555}
556
557// Offers the held lines as the prompt box's suggestion. With text in the box it waits (false);
558// where a suggestion cannot show, the lines go to Claude at the next carrier.
559async function offer($: EngineInterface, st: State, s: Session, fire: Fire) {
560  if (st.notice?.kind !== 'operator') return true
561  const box = await $.prompt.read()
562  if (box.text.trim() !== '') return false
563  const { isShown } = await $.prompt.suggest({ text: st.notice.text })
564  if (isShown) {
565    await emitTelemetry($, 'zone-crossing-inject', 'ok', crossingData(s, s.pending, { injected: false, suggested: true }), fire)
566    // Shown is not taken: kept until the next turn says whether a person saw it.
567    s.offered.push(...s.pending.splice(0))
568  } else {
569    st.notice = undefined
570    st.forceAutomatic = true
571  }
572  $.ui.invalidate('ui.render')
573  return true
574}
575
576function stopTimer(timer: Timer | undefined) {
577  timer?.cancel()
578  return undefined
579}
580
581// The band row: context-guard: <zone> <n>%. The zone comes before the figure, so a cut row still shows it.
582export const bandText = (r: Reading | undefined) => {
583  if (r?.percent === undefined) return `${PREFIX}-`
584  const zone = r.zone === undefined ? '' : `${r.degraded && r.zone === 'dumb' ? 'dumb, compacted' : r.zone} `
585  return `${PREFIX}${zone}${r.percent}%`
586}
587
588const USAGE = 'usage: /context-guard [band [on|off]]'
589const README = 'https://github.com/melodic-software/claude-code-plugins/blob/main/plugins/context-guard/README.md'
590const DOCS = 'https://code.claude.com/docs/en/context-window#when-your-context-fills-up'
591
592// /context-guard with no argument: the verdict with its figures and the settings in force. The reply
593// is stored as a transcript row Claude reads, so it carries no menu, router pointer or link; those
594// go to a transcript line Claude does not read.
595const POINTER = `context-guard: next step: route it with /session-flow:workflow (if installed), or see ${DOCS} · more: ${README}`
596async function statusText($: EngineInterface, st: State, cfg: Config) {
597  const { s, body, settings } = await refresh($, st)
598  await showPending($, st, cfg)
599  const r = s.reading
600  const w = body.context_window
601  const verdict = r?.zone === undefined ? 'zone unknown' : verdictText(r.zone, r.degraded)
602  const figures =
603    w.used_percentage === null
604      ? `no reading yet (a ${w.context_window_size}-token window)`
605      : `${w.used_percentage}% of a ${w.context_window_size}-token window used (${w.total_input_tokens ?? '?'} tokens)`
606  const home = await homeDir($)
607  const zones = home === undefined ? 'zones.json: no home directory' : `${home}/.claude/${CONTRACT_DIR}/zones.json (${st.zonesText === null ? 'absent' : 'present'})`
608  const { smart, acceptable } = settings.bands
609  const t = tokenShape(w, body.cli_version, settings.bands)
610  const bands = t
611    ? `Bands (the worse decides): smart up to ${smart}% and ${t.smart} tokens, acceptable up to ${acceptable}% and ${t.acceptable} tokens`
612    : `Bands: smart up to ${smart}%, acceptable up to ${acceptable}%`
613  return [
614    `${verdict}, ${figures}`,
615    `${bands}; approach margin ${settings.margin} points`,
616    `This session: band row ${st.bandShown ? 'on' : 'off'}, zone-change toast ${cfg.toast ? 'on' : 'off'}`,
617    `Settings: ${zones}`,
618  ].join('\n')
619}
620
621async function statusJson($: EngineInterface, st: State, cfg: Config) {
622  const { s, body, settings } = await refresh($, st)
623  await showPending($, st, cfg)
624  const w = body.context_window
625  const t = tokenShape(w, body.cli_version, settings.bands)
626  return JSON.stringify({
627    source: 'the last API response',
628    zone: s.reading?.zone ?? 'unknown',
629    evidence_degraded: s.compacted,
630    used_percentage: w.used_percentage,
631    total_input_tokens: w.total_input_tokens ?? null,
632    total_output_tokens: w.total_output_tokens ?? null,
633    context_window_size: w.context_window_size,
634    bands: {
635      smart_max_used_percentage: settings.bands.smart,
636      acceptable_max_used_percentage: settings.bands.acceptable,
637      smart_max_tokens: t?.smart ?? null,
638      acceptable_max_tokens: t?.acceptable ?? null,
639    },
640    approach_margin: settings.margin,
641  })
642}
643
644const logOnce = ($: EngineInterface, st: State, key: string, text: string) => {
645  if (st.loggedOnce.has(key)) return
646  st.loggedOnce.add(key)
647  $.ui.log(`context-guard: ${text}`, { to: 'debug' })
648}
649
650// Writes the session's snapshot through the shared helper. Decided in memory: a body unchanged
651// since the last write is rewritten at most once per 60 s (floor-bound in the helper too), so a
652// call that writes nothing starts no process. Where $.process.run is unavailable nothing is
653// written; readers then read unknown, as they do with no file.
654async function writeSnapshot($: EngineInterface, st: State, read: boolean) {
655  const sid = await $.session.id()
656  if (read) await refresh($, st)
657  const s = st.sessions.get(sid)
658  const body = s?.body
659  if (s === undefined || body === undefined) return
660  const home = await homeDir($)
661  if (home === undefined || !SESSION_ID.test(sid)) return
662  const now = await $.clock.now()
663  const sig = JSON.stringify({ ...body, captured_at: undefined })
664  const same = s.written?.sig === sig
665  if (same && s.written !== undefined && now - s.written.at < FLOOR_MS) return
666  const target = `${home}/.claude/${CONTRACT_DIR}/context/${sid}.json`
667  // A body with no figures (before a session's first response, or after session.end or a fresh
668  // load dropped the in-memory one) never goes over a file on disk that has them.
669  if (body.context_window.used_percentage === null && (await diskHasFigures($, target))) return
670  const argv = ['node', `${$.plugin.root}/${HELPER}`, target, '--prune', ...(same ? ['--floor', String(FLOOR_MS / 1000)] : [])]
671  // Only a write the helper decided (written, or skipped by rule) dedupes; a failed one is tried at the next carrier.
672  try {
673    const run = await $.process.run(argv, { stdin: JSON.stringify(body), timeoutMs: 10_000 })
674    if (run.exitCode === 0 || run.exitCode === 3) s.written = { sig, at: now }
675    else logOnce($, st, 'write-failed', `snapshot write failed (exit ${run.exitCode}): ${run.stderr.trim()}`)
676  } catch (error) {
677    logOnce($, st, 'write-threw', `snapshot write did not run: ${error instanceof Error ? error.message : String(error)}`)
678  }
679}
680
681async function diskHasFigures($: EngineInterface, target: string) {
682  const text = await $.fs.read(target).then(String).catch(() => null)
683  if (text === null) return false
684  try {
685    return typeof JSON.parse(text)?.context_window?.used_percentage === 'number'
686  } catch {
687    return false
688  }
689}
690
691function queueWrite($: EngineInterface, st: State, read = false) {
692  st.writing = st.writing.then(() => writeSnapshot($, st, read)).catch(() => undefined)
693  return st.writing
694}
695
696// A refused tool registration (a policy can refuse a user mod's tools) is logged once; everything
697// else the module does carries on without the tool.
698async function registerSurfaces($: EngineInterface, st: State) {
699  const [tool] = await Promise.allSettled([
700    $.tool.register({
701      name: 'status',
702      description:
703        "Returns this session's context-window reading as JSON: `zone` (smart, acceptable, dumb or unknown; the worse of the percent and token bands decides it), `used_percentage`, input and output token totals, `context_window_size`, the band edges and approach margin in force, `evidence_degraded` (true after a compaction, which forces the zone to dumb). Figures come from the last API response: before the first response and right after a compaction, `used_percentage` and the token totals are null and the zone is unknown (dumb after a compaction), and they never include text added since that response, so they change only when a response arrives. With the model_notices option on (off by default), context-guard also adds a line to the next prompt or tool result when the zone worsens or nears a boundary. Read-only.",
704      inputSchema: { type: 'object', properties: {}, additionalProperties: false },
705    }),
706    $.command.register({
707      name: 'context-guard',
708      description: 'Context zone status and details; band on or off sets the band row for this session, bare band toggles it',
709      argumentHint: '[band [on|off]]',
710    }),
711  ])
712  if (tool.status === 'rejected') {
713    const reason = tool.reason instanceof Error ? tool.reason.message : String(tool.reason)
714    logOnce($, st, 'tool-register', `the status tool could not register: ${reason}`)
715  }
716}
717
718export const register: Register = (on, options) => {
719  const cfg = parseConfig(options)
720  const st: State = {
721    origin: undefined,
722    forceAutomatic: false,
723    notice: undefined,
724    bandShown: cfg.band,
725    band: undefined,
726    reading: undefined,
727    recheckTool: false,
728    reofferTimer: undefined,
729    writeTimer: undefined,
730    writing: Promise.resolve(),
731    loggedOnce: new Set(),
732    sessions: new Map(),
733    carry: false,
734    settings: parseSettings(null),
735    zonesText: null,
736    zonesKey: undefined,
737  }
738
739  on('session.start', async ($, e, next) => {
740    for (const line of cfg.bad) {
741      if (!st.loggedOnce.has(line)) $.ui.log(line)
742      st.loggedOnce.add(line)
743    }
744    await registerSurfaces($, st)
745    // A fresh load mid-session (a reload, a worker respawn, an enable, a --resume launch): the
746    // earlier lines already reached Claude, so only a verdict past smart is restated.
747    if ((await $.session.turns()) > 0) {
748      const s = await current($, st)
749      s.pending = []
750      s.restate = true
751    }
752    return next(e)
753  }).catch(($, e, next) => next(e))
754
755  on('session.end', async ($, e, next) => {
756    st.reofferTimer = stopTimer(st.reofferTimer)
757    st.writeTimer = stopTimer(st.writeTimer)
758    // A -p exit does not drop the last reading the floor held back. The last refreshed body, not
759    // a fresh read: usage at exit can come back empty, and a session never refreshed writes nothing.
760    await queueWrite($, st)
761    st.sessions.delete(e.sessionId)
762    st.carry = e.reason === 'resume'
763    st.origin = undefined
764    st.recheckTool = true
765    return next(e)
766  }).catch(($, e, next) => next(e))
767
768  on('session.compact', async ($, e, next) => {
769    const result = await next(e)
770    if (e.agentId === undefined && e.trigger !== 'precompute' && !('skip' in result && result.skip)) {
771      const s = await current($, st)
772      s.compacted = true
773      s.restate = true
774      s.awaiting = false
775    }
776    return result
777  }).catch(($, e, next) => next(e))
778
779  on('prompt.submit', async ($, e, next) => {
780    const startMs = await $.clock.now()
781    // Only a prompt that starts a turn sets its origin; one delivered into a running turn does not.
782    if (e.turnId === undefined) {
783      st.origin = e.origin
784      // A shown suggestion: a person's turn means they saw it and chose, so it goes unsent; a turn
785      // no person started (a --bg launch turn reads as typed, so its suggestion went unseen) gets
786      // it as the ordinary line.
787      const s = await current($, st)
788      const handOff = s.offered.splice(0)
789      if (!isPersonTurn(st)) s.pending.unshift(...handOff.map(ev => (ev.kind === 'crossing' ? { ...ev, handedOff: true } : ev)))
790      if (st.notice !== undefined && (isPersonTurn(st) || handOff.length > 0)) {
791        st.notice = undefined
792        st.reofferTimer = stopTimer(st.reofferTimer)
793        $.ui.invalidate('ui.render')
794      }
795    }
796    // session.start does not fire after /clear or a resume: register the tool again if it is gone.
797    if (st.recheckTool) {
798      st.recheckTool = false
799      const tools = await $.tool.list().catch(() => undefined)
800      if (tools !== undefined && !tools.some(t => t.name === `mcp__${$.plugin.name}__status`)) await registerSurfaces($, st)
801    }
802    await refresh($, st)
803    return next(withLines($, e, await takeLines($, st, cfg, { event: 'prompt.submit', startMs })))
804  }).catch(($, e, next) => next(e))
805
806  on('session.measure', async ($, e, next) => {
807    await refresh($, st)
808    // The person's toast first, so a slow snapshot helper (10 s per run) cannot delay it; the
809    // finally keeps a failing toast step from skipping the write.
810    try {
811      await showPending($, st, cfg)
812    } finally {
813      await queueWrite($, st)
814    }
815    return next(e)
816  }).catch(($, e, next) => next(e))
817
818  on('turn.start', async ($, e, next) => {
819    st.reofferTimer = stopTimer(st.reofferTimer)
820    // Keeps the snapshot fresh through one long tool call or subagent run.
821    st.writeTimer ??= $.clock.every(WRITE_TIMER_MS, () => {
822      void queueWrite($, st, true)
823    })
824    return next(e)
825  }).catch(($, e, next) => next(e))
826
827  on('turn.complete', async ($, e, next) => {
828    if (e.agentId !== undefined) return next(e)
829    const startMs = await $.clock.now()
830    st.writeTimer = stopTimer(st.writeTimer)
831    if (cfg.enabled && cfg.lines && (await operatorHolds($, st, cfg))) {
832      const s = await current($, st)
833      s.pending = mergeRestated(s.pending)
834      const lines = renderAll(s.pending, s, cfg, st.settings)
835      if (lines.length > 0) {
836        st.notice = { text: `FYI, ${PREFIX}${lines.map(l => l.replace(PREFIX, '')).join(' ')}`, kind: 'operator' }
837        $.ui.invalidate('ui.render')
838        const fire: Fire = { event: 'turn.complete', startMs }
839        if (!(await offer($, st, s, fire))) {
840          st.reofferTimer ??= $.clock.every(REOFFER_MS, () => {
841            void offer($, st, s, fire)
842              .then(done => {
843                if (done) st.reofferTimer = stopTimer(st.reofferTimer)
844              })
845              .catch(() => undefined)
846          })
847        }
848      }
849    }
850    return next(e)
851  }).catch(($, e, next) => next(e))
852
853  on('command.run', { command: 'context-guard' }, async ($, e, next) => {
854    const [sub, arg, ...rest] = e.args.trim().toLowerCase().split(/\s+/).filter(Boolean)
855    if (sub === undefined) {
856      const text = await statusText($, st, cfg)
857      $.ui.log(POINTER, { to: 'transcript' })
858      return { text }
859    }
860    if (sub !== 'band' || rest.length > 0 || (arg !== undefined && arg !== 'on' && arg !== 'off')) return { text: USAGE }
861    st.bandShown = arg === undefined ? !st.bandShown : arg === 'on'
862    $.ui.invalidate('ui.render')
863    // Claude Code puts the plugin's name before a command's reply, so no reply carries it again.
864    return { text: `band row ${st.bandShown ? 'on' : 'off'} for this session` }
865  }).catch(($, e, next) => next(e))
866
867  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
868    const theirs = await next(e)
869    const notice = noticeShows(st, e.surface) ? st.notice?.text : undefined
870    if (e.props.hasSurvey || (!st.bandShown && notice === undefined)) return theirs
871    const { Box, Text } = $.ui.resolve(e)
872    return (
873      <Box flexDirection="column">
874        {st.bandShown ? (
875          <Text dimColor wrap="truncate">
876            {bandText(st.reading)}
877          </Text>
878        ) : null}
879        {notice !== undefined ? <Text wrap="wrap">{notice}</Text> : null}
880        {theirs}
881      </Box>
882    )
883  }).catch(($, e, next) => next(e))
884
885  on('tool.call', async ($, e, next) => {
886    if (e.tool === `mcp__${$.plugin.name}__status`) return { result: await statusJson($, st, cfg) }
887    const result = await next(e)
888    const fire: Fire = { event: 'tool.call', startMs: await $.clock.now(), toolUseId: (e as { tool_use_id?: unknown }).tool_use_id, agentId: e.agentId }
889    await refresh($, st)
890    await queueWrite($, st)
891    if (e.agentId !== undefined) return result
892    if (result.deny !== undefined || result.isError) return result
893    return withLines($, result, await takeLines($, st, cfg, fire))
894  }).catch(($, e, next) => next(e))
895}
896
hooks/zone.ts 154 lines
1// The zone resolver of scripts/context-zone.sh, in TypeScript: the same gates, bands, combination
2// rule and malformed-file notices over the same snapshot and zones.json text. The shared fixture
3// (scripts/context-zone.fixtures.mjs) holds the two equal; the reader contract is the authority.
4
5export type Word = 'smart' | 'acceptable' | 'dumb' | 'unknown'
6export type Zone = Exclude<Word, 'unknown'>
7export type Bands = { smart: number; acceptable: number; tokens: [number, number, number][] }
8
9export const STALENESS_SECONDS = 600
10const TOKEN_SEMANTICS_MIN_VERSION = '2.1.132'
11export const DEFAULT_BANDS: Bands = {
12  smart: 50,
13  acceptable: 75,
14  tokens: [
15    [200_000, 100_000, 150_000],
16    [1_000_000, 128_000, 500_000],
17  ],
18}
19export const RANK: Record<Zone, number> = { smart: 0, acceptable: 1, dumb: 2 }
20const ZONES: Zone[] = ['smart', 'acceptable', 'dumb']
21
22type Json = Record<string, unknown>
23const isObject = (v: unknown): v is Json => typeof v === 'object' && v !== null && !Array.isArray(v)
24const isNumber = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
25// jq's `x // null`: false and null both fall through.
26const orNull = (v: unknown) => (v === undefined || v === null || v === false ? null : v)
27
28const parse = (text: string): { ok: true; value: unknown } | { ok: false } => {
29  try {
30    return { ok: true, value: JSON.parse(text) }
31  } catch {
32    return { ok: false }
33  }
34}
35
36// Keys an object with no edge keys may hold and still keep the default bands silently; the mod
37// reads all but token_bands.
38const KNOWN_KEYS = ['token_bands', 'actions', 'approach_margin', 'thresholds']
39
40// zones.json: each shape validated on its own, a malformed one falls back with its notice.
41export const readBands = (zones: string | null): { bands: Bands; notices: string[] } => {
42  if (zones === null) return { bands: DEFAULT_BANDS, notices: [] }
43  const parsed = parse(zones)
44  if (!parsed.ok) return { bands: DEFAULT_BANDS, notices: ['percent', 'token_bands'] }
45  const z = parsed.value
46  const bands: Bands = { ...DEFAULT_BANDS }
47  const notices: string[] = []
48  const s = isObject(z) ? orNull(z.smart_max_used_percentage) : null
49  const a = isObject(z) ? orNull(z.acceptable_max_used_percentage) : null
50  if (isNumber(s) && isNumber(a) && s > 0 && s < a && a <= 100) {
51    bands.smart = s
52    bands.acceptable = a
53  } else if (!(isObject(z) && s === null && a === null && Object.keys(z).every(k => KNOWN_KEYS.includes(k)))) {
54    notices.push('percent')
55  }
56  const tb = isObject(z) ? orNull(z.token_bands) : null
57  if (tb !== null) {
58    const entries = isObject(tb) ? Object.entries(tb) : []
59    const valid =
60      entries.length > 0 &&
61      entries.every(([key, v]) => {
62        if (!/^[0-9]+$/.test(key) || !isObject(v)) return false
63        const sm = orNull(v.smart_max_tokens)
64        const am = orNull(v.acceptable_max_tokens)
65        return isNumber(sm) && isNumber(am) && sm > 0 && sm < am && am <= Number(key)
66      })
67    if (valid) {
68      bands.tokens = entries
69        .map(([key, v]) => [Number(key), (v as Json).smart_max_tokens as number, (v as Json).acceptable_max_tokens as number] as [number, number, number])
70        .sort((x, y) => x[0] - y[0])
71    } else {
72      notices.push('token_bands')
73    }
74  }
75  return { bands, notices }
76}
77
78const versionAtLeast = (candidate: string, min: string) => {
79  if (!/^[0-9]+(\.[0-9]+)*$/.test(candidate)) return false
80  const c = candidate.split('.').map(Number)
81  const m = min.split('.').map(Number)
82  const n = Math.max(c.length, m.length)
83  for (let i = 0; i < n; i += 1) {
84    const x = c[i] ?? 0
85    const y = m[i] ?? 0
86    if (x !== y) return x > y
87  }
88  return true
89}
90
91const band = (value: number, smart: number, acceptable: number): Zone => (value <= smart ? 'smart' : value <= acceptable ? 'acceptable' : 'dumb')
92export const worse = (a: Zone, b: Zone): Zone => (RANK[a] >= RANK[b] ? a : b)
93
94// A strict YYYY-MM-DDTHH:MM:SSZ that names a real instant, refusing values a lenient parser
95// would normalize (February 30, second 60, hour 24).
96const epochOf = (capturedAt: string): number | undefined => {
97  const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/.exec(capturedAt)
98  if (!m) return undefined
99  const d = new Date(0)
100  d.setUTCFullYear(Number(m[1]), Number(m[2]) - 1, Number(m[3]))
101  d.setUTCHours(Number(m[4]), Number(m[5]), Number(m[6]), 0)
102  const ms = d.getTime()
103  if (!Number.isFinite(ms)) return undefined
104  const back = d.toISOString().replace(/\.\d{3}Z$/, 'Z')
105  return back === capturedAt ? ms / 1000 : undefined
106}
107
108export type TokenShape = { used: number; size: number; smart: number; acceptable: number }
109
110// The token shape of one snapshot body: occupancy, window size and the band row's edges;
111// undefined when it is not computable.
112export const tokenShape = (w: Json, cliVersion: unknown, bands: Bands): TokenShape | undefined => {
113  const input = orNull(w.total_input_tokens)
114  const output = orNull(w.total_output_tokens)
115  const size = orNull(w.context_window_size)
116  if (
117    !(isNumber(input) && input >= 0 && isNumber(output) && output >= 0 && isNumber(size) && size > 0) ||
118    !versionAtLeast(typeof cliVersion === 'string' ? cliVersion : '', TOKEN_SEMANTICS_MIN_VERSION)
119  ) return undefined
120  const used = input + output
121  const row = bands.tokens.filter(([cls]) => cls <= size).at(-1)
122  return used <= size && row !== undefined ? { used, size, smart: row[1], acceptable: row[2] } : undefined
123}
124
125// The zone of one snapshot body, both shapes, worse wins; undefined when neither is computable.
126export const zoneOfWindow = (w: Json, cliVersion: unknown, bands: Bands): Zone | undefined => {
127  const p = orNull(w.used_percentage)
128  const pz = isNumber(p) && p >= 0 && p <= 100 ? band(p, bands.smart, bands.acceptable) : undefined
129  const t = tokenShape(w, cliVersion, bands)
130  const tz = t && band(t.used, t.smart, t.acceptable)
131  return pz && tz ? worse(pz, tz) : (pz ?? tz)
132}
133
134export const resolveZone = (args: { sid: string; snapshot: string | null; zones: string | null; nowSec: number }): { word: Word; notices: string[] } => {
135  const unknown = (notices: string[] = []) => ({ word: 'unknown' as const, notices })
136  if (!/^[A-Za-z0-9_-]+$/.test(args.sid) || args.snapshot === null) return unknown()
137  const { bands, notices } = readBands(args.zones)
138  const parsed = parse(args.snapshot)
139  if (!parsed.ok || !isObject(parsed.value)) return unknown(notices)
140  const s = parsed.value
141  if (typeof orNull(s.captured_at) !== 'string') return unknown(notices)
142  if (orNull(s.session_id) !== args.sid) return unknown(notices)
143  const w = orNull(s.context_window)
144  if (!isObject(w) || orNull(w.current_usage) === null) return unknown(notices)
145  const at = epochOf(s.captured_at as string)
146  if (at === undefined) return unknown(notices)
147  const age = args.nowSec - at
148  if (age < -60 || age > STALENESS_SECONDS) return unknown(notices)
149  const zone = zoneOfWindow(w, s.cli_version, bands)
150  return zone === undefined ? unknown(notices) : { word: zone, notices }
151}
152
153export const isZone = (word: unknown): word is Zone => ZONES.includes(word as Zone)
154