Guardians of the Token · engineering notes · v1.4.0

How GOT decides what gets into the context window

GOT is a set of Claude Code and Codex hooks plus a small Python package. Each hook gets one JSON event on stdin and decides, usually in milliseconds, whether to let a tool call, a prompt, or a tool result through. Nothing calls a model. Every hook fails open.

Python ≥ 3.10package: guardians-of-the-tokenMIT

Runtime

The plugin ships hooks, an MCP server declaration, and three skills. Every hook command goes through one launcher, so the plugin doesn’t depend on PATH or on which Python owns the package.

On the first session, scripts/bootstrap.py starts a detached install into ~/.guardians/plugin-venv, pinned to the plugin’s version (guardians-of-the-token==<version>), then fetches the embedding model. It returns at once with a systemMessage for the user. A lock file stops parallel installs, and a status file lets the next session report a failure instead of retrying it every time.

guardians-install installs this same plugin through the claude CLI and removes any GOT hooks an older install left in ~/.claude/settings.json, so nothing runs twice. Without the claude CLI it writes the hooks into settings directly, calling the full path of the Python GOT was installed into (never a bare python3, which can’t import a pipx install). Codex hooks and every MCP entry use that same path.

Hook map

Claude Code reads each hook’s exit code and output differently by event. The last column is the channel GOT uses to talk back.

EventMatcherModuleDecidesOutput channel
SessionStartallscripts/bootstrap.pyInstall or update the packagesystemMessage to the user
SessionStartallclaude.session_startOffer to resume a snapshot (cold starts only); optional update checkadditionalContext to Claude
PreToolUseRead|Bash|WebFetchclaude.pre_tool_guardAsk before a read or fetch over the warn thresholdpermissionDecision: ask (exit 2 when it can’t prompt)
PostToolUseWebFetch|WebSearchclaude.post_tool_guardFlag output over the soft capexit 2, message on stderr
UserPromptSubmitallclaude.prompt_guardBlock an off-topic prompt in a large session{"decision": "block"}
PreCompactallclaude.pre_compactSave a project-state snapshotnone
Codex PreToolUseBashcodex.pre_tool_guardDeny cat/curl-style dumps of large files and URLspermissionDecision: deny
Codex PostToolUseBashcodex.post_tool_guardFlag large command outputhook JSON with feedback

Before any work, each guard checks the global pause (~/.got/pause_until) and the one-shot bypass (/tmp/guardians_bypass, or GUARDIANS_BYPASS in the environment) and exits 0 if either applies.

Read decision

  1. Skip if the file doesn’t exist, or if .guardians.toml whitelists or ignores the path.
  2. Read the last 32 KB of the transcript for the model name and the latest usage block. Used tokens = input + cache read + cache creation + output.
  3. Resolve the window from the model id; the longest matching prefix wins. Current claude-* models and ids marked [1m] → 1,000,000; older Claude models (3.x, 4.0–4.5) → 200,000; unknown → 200,000. A context_window setting overrides all of it.
  4. Estimate the file’s tokens (see Estimation). Pass if it is at or under warn_threshold_pct of the window (default 20%).
  5. Pass if the call already sets a limit at or under a tenth of the warn budget. Bounded reads are what GOT would suggest anyway.
  6. Otherwise return permissionDecision: "ask". Claude Code shows its own Yes/No permission prompt with GOT’s estimate as the reason, and Claude gets the smaller options as additionalContext in case the user says No. Logs an asked event. If used + estimate reaches 90% of the window, the reason says compaction is likely.
  7. When the prompt can’t be shown (bypassPermissions mode, or confirm_with_prompt set to false), block instead: exit 2, the full message on stderr, and a blocked event.

WebFetch works the same way, except step 4 starts from a HEAD request for Content-Length and Content-Type. If the size can’t be known, the risk is unknown and the call passes.

Estimation

Token counts come from file size, not from tokenizing the file. The estimate has two stages.

  • Stage 1: bytes × a ratio chosen by file extension. Binary types are never sampled.
  • Stage 2: only when stage 1 lands in the gray zone, between 50% and 125% of the warn budget, a sample of the file is read to measure its real density. The result is marked high confidence.
RiskRuleEffect
safetokens ≤ warn_pct × windowPass
warningtokens > warn_pct × windowAsk (Claude Code) or deny (Codex) with options
criticaltokens ≥ 90% × windowSame, and the message adds compaction risk
unknownURL size not availablePass

Prompt guard

The prompt guard runs on every UserPromptSubmit and only blocks when all of these hold:

  1. The prompt isn’t allow-listed. Allow-listed prompts are control commands (/clear, /compact, /got-* and their plugin-namespaced forms), short continuations (“yes”, “continue”, “lgtm”…), single digits 1–9 (replies to numbered options), and anything starting with GOT_UNBLOCK.
  2. The session is past block_context_pct of its window (default 0.30), measured from the transcript’s latest usage.
  3. A topic anchor exists: the latest away-recap, else the latest compaction summary, else the first and last real user prompts. Synthetic and command entries are filtered out.
  4. The prompt’s best cosine similarity against the anchor chunks is under very_low_similarity (0.10 for all-MiniLM-L6-v2). Each chunk is scored on its own, because one long concatenated anchor dilutes the topic signal.

A block ends with two choices: New topic → run /clear, then send it again, or Keep it here → send it again starting with GOT_UNBLOCK. A UserPromptSubmit hook can only return text, so there are no buttons here; Claude Code’s own Edit prompt puts the text back for the prefix.

