Skip to content

feat: token guard, usage report and handoff note for Claude Code - #5313

Open
cell3790 wants to merge 3 commits into
Graphify-Labs:v8from
cell3790:feat/token-guard
Open

cell3790 wants to merge 3 commits into
Graphify-Labs:v8from
cell3790:feat/token-guard

Conversation

@cell3790

@cell3790 cell3790 commented Nov 18, 2026 •

Copy link
Copy Markdown

What does this PR do?

Long Claude Code sessions spend most of their tokens re-reading a large context on every request, and graphify's existing hooks only address the first read of a file. On the machine this was built on, 58,000 requests over two months averaged 356k tokens of context; requests sent with more than 200k of context were 88% of all tokens; Bash output was two thirds of all tool-result text; repeated reads of the same file were about 10% of Read calls.

This adds three commands that work without a graph. They live in three new modules and are wired through three elif branches in cli.py; the existing hook-guard code and install.py are untouched.

  • graphify usage reads the Claude Code transcripts and reports tokens by model, day and project, context size per request, the heaviest sessions, a fixed-overhead estimate, tool-result size per tool and repeated reads, as text, --json or a self-contained --html report.
  • graphify token-guard install|uninstall|status|savings manages six Claude Code hooks:
    • bash-cap (PostToolUse/Bash): output above 20,000 chars is cut to head and tail through updatedToolOutput; the full output is saved to a file named in the cut.
    • budget (UserPromptSubmit): states the context size when it first passes 200k tokens and at each further 100k.
    • reread (PreToolUse/Read): declines once a repeated read of an unchanged file whose range is already in context; the retry is allowed.
    • read-done (PostToolUse/Read): records what a successful read put in context, so a failed or blocked read is never counted.
    • reset (SessionStart/compact): clears the read records, since compaction drops file contents.
    • daily (SessionStart/startup): once a day, a user-visible line with what was kept out of context the day before. It adds nothing to the model's context.
  • graphify handoff writes graphify-out/HANDOFF.md from the transcript, git state and the graph, with no LLM call, so a fresh session can replace a bloated one.

Docs: docs/token-guard.md.

This is three commands in one PR because they serve one purpose and the hooks point at handoff and savings. I can split it into three PRs if you prefer.

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Tests or CI
  • Refactor
  • Security fix

Verification & Invariants

Invariants this code protects:

  • A hook never blocks or breaks a tool call by mistake. Every hook fails open: any exception or unparseable stdin prints nothing and exits 0. reread denies at most once per file version and always allows the retry. bash-cap saves the full output before it prints a replacement, and prints nothing if the save fails.

  • Nothing in graphify's own install is disturbed. The hook commands contain token-guard and none of hook-guard, hook-check or graphify-out/, so _is_graphify_hook_command and _strip_graphify_hooks ignore them (tested). token-guard install preserves all other settings, is idempotent, writes atomically and refuses an unparseable settings file.

  • No transcript content is persisted. usage reports counts, sizes, paths, models and dates. The savings ledger holds kind, size and session key. handoff holds truncated user prompts with secrets masked, paths, counts and a git summary.

  • Extraction is not involved. No extractor, graph or cache code is changed, and no persisted graph state is affected. State lives under ~/.cache/graphify/token-guard (GRAPHIFY_TOKEN_GUARD_DIR overrides).

  • Read the CONTRIBUTING.md guide.

  • Reproduced the issue and identified the invariant. (Not a bug fix.)

  • Made the smallest fix necessary. (Not a bug fix.)

  • Added a regression test (if bug fix) or isolated boundary test.

  • Kept the PR description synchronized with the final implementation.

  • Documented any limitations / unsupported cases explicitly.

Limitations:

  • Live coverage is partial. The budget hook was seen firing in a real Claude Code 2.1.322 session. The reread deny, the bash-cap replacement and the daily message were exercised only with synthetic payloads through the installed CLI, against the documented hook schema.
  • systemMessage on SessionStart is documented as a universal field but not stated explicitly for that event.
  • Windows was not exercised. O_APPEND/O_EXCL use and path handling are untested there.
  • The transcript format is undocumented. Parsers match what current transcripts contain and skip anything else.
  • Estimates. Savings are characters / 4 and exclude the effect of later re-reads. Fixed overhead is first-request context (capped at twice the median) times requests.
  • Read's tool_response shape is undocumented. read-done matches the shape current transcripts show; if it differs, nothing is recorded and the guard never denies.
  • No LLM labelling or README change is included.

How was this tested?

macOS 15, Python 3.12, uv run --frozen (plain uv run rewrote uv.lock here, so the lockfile is unchanged in this PR).

uv run --frozen pytest tests/test_tokenguard.py tests/test_usage.py tests/test_handoff.py -q
  252 passed (re-run after the review fixes in 3929a02; the full-suite and other figures below are from the first push)

uv run --frozen pytest tests -q            # this branch
  27 failed, 11338 passed, 400 skipped, 1 xfailed
uv run --frozen pytest tests -q            # origin/v8 at 340268a, same machine
  27 failed, 11131 passed, 400 skipped, 1 xfailed
  The 27 failures are the same tests on both (test_ext_tagged_id_clash.py,
  test_pascal_singleton_resolution.py, test_skillgen.py); none is in a file
  this PR touches. I did not install --all-extras.

