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
fix: put the tokens-saved line on top of tool output
anirudhkumar-nanonets9c4a2e089c0e
diff --git a/.claude/skills/graft/SKILL.md b/.claude/skills/graft/SKILL.mdindex 54fef61b..4302ec8e 100644--- a/.claude/skills/graft/SKILL.md+++ b/.claude/skills/graft/SKILL.md@@ -122,13 +122,19 @@ you already know where you're working, narrow with `graft ask "<task>" --in <scothe symbol to find where it lives now, or run `graft build` to refresh.## Report what graft saved, every turn-Each retrieval tool ends its output with a `[graft] tokens saved ≈ N` line: the-estimated tokens that call saved versus reading the files it covers whole.+Each retrieval tool **opens** its output with a `[graft] tokens saved ≈ N` line:+the estimated tokens that call saved versus reading the files it covers whole.Whenever you used any graft tool in a turn, close your reply with a one-linetally summing 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, so skip it.-This is the per-turn figure; the statusline carries the running session total.+`🌱 graft saved ~12,400 tokens this turn (3 calls)`. A call with no such line+(tiny files, where the pointers cost as much as the source) saved nothing, so+skip it. This is the per-turn figure; the statusline carries the running+session total.++**Never pipe a graft command through `head`, `tail`, or `sed -n`.** Every tool+is already capped and states what it dropped; clipping it costs you hits you+asked for, and it silently drops the savings line the statusline's running+total is parsed from.## When graft isn't enough- Span truncated ("+N more lines"): open the file at that exact range.diff --git a/package-lock.json b/package-lock.jsonindex 8c9858da..4cada95d 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "@nanonets/graft",- "version": "0.8.0",+ "version": "0.9.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@nanonets/graft",- "version": "0.8.0",+ "version": "0.9.1","hasInstallScript": true,"license": "MIT","dependencies": {diff --git a/package.json b/package.jsonindex 8f78e073..a5328e98 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "@nanonets/graft",- "version": "0.9.0",+ "version": "0.9.1","description": "Build a repo's context graph as a folder of linked markdown files that live in the repo and stay in sync with the code through git.","keywords": ["ai",diff --git a/src/ask/ask.ts b/src/ask/ask.tsindex e4b7408b..c4d8d474 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, SAVINGS_TURN_NUDGE, type Savings } from "../context/savings.js";+import { withSavings, savingsFor, SAVINGS_TURN_NUDGE, type Savings } from "../context/savings.js";import { loadGraphCached, loadAskIndexCached } from "../graph/load.js";import {assertPrefixIndexed,@@ -914,7 +914,7 @@ export function formatSkeleton(r: SkeletonResult): string {return `- ${e.span} ${e.kind} ${e.name}${sig}${sum}`;});const body = `${head}\n${lines.join("\n")}`;- return body + savingsFooter(body, r.saved) + "\n";+ return withSavings(body, r.saved) + "\n";}/** Rough tokens for a byte length (≈ 4 chars/token; good enough for an estimate). */@@ -964,7 +964,8 @@ export function formatAsk(r: AskResult): string {lines.push(...scopeFooterLines(r));}const body = lines.join("\n").trimEnd();- return body + askSavingsFooter(r, body) + escalationNudge(r) + "\n";+ const savings = askSavingsLine(r, body);+ return (savings ? `${savings}\n\n${body}` : body) + escalationNudge(r) + "\n";}/** When a lexical `ask` returns thin/no results, the productive next move is a@@ -981,10 +982,12 @@ function escalationNudge(r: AskResult): string {);}-/** The one-line token-saving estimate `ask` appends in retriever mode, so the+/** The one-line token-saving estimate `ask` prepends in retriever mode, so the* agent gets the number for free in the tool output — no extra work on its end.- * `packChars` is measured from the rendered body: exactly what the agent reads. */-function askSavingsFooter(r: AskResult, body: string): string {+ * `packChars` is measured from the rendered body: exactly what the agent reads.+ * Header, not footer, for the reason documented on `withSavings`: a trailing+ * line dies to `head -N` and to host output truncation. */+function askSavingsLine(r: AskResult, body: string): string {if (!r.saved || r.saved.baselineChars <= 0) return "";const pack = toTokens(body.length);const base = toTokens(r.saved.baselineChars);@@ -992,7 +995,7 @@ function askSavingsFooter(r: AskResult, body: string): string {const saved = base - pack;const pct = Math.round((saved / base) * 100);return (- `\n\n[graft] tokens saved ≈ ${saved.toLocaleString()} (${pct}%) — this pack ≈ ` ++ `[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).` +SAVINGS_TURN_NUDGEdiff --git a/src/claude/format.ts b/src/claude/format.tsindex eec39b6e..38d5f888 100644--- a/src/claude/format.ts+++ b/src/claude/format.ts@@ -217,7 +217,7 @@ export function formatOrientation(indexMd: string, budgetBytes = 1500, staleNote` In a monorepo, add --in <path>/ to ask/grep/callers to scope to one sub-project; hits are labeled [scope/].\n` +` Already know the file or symbol to change? Go straight to it: graft grep "<symbol>", read the span, edit. Save ask for when you don't yet know where the code lives.\n` +` Refactor, rename, or multi-file change? Run graft callers <sym> --depth all FIRST to map every connected file; editing the primary file and stopping is the classic miss (platform siblings, a new file to extract).\n` +- `Each tool prints a "[graft] tokens saved ≈ N" footer; when you used graft this turn, close your reply with a one-line tally of the total saved (e.g. 🌱 graft saved ~12k tokens this turn, 3 calls).\n`;+ `Each tool opens its output with a "[graft] tokens saved ≈ N" line; when you used graft this turn, close your reply with a one-line tally of the total saved (e.g. 🌱 graft saved ~12k tokens this turn, 3 calls). Never pipe a graft command through head/tail — it is already capped, and clipping drops that line.\n`;const banner = staleNote ? `${staleNote}\n\n` : "";return `${banner}${directive}\nrepo map (graft/INDEX.md):\n${indexMd.slice(0, budgetBytes)}`;}diff --git a/src/claude/skill-template.ts b/src/claude/skill-template.tsindex a2184ab8..84740e3b 100644--- a/src/claude/skill-template.ts+++ b/src/claude/skill-template.ts@@ -128,13 +128,19 @@ you already know where you're working, narrow with \`graft ask "<task>" --in <scthe symbol to find where it lives now, or run \`graft build\` to refresh.## Report what graft saved, every turn-Each retrieval tool ends its output with a \`[graft] tokens saved ≈ N\` line: the-estimated tokens that call saved versus reading the files it covers whole.+Each retrieval tool **opens** its output with a \`[graft] tokens saved ≈ N\` line:+the estimated tokens that call saved versus reading the files it covers whole.Whenever you used any graft tool in a turn, close your reply with a one-linetally summing 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, so skip it.-This is the per-turn figure; the statusline carries the running session total.+\`🌱 graft saved ~12,400 tokens this turn (3 calls)\`. A call with no such line+(tiny files, where the pointers cost as much as the source) saved nothing, so+skip it. This is the per-turn figure; the statusline carries the running+session total.++**Never pipe a graft command through \`head\`, \`tail\`, or \`sed -n\`.** Every tool+is already capped and states what it dropped; clipping it costs you hits you+asked for, and it silently drops the savings line the statusline's running+total is parsed from.## When graft isn't enough- Span truncated ("+N more lines"): open the file at that exact range.diff --git a/src/context/savings.ts b/src/context/savings.tsindex 034aacfe..2848352b 100644--- a/src/context/savings.ts+++ b/src/context/savings.ts@@ -10,7 +10,7 @@** `graft ask` keeps its own footer (it carries an escalation nudge and feeds* the session saved-token counter); everything else — skeleton, grep, callers,- * map — routes through {@link savingsFor} + {@link savingsFooter} here.+ * map — routes through {@link savingsFor} + {@link withSavings} here.*/import type { GraphV1 } from '../graph/types.js';@@ -61,12 +61,12 @@ 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 one-line savings estimate for a command's 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:* no baseline, or the output isn't actually smaller than reading the files* (tiny files, where the pointers cost more than the source). */-export function savingsFooter(body: string, saved: Savings | undefined): string {+export function savingsLine(body: string, saved: Savings | undefined): string {if (!saved || saved.baselineChars <= 0) return '';const pack = toTokens(body.length);const base = toTokens(saved.baselineChars);@@ -74,9 +74,22 @@ export function savingsFooter(body: string, saved: Savings | undefined): stringconst delta = base - pack;const pct = Math.round((delta / base) * 100);return (- `\n\n[graft] tokens saved ≈ ${delta.toLocaleString()} (${pct}%) — this output ≈ ` ++ `[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).` +SAVINGS_TURN_NUDGE);}++/** Render `body` with the savings line on TOP.+ *+ * Deliberately a header, not a footer: agents routinely pipe graft through+ * `head -N` (and hosts truncate long tool output from the end), which silently+ * ate the number and, with it, the PostToolUse accumulator that feeds the+ * statusline's `~N tok saved`. Every clipper keeps the head, so the number+ * survives. Emitted once — a second copy at the bottom would be double-counted+ * by that accumulator's `matchAll`. */+export function withSavings(body: string, saved: Savings | undefined): string {+ const line = savingsLine(body, saved);+ return line ? `${line}\n\n${body}` : body;+}diff --git a/src/graph/map.ts b/src/graph/map.tsindex b7db88a0..d5d2fc4f 100644--- a/src/graph/map.ts+++ b/src/graph/map.ts@@ -22,7 +22,7 @@ import type { GraphV1, NodeV1 } from "./types.js";import { languageLabelOf } from "./extract.js";import { WALK_RELATIONS } from "./relations.js";import { scopeLabel, scopeOf, scopesOfGraph } from "./scopes.js";-import { savingsFooter, savingsFor, type Savings } from "../context/savings.js";+import { withSavings, savingsFor, type Savings } from "../context/savings.js";export interface Hub {name: string;@@ -346,5 +346,5 @@ export function formatRepoMap(map: RepoMap): string {lines.push(`hotspots: ${map.hotspots.map(formatHotspot).join(" ")}`);const body = lines.join("\n");- return body + savingsFooter(body, map.saved) + "\n";+ return withSavings(body, map.saved) + "\n";}diff --git a/src/graph/traverse-cli.ts b/src/graph/traverse-cli.tsindex 674b436b..462e07ae 100644--- a/src/graph/traverse-cli.ts+++ b/src/graph/traverse-cli.ts@@ -13,7 +13,7 @@*/import { resolve } from "node:path";import { contextDirFor } from "../context/node-file.js";-import { savingsFooter, savingsFor, type Savings } from "../context/savings.js";+import { withSavings, savingsFor, type Savings } from "../context/savings.js";import { loadGraphCached } from "./load.js";import { resolveSymbol, edgeWalk, type Direction, type EdgeHit } from "./traverse.js";import type { GraphV1, NodeV1 } from "./types.js";@@ -207,5 +207,5 @@ export function runCallersCommand(query: string, dir: string, opts: CallersCliOplines.push("");}const body = lines.join("\n").replace(/\n+$/, "\n");- process.stdout.write(body + savingsFooter(body, saved));+ process.stdout.write(withSavings(body, saved));}diff --git a/src/graph/workspace.ts b/src/graph/workspace.tsindex 1ec03f50..b272d400 100644--- a/src/graph/workspace.ts+++ b/src/graph/workspace.ts@@ -37,7 +37,7 @@ import { ask, type AskHit, type AskResult } from "../ask/ask.js";import { fuseScopes, STRONG_FLOOR, HIGH_FLOOR, type ScopedDoc } from "../ask/fuse.js";import { grepGraph, type GrepGroup, type GrepResult } from "../search/grep.js";import { formatGrepResult, zeroHitNote } from "../search/grep-cli.js";-import { savingsFooter, type Savings } from "../context/savings.js";+import { withSavings, type Savings } from "../context/savings.js";/** The parent index written to `<parent>/graft/workspace.json`. Nodes/edges* never live at the parent — they live in each child's own `graft/`. */@@ -429,7 +429,7 @@ export function federateCallers(else for (const h of hits) lines.push(hitLine(direction, h, showDepth));}const body = lines.join("\n");- blocks.push(body + savingsFooter(body, callersSavings(graph, results)));+ blocks.push(withSavings(body, callersSavings(graph, results)));}const cov = coverageNote(wg);diff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex f8167e73..bb98d2a8 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -11,7 +11,7 @@ import { ensureFreshChildren, ensureFreshGraph, refreshNote } from '../graph/refimport { contextDirFor } from '../context/node-file.js';import { resolveSymbol, edgeWalk, type Direction, type EdgeHit } from '../graph/traverse.js';import { callersSavings, headerOf, hitLine, looseNoteFor } from '../graph/traverse-cli.js';-import { savingsFooter } from '../context/savings.js';+import { withSavings } from '../context/savings.js';import { grepGraph } from '../search/grep.js';import { formatGrepResult, zeroHitNote } from '../search/grep-cli.js';import { buildRepoMap, formatRepoMap } from '../graph/map.js';@@ -309,7 +309,7 @@ function callSingleTool(const results = matches.map((m) => ({ symbol: m, hits: edgeWalk(w, m, direction, depth) }));const byId = new Map(results.map((r) => [r.symbol.id, r.hits]));const body = renderMatches(direction, depth > 1, matches, (m) => byId.get(m.id) ?? []);- const text = body + savingsFooter(body, callersSavings(w, results));+ const text = withSavings(body, callersSavings(w, results));return { text, isError: false };}case 'graft_find_all': {diff --git a/src/search/grep-cli.ts b/src/search/grep-cli.tsindex 952ab62c..d2c3fc36 100644--- a/src/search/grep-cli.ts+++ b/src/search/grep-cli.ts@@ -9,7 +9,7 @@*/import { resolve } from "node:path";import { contextDirFor } from "../context/node-file.js";-import { savingsFooter } from "../context/savings.js";+import { withSavings } from "../context/savings.js";import { loadGraphCached } from "../graph/load.js";import { grepGraph, type GrepGroup, type GrepResult } from "./grep.js";@@ -52,13 +52,14 @@ function truncationNote(result: GrepResult): string | null {/** Full human report: header, blank line, then one block per group (header +* indented hit lines), each block separated by a blank line. */export function formatGrepResult(result: GrepResult): string {- const blocks = [formatGrepHeader(result), "", ...result.groups.map((g) => formatGroup(g) + "\n")];- let out = blocks.join("\n").replace(/\n+$/, "\n");+ // The truncation note rides directly under the header, not at the bottom:+ // "never silent" has to survive a `head -N` too (same reason the savings+ // line is a header — see withSavings).const note = truncationNote(result);- if (note) out += note + "\n";- const footer = savingsFooter(out, result.saved);- if (footer) out += footer + "\n";- return out;+ const head = note ? `${formatGrepHeader(result)}\n${note}` : formatGrepHeader(result);+ const blocks = [head, "", ...result.groups.map((g) => formatGroup(g) + "\n")];+ const out = blocks.join("\n").replace(/\n+$/, "\n");+ return withSavings(out, result.saved);}/** Loud, actionable zero-hit note (never a bare empty result) — printed todiff --git a/test/claude-hooks.test.ts b/test/claude-hooks.test.tsindex b35e1e71..a9ae6355 100644--- a/test/claude-hooks.test.ts+++ b/test/claude-hooks.test.ts@@ -6,7 +6,7 @@ import { join } from 'node:path';import { underGraft, main, lastFileScopeHint, promptAskTimeout } from '../src/claude/hooks.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 { savingsLine } from '../src/context/savings.js';import { writeStats, emptyStats, acquireLock } from '../src/claude/state.js';test('underGraft detects edits inside graft/', () => {@@ -426,13 +426,13 @@ test('tool-savings is a no-op (no session file) when the tool output has no graf}});-test('tool-savings counts a REAL savingsFooter (with the turn nudge) exactly once', async () => {+test('tool-savings counts a REAL savings line (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 footer = savingsLine('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);diff --git a/test/savings.test.ts b/test/savings.test.tsindex 59cb8b0f..cb287b8e 100644--- a/test/savings.test.ts+++ b/test/savings.test.ts@@ -1,10 +1,10 @@/*** Tests for the shared "tokens saved" estimate ({@link savingsFor} +- * {@link savingsFooter}) that every retrieval-style command routes through.+ * {@link withSavings}) 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 { savingsFor, savingsLine, withSavings, toTokens } from '../src/context/savings.js';import type { GraphV1, NodeV1 } from '../src/graph/types.js';function fileNode(path: string, chars?: number): NodeV1 {@@ -42,9 +42,9 @@ test('savingsFor: skips files with no known size, returns undefined when none arassert.equal(savingsFor(g, ['missing.ts']), undefined);});-test('savingsFooter: reports saved tokens and percent when the output is smaller', () => {+test('savingsLine: 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+ const footer = savingsLine(body, { files: 2, baselineChars: 8000 }); // baseline ≈ 2000 tokassert.match(footer, /tokens saved ≈ [\d,]+ \(\d+%\)/);assert.match(footer, /2 file\(s\)/);const base = toTokens(8000);@@ -57,9 +57,24 @@ test('savingsFooter: reports saved tokens and percent when the output is smallerassert.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 }), '');+test('savingsLine: stays silent when there is nothing honest to claim', () => {+ assert.equal(savingsLine('anything', undefined), '');+ assert.equal(savingsLine('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 }), '');+ assert.equal(savingsLine('x'.repeat(1000), { files: 1, baselineChars: 40 }), '');+});++test('withSavings: puts the line on top so `head -N` and host truncation keep it', () => {+ const body = 'line1\nline2\nline3';+ const out = withSavings(body, { files: 2, baselineChars: 8000 });+ const first = out.split('\n')[0];+ assert.match(first, /^\[graft\] tokens saved ≈ [\d,]+/);+ assert.ok(out.endsWith(body), 'body follows the header verbatim');+ // Exactly one number in the whole output — a second copy would be+ // double-counted by the PostToolUse accumulator's matchAll.+ assert.equal((out.match(/\[graft\] tokens saved ≈ [\d,]+/g) ?? []).length, 1);+});++test('withSavings: returns the body untouched when there is nothing to claim', () => {+ assert.equal(withSavings('body', undefined), 'body');});