Repository navigation
Conversation
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>
|
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. |
There was a problem hiding this comment.
Graphify review 
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
elifbranches incli.py; the existinghook-guardcode andinstall.pyare untouched.graphify usagereads 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,--jsonor a self-contained--htmlreport.graphify token-guard install|uninstall|status|savingsmanages six Claude Code hooks:bash-cap(PostToolUse/Bash): output above 20,000 chars is cut to head and tail throughupdatedToolOutput; 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 handoffwritesgraphify-out/HANDOFF.mdfrom 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
handoffandsavings. I can split it into three PRs if you prefer.Type of change
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.
rereaddenies at most once per file version and always allows the retry.bash-capsaves 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-guardand none ofhook-guard,hook-checkorgraphify-out/, so_is_graphify_hook_commandand_strip_graphify_hooksignore them (tested).token-guard installpreserves all other settings, is idempotent, writes atomically and refuses an unparseable settings file.No transcript content is persisted.
usagereports counts, sizes, paths, models and dates. The savings ledger holds kind, size and session key.handoffholds 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_DIRoverrides).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:
budgethook was seen firing in a real Claude Code 2.1.322 session. Therereaddeny, thebash-capreplacement and thedailymessage were exercised only with synthetic payloads through the installed CLI, against the documented hook schema.systemMessageon SessionStart is documented as a universal field but not stated explicitly for that event.O_APPEND/O_EXCLuse and path handling are untested there.tool_responseshape is undocumented.read-donematches the shape current transcripts show; if it differs, nothing is recorded and the guard never denies.How was this tested?
macOS 15, Python 3.12,
uv run --frozen(plainuv runrewroteuv.lockhere, so the lockfile is unchanged in this PR).Tests use synthetic transcripts and payloads under
tmp_pathand the sandboxed home fromtests/conftest.py; they do not read the real~/.claude.Graphify-specific checklist
uv run python -m tools.skillgen --bless) when changing their source fragments. (No skill fragments changed.)AI disclosure: the implementation and this description were written with Claude (see the
Co-Authored-Bytrailers).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 ambiguoushandoff --sessionprefix is an error. The hook's stdin read and the settings read are now bounded.🤖 Generated with Claude Code