uv run --frozen ruff check .
  All checks passed!

uv run --frozen pyright graphify/tokenguard.py graphify/usage.py graphify/handoff.py \
    tests/test_tokenguard.py tests/test_usage.py tests/test_handoff.py
  0 errors
  (repo-wide pyright reports unresolved optional imports in this environment,
  with or without this PR)

graphify usage --days 7                    # real ~/.claude/projects, 6 GB: about 20 s for the full history
graphify handoff --transcript <637 MB transcript> --stdout   # 1.3 s
graphify token-guard install / status / savings              # against real user settings

Tests use synthetic transcripts and payloads under tmp_path and the sandboxed home from tests/conftest.py; they do not read the real ~/.claude.

Graphify-specific checklist

  • I updated generated skill artifacts (uv run python -m tools.skillgen --bless) when changing their source fragments. (No skill fragments changed.)
  • I confirmed that AST/structural extraction remains deterministic (no ambient state dependencies like ENV variables). (Extraction is untouched; the new env vars only affect the hooks.)
  • I reviewed changes for security implications (no unsafe interpolation into shell/Python).
  • I confirmed no API keys or local-only graph data are included.
  • (If applicable) I disclosed AI authorship in my commit messages.

AI disclosure: the implementation and this description were written with Claude (see the Co-Authored-By trailers).

Update, review findings (3929a02): the three P2 findings from the automated review are fixed, each with a regression test that failed before the fix: reads are recorded only after they succeed; install/uninstall recognise only <graphify> token-guard <sub> commands; an ambiguous handoff --session prefix is an error. The hook's stdin read and the settings read are now bounded.

🤖 Generated with Claude Code

cell3790 and others added 2 commits November 18, 2026 15:38
Long Claude Code sessions spend most of their tokens re-reading a large
context on every request. Three commands address that; none needs a graph.

- graphify usage: reads the Claude Code transcripts and reports tokens by
  model, day and project, context size per request, the heaviest sessions,
  a fixed-overhead estimate, tool-result size per tool and repeated reads,
  as text, JSON or a self-contained HTML report.
- graphify token-guard: Claude Code hooks that cap large Bash output (full
  output saved to a file), state the context size when it passes a budget,
  decline one repeated read of an unchanged file, and show once a day what
  was kept out of context. install/uninstall/status manage the settings
  entries; savings prints the per-day ledger. Every hook fails open.
- graphify handoff: writes graphify-out/HANDOFF.md from the transcript, git
  state and the graph, with no LLM call, so a fresh session can replace a
  bloated one.

See docs/token-guard.md.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Annotate the test helpers and narrow one Optional in usage.py. No
behaviour change.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@cell3790
cell3790 requested a review from safishamsi as a code owner November 18, 2026 13:41
@github-actions

Copy link
Copy Markdown

Thanks for the pull request, @cell3790. A maintainer will review it soon.

Want to talk it through while it is in review? Come join us on our Discord server. For longer-form discussion there is also GitHub Discussions.

A couple of things that speed up review: make sure the test suite passes on Python 3.11 and 3.13, and that the change keeps extraction deterministic.

@graphify-labs graphify-labs Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Graphify review View in Graphify

Nothing blocking · 3 possible issues to check · Merge confidence 5/5

3 possible issues to check · High impact

This change adds CLI commands for Claude Code usage reports, session handoff notes, and context-saving hooks.

3 possible issues we couldn't confirm
  • Failed-write test may not simulate a failed write, so it can pass without testing the keep-previous-note behavior · tests/test_handoff.py:632
  • The malformed-line test asserts zero skipped lines and never checks a malformed line that reaches the parser · tests/test_usage.py:156
  • token-guard status and savings skip the stale skill warning, and any argument named token-guard does too · graphify/__main__.py:843

They don't change the score.

What this review covered
  • We didn't review 1 file that isn't source code, such as docs, config, images, or generated or third-party code.
  • A changed file's diff was too long to show in full, so the review may not have seen every changed line in it.
  • Some lookups asked for files or lines that do not exist; the review was told and carried on.
  • +1 more notes in Graphify.
  • 8 of 8 changed files inspected. This is scope, not a correctness guarantee.
Code graph · 1011 functions depend on this change
  • 29 functions became more coupled. Largest: main() (24 callers), analyze() (12 callers), scan_transcript() (12 callers).
  • 596 of 596 test files are affected by this change.
  • Gate, test list and every flagged function: in the Graphify check.

Reviewed 3929a02 · 2 of 2 earlier findings resolved · 1 earlier finding not re-checked · Full report in the Graphify check

…ndoff

- reread: record a read only after it succeeded. Coverage is now written
  by a PostToolUse Read hook (read-done) instead of before the tool runs,
  so a failed or blocked Read no longer makes the next attempt look like
  a repeat. An install without read-done records nothing and denies
  nothing.
- install/uninstall: an entry is ours only when the whole command is
  `<graphify> token-guard <sub>`. A user's own hook that merely contains
  those words is left alone.
- handoff: a --session prefix that matches several sessions is an error
  that lists the candidates, instead of silently using the newest.
- Bound the hook's stdin read (64 MB, fail open beyond) and the settings
  read (4 MB, refused untouched beyond).

Each fix has a regression test that failed before it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant