Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
feat(claude): live tokens-saved statusline accumulator + per-turn skill report
anirudhkumar-nanonets4657ef8776f5
diff --git a/.claude/settings.json b/.claude/settings.jsonindex 89135251..2c42314b 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -21,6 +21,16 @@"timeout": 10000}]+ },+ {+ "matcher": "Bash|mcp__graft__",+ "hooks": [+ {+ "type": "command",+ "command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-hooks.cjs\" tool-savings",+ "timeout": 8000+ }+ ]}],"Stop": [diff --git a/.claude/skills/graft/SKILL.md b/.claude/skills/graft/SKILL.mdindex 9523f485..314bce99 100644--- a/.claude/skills/graft/SKILL.md+++ b/.claude/skills/graft/SKILL.md@@ -78,6 +78,15 @@ available.If a returned span is truncated ("+N more lines"), open the file at that exactrange before finalizing.+**Report what graft saved — every turn.** Each retrieval tool ends its output+with a `[graft] tokens saved ≈ N` line: the estimated tokens that one call+saved versus reading the files it covers whole. Whenever you used any graft tool+in a turn, close your reply with a one-line tally that sums those numbers across+every graft call you made — e.g. `🌱 graft saved ~12,400 tokens this turn (3+calls)`. A call with no footer (tiny files, where the pointers cost as much as+the source) saved nothing — skip it. This is the per-turn figure; the statusline+carries the running session total.+If a node genuinely lacks a detail you need, ask for a more specific node, andif it still lacks it, read the source — at the exact file:line the node pointsto, not the whole file. Reading whole source files to build understanding isdiff --git a/graft/.graph/wiring.json b/graft/.graph/wiring.jsonindex 6b3d616c..6be31070 100644--- a/graft/.graph/wiring.json+++ b/graft/.graph/wiring.json@@ -1,8 +1,8 @@{"meta": {"version": 1,- "nodeCount": 849,- "edgeCount": 2295,+ "nodeCount": 853,+ "edgeCount": 2312,"languages": ["typescript"],@@ -2105,12 +2105,12 @@"name": "ask.ts","kind": "file","path": "src/ask/ask.ts",- "span": "L1-L988",+ "span": "L1-L989","signature": null,"exported": true,"origin": "ast",- "body_hash": "fdd99ac315e941001c25ac1fd7e704aac9e028ec0476fd96533a271a0fafde55",- "chars": 46983,+ "body_hash": "40233f975f0f2040fd7b0b40cfd01df9a45e6f671dd4ba1ba4533813c2ae3b8c",+ "chars": 47028,"summary_state": "stale","summary": "This module provides a mechanism to process natural language queries and return structured results from a codebase, enhancing the ability to find relevant code snippets and their relationships.","crux": {@@ -2188,11 +2188,11 @@"name": "askSavingsFooter","kind": "function","path": "src/ask/ask.ts",- "span": "L956-L968",+ "span": "L956-L969","signature": "function askSavingsFooter(r: AskResult, body: string): string","exported": false,"origin": "ast",- "body_hash": "6d41a7ba0226bbe165fcaaf3024079b957cfb23397111727ab8c642871a10718",+ "body_hash": "f857cd0ab442a19a66ef012cdf4e5edf35a95c1ddfcfe0264f5e94b0aab8cfe0","summary_state": "pending","summary": null,"crux": null@@ -2539,7 +2539,7 @@"name": "scopeFooterLines","kind": "function","path": "src/ask/ask.ts",- "span": "L975-L987",+ "span": "L976-L988","signature": "function scopeFooterLines(r: AskResult): string[]","exported": false,"origin": "ast",@@ -3317,12 +3317,12 @@"name": "hooks.ts","kind": "file","path": "src/claude/hooks.ts",- "span": "L1-L167",+ "span": "L1-L187","signature": null,"exported": true,"origin": "ast",- "body_hash": "50f06a7c6c0273e9a18ee6bb7c8d028098a1fa98ab12733d4dd2d94878f418ec",- "chars": 7870,+ "body_hash": "fa521cf3393ae31b324f2a615f156e387f402c1f4bc1f0addb3cf521f1eced9b",+ "chars": 8866,"summary_state": "stale","summary": "Handles various events related to the Graft system, including session management and user prompts.","crux": {@@ -3403,7 +3403,7 @@"name": "handleStop","kind": "function","path": "src/claude/hooks.ts",- "span": "L107-L121",+ "span": "L125-L139","signature": "function handleStop(dir: string): void","exported": false,"origin": "ast",@@ -3415,6 +3415,20 @@"span": "L68-L72"}},+ {+ "id": "src/claude/hooks.ts#handleToolSavings",+ "name": "handleToolSavings",+ "kind": "function",+ "path": "src/claude/hooks.ts",+ "span": "L113-L123",+ "signature": "function handleToolSavings(input: any, dir: string): void",+ "exported": false,+ "origin": "ast",+ "body_hash": "c29390cdd2879e48a0c05210ae252be3a9e8b615eae3ffd2b025f296841e7355",+ "summary_state": "pending",+ "summary": null,+ "crux": null+ },{"id": "src/claude/hooks.ts#lastFileScopeHint","name": "lastFileScopeHint",@@ -3434,11 +3448,11 @@"name": "main","kind": "function","path": "src/claude/hooks.ts",- "span": "L123-L166",+ "span": "L141-L186","signature": "async function main(event: string): Promise<void>","exported": true,"origin": "ast",- "body_hash": "35b36c608f337b1afd4a2633a08fb658e19c4a15cd62f36874c0b24d4e166d60",+ "body_hash": "3e8594154785cb8910fc39de294ab1b7e557e35587b9baddfe9fe995acb5017d","summary_state": "stale","summary": "Main entry point for handling various events and orchestrating the application logic.","crux": {@@ -3634,13 +3648,13 @@"name": "settings-merge.ts","kind": "file","path": "src/claude/settings-merge.ts",- "span": "L1-L56",+ "span": "L1-L63","signature": null,"exported": true,"origin": "ast",- "body_hash": "eda59409ff8c470e7d3726a6740ba19e36e511ab40c67234aa794fabd9eacb8d",- "chars": 2653,- "summary_state": "ready",+ "body_hash": "6f5516f451595ecb86078abd33dc47a92900fcf5e764200b26b068b412f62f2b",+ "chars": 3146,+ "summary_state": "stale","summary": "Merges existing settings with new graft configurations, ensuring proper command hooks and permissions are set while avoiding conflicts.","crux": {"code": "export function mergeGraftSettings(existing: Json): { merged: Json; warnings: string[] } {\n const merged: Json = { ...(existing ?? {}) };\n const warnings: string[] = [];\n\n if (!merged.statusLine) merged.statusLine = { type: 'command', command: SL_CMD };\n else if (merged.statusLine.command !== SL_CMD)\n warnings.push('Existing statusLine left untouched (a session allows only one). To use Graft, point it at .claude/helpers/graft-statusline.cjs.');\n\n if (!merged.subagentStatusLine) merged.subagentStatusLine = { type: 'command', command: SL_CMD };\n else if (merged.subagentStatusLine.command !== SL_CMD)\n warnings.push('Existing subagentStatusLine left untouched.');\n",@@ -3652,12 +3666,12 @@"name": "graftBlocks","kind": "function","path": "src/claude/settings-merge.ts",- "span": "L10-L17",- "signature": "function graftBlocks(): Record<string, Json>",+ "span": "L10-L24",+ "signature": "function graftBlocks(): Record<string, Json[]>","exported": false,"origin": "ast",- "body_hash": "b63b7e0ffcf1d915291072b9cef941ddc0f0a242052a955287c2c49bd21d38ed",- "summary_state": "ready",+ "body_hash": "e070fcf4acbe04f0ba2fd5c723b6ca72dea77bfc51b90e77cccb2124d3d59449",+ "summary_state": "stale","summary": "Creates a mapping of events to their corresponding Graft command hooks for processing user actions.","crux": {"code": " PostToolUse: { matcher: 'Write|Edit|MultiEdit', hooks: [{ type: 'command', command: hookCmd('post-edit'), timeout: 10000 }] },\n UserPromptSubmit: { hooks: [{ type: 'command', command: hookCmd('prompt'), timeout: 8000 }] },\n SessionStart: { hooks: [{ type: 'command', command: hookCmd('session-start'), timeout: 8000 }] },",@@ -3686,7 +3700,7 @@"name": "isGraftHookEntry","kind": "function","path": "src/claude/settings-merge.ts",- "span": "L18-L20",+ "span": "L25-L27","signature": "function isGraftHookEntry(entry: Json): boolean","exported": false,"origin": "ast",@@ -3717,12 +3731,12 @@"name": "mergeGraftSettings","kind": "function","path": "src/claude/settings-merge.ts",- "span": "L22-L55",+ "span": "L29-L62","signature": "function mergeGraftSettings(existing: Json): { merged: Json; warnings: string[] }","exported": true,"origin": "ast",- "body_hash": "ea1e86633976a209debc5f9a83ac8ef1e7fd74f5327e196617b64ae8849ff8c5",- "summary_state": "ready",+ "body_hash": "58794bc801bfb40081268ebe4759db6c809d81a619bc0a778604c153c525ed5c",+ "summary_state": "stale","summary": "Merges existing settings with Graft-specific configurations, ensuring idempotency and compliance with Graft rules.","crux": {"code": " if (!merged.statusLine) merged.statusLine = { type: 'command', command: SL_CMD };\n else if (merged.statusLine.command !== SL_CMD)\n warnings.push('Existing statusLine left untouched (a session allows only one). To use Graft, point it at .claude/helpers/graft-statusline.cjs.');\n\n if (!merged.subagentStatusLine) merged.subagentStatusLine = { type: 'command', command: SL_CMD };\n else if (merged.subagentStatusLine.command !== SL_CMD)\n warnings.push('Existing subagentStatusLine left untouched.');",@@ -3797,12 +3811,12 @@"name": "skill-template.ts","kind": "file","path": "src/claude/skill-template.ts",- "span": "L1-L93",+ "span": "L1-L102","signature": null,"exported": true,"origin": "ast",- "body_hash": "d5ee0ef3211ef27c0ba34fd6709befe4d25aa4d61920be8f72094f784817d431",- "chars": 5176,+ "body_hash": "80ea21212897a7c0e6b94029d75b3e4567f24a3496e6c72d290c978cc2bbbc3d",+ "chars": 5768,"summary_state": "stale","summary": "Provides a structured template for the graft Claude Code skill, enabling efficient onboarding and understanding of the codebase.","crux": {@@ -3815,11 +3829,11 @@"name": "skillTemplate","kind": "function","path": "src/claude/skill-template.ts",- "span": "L6-L92",+ "span": "L6-L101","signature": "function skillTemplate(): string","exported": true,"origin": "ast",- "body_hash": "f95b4bb7d0b4bb9bae81edea626412e887e096d0d0c54b28cc0d99f05f4ad9cf",+ "body_hash": "bc06430568ac09424dd30bc8afca2a5321183ebf0fb46f2804aeca3f89116b54","summary_state": "stale","summary": "Generates a markdown string that serves as a comprehensive guide for using the graft tool effectively within a code repository.","crux": {@@ -5399,12 +5413,12 @@"name": "savings.ts","kind": "file","path": "src/context/savings.ts",- "span": "L1-L73",+ "span": "L1-L83","signature": null,"exported": true,"origin": "ast",- "body_hash": "ff8cc5330d8d1ac27285e75ce1b87852fb3c91d3909ddd392cd0458dbd5bf7e6",- "chars": 3101,+ "body_hash": "43e2cfc29123851a5f4bee55fe5716de8ab4a102ff39201e65c9907eb914b9bb",+ "chars": 3723,"summary_state": "pending","summary": null,"crux": null@@ -5442,11 +5456,11 @@"name": "savingsFooter","kind": "function","path": "src/context/savings.ts",- "span": "L60-L72",+ "span": "L69-L82","signature": "function savingsFooter(body: string, saved: Savings | undefined): string","exported": true,"origin": "ast",- "body_hash": "a52162795bb01ef973dded780df072bf49a5c03e5823baed4d4bc1cefd0c82ae",+ "body_hash": "d515334ac994b49da696c652441cfcb49a6c3f502fb0d44b428bcdbb3f93ad19","summary_state": "pending","summary": null,"crux": null@@ -7177,12 +7191,12 @@"name": "map.ts","kind": "file","path": "src/graph/map.ts",- "span": "L1-L331",+ "span": "L1-L349","signature": null,"exported": true,"origin": "ast",- "body_hash": "663da62a0d0be1c167f0eddf0f281e4e8082f05da279e2ad3055eece2e31ef4b",- "chars": 13078,+ "body_hash": "ff983cae1ca4418ca34200cf6a3d073be3ca2bf281d6d0ce7db5d839c70724fc",+ "chars": 14233,"summary_state": "stale","summary": "Builds a structured representation of a repository's file and symbol organization based on their relationships, facilitating easier navigation and understanding of the codebase.","crux": {@@ -7195,7 +7209,7 @@"name": "basenameOf","kind": "function","path": "src/graph/map.ts",- "span": "L273-L276",+ "span": "L287-L290","signature": "function basenameOf(path: string): string","exported": false,"origin": "ast",@@ -7212,7 +7226,7 @@"name": "buildRepoMap","kind": "function","path": "src/graph/map.ts",- "span": "L219-L269",+ "span": "L233-L283","signature": "function buildRepoMap(graph: GraphV1, opts: BuildRepoMapOptions = {}): RepoMap","exported": true,"origin": "ast",@@ -7229,7 +7243,7 @@"name": "BuildRepoMapOptions","kind": "interface","path": "src/graph/map.ts",- "span": "L77-L84",+ "span": "L83-L90","signature": "interface BuildRepoMapOptions","exported": true,"origin": "ast",@@ -7246,11 +7260,11 @@"name": "computeDirEntries","kind": "function","path": "src/graph/map.ts",- "span": "L144-L206",+ "span": "L150-L220","signature": "function computeDirEntries( nodes: NodeV1[], inDegree: Map<string, number>, maxDirs: number, hubsPerDir: number, stripPrefix: string, ): { dirs: DirEntry[]; dropped: number }","exported": false,"origin": "ast",- "body_hash": "628ff92b44a21ceecbf4096bf5e22dd1fc73b6c7c6fe84915ccee6645fd76905",+ "body_hash": "89ce156fc147c16ae2389d80a35f5c78bc15585be723b7f9be1375edddc08ccb","summary_state": "pending","summary": null,"crux": null@@ -7260,7 +7274,7 @@"name": "depthFor","kind": "function","path": "src/graph/map.ts",- "span": "L175-L175",+ "span": "L181-L181","signature": "depthFor = (rp: string): number","exported": false,"origin": "ast",@@ -7274,7 +7288,7 @@"name": "fullPath","kind": "function","path": "src/graph/map.ts",- "span": "L191-L192",+ "span": "L197-L198","signature": "fullPath = (relKey: string): string","exported": false,"origin": "ast",@@ -7288,7 +7302,7 @@"name": "relPath","kind": "function","path": "src/graph/map.ts",- "span": "L154-L155",+ "span": "L160-L161","signature": "relPath = (path: string): string","exported": false,"origin": "ast",@@ -7302,7 +7316,7 @@"name": "computeInDegree","kind": "function","path": "src/graph/map.ts",- "span": "L104-L111",+ "span": "L110-L117","signature": "function computeInDegree(graph: GraphV1): Map<string, number>","exported": false,"origin": "ast",@@ -7319,12 +7333,12 @@"name": "DirEntry","kind": "interface","path": "src/graph/map.ts",- "span": "L35-L41",+ "span": "L35-L47","signature": "interface DirEntry","exported": true,"origin": "ast",- "body_hash": "1aed0e0df317b263286233153a93927552e23d59efef6822065986f6b9efb90b",- "summary_state": "ready",+ "body_hash": "158040217cb955840c0f2108e9ad39ee425c252f7c25a87f504f2c09c45d116f",+ "summary_state": "stale","summary": "Represents a directory entry in the repository map, summarizing its contents and associated hubs for better navigation.","crux": {"code": "export interface DirEntry {\n path: string;\n files: number;\n symbols: number;\n languages: string[];\n hubs: Hub[];\n}",@@ -7336,7 +7350,7 @@"name": "dirKey","kind": "function","path": "src/graph/map.ts",- "span": "L96-L99",+ "span": "L102-L105","signature": "function dirKey(path: string, depth: number): string","exported": false,"origin": "ast",@@ -7353,7 +7367,7 @@"name": "droppedNote","kind": "function","path": "src/graph/map.ts",- "span": "L294-L297",+ "span": "L312-L315","signature": "function droppedNote(dropped: number): string | null","exported": false,"origin": "ast",@@ -7367,7 +7381,7 @@"name": "formatDirHub","kind": "function","path": "src/graph/map.ts",- "span": "L278-L280",+ "span": "L292-L294","signature": "function formatDirHub(h: Hub): string","exported": false,"origin": "ast",@@ -7384,12 +7398,12 @@"name": "formatDirLine","kind": "function","path": "src/graph/map.ts",- "span": "L282-L287",+ "span": "L296-L305","signature": "function formatDirLine(d: DirEntry): string","exported": false,"origin": "ast",- "body_hash": "9a3db58b03fcc2ffa99b84aab037542b6ca49d55fac6441b9ca23edfede291b6",- "summary_state": "ready",+ "body_hash": "0ec18de44fc444674ed72472aac2bbd15cc8c12ec3b8ed06014b58467bc487a6",+ "summary_state": "stale","summary": "Formats a directory entry for display, summarizing its contents and associated hubs in a readable format.","crux": {"code": "function formatDirLine(d: DirEntry): string {\n const label = `${d.path}/`.padEnd(DIR_COL_WIDTH);\n const counts = `${d.files} files · ${d.symbols} symbols`;\n const hubs = d.hubs.length ? ` hubs: ${d.hubs.map(formatDirHub).join(\", \")}` : \"\";\n return `${label}${counts}${hubs}`;\n}",@@ -7401,7 +7415,7 @@"name": "formatHotspot","kind": "function","path": "src/graph/map.ts",- "span": "L289-L291",+ "span": "L307-L309","signature": "function formatHotspot(h: Hub): string","exported": false,"origin": "ast",@@ -7418,7 +7432,7 @@"name": "formatRepoMap","kind": "function","path": "src/graph/map.ts",- "span": "L305-L330",+ "span": "L323-L348","signature": "function formatRepoMap(map: RepoMap): string","exported": true,"origin": "ast",@@ -7452,7 +7466,7 @@"name": "RepoMap","kind": "interface","path": "src/graph/map.ts",- "span": "L55-L75",+ "span": "L61-L81","signature": "interface RepoMap","exported": true,"origin": "ast",@@ -7469,7 +7483,7 @@"name": "ScopeGroup","kind": "interface","path": "src/graph/map.ts",- "span": "L46-L53",+ "span": "L52-L59","signature": "interface ScopeGroup","exported": true,"origin": "ast",@@ -7483,7 +7497,7 @@"name": "sortedLanguages","kind": "function","path": "src/graph/map.ts",- "span": "L124-L131",+ "span": "L130-L137","signature": "function sortedLanguages(paths: string[]): string[]","exported": false,"origin": "ast",@@ -7500,7 +7514,7 @@"name": "topHubs","kind": "function","path": "src/graph/map.ts",- "span": "L116-L122",+ "span": "L122-L128","signature": "function topHubs(nodes: NodeV1[], inDegree: Map<string, number>, cap: number): Hub[]","exported": false,"origin": "ast",@@ -10888,12 +10902,12 @@"name": "claude-hooks.test.ts","kind": "file","path": "test/claude-hooks.test.ts",- "span": "L1-L364",+ "span": "L1-L443","signature": null,"exported": true,"origin": "ast",- "body_hash": "faabd12d53807148c5d3462647fc6c12f1fe5de9390e837dd07b6411c603e1c6",- "chars": 16427,+ "body_hash": "062187284e1e6fe9bd51da4a3adad6cf8d9c7b1d94c332c9234abf159ab105af",+ "chars": 19625,"summary_state": "stale","summary": "This file contains tests for the functionality of the graft hooks in the Claude project, ensuring that edits are detected and state is managed correctly.","crux": {@@ -10906,7 +10920,7 @@"name": "fakeBuild","kind": "function","path": "test/claude-hooks.test.ts",- "span": "L84-L87",+ "span": "L85-L88","signature": "fakeBuild = (dir: string)","exported": false,"origin": "ast",@@ -10923,7 +10937,7 @@"name": "runWithStdin","kind": "function","path": "test/claude-hooks.test.ts",- "span": "L38-L41",+ "span": "L39-L42","signature": "async function runWithStdin(text: string, fn: () => Promise<void>): Promise<void>","exported": false,"origin": "ast",@@ -10940,7 +10954,7 @@"name": "writeAskArgsStub","kind": "function","path": "test/claude-hooks.test.ts",- "span": "L247-L258",+ "span": "L248-L259","signature": "function writeAskArgsStub(d: string): { stub: string; argsFile: string }","exported": false,"origin": "ast",@@ -10954,7 +10968,7 @@"name": "writeMultiScopeWiring","kind": "function","path": "test/claude-hooks.test.ts",- "span": "L126-L145",+ "span": "L127-L146","signature": "function writeMultiScopeWiring(d: string): void","exported": false,"origin": "ast",@@ -10972,9 +10986,9 @@"signature": null,"exported": true,"origin": "ast",- "body_hash": "b582cd79b2a1e4952ff83ac1b2e85f742756443c2896e08d96a75dc76e2971a5",- "chars": 6213,- "summary_state": "ready",+ "body_hash": "08dbd597b9b05cc11404b539ffea0f1857238e4022c81bc766554eb5c4d35ff3",+ "chars": 6268,+ "summary_state": "stale","summary": "This file contains tests for the initialization logic of the graft system, ensuring that settings and skills are correctly scaffolded and managed during the initialization process.","crux": {"code": "test('runInit scaffolds settings + both shims + the skill (build skipped)', () => {\n const d = fresh();\n const r = runInit(d, { build: false });\n assert.ok(existsSync(join(d, '.claude', 'settings.json')));\n assert.ok(existsSync(join(d, '.claude', 'helpers', 'graft-statusline.cjs')));\n assert.ok(existsSync(join(d, '.claude', 'helpers', 'graft-hooks.cjs')));\n const skillPath = join(d, '.claude', 'skills', 'graft', 'SKILL.md');\n assert.ok(existsSync(skillPath), 'writes the graft skill');\n assert.equal(r.skill, skillPath);\n assert.match(readFileSync(skillPath, 'utf8'), /name: graft/);\n assert.equal(r.built, false);\n const s = JSON.parse(readFileSync(join(d, '.claude', 'settings.json'), 'utf8'));",@@ -11055,13 +11069,13 @@"name": "claude-settings-merge.test.ts","kind": "file","path": "test/claude-settings-merge.test.ts",- "span": "L1-L84",+ "span": "L1-L91","signature": null,"exported": true,"origin": "ast",- "body_hash": "4c8b800f02d1b72050082bdbcdcda0878e5d9760563d2e1ca4a31cb06ffaaabb",- "chars": 4109,- "summary_state": "ready",+ "body_hash": "7fed008f3dca41eb509b1978124bf3defd9fa967fa6fc0b0ce32616cb323729c",+ "chars": 4654,+ "summary_state": "stale","summary": "This test suite verifies the behavior of merging Graft settings, ensuring that defaults are applied correctly, existing configurations are preserved, and no duplicates are introduced during re-initialization.","crux": {"code": "test('empty settings gets the full Graft blocks', () => {\n const { merged, warnings } = mergeGraftSettings({});\n assert.equal(merged.statusLine.command, SL);\n assert.equal(merged.subagentStatusLine.command, SL);\n assert.ok(Array.isArray(merged.hooks.PostToolUse));\n assert.equal(merged.hooks.PostToolUse[0].matcher, 'Write|Edit|MultiEdit');\n for (const e of ['PostToolUse', 'UserPromptSubmit', 'SessionStart', 'Stop']) {\n assert.ok(merged.hooks[e][0].hooks[0].command.includes('graft-hooks.cjs'), `${e} wired`);\n }\n assert.ok(merged.footerLinksRegexes.includes('graft/[\\\\w./-]+\\\\.md'));\n assert.deepEqual(warnings, []);\n});",@@ -11091,12 +11105,12 @@"name": "claude-skill-template.test.ts","kind": "file","path": "test/claude-skill-template.test.ts",- "span": "L1-L23",+ "span": "L1-L25","signature": null,"exported": true,"origin": "ast",- "body_hash": "4cd70d1c165527b023ade24e24ade06c91b7dd4c83120f1cc84cc200f2f98205",- "chars": 1380,+ "body_hash": "e3bb9465bee23b368bf6c9e79c9658d664c67c1c3da2ef0fa4b2457535c16cc2",+ "chars": 1551,"summary_state": "stale","summary": "This test ensures that the generated skill template adheres to the expected format and contains the necessary components for functionality.","crux": {@@ -11486,12 +11500,12 @@"name": "graph-map.test.ts","kind": "file","path": "test/graph-map.test.ts",- "span": "L1-L449",+ "span": "L1-L487","signature": null,"exported": true,"origin": "ast",- "body_hash": "e1ad7fedef64ce3f62d0218a6b53bea3e3073777e6fc07d05a77f7a8d587371f",- "chars": 18768,+ "body_hash": "617c2dedc79ac3c36e7f89e095f21cf98268432f6b80d7e4afb5c18db71d33cc",+ "chars": 20498,"summary_state": "stale","summary": "This file contains tests for the `buildRepoMap` and `formatRepoMap` functions, ensuring they correctly process and format repository data.","crux": {@@ -11504,7 +11518,7 @@"name": "bigFixture","kind": "function","path": "test/graph-map.test.ts",- "span": "L381-L400",+ "span": "L419-L438","signature": "function bigFixture(): GraphV1","exported": false,"origin": "ast",@@ -11603,7 +11617,7 @@"name": "twoScopeFixture","kind": "function","path": "test/graph-map.test.ts",- "span": "L249-L264",+ "span": "L287-L302","signature": "function twoScopeFixture(): GraphV1","exported": false,"origin": "ast",@@ -12684,6 +12698,49 @@"summary": null,"crux": null},+ {+ "id": "test/savings.test.ts",+ "name": "savings.test.ts",+ "kind": "file",+ "path": "test/savings.test.ts",+ "span": "L1-L66",+ "signature": null,+ "exported": true,+ "origin": "ast",+ "body_hash": "c72e0b930bc106083b6a69b366c83e3b4f96d816cb4be4f62c45578fdb3ae21b",+ "chars": 2776,+ "summary_state": "pending",+ "summary": null,+ "crux": null+ },+ {+ "id": "test/savings.test.ts#fileNode",+ "name": "fileNode",+ "kind": "function",+ "path": "test/savings.test.ts",+ "span": "L10-L26",+ "signature": "function fileNode(path: string, chars?: number): NodeV1",+ "exported": false,+ "origin": "ast",+ "body_hash": "a511e0353d36f5c20370f000f5314d5ee3880e70ae68027ec09cdb17c98c35a4",+ "summary_state": "pending",+ "summary": null,+ "crux": null+ },+ {+ "id": "test/savings.test.ts#graphOf",+ "name": "graphOf",+ "kind": "function",+ "path": "test/savings.test.ts",+ "span": "L28-L30",+ "signature": "function graphOf(nodes: NodeV1[]): GraphV1",+ "exported": false,+ "origin": "ast",+ "body_hash": "24dbd41a16d5d267b695d299a8510734f9d6cee0ce8608bd7a0530520c0f4ebd",+ "summary_state": "pending",+ "summary": null,+ "crux": null+ },{"id": "test/search-grep.test.ts","name": "search-grep.test.ts",@@ -16339,6 +16396,12 @@"relation": "contains","confidence": "extracted"},+ {+ "source": "src/claude/hooks.ts",+ "target": "src/claude/hooks.ts#handleToolSavings",+ "relation": "contains",+ "confidence": "extracted"+ },{"source": "src/claude/hooks.ts","target": "src/claude/hooks.ts#lastFileScopeHint",@@ -16495,6 +16558,18 @@"relation": "calls","confidence": "inferred"},+ {+ "source": "src/claude/hooks.ts#handleToolSavings",+ "target": "src/claude/state.ts#readSession",+ "relation": "calls",+ "confidence": "inferred"+ },+ {+ "source": "src/claude/hooks.ts#handleToolSavings",+ "target": "src/claude/state.ts#writeSession",+ "relation": "calls",+ "confidence": "inferred"+ },{"source": "src/claude/hooks.ts#lastFileScopeHint","target": "src/claude/stats.ts#readWiring",@@ -16549,6 +16624,12 @@"relation": "calls","confidence": "extracted"},+ {+ "source": "src/claude/hooks.ts#main",+ "target": "src/claude/hooks.ts#handleToolSavings",+ "relation": "calls",+ "confidence": "extracted"+ },{"source": "src/claude/hooks.ts#main","target": "src/claude/hooks.ts#lastFileScopeHint",@@ -23395,6 +23476,12 @@"relation": "calls","confidence": "inferred"},+ {+ "source": "test/claude-hooks.test.ts",+ "target": "src/claude/state.ts#readSession",+ "relation": "calls",+ "confidence": "inferred"+ },{"source": "test/claude-hooks.test.ts","target": "src/claude/state.ts#readStats",@@ -23413,6 +23500,12 @@"relation": "calls","confidence": "inferred"},+ {+ "source": "test/claude-hooks.test.ts",+ "target": "src/context/savings.ts#savingsFooter",+ "relation": "calls",+ "confidence": "inferred"+ },{"source": "test/claude-hooks.test.ts","target": "test/claude-hooks.test.ts#runWithStdin",@@ -23503,6 +23596,12 @@"relation": "imports","confidence": "extracted"},+ {+ "source": "test/claude-hooks.test.ts",+ "target": "src/context/savings.ts",+ "relation": "imports",+ "confidence": "extracted"+ },{"source": "test/claude-init.test.ts","target": "src/claude/init.ts#runInit",@@ -26245,6 +26344,66 @@"relation": "imports","confidence": "extracted"},+ {+ "source": "test/savings.test.ts",+ "target": "src/context/savings.ts#savingsFooter",+ "relation": "calls",+ "confidence": "inferred"+ },+ {+ "source": "test/savings.test.ts",+ "target": "src/context/savings.ts#savingsFor",+ "relation": "calls",+ "confidence": "inferred"+ },+ {+ "source": "test/savings.test.ts",+ "target": "test/savings.test.ts#fileNode",+ "relation": "calls",+ "confidence": "extracted"+ },+ {+ "source": "test/savings.test.ts",+ "target": "test/savings.test.ts#graphOf",+ "relation": "calls",+ "confidence": "extracted"+ },+ {+ "source": "test/savings.test.ts",+ "target": "test/savings.test.ts#fileNode",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "test/savings.test.ts",+ "target": "test/savings.test.ts#graphOf",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "test/savings.test.ts",+ "target": "node:assert/strict",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "test/savings.test.ts",+ "target": "node:test",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "test/savings.test.ts",+ "target": "src/context/savings.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "test/savings.test.ts",+ "target": "src/graph/types.ts",+ "relation": "imports",+ "confidence": "extracted"+ },{"source": "test/search-grep.test.ts","target": "src/search/grep-cli.ts#zeroHitNote",diff --git a/graft/INDEX.md b/graft/INDEX.mdindex 81b20a85..05a69e9f 100644--- a/graft/INDEX.md+++ b/graft/INDEX.md@@ -38,5 +38,5 @@ filename here, or run `graft ask "<task>"`. Each node carries prose plus exact## Files-120 per-file wiring cards mirror the source tree under `graft/` (109 carry extracted symbols). They are deliberately not enumerated here —+121 per-file wiring cards mirror the source tree under `graft/` (110 carry extracted symbols). They are deliberately not enumerated here —`grep` a symbol or `find`/`ls` a filename under `graft/` to land on the card for that file.diff --git a/graft/configuration-management.md b/graft/configuration-management.mdindex 7d1ea85d..54e75c01 100644--- a/graft/configuration-management.md+++ b/graft/configuration-management.md@@ -32,13 +32,13 @@ covers:at: 'src/claude/settings-merge.ts:L7-L9'- symbol: graftBlockskind: function- at: 'src/claude/settings-merge.ts:L10-L17'+ at: 'src/claude/settings-merge.ts:L10-L24'- symbol: isGraftHookEntrykind: function- at: 'src/claude/settings-merge.ts:L18-L20'+ at: 'src/claude/settings-merge.ts:L25-L27'- symbol: mergeGraftSettingskind: function- at: 'src/claude/settings-merge.ts:L22-L55'+ at: 'src/claude/settings-merge.ts:L29-L62'---<!-- context:generated:start -->## Summarydiff --git a/graft/src/ask/ask.md b/graft/src/ask/ask.mdindex d46d0eec..70da269e 100644--- a/graft/src/ask/ask.md+++ b/graft/src/ask/ask.md@@ -37,5 +37,5 @@ This module provides a mechanism to process natural language queries and return- toTokens · function · L890-L892 — Converts a character count into a token count, facilitating the processing of text for queries.- formatAsk · function · L895-L937 — Formats the results of an ask query into a string for presentation, ensuring clarity and usability.- escalationNudge · function · L944-L951 — function escalationNudge(r: AskResult): string-- askSavingsFooter · function · L956-L968 — function askSavingsFooter(r: AskResult, body: string): string-- scopeFooterLines · function · L975-L987 — function scopeFooterLines(r: AskResult): string[]+- askSavingsFooter · function · L956-L969 — function askSavingsFooter(r: AskResult, body: string): string+- scopeFooterLines · function · L976-L988 — function scopeFooterLines(r: AskResult): string[]diff --git a/graft/src/claude/hooks.md b/graft/src/claude/hooks.mdindex 71c03db3..b24490d3 100644--- a/graft/src/claude/hooks.md+++ b/graft/src/claude/hooks.md@@ -11,5 +11,6 @@ Handles various events related to the Graft system, including session management- emit · function · L53-L55 — Outputs a JSON object to standard output for event tracking.- handlePostEdit · function · L57-L63 — Handles post-edit events by updating stats and emitting relevant information.- lastFileScopeHint · function · L80-L105 — function lastFileScopeHint(dir: string, lastFile: string | null | undefined): string | null-- handleStop · function · L107-L121 — Handles the stop event by syncing state if necessary.-- main · function · L123-L166 — Main entry point for handling various events and orchestrating the application logic.+- handleToolSavings · function · L113-L123 — function handleToolSavings(input: any, dir: string): void+- handleStop · function · L125-L139 — Handles the stop event by syncing state if necessary.+- main · function · L141-L186 — Main entry point for handling various events and orchestrating the application logic.diff --git a/graft/src/claude/settings-merge.md b/graft/src/claude/settings-merge.mdindex 85a5da61..9cc38d57 100644--- a/graft/src/claude/settings-merge.md+++ b/graft/src/claude/settings-merge.md@@ -4,6 +4,6 @@ Merges existing settings with new graft configurations, ensuring proper command- Json · type · L1-L1 — Defines a flexible JSON type for various settings configurations.- hookCmd · function · L7-L9 — Generates a command string to execute a specified hook in the Graft environment.-- graftBlocks · function · L10-L17 — Creates a mapping of events to their corresponding Graft command hooks for processing user actions.-- isGraftHookEntry · function · L18-L20 — Checks if a given entry is a Graft hook by inspecting its command reference.-- mergeGraftSettings · function · L22-L55 — Merges existing settings with Graft-specific configurations, ensuring idempotency and compliance with Graft rules.+- graftBlocks · function · L10-L24 — Creates a mapping of events to their corresponding Graft command hooks for processing user actions.+- isGraftHookEntry · function · L25-L27 — Checks if a given entry is a Graft hook by inspecting its command reference.+- mergeGraftSettings · function · L29-L62 — Merges existing settings with Graft-specific configurations, ensuring idempotency and compliance with Graft rules.diff --git a/graft/src/claude/skill-template.md b/graft/src/claude/skill-template.mdindex 463c63d3..927b8827 100644--- a/graft/src/claude/skill-template.md+++ b/graft/src/claude/skill-template.md@@ -2,4 +2,4 @@Provides a structured template for the graft Claude Code skill, enabling efficient onboarding and understanding of the codebase.-- skillTemplate · function · L6-L92 — Generates a markdown string that serves as a comprehensive guide for using the graft tool effectively within a code repository.+- skillTemplate · function · L6-L101 — Generates a markdown string that serves as a comprehensive guide for using the graft tool effectively within a code repository.diff --git a/graft/src/context/savings.md b/graft/src/context/savings.mdindex 53ea6afc..b708f7d9 100644--- a/graft/src/context/savings.md+++ b/graft/src/context/savings.md@@ -4,4 +4,4 @@- toTokens · function · L25-L27 — function toTokens(chars: number): number- fileSizes · function · L32-L37 — function fileSizes(graph: GraphV1): Map<string, number>- savingsFor · function · L42-L53 — function savingsFor(graph: GraphV1, paths: Iterable<string>): Savings | undefined-- savingsFooter · function · L60-L72 — function savingsFooter(body: string, saved: Savings | undefined): string+- savingsFooter · function · L69-L82 — function savingsFooter(body: string, saved: Savings | undefined): stringdiff --git a/graft/src/graph/map.md b/graft/src/graph/map.mdindex e055d8ff..2ebdceef 100644--- a/graft/src/graph/map.md+++ b/graft/src/graph/map.md@@ -3,22 +3,22 @@Builds a structured representation of a repository's file and symbol organization based on their relationships, facilitating easier navigation and understanding of the codebase.- Hub · interface · L27-L33 — Defines the structure of a hub in the repository map, capturing its essential attributes for identification and ranking.-- DirEntry · interface · L35-L41 — Represents a directory entry in the repository map, summarizing its contents and associated hubs for better navigation.-- ScopeGroup · interface · L46-L53 — interface ScopeGroup-- RepoMap · interface · L55-L75 — Encapsulates the entire repository map structure, providing a comprehensive overview of files, symbols, and their relationships.-- BuildRepoMapOptions · interface · L77-L84 — Specifies options for building the repository map, allowing customization of directory and hub limits.-- dirKey · function · L96-L99 — Generates a directory key based on the specified depth, facilitating the grouping of files in the repository map.-- computeInDegree · function · L104-L111 — Calculates the in-degree of nodes in the graph, determining the number of incoming edges for each target, which is crucial for identifying hubs.-- topHubs · function · L116-L122 — Identifies the top hubs based on in-degree, ensuring that only significant nodes are included in the repository map.-- sortedLanguages · function · L124-L131 — Sorts and deduplicates the programming languages used in the repository, enhancing the metadata of the repository map.-- computeDirEntries · function · L144-L206 — function computeDirEntries( nodes: NodeV1[], inDegree: Map<string, number>, maxDirs: number, hubsPerDir: number, stripPrefix: string, ): { dirs: DirEntry[]; dropped: number }-- relPath · function · L154-L155 — relPath = (path: string): string-- depthFor · function · L175-L175 — depthFor = (rp: string): number-- fullPath · function · L191-L192 — fullPath = (relKey: string): string-- buildRepoMap · function · L219-L269 — Constructs the repository map from a given graph, organizing files and symbols into a structured format for easy access.-- basenameOf · function · L273-L276 — Extracts the base name from a file path, simplifying the representation of file names in the output.-- formatDirHub · function · L278-L280 — Formats a hub's information for display, providing a user-friendly representation of its attributes.-- formatDirLine · function · L282-L287 — Formats a directory entry for display, summarizing its contents and associated hubs in a readable format.-- formatHotspot · function · L289-L291 — Formats a hotspot's information for display, detailing its attributes in a clear manner.-- droppedNote · function · L294-L297 — function droppedNote(dropped: number): string | null-- formatRepoMap · function · L305-L330 — Renders the repository map as a human-readable string, summarizing its contents and structure for easy understanding.+- DirEntry · interface · L35-L47 — Represents a directory entry in the repository map, summarizing its contents and associated hubs for better navigation.+- ScopeGroup · interface · L52-L59 — interface ScopeGroup+- RepoMap · interface · L61-L81 — Encapsulates the entire repository map structure, providing a comprehensive overview of files, symbols, and their relationships.+- BuildRepoMapOptions · interface · L83-L90 — Specifies options for building the repository map, allowing customization of directory and hub limits.+- dirKey · function · L102-L105 — Generates a directory key based on the specified depth, facilitating the grouping of files in the repository map.+- computeInDegree · function · L110-L117 — Calculates the in-degree of nodes in the graph, determining the number of incoming edges for each target, which is crucial for identifying hubs.+- topHubs · function · L122-L128 — Identifies the top hubs based on in-degree, ensuring that only significant nodes are included in the repository map.+- sortedLanguages · function · L130-L137 — Sorts and deduplicates the programming languages used in the repository, enhancing the metadata of the repository map.+- computeDirEntries · function · L150-L220 — function computeDirEntries( nodes: NodeV1[], inDegree: Map<string, number>, maxDirs: number, hubsPerDir: number, stripPrefix: string, ): { dirs: DirEntry[]; dropped: number }+- relPath · function · L160-L161 — relPath = (path: string): string+- depthFor · function · L181-L181 — depthFor = (rp: string): number+- fullPath · function · L197-L198 — fullPath = (relKey: string): string+- buildRepoMap · function · L233-L283 — Constructs the repository map from a given graph, organizing files and symbols into a structured format for easy access.+- basenameOf · function · L287-L290 — Extracts the base name from a file path, simplifying the representation of file names in the output.+- formatDirHub · function · L292-L294 — Formats a hub's information for display, providing a user-friendly representation of its attributes.+- formatDirLine · function · L296-L305 — Formats a directory entry for display, summarizing its contents and associated hubs in a readable format.+- formatHotspot · function · L307-L309 — Formats a hotspot's information for display, detailing its attributes in a clear manner.+- droppedNote · function · L312-L315 — function droppedNote(dropped: number): string | null+- formatRepoMap · function · L323-L348 — Renders the repository map as a human-readable string, summarizing its contents and structure for easy understanding.diff --git a/graft/test/claude-hooks.test.md b/graft/test/claude-hooks.test.mdindex 6aef9638..c334f08a 100644--- a/graft/test/claude-hooks.test.md+++ b/graft/test/claude-hooks.test.md@@ -2,7 +2,7 @@This file contains tests for the functionality of the graft hooks in the Claude project, ensuring that edits are detected and state is managed correctly.-- runWithStdin · function · L38-L41 — This function sets up the environment to run a given asynchronous function with specified input from stdin, managing the environment variable for the duration of the execution.-- fakeBuild · function · L84-L87 — This function simulates a build process by writing a mock wiring.json file to the specified directory, allowing tests to verify behavior based on the build output.-- writeMultiScopeWiring · function · L126-L145 — function writeMultiScopeWiring(d: string): void-- writeAskArgsStub · function · L247-L258 — function writeAskArgsStub(d: string): { stub: string; argsFile: string }+- runWithStdin · function · L39-L42 — This function sets up the environment to run a given asynchronous function with specified input from stdin, managing the environment variable for the duration of the execution.+- fakeBuild · function · L85-L88 — This function simulates a build process by writing a mock wiring.json file to the specified directory, allowing tests to verify behavior based on the build output.+- writeMultiScopeWiring · function · L127-L146 — function writeMultiScopeWiring(d: string): void+- writeAskArgsStub · function · L248-L259 — function writeAskArgsStub(d: string): { stub: string; argsFile: string }diff --git a/graft/test/graph-map.test.md b/graft/test/graph-map.test.mdindex 59b13db4..7c9cd799 100644--- a/graft/test/graph-map.test.md+++ b/graft/test/graph-map.test.md@@ -7,5 +7,5 @@ This file contains tests for the `buildRepoMap` and `formatRepoMap` functions, e- edge · function · L51-L53 — Defines a connection between two nodes in the graph, representing relationships such as function calls.- graphOf · function · L55-L61 — Constructs a graph structure from nodes and edges, serving as the foundational data for repository mapping.- graphOfWithScopes · function · L66-L70 — function graphOfWithScopes(nodes: NodeV1[], edges: EdgeV1[], scopes: ScopeV1[]): GraphV1-- twoScopeFixture · function · L249-L264 — function twoScopeFixture(): GraphV1-- bigFixture · function · L381-L400 — Creates a large fixture graph for testing, simulating a repository with multiple directories and symbols.+- twoScopeFixture · function · L287-L302 — function twoScopeFixture(): GraphV1+- bigFixture · function · L419-L438 — Creates a large fixture graph for testing, simulating a repository with multiple directories and symbols.diff --git a/graft/test/savings.test.md b/graft/test/savings.test.mdnew file mode 100644index 00000000..353b5df3--- /dev/null+++ b/graft/test/savings.test.md@@ -0,0 +1,4 @@+# test/savings.test.ts++- fileNode · function · L10-L26 — function fileNode(path: string, chars?: number): NodeV1+- graphOf · function · L28-L30 — function graphOf(nodes: NodeV1[]): GraphV1diff --git a/graft/testing-and-validation.md b/graft/testing-and-validation.mdindex 110f6f3d..c10dc635 100644--- a/graft/testing-and-validation.md+++ b/graft/testing-and-validation.md@@ -106,16 +106,16 @@ covers:at: 'test/claude-format.test.ts:L105-L105'- symbol: runWithStdinkind: function- at: 'test/claude-hooks.test.ts:L38-L41'+ at: 'test/claude-hooks.test.ts:L39-L42'- symbol: fakeBuildkind: function- at: 'test/claude-hooks.test.ts:L84-L87'+ at: 'test/claude-hooks.test.ts:L85-L88'- symbol: writeMultiScopeWiringkind: function- at: 'test/claude-hooks.test.ts:L126-L145'+ at: 'test/claude-hooks.test.ts:L127-L146'- symbol: writeAskArgsStubkind: function- at: 'test/claude-hooks.test.ts:L247-L258'+ at: 'test/claude-hooks.test.ts:L248-L259'- symbol: freshkind: functionat: 'test/claude-init.test.ts:L10-L10'@@ -181,10 +181,10 @@ covers:at: 'test/graph-map.test.ts:L66-L70'- symbol: twoScopeFixturekind: function- at: 'test/graph-map.test.ts:L249-L264'+ at: 'test/graph-map.test.ts:L287-L302'- symbol: bigFixturekind: function- at: 'test/graph-map.test.ts:L381-L400'+ at: 'test/graph-map.test.ts:L419-L438'- symbol: 'n'kind: functionat: 'test/graph-resolve-typed.test.ts:L6-L10'diff --git a/src/ask/ask.ts b/src/ask/ask.tsindex 9c7b56ae..a4ba6a63 100644--- a/src/ask/ask.ts+++ b/src/ask/ask.ts@@ -17,7 +17,7 @@ import { existsSync, readdirSync, readFileSync } from "node:fs";import { join, resolve } from "node:path";import matter from "gray-matter";import { contextDirFor } from "../context/node-file.js";-import { savingsFooter, savingsFor, type Savings } from "../context/savings.js";+import { savingsFooter, savingsFor, SAVINGS_TURN_NUDGE, type Savings } from "../context/savings.js";import { loadGraphCached, loadAskIndexCached } from "../graph/load.js";import { pathUnderPrefix, scopeLabel, scopeOf, scopesHereClause, scopesOfGraph } from "../graph/scopes.js";import { resolveSymbol } from "../graph/traverse.js";@@ -963,7 +963,8 @@ function askSavingsFooter(r: AskResult, body: string): string {return (`\n\n[graft] tokens saved ≈ ${saved.toLocaleString()} (${pct}%) — this pack ≈ ` +`${pack.toLocaleString()} tok vs reading the ${r.saved.files} source file(s) whole ≈ ` +- `${base.toLocaleString()} tok. Estimate (baseline = those files read in full).`+ `${base.toLocaleString()} tok. Estimate (baseline = those files read in full).` ++ SAVINGS_TURN_NUDGE);}diff --git a/src/claude/hooks.ts b/src/claude/hooks.tsindex 968672b4..046e0605 100644--- a/src/claude/hooks.ts+++ b/src/claude/hooks.ts@@ -104,6 +104,24 @@ export function lastFileScopeHint(dir: string, lastFile: string | null | undefin}}+/** PostToolUse on a graft retrieval tool. Its rendered output carries one (or+ * more) `[graft] tokens saved ≈ N` footers — the same numbers the agent just+ * read. Sum them and add to the session's running total so the statusline's+ * `~N tok saved` reflects what graft saved this session, across CLI and MCP.+ * Pure parse of the payload the hook already received (no re-run), and a no-op+ * unless a footer is present — so it stays cheap on unrelated Bash calls. */+function handleToolSavings(input: any, dir: string): void {+ const blob = JSON.stringify(input?.tool_response ?? input ?? '');+ let total = 0;+ for (const m of blob.matchAll(/\[graft\] tokens saved ≈ ([\d,]+)/g))+ total += Number(m[1].replace(/,/g, '')) || 0;+ if (total <= 0) return;+ const id = input?.session_id || 'default';+ const s = readSession(dir, id);+ s.savedTokens = (s.savedTokens ?? 0) + total;+ writeSession(dir, id, s);+}+function handleStop(dir: string): void {// sync-run.js ships next to this module inside the package, so it resolves in// any repo that installs graft (not just graft's own). Defensive existsSync:@@ -134,6 +152,8 @@ export async function main(event: string): Promise<void> {if (event === 'post-edit') { await handlePostEdit(input, dir); return; }+ if (event === 'tool-savings') { handleToolSavings(input, dir); return; }+if (event === 'stop') { handleStop(dir); return; }if (event === 'post-edit-sync') { await handlePostEdit(input, dir); handleStop(dir); return; }diff --git a/src/claude/settings-merge.ts b/src/claude/settings-merge.tsindex d0cdd244..f1aeadc4 100644--- a/src/claude/settings-merge.ts+++ b/src/claude/settings-merge.ts@@ -7,12 +7,19 @@ const ALLOW_ENTRIES = ['Bash(graft:*)', 'Bash(npx graft:*)'];function hookCmd(arg: string): string {return `node "\${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-hooks.cjs" ${arg}`;}-function graftBlocks(): Record<string, Json> {+function graftBlocks(): Record<string, Json[]> {return {- PostToolUse: { matcher: 'Write|Edit|MultiEdit', hooks: [{ type: 'command', command: hookCmd('post-edit'), timeout: 10000 }] },- UserPromptSubmit: { hooks: [{ type: 'command', command: hookCmd('prompt'), timeout: 8000 }] },- SessionStart: { hooks: [{ type: 'command', command: hookCmd('session-start'), timeout: 8000 }] },- Stop: { hooks: [{ type: 'command', command: hookCmd('stop'), timeout: 8000 }] },+ PostToolUse: [+ { matcher: 'Write|Edit|MultiEdit', hooks: [{ type: 'command', command: hookCmd('post-edit'), timeout: 10000 }] },+ // A retrieval tool (CLI `graft …` via Bash, or the `graft_*` MCP tools) prints a+ // `[graft] tokens saved ≈ N` footer; this hook sums it into the session total the+ // statusline shows. Broad matcher, but the handler no-ops instantly unless a footer+ // is actually present, so non-graft Bash calls cost only a stdin read.+ { matcher: 'Bash|mcp__graft__', hooks: [{ type: 'command', command: hookCmd('tool-savings'), timeout: 8000 }] },+ ],+ UserPromptSubmit: [{ hooks: [{ type: 'command', command: hookCmd('prompt'), timeout: 8000 }] }],+ SessionStart: [{ hooks: [{ type: 'command', command: hookCmd('session-start'), timeout: 8000 }] }],+ Stop: [{ hooks: [{ type: 'command', command: hookCmd('stop'), timeout: 8000 }] }],};}function isGraftHookEntry(entry: Json): boolean {@@ -32,10 +39,10 @@ export function mergeGraftSettings(existing: Json): { merged: Json; warnings: stwarnings.push('Existing subagentStatusLine left untouched.');merged.hooks = { ...(merged.hooks ?? {}) };- for (const [event, block] of Object.entries(graftBlocks())) {+ for (const [event, blocks] of Object.entries(graftBlocks())) {const prior = Array.isArray(merged.hooks[event]) ? merged.hooks[event] : [];const foreign = prior.filter((e: Json) => !isGraftHookEntry(e)); // drop old Graft entries → idempotent- merged.hooks[event] = [...foreign, block];+ merged.hooks[event] = [...foreign, ...blocks];}const footer = Array.isArray(merged.footerLinksRegexes) ? [...merged.footerLinksRegexes] : [];diff --git a/src/claude/skill-template.ts b/src/claude/skill-template.tsindex a995bcc6..0f49c036 100644--- a/src/claude/skill-template.ts+++ b/src/claude/skill-template.ts@@ -84,6 +84,15 @@ available.If a returned span is truncated ("+N more lines"), open the file at that exactrange before finalizing.+**Report what graft saved — every turn.** Each retrieval tool ends its output+with a \`[graft] tokens saved ≈ N\` line: the estimated tokens that one call+saved versus reading the files it covers whole. Whenever you used any graft tool+in a turn, close your reply with a one-line tally that sums those numbers across+every graft call you made — e.g. \`🌱 graft saved ~12,400 tokens this turn (3+calls)\`. A call with no footer (tiny files, where the pointers cost as much as+the source) saved nothing — skip it. This is the per-turn figure; the statusline+carries the running session total.+If a node genuinely lacks a detail you need, ask for a more specific node, andif it still lacks it, read the source — at the exact file:line the node pointsto, not the whole file. Reading whole source files to build understanding isdiff --git a/src/context/savings.ts b/src/context/savings.tsindex ec9327f8..034aacfe 100644--- a/src/context/savings.ts+++ b/src/context/savings.ts@@ -52,6 +52,15 @@ export function savingsFor(graph: GraphV1, paths: Iterable<string>): Savings | ureturn files > 0 ? { files, baselineChars } : undefined;}+/** Appended to every retrieval footer so the agent reports the turn's running+ * total even when SKILL.md isn't loaded — the instruction rides along in the+ * tool output itself. Deliberately free of the `[graft] tokens saved ≈ <n>`+ * pattern so the PostToolUse accumulator that parses these footers never+ * mistakes the nudge (or its example) for a second number to count. */+export const SAVINGS_TURN_NUDGE =+ ' At the end of your reply, tell the user the total graft tokens saved this ' ++ 'turn — sum each such line across your graft calls — e.g. "🌱 graft saved ~N tokens this turn".';+/** The one-line footer a command appends to its text output, so the agent gets* the number for free — no extra tool call. `body` is the exact rendered output* the agent reads (the pack). Returns "" when there's nothing honest to claim:@@ -67,6 +76,7 @@ export function savingsFooter(body: string, saved: Savings | undefined): stringreturn (`\n\n[graft] tokens saved ≈ ${delta.toLocaleString()} (${pct}%) — this output ≈ ` +`${pack.toLocaleString()} tok vs reading the ${saved.files} file(s) it covers whole ≈ ` +- `${base.toLocaleString()} tok (estimate).`+ `${base.toLocaleString()} tok (estimate).` ++ SAVINGS_TURN_NUDGE);}diff --git a/test/claude-hooks.test.ts b/test/claude-hooks.test.tsindex d2933fec..60215d51 100644--- a/test/claude-hooks.test.ts+++ b/test/claude-hooks.test.ts@@ -4,8 +4,9 @@ import { existsSync, mkdtempSync, mkdirSync, writeFileSync, readFileSync } fromimport { tmpdir } from 'node:os';import { join } from 'node:path';import { underGraft, main, lastFileScopeHint } from '../src/claude/hooks.js';-import { readStats } from '../src/claude/state.js';+import { readStats, readSession } from '../src/claude/state.js';import { runSync } from '../src/claude/sync-run.js';+import { savingsFooter } from '../src/context/savings.js';import { writeStats, emptyStats, acquireLock } from '../src/claude/state.js';test('underGraft detects edits inside graft/', () => {@@ -361,3 +362,81 @@ test('prompt branch stays silent and writes no session when graft is not built',assert.equal(chunks.join(''), '', 'no stdout when graft ask unavailable (no dist/cli.js in temp dir)');assert.equal(existsSync(join(d, 'graft', '.cache', 'session', 'p1.json')), false, 'no session file on no-op');});++test('tool-savings sums the [graft] footer into the session total, keyed by session_id', async () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-savings-'));+ process.env.CLAUDE_PROJECT_DIR = d;+ try {+ // A graft tool result the agent just read (shape mirrors a Bash tool_response).+ const stdin = JSON.stringify({+ session_id: 's1',+ tool_name: 'Bash',+ tool_response: { stdout: 'skeleton …\n\n[graft] tokens saved ≈ 2,181 (89%) — this output ≈ 258 tok …' },+ });+ await runWithStdin(stdin, () => main('tool-savings'));+ assert.equal(readSession(d, 's1').savedTokens, 2181);++ // A second graft call in the same session accumulates.+ const again = JSON.stringify({+ session_id: 's1',+ tool_response: { stdout: '[graft] tokens saved ≈ 7,510 (99%) — this output ≈ 57 tok …' },+ });+ await runWithStdin(again, () => main('tool-savings'));+ assert.equal(readSession(d, 's1').savedTokens, 2181 + 7510);++ // A different session keeps its own tally.+ assert.equal(readSession(d, 's2').savedTokens, 0);+ } finally {+ delete process.env.CLAUDE_PROJECT_DIR;+ }+});++test('tool-savings sums every footer when one payload carries several', async () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-savings-'));+ process.env.CLAUDE_PROJECT_DIR = d;+ try {+ const stdin = JSON.stringify({+ session_id: 'multi',+ tool_response: {+ stdout:+ 'graft callers …\n[graft] tokens saved ≈ 100 (90%) — …\n' ++ 'graft map …\n[graft] tokens saved ≈ 1,000 (99%) — …',+ },+ });+ await runWithStdin(stdin, () => main('tool-savings'));+ assert.equal(readSession(d, 'multi').savedTokens, 1100);+ } finally {+ delete process.env.CLAUDE_PROJECT_DIR;+ }+});++test('tool-savings is a no-op (no session file) when the tool output has no graft footer', async () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-savings-'));+ process.env.CLAUDE_PROJECT_DIR = d;+ try {+ const stdin = JSON.stringify({+ session_id: 'nofooter',+ tool_name: 'Bash',+ tool_response: { stdout: 'total 12\ndrwxr-xr-x ...' },+ });+ await runWithStdin(stdin, () => main('tool-savings'));+ assert.equal(existsSync(join(d, 'graft', '.cache', 'session', 'nofooter.json')), false, 'no write without a footer');+ } finally {+ delete process.env.CLAUDE_PROJECT_DIR;+ }+});++test('tool-savings counts a REAL savingsFooter (with the turn nudge) exactly once', async () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-savings-real-'));+ process.env.CLAUDE_PROJECT_DIR = d;+ try {+ // body ≈ 10 tok, baseline ≈ 2000 tok → footer claims ≈ 1990 saved. The nudge+ // (with its "🌱 graft saved ~N tokens" example) must NOT be double-counted.+ const footer = savingsFooter('x'.repeat(40), { files: 2, baselineChars: 8000 });+ const stdin = JSON.stringify({ session_id: 'real', tool_response: { stdout: `callers …${footer}` } });+ await runWithStdin(stdin, () => main('tool-savings'));+ assert.equal(readSession(d, 'real').savedTokens, 1990);+ } finally {+ delete process.env.CLAUDE_PROJECT_DIR;+ }+});diff --git a/test/claude-init.test.ts b/test/claude-init.test.tsindex 71183adc..804d3770 100644--- a/test/claude-init.test.ts+++ b/test/claude-init.test.ts@@ -58,7 +58,7 @@ test('runInit is idempotent', () => {runInit(d, { build: false });runInit(d, { build: false });const s = JSON.parse(readFileSync(join(d, '.claude', 'settings.json'), 'utf8'));- assert.equal(s.hooks.PostToolUse.length, 1);+ assert.equal(s.hooks.PostToolUse.length, 2); // post-edit + tool-savings, not duplicated on re-initassert.deepEqual(s.permissions.allow, ['Bash(graft:*)', 'Bash(npx graft:*)']);});diff --git a/test/claude-settings-merge.test.ts b/test/claude-settings-merge.test.tsindex a306e1ce..3d23427e 100644--- a/test/claude-settings-merge.test.ts+++ b/test/claude-settings-merge.test.ts@@ -13,6 +13,11 @@ test('empty settings gets the full Graft blocks', () => {for (const e of ['PostToolUse', 'UserPromptSubmit', 'SessionStart', 'Stop']) {assert.ok(merged.hooks[e][0].hooks[0].command.includes('graft-hooks.cjs'), `${e} wired`);}+ // PostToolUse carries a second graft block: the tokens-saved accumulator over+ // the retrieval tools (Bash `graft …` + the graft_* MCP tools).+ const savings = merged.hooks.PostToolUse[1];+ assert.equal(savings.matcher, 'Bash|mcp__graft__');+ assert.ok(savings.hooks[0].command.includes('tool-savings'), 'savings hook wired');assert.ok(merged.footerLinksRegexes.includes('graft/[\\w./-]+\\.md'));assert.deepEqual(warnings, []);});@@ -27,15 +32,17 @@ test('foreign statusLine is preserved with a warning; Graft not forced in', () =test('existing foreign hooks are preserved; Graft appended', () => {const existing = { hooks: { PostToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: 'mine.sh' }] }] } };const { merged } = mergeGraftSettings(existing);- assert.equal(merged.hooks.PostToolUse.length, 2);+ // foreign block + graft's two PostToolUse blocks (post-edit, tool-savings).+ assert.equal(merged.hooks.PostToolUse.length, 3);assert.equal(merged.hooks.PostToolUse[0].hooks[0].command, 'mine.sh');assert.ok(merged.hooks.PostToolUse[1].hooks[0].command.includes('graft-hooks.cjs'));+ assert.ok(merged.hooks.PostToolUse[2].hooks[0].command.includes('graft-hooks.cjs'));});test('re-running is idempotent (no duplicate Graft entries or footer)', () => {const once = mergeGraftSettings({}).merged;const twice = mergeGraftSettings(once).merged;- assert.equal(twice.hooks.PostToolUse.length, 1);+ assert.equal(twice.hooks.PostToolUse.length, 2); // post-edit + tool-savings, not duplicatedassert.equal(twice.hooks.Stop.length, 1);assert.equal(twice.footerLinksRegexes.filter((r: string) => r === 'graft/[\\w./-]+\\.md').length, 1);});diff --git a/test/claude-skill-template.test.ts b/test/claude-skill-template.test.tsindex 7f9ebde4..8bbfd096 100644--- a/test/claude-skill-template.test.ts+++ b/test/claude-skill-template.test.ts@@ -19,4 +19,6 @@ test('skill template is a well-formed SKILL.md', () => {assert.match(body, /graft map/, 'body tells the agent to orient with graft map before exploring');assert.match(body, /\[scope\/\]/, 'body teaches the [scope/] label on multi-scope hits');assert.match(body, /--in <scope>\//, 'body teaches narrowing with ask --in <scope>/');+ assert.match(body, /tokens saved/i, 'body references the tokens-saved footer');+ assert.match(body, /every turn/i, 'body tells the agent to report savings each turn');});diff --git a/test/savings.test.ts b/test/savings.test.tsnew file mode 100644index 00000000..59cb8b0f--- /dev/null+++ b/test/savings.test.ts@@ -0,0 +1,65 @@+/**+ * Tests for the shared "tokens saved" estimate ({@link savingsFor} ++ * {@link savingsFooter}) that every retrieval-style command routes through.+ */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { savingsFor, savingsFooter, toTokens } from '../src/context/savings.js';+import type { GraphV1, NodeV1 } from '../src/graph/types.js';++function fileNode(path: string, chars?: number): NodeV1 {+ return {+ id: path,+ name: path,+ kind: 'file',+ path,+ span: 'L1-L1',+ signature: null,+ exported: true,+ origin: 'ast',+ body_hash: '',+ summary_state: 'pending',+ summary: null,+ crux: null,+ chars,+ };+}++function graphOf(nodes: NodeV1[]): GraphV1 {+ return { meta: { version: 1, nodeCount: nodes.length, edgeCount: 0, languages: [] }, nodes, edges: [] };+}++test('savingsFor: sums the sizes of the distinct baseline files', () => {+ const g = graphOf([fileNode('a.ts', 400), fileNode('b.ts', 600)]);+ const s = savingsFor(g, ['a.ts', 'b.ts', 'a.ts']); // duplicate a.ts counted once+ assert.deepEqual(s, { files: 2, baselineChars: 1000 });+});++test('savingsFor: skips files with no known size, returns undefined when none are sized', () => {+ const g = graphOf([fileNode('a.ts'), fileNode('b.ts', 800)]);+ assert.deepEqual(savingsFor(g, ['a.ts', 'b.ts']), { files: 1, baselineChars: 800 });+ assert.equal(savingsFor(graphOf([fileNode('a.ts')]), ['a.ts']), undefined);+ assert.equal(savingsFor(g, ['missing.ts']), undefined);+});++test('savingsFooter: reports saved tokens and percent when the output is smaller', () => {+ const body = 'x'.repeat(40); // ≈ 10 tok+ const footer = savingsFooter(body, { files: 2, baselineChars: 8000 }); // baseline ≈ 2000 tok+ assert.match(footer, /tokens saved ≈ [\d,]+ \(\d+%\)/);+ assert.match(footer, /2 file\(s\)/);+ const base = toTokens(8000);+ assert.ok(footer.includes((base - toTokens(body.length)).toLocaleString()));+ // The nudge rides along so the agent reports the turn total without SKILL.md.+ assert.match(footer, /end of your reply/i);+ assert.match(footer, /graft saved ~N tokens this turn/);+ // The nudge must NOT introduce a second "[graft] tokens saved ≈ <n>" token —+ // the PostToolUse accumulator sums every such match, so a stray one double-counts.+ assert.equal((footer.match(/\[graft\] tokens saved ≈ [\d,]+/g) ?? []).length, 1);+});++test('savingsFooter: stays silent when there is nothing honest to claim', () => {+ assert.equal(savingsFooter('anything', undefined), '');+ assert.equal(savingsFooter('anything', { files: 1, baselineChars: 0 }), '');+ // Baseline no bigger than the output itself (tiny file) → no claim.+ assert.equal(savingsFooter('x'.repeat(1000), { files: 1, baselineChars: 40 }), '');+});