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.
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.
| Event | Matcher | Module | Decides | Output channel |
|---|---|---|---|---|
| SessionStart | all | scripts/bootstrap.py | Install or update the package | systemMessage to the user |
| SessionStart | all | claude.session_start | Offer to resume a snapshot (cold starts only); optional update check | additionalContext to Claude |
| PreToolUse | Read|Bash|WebFetch | claude.pre_tool_guard | Ask before a read or fetch over the warn threshold | permissionDecision: ask (exit 2 when it can’t prompt) |
| PostToolUse | WebFetch|WebSearch | claude.post_tool_guard | Flag output over the soft cap | exit 2, message on stderr |
| UserPromptSubmit | all | claude.prompt_guard | Block an off-topic prompt in a large session | {"decision": "block"} |
| PreCompact | all | claude.pre_compact | Save a project-state snapshot | none |
| Codex PreToolUse | Bash | codex.pre_tool_guard | Deny cat/curl-style dumps of large files and URLs | permissionDecision: deny |
| Codex PostToolUse | Bash | codex.post_tool_guard | Flag large command output | hook 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
- Skip if the file doesn’t exist, or if
.guardians.tomlwhitelists or ignores the path. - 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.
- 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. Acontext_windowsetting overrides all of it. - Estimate the file’s tokens (see Estimation). Pass if it is at or under
warn_threshold_pctof the window (default 20%). - Pass if the call already sets a
limitat or under a tenth of the warn budget. Bounded reads are what GOT would suggest anyway. - 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 asadditionalContextin case the user says No. Logs anaskedevent. If used + estimate reaches 90% of the window, the reason says compaction is likely. - When the prompt can’t be shown (
bypassPermissionsmode, orconfirm_with_promptset to false), block instead: exit 2, the full message on stderr, and ablockedevent.
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
highconfidence.
| Risk | Rule | Effect |
|---|---|---|
| safe | tokens ≤ warn_pct × window | Pass |
| warning | tokens > warn_pct × window | Ask (Claude Code) or deny (Codex) with options |
| critical | tokens ≥ 90% × window | Same, and the message adds compaction risk |
| unknown | URL size not available | Pass |
Prompt guard
The prompt guard runs on every UserPromptSubmit and only blocks when all of these hold:
- 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 withGOT_UNBLOCK. - The session is past
block_context_pctof its window (default 0.30), measured from the transcript’s latest usage. - 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.
- 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
| Path | Written by | Purpose |
|---|---|---|
<project>/.got/events.jsonl | all guards | One line per ask, block, flag, or snapshot; read by guardians-report and the dashboard |
<project>/.got/project_state.md, .json | pre_compact, prompt_guard | Resume snapshot |
~/.guardians.json | you, guardians CLI | User configuration |
<project>/.guardians.toml | you | Per-project overrides, whitelist, ignore |
~/.got/pause_until | guardians pause | ISO timestamp; expired pauses are deleted on read |
/tmp/guardians_bypass | you or the agent | One-shot bypass for blocks without a permission prompt, deleted when used |
~/.guardians/plugin-venv | bootstrap | Private install for the plugin |
~/.guardians/plugin-install.{lock,json,log} | bootstrap | Install lock, last result, pip log |
Configuration
| Key | Default | Meaning |
|---|---|---|
warn_threshold_pct | 20 | Ask before a read or fetch above this % of the window |
context_window | from model | Pin the window size in tokens instead of deriving it from the model id |
confirm_with_prompt | true | Ask with Claude Code’s Yes/No prompt; false blocks instead |
max_output_tokens | 8000 | Soft cap for flagged tool output |
prompt_guard.enabled | true | Turn the prompt guard on or off |
prompt_guard.block_context_pct | 0.30 | Session size where the prompt guard starts |
prompt_guard.very_low_similarity | 0.10 | Similarity under which a prompt is blocked |
prompt_guard.unblock_prefix | GOT_UNBLOCK | Prefix that sends a prompt anyway |
project_state.enabled | true | Turn snapshots on or off |
project_state.save_context_pct | 0.70 | Session size where pressure snapshots start |
project_state.min_save_interval_seconds | 300 | Throttle between pressure snapshots |
project_state.max_age_hours | 168 | Only offer snapshots newer than this |
auto_update_enabled | false | Daily same-major upgrade from PyPI |
telemetry_enabled | false | One 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