Embeddings come from a quantized all-MiniLM-L6-v2 ONNX model (~22 MB) run with onnxruntime: mean-pooled, then L2-normalized. If the model or runtime is missing, the guard allows the prompt.

Snapshots

A snapshot is captured at two moments: on PreCompact, and after any prompt once the session passes save_context_pct (default 0.70). Pressure captures are throttled to one every 300 seconds. Each snapshot is built from the transcript with no model call:

  • summary: the latest away-recap, else the latest compaction summary
  • goals: recent real user prompts (up to 6)
  • files: paths from Edit, Write, MultiEdit, and NotebookEdit calls (up to 20)
  • commands: recent Bash commands (up to 12)
  • metadata: branch (read from .git/HEAD), session id, live tokens, context %

On a cold start (startup or clear), if a snapshot for this project is younger than max_age_hours (168), session_start adds context asking Claude to mention it and offer /got-resume. It never injects the snapshot itself.

User replies

Large reads and fetches use Claude Code’s permission prompt. The tool call and the buttons are Claude Code’s; the reason is GOT’s:

🛡️ Guardians of the Token: large file (~120,000 tokens, 60% of the window, ~$0.48).
Context 20% → 80%.
Yes loads it in full. No lets Claude suggest a smaller read.

Yes runs the call once, so it is the bypass. No cancels it, and Claude offers the smaller options GOT passed it (first or last part, search, bounded summary).

Where there’s no prompt to hand off to (flagged WebFetch/WebSearch output, and blocks under bypassPermissions), the message still ends with numbered options for the user and a relay line that maps each number to an action for the agent:

Next options (reply with a number):
1. Inspect a smaller slice
…
4. Bypass once for the full output
[Guardians of the Token] … When they pick an option (by number or name):
1 = rerun with output limited to a small slice; …
4 = run `touch /tmp/guardians_bypass`, then rerun once.

The user replies with a digit. The prompt guard lets single digits through, the agent carries out the action, and a bypass file is used up by the next guarded call.

State on disk

PathWritten byPurpose
<project>/.got/events.jsonlall guardsOne line per ask, block, flag, or snapshot; read by guardians-report and the dashboard
<project>/.got/project_state.md, .jsonpre_compact, prompt_guardResume snapshot
~/.guardians.jsonyou, guardians CLIUser configuration
<project>/.guardians.tomlyouPer-project overrides, whitelist, ignore
~/.got/pause_untilguardians pauseISO timestamp; expired pauses are deleted on read
/tmp/guardians_bypassyou or the agentOne-shot bypass for blocks without a permission prompt, deleted when used
~/.guardians/plugin-venvbootstrapPrivate install for the plugin
~/.guardians/plugin-install.{lock,json,log}bootstrapInstall lock, last result, pip log

Configuration

KeyDefaultMeaning
warn_threshold_pct20Ask before a read or fetch above this % of the window
context_windowfrom modelPin the window size in tokens instead of deriving it from the model id
confirm_with_prompttrueAsk with Claude Code’s Yes/No prompt; false blocks instead
max_output_tokens8000Soft cap for flagged tool output
prompt_guard.enabledtrueTurn the prompt guard on or off
prompt_guard.block_context_pct0.30Session size where the prompt guard starts
prompt_guard.very_low_similarity0.10Similarity under which a prompt is blocked
prompt_guard.unblock_prefixGOT_UNBLOCKPrefix that sends a prompt anyway
project_state.enabledtrueTurn snapshots on or off
project_state.save_context_pct0.70Session size where pressure snapshots start
project_state.min_save_interval_seconds300Throttle between pressure snapshots
project_state.max_age_hours168Only offer snapshots newer than this
auto_update_enabledfalseDaily same-major upgrade from PyPI
telemetry_enabledfalseOne anonymous install event, opt-in

Known limits

Bash output capping is not applied in Claude Code

The PreToolUse guard rewrites Bash commands to pipe through cap_output, but returns the new input as a top-level tool_input key. Claude Code only reads hookSpecificOutput.updatedInput, so the rewrite never takes effect. Turning it on would wrap every command in a pipe and lose its exit code, so this needs a redesign rather than a one-line fix.

Post-tool checks can warn, not trim

By the time PostToolUse runs, the WebFetch or WebSearch result is already in context. The guard can only tell Claude to stop carrying it forward.

Context windows come from model ids

Windows are looked up by model-id prefix. A new model with a smaller window than its family, or a custom id behind a proxy, is judged against the wrong size until the table is updated or context_window is set.

The prompt guard has no buttons

UserPromptSubmit hooks can block with text, add context, or set the title, nothing more. The two choices are written out, and the user acts on them by hand.

The bypass file is global

/tmp/guardians_bypass is shared by every session on the machine, so another session’s next guarded call can use it up first. It now only matters where there’s no permission prompt to hand off to.

First plugin session is unguarded

The background install takes about a minute. Until it finishes, the launcher fails open.

Testing

The test suite is pytest. Hooks are tested end to end as subprocesses, fed JSON on stdin, with fixture sizes injected through GUARDIANS_TEST_SIZE and GUARDIANS_TEST_TOKENS. A local fixture server (guardians-test-server) serves /small, /large, and /compact with fake Content-Length headers for the URL guards.

CI runs on Ubuntu with Python 3.10 and 3.12. It downloads the model, runs the suite, smoke-tests the console scripts, and sends an MCP initialize request. Coverage now measures subprocesses too, and the target is 100%.

pip install -e '.[test]'
guardians-download-models
python -m pytest