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): publish the dollar value of what graft saved (#282)
anirudhkumar-nanonets65c29667bd59
diff --git a/src/ask/ask.ts b/src/ask/ask.tsindex 8fc16cca..1ba860ca 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 { withSavings, savingsFor, SAVINGS_TURN_NUDGE, type Savings } from "../context/savings.js";+import { withSavings, savingsFor, savingsTurnNudge, type Savings } from "../context/savings.js";import { loadGraphCached, loadAskIndexCached } from "../graph/load.js";import {assertPrefixIndexed,@@ -1535,7 +1535,7 @@ function askSavingsLine(r: AskResult, body: string): string {`[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_NUDGE+ savingsTurnNudge(saved));}diff --git a/src/claude/format.ts b/src/claude/format.tsindex e74e67d1..e45bf9c5 100644--- a/src/claude/format.ts+++ b/src/claude/format.ts@@ -5,6 +5,7 @@ import type { GraphV1, EdgeV1 } from '../graph/types.js';// "did we hit a real name, or match broadly enough to trust anyway" is the same// question in both places, and one set of calibrated numbers beats two.import { HIGH_FLOOR, STRONG_FLOOR } from '../ask/fuse.js';+import { dollarsSaved, formatDollars } from '../context/price.js';const C = {indigo: (s: string) => `\x1b[38;2;84;111;255m${s}\x1b[0m`,@@ -32,7 +33,14 @@ export function renderStatusline(const top = [C.muted('◤ ') + C.indigo('graft'), C.text(`${stats.nodeCount} nodes / ${stats.edgeCount} edges`)];top.push(freshnessSegment(stats));const saved = session?.savedTokens ?? 0;- if (saved > 0) top.push(C.indigo(`~${saved.toLocaleString()} tok saved`));+ if (saved > 0) {+ // Dollars only once a turn has actually been billed — see context/price.ts.+ // Until then (turn one, or a host with no transcript) the token count+ // stands alone rather than carrying a rate nobody measured.+ const usd = dollarsSaved(saved, session?.inputCostMicros, session?.inputTokensBilled);+ const money = usd === null ? '' : ` · ~${formatDollars(usd)}`;+ top.push(C.indigo(`~${saved.toLocaleString()} tok saved${money}`));+ }const bottom: string[] = [];if (typeof ctx.ctxPct === 'number') bottom.push(C.text(`ctx ${ctx.ctxPct}%`));@@ -217,7 +225,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 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`;+ `Each tool opens its output with a "[graft] tokens saved ≈ N" line, sometimes with its dollar value; when you used graft this turn, close your reply with a one-line tally of the total saved, dollars included when given (e.g. 🌱 graft saved ~12k tokens (~$0.04) this turn, 3 calls). Never price tokens yourself; never pipe graft 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/hooks.ts b/src/claude/hooks.tsindex cf45867e..6bf7a3fb 100644--- a/src/claude/hooks.ts+++ b/src/claude/hooks.ts@@ -10,7 +10,7 @@ import { graftCliPath, claudeScriptPath } from './paths.js';import { runUpkeep } from '../upkeep-run.js';import { runningVersion } from '../upkeep.js';import { flushClosedSessions, summarizeSession } from '../telemetry/sessions.js';-import { hasSavingsTally, lastAssistantTurn } from './tally.js';+import { hasSavingsTally, lastAssistantTurn, lastTurnBilling } from './tally.js';import { scopeOf, scopesOfGraph } from '../graph/scopes.js';import { classifyToolUse, isMcpToolName, isGraftMcpTool, parseSavings, recordToolUse, type ToolKind } from './session-metrics.js';@@ -313,6 +313,34 @@ function cursorSessionId(input: any): string {return input?.conversation_id || input?.session_id || 'default';}+/**+ * At turn end: what did this turn's input tokens actually cost?+ *+ * Deliberately ungated, unlike {@link countTallyTurn}: the blended rate has to+ * describe the session, and graft turns are not a fair sample of it — they are+ * the long, tool-heavy, cache-warm ones. Sampling only those would report a+ * cheaper token than the session really pays.+ *+ * Accumulates the pair, never the ratio, so the rate re-blends every turn. A+ * turn already billed (a duplicate Stop, or a Stop racing the transcript write)+ * is skipped on its uuid.+ */+function sampleTurnCost(input: any, dir: string): void {+ try {+ const id = input?.session_id || 'default';+ const billing = lastTurnBilling(input?.transcript_path);+ if (!billing) return;+ const s = readSession(dir, id);+ if (billing.uuid === s.lastBillingUuid) return;+ s.inputCostMicros = (s.inputCostMicros ?? 0) + billing.costMicros;+ s.inputTokensBilled = (s.inputTokensBilled ?? 0) + billing.tokens;+ s.lastBillingUuid = billing.uuid;+ writeSession(dir, id, s);+ } catch {+ // A billing estimate is never worth failing the graph sync over.+ }+}+/*** At turn end: did the reply the user just read say what graft saved?*@@ -346,6 +374,7 @@ function countTallyTurn(input: any, dir: string): void {}function handleStop(input: any, dir: string): void {+ sampleTurnCost(input, dir);countTallyTurn(input, dir);// 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:diff --git a/src/claude/session-metrics.ts b/src/claude/session-metrics.tsindex 211b902d..660b2c9f 100644--- a/src/claude/session-metrics.ts+++ b/src/claude/session-metrics.ts@@ -32,6 +32,7 @@import { statSync } from 'node:fs';import { join } from 'node:path';import { sumSavingsFooters } from '../context/savings.js';+import { dollarsSaved, formatDollars } from '../context/price.js';import { readSession, writeSession, sessionDir, listSessionIds, type SessionState } from './state.js';import type { AgentHost } from '../telemetry/contract.js';import { GRAFT_MCP_TOOL_NAMES } from '../mcp/tool-names.js';@@ -165,6 +166,24 @@ export function latestSession(dir: string): SessionSummary | null {* statusline, so this is how you see the numbers the Claude Code bar would show.* Reads local JSON only; sends nothing.*/+/**+ * What this repo's most recent session has actually been paying per million+ * input tokens, or null when no turn has been billed yet.+ *+ * `latestSession` rather than a session id because the callers are CLI and MCP+ * processes answering one query: they know the repo, never the host's session+ * id. The rate belongs to the repo's current session, which is the one whose+ * reply the number is about to appear in.+ */+export function sessionInputRate(dir: string): number | null {+ const s = latestSession(dir);+ if (!s?.inputCostMicros || !s?.inputTokensBilled) return null;+ // Micro-dollars per token and dollars per million tokens are the same number:+ // both divide by 1e6 once. Returned as $/Mtok because that is the unit the+ // price table is written in and the one a reader can sanity-check against it.+ return s.inputCostMicros / s.inputTokensBilled;+}+export function formatSessionStats(s: SessionSummary | null): string {if (s === null) {return 'graft stats: no session recorded yet — use graft in an agent session, then look again.';@@ -182,6 +201,11 @@ export function formatSessionStats(s: SessionSummary | null): string {` mix: ${mix}`,` tokens saved: ~${saved.toLocaleString()}`,];+ // Omitted, not zeroed, when no turn has been billed yet: a host whose hooks+ // name no transcript can't know what a token costs here, and a made-up rate+ // would be worse than the silence.+ const usd = dollarsSaved(saved, s.inputCostMicros, s.inputTokensBilled);+ if (usd !== null) lines.push(` value saved: ~${formatDollars(usd)}`);if (s.lastQuery) lines.push(` last query: ${s.lastQuery}`);return lines.join('\n');}diff --git a/src/claude/skill-template.ts b/src/claude/skill-template.tsindex 84740e3b..57fac7dc 100644--- a/src/claude/skill-template.ts+++ b/src/claude/skill-template.ts@@ -137,6 +137,12 @@ tally summing those numbers across every graft call you made, e.g.skip it. This is the per-turn figure; the statusline carries the runningsession total.+Once a turn has been billed, each line also states what that call was worth in+dollars, at the rate this session is actually paying for input tokens — include+that total alongside the tokens, e.g. \`🌱 graft saved ~12,400 tokens (~$0.04)+this turn\`. When a line carries no dollar figure, report tokens alone rather+than pricing them yourself.+**Never pipe a graft command through \`head\`, \`tail\`, or \`sed -n\`.** Every toolis already capped and states what it dropped; clipping it costs you hits youasked for, and it silently drops the savings line the statusline's runningdiff --git a/src/claude/state.ts b/src/claude/state.tsindex 832793bf..5d254690 100644--- a/src/claude/state.ts+++ b/src/claude/state.ts@@ -51,6 +51,20 @@ export interface SessionState {/** `uuid` of the last assistant reply already examined, so a Stop that fires* without new prose (or fires twice) can't count one reply as two turns. */lastTallyUuid?: string;+ /** Running micro-dollar cost of the input tokens this session has been billed+ * for, and the tokens that bought. Their ratio is the blended price of one+ * input token here — model and cache-hit ratio already folded in — which is+ * what turns `savedTokens` into a dollar figure. Stored as the pair rather+ * than the ratio so the rate re-blends as the session's cache warms rather+ * than freezing at whatever turn one happened to pay. Optional: absent on a+ * host that exposes no transcript, and on turn one of every session. */+ inputCostMicros?: number;+ inputTokensBilled?: number;+ /** `uuid` of the last assistant entry already billed, so a duplicate Stop+ * can't charge one turn twice. Separate from `lastTallyUuid` because the two+ * are sampled on different turns: the tally only on graft turns, the cost on+ * every one. */+ lastBillingUuid?: string;/** Set once this session has been rolled up into a `session_summary`* telemetry event, so a resumed or long-lived session is counted once.* A flag rather than deleting the file: the file still holds `lastQuery` anddiff --git a/src/claude/tally.ts b/src/claude/tally.tsindex 1ec1a324..93c77114 100644--- a/src/claude/tally.ts+++ b/src/claude/tally.ts@@ -5,7 +5,7 @@* `[graft] tokens saved ≈ N` footer the PostToolUse accumulator swept up. That* number is real whether or not anyone sees it. This module measures the other* half: whether the reply the user read closed with the one-line tally that- * SKILL.md and `SAVINGS_TURN_NUDGE` (context/savings.ts) both ask for. A turn+ * SKILL.md and `savingsTurnNudge` (context/savings.ts) both ask for. A turn* that saved 20k tokens in silence is a turn where the product did its job and* got no credit for it, and the two are indistinguishable in the numbers we* ship today.@@ -21,6 +21,7 @@* hook that read the whole file would get slower every turn for no extra signal.*/import { closeSync, fstatSync, openSync, readSync } from 'node:fs';+import { turnInputCostMicros, turnInputTokens } from '../context/price.js';/*** How much of the transcript's end to read. Comfortably larger than any single@@ -53,6 +54,17 @@ export interface AssistantTurn {text: string;}+/** What the last turn's input tokens cost, alongside how many there were. The+ * pair is what a blended rate is made of; neither half means much alone. */+export interface TurnBilling {+ /** `uuid` of the last assistant entry, so a repeated Stop can't bill a turn twice. */+ uuid: string;+ /** Micro-dollars this turn's input tokens cost, cache multipliers applied. */+ costMicros: number;+ /** Input tokens billed this turn, cached and fresh alike. */+ tokens: number;+}+/** Read the last {@link TAIL_BYTES} of a file as utf8, dropping the leading* partial line a byte-offset read leaves behind. Returns '' on any I/O trouble —* a hook never fails over a metric. */@@ -129,3 +141,64 @@ export function lastAssistantTurn(transcriptPath: unknown): AssistantTurn | nullif (uuid === null || parts.length === 0) return null;return { uuid, text: parts.join('\n') };}++/**+ * What the turn the transcript ends on cost in input tokens — the measured+ * half of the dollar figure the statusline and the turn nudge report.+ *+ * Costed per API response, not per turn, so a turn that switched models is+ * priced correctly rather than labelled with whichever model happened to go+ * last. Responses are deduped by `message.id`: one response is written to the+ * transcript as several entries (a `thinking` block and a `tool_use` block land+ * on their own lines) and every one of them repeats the same `usage`, so+ * summing the lines would bill the turn two or three times over.+ *+ * Null when there is nothing to bill — no transcript path (a host whose Stop+ * hook names none), an unreadable file, a turn whose entries carry no `usage`,+ * or a model with no price in {@link inputUsdPerMtok}. As everywhere in this+ * file, null means "not observed", never "zero".+ */+export function lastTurnBilling(transcriptPath: unknown): TurnBilling | null {+ if (typeof transcriptPath !== 'string' || !transcriptPath) return null;+ const tail = readTail(transcriptPath);+ if (!tail) return null;++ const entries: any[] = [];+ for (const line of tail.split('\n')) {+ if (!line.trim()) continue;+ try { entries.push(JSON.parse(line)); } catch { /* clipped or partial line */ }+ }++ const seen = new Set<string>();+ let uuid: string | null = null;+ let costMicros = 0;+ let tokens = 0;+ for (let i = entries.length - 1; i >= 0; i--) {+ const e = entries[i];+ if (e?.isSidechain) continue;+ if (isUserPrompt(e)) break;+ if (e?.type !== 'assistant') continue;+ if (uuid === null && typeof e?.uuid === 'string') uuid = e.uuid;+ const msg = e?.message;+ const id = msg?.id;+ if (typeof id !== 'string' || seen.has(id)) continue;+ const usage = msg?.usage;+ if (!usage) continue;+ seen.add(id);+ const turn = {+ model: String(msg?.model ?? ''),+ input: Number(usage.input_tokens) || 0,+ cacheCreate: Number(usage.cache_creation_input_tokens) || 0,+ cacheRead: Number(usage.cache_read_input_tokens) || 0,+ };+ const micros = turnInputCostMicros(turn);+ // An unpriced model contributes neither cost nor tokens: leaving its tokens+ // in the denominator alone would drag the blended rate toward zero and+ // quietly under-report every saving after it.+ if (micros === null) continue;+ costMicros += micros;+ tokens += turnInputTokens(turn);+ }+ if (uuid === null || tokens === 0) return null;+ return { uuid, costMicros, tokens };+}diff --git a/src/cli.ts b/src/cli.tsindex edd7ef4e..12130c77 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -40,7 +40,8 @@ import { homedir } from "node:os";import { formatUpgradeReport, formatVersionReport, getNpmViewVersion, readCurrentVersion, runUpgrade } from "./cli-meta.js";import { patchBuildConfig, type BuildConfig } from "./util/state.js";import { normalizePathPrefix } from "./util/paths.js";-import { latestSession, formatSessionStats } from "./claude/session-metrics.js";+import { latestSession, formatSessionStats, sessionInputRate } from "./claude/session-metrics.js";+import { setInputRate } from "./context/savings.js";import { formatUpdateNudge, maybeRefreshInBackground, readUpdateCache, refreshUpdateCache, writeStamp } from "./upkeep.js";import {errorCode,@@ -77,6 +78,9 @@ let queryNote: { repo?: string; hit?: "yes" | "no" } = {};* sites stay one line. */function noteQuery(dir: string): string {queryNote.repo = dir;+ // Every retrieval command funnels through here, which makes it the one place+ // that can price this session's tokens before a formatter needs the number.+ setInputRate(sessionInputRate(dir));return dir;}diff --git a/src/context/price.ts b/src/context/price.tsnew file mode 100644index 00000000..e652dd69--- /dev/null+++ b/src/context/price.ts@@ -0,0 +1,100 @@+/**+ * What a saved token was actually worth, in dollars.+ *+ * `savings.ts` answers "how many input tokens did graft keep out of the+ * context"; this answers "what does an input token cost here". The two are+ * deliberately separate: the token count is arithmetic over file sizes and is+ * true everywhere, while the price depends on which model the session ran and+ * how much of its context was served from cache — facts only the host's+ * transcript knows.+ *+ * Nothing here guesses. There is no default rate and no env override: a model+ * we don't have a price for yields null, and the callers then render the token+ * count alone rather than a dollar figure we made up. A wrong number on the+ * statusline is worse than no number.+ */++/** Input $/Mtok, list price, per model family. Output tokens are irrelevant —+ * what graft saves is context the agent would otherwise have read IN. */+const INPUT_USD_PER_MTOK: ReadonlyArray<readonly [RegExp, number]> = [+ [/^claude-(fable|mythos)-5/, 10],+ [/^claude-opus-(5|4-[678])/, 5],+ [/^claude-sonnet-5/, 2],+ [/^claude-sonnet-4-6/, 3],+ [/^claude-haiku-4-5/, 1],+];++/** List input price for a model id, or null when we don't know it — a model+ * released after this table was written, or a host reporting something else+ * entirely. Null propagates all the way to "render tokens only". */+export function inputUsdPerMtok(model: unknown): number | null {+ if (typeof model !== 'string') return null;+ for (const [pattern, usd] of INPUT_USD_PER_MTOK) if (pattern.test(model)) return usd;+ return null;+}++/** One turn's input-token usage, as the host's transcript reports it. */+export interface TurnUsage {+ model: string;+ /** Fresh tokens, billed at the list rate. */+ input: number;+ /** Written to the cache this turn — a 25% premium over list. */+ cacheCreate: number;+ /** Served from cache — a tenth of list, and usually the bulk of a long turn. */+ cacheRead: number;+}++/** Cache-write costs 1.25x list, a cache read a tenth of it. The multipliers are+ * why a measured rate beats an assumed one: a session deep into a long+ * conversation pays nearer $0.50/Mtok than the $5.00 its model lists at. */+const CACHE_CREATE_MULTIPLIER = 1.25;+const CACHE_READ_MULTIPLIER = 0.1;++/** Micro-dollars, so a running total stays an integer and never drifts. */+const MICROS_PER_USD = 1_000_000;++/** What this turn's input tokens cost, in micro-dollars, or null on a model we+ * have no price for. */+export function turnInputCostMicros(usage: TurnUsage): number | null {+ const list = inputUsdPerMtok(usage.model);+ if (list === null) return null;+ const weighted =+ usage.input ++ usage.cacheCreate * CACHE_CREATE_MULTIPLIER ++ usage.cacheRead * CACHE_READ_MULTIPLIER;+ return Math.round((weighted * list * MICROS_PER_USD) / 1_000_000);+}++/** Every input token this turn was billed for, cached or not — the denominator+ * of the blended rate. */+export function turnInputTokens(usage: TurnUsage): number {+ return usage.input + usage.cacheCreate + usage.cacheRead;+}++/**+ * Dollars saved, at the rate the session has actually been paying.+ *+ * `costMicros / tokensBilled` is the blended price of one input token here —+ * model and cache-hit ratio already folded in — so this re-blends as the+ * session goes rather than freezing turn one's rate. Returns null when nothing+ * has been sampled yet (turn one, or a host whose hooks name no transcript).+ */+export function dollarsSaved(+ savedTokens: number,+ costMicros: number | undefined,+ tokensBilled: number | undefined,+): number | null {+ if (!costMicros || !tokensBilled || savedTokens <= 0) return null;+ const usd = (savedTokens * (costMicros / tokensBilled)) / MICROS_PER_USD;+ // Belt and braces against a non-finite accumulator reaching a rendered+ // surface: "$NaN" on the statusline is worse than no dollar figure at all.+ return Number.isFinite(usd) ? usd : null;+}++/** `$1.23`, or `<$0.01` for a real but sub-cent saving. Never `$0.00`: a+ * rounded-to-nothing number reads as "graft saved you nothing", which is a+ * different claim from "graft saved you less than a cent". */+export function formatDollars(usd: number): string {+ if (usd < 0.01) return '<$0.01';+ return `$${usd.toFixed(2)}`;+}diff --git a/src/context/savings.ts b/src/context/savings.tsindex e1cddb93..bacc7c25 100644--- a/src/context/savings.ts+++ b/src/context/savings.ts@@ -13,6 +13,7 @@* map — routes through {@link savingsFor} + {@link withSavings} here.*/import type { GraphV1 } from '../graph/types.js';+import { formatDollars } from './price.js';export interface Savings {/** How many source files the baseline covers. */@@ -52,14 +53,57 @@ export function savingsFor(graph: GraphV1, paths: Iterable<string>): Savings | ureturn files > 0 ? { files, baselineChars } : undefined;}+/**+ * The blended input rate this session is paying, in $/Mtok, or null when nobody+ * has measured one.+ *+ * Process-level because it is a process-level fact: one CLI invocation answers+ * one query for one session, and the alternative — threading a rate through+ * `withSavings` and all seven of its callers — would put a billing parameter in+ * the signature of every retrieval formatter for no gain. Set by the CLI's+ * `noteQuery` and by the MCP dispatch, both of which already resolve the repo+ * root; unset everywhere else, which is why every consumer treats null as+ * "report tokens only" rather than as zero.+ */+let inputRateUsdPerMtok: number | null = null;++/** Tell this module what an input token costs here. Null clears it, and so does+ * anything that isn't a positive finite number — a NaN from a zero-denominator+ * rate must render as "no dollars known", never as `$NaN` in the agent's face. */+export function setInputRate(usdPerMtok: number | null): void {+ inputRateUsdPerMtok =+ typeof usdPerMtok === 'number' && Number.isFinite(usdPerMtok) && usdPerMtok > 0+ ? usdPerMtok+ : null;+}+/** 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".';+ * mistakes the nudge (or its example) for a second number to count.+ *+ * Carries this call's dollar value once a rate has been measured, because the+ * agent has no way to price a token itself — the ask it's given has to contain+ * the number, not just request one. The example phrasing stays inside what+ * `hasSavingsTally` (claude/tally.ts) recognises, so adding money here does not+ * quietly zero the reported-turns metric. */+export function savingsTurnNudge(savedTokens: number): string {+ const sum = ' — sum each such line across your graft calls — e.g. ';+ if (inputRateUsdPerMtok === null || savedTokens <= 0) {+ return (+ ' At the end of your reply, tell the user the total graft tokens saved ' ++ `this turn${sum}"🌱 graft saved ~N tokens this turn".`+ );+ }+ const usd = (savedTokens * inputRateUsdPerMtok) / 1_000_000;+ return (+ ` This call is worth ${formatDollars(usd)} at the rate this session is ` ++ 'actually paying for input tokens. At the end of your reply, tell the user ' ++ `the total graft tokens saved this turn and what they were worth${sum}` ++ '"🌱 graft saved ~N tokens (~$X) this turn".'+ );+}/** 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@@ -77,7 +121,7 @@ export function savingsLine(body: string, saved: Savings | undefined): string {`[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+ savingsTurnNudge(delta));}@@ -85,7 +129,7 @@ export function savingsLine(body: string, saved: Savings | undefined): string {* Sum every `[graft] tokens saved ≈ N` footer in a blob of text — the reader* half of {@link savingsLine}, kept next to the writer so the two never drift.* A single blob can carry several (an agent that made two graft calls in one- * turn); the `SAVINGS_TURN_NUDGE` deliberately omits the pattern, so its example+ * turn); the nudge from `savingsTurnNudge` deliberately omits the pattern, so its example* text is not miscounted here.*/export function sumSavingsFooters(text: string): number {diff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex 5b4ba5b4..1167ae30 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -11,7 +11,8 @@ 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 { withSavings } from '../context/savings.js';+import { withSavings, setInputRate } from '../context/savings.js';+import { sessionInputRate } from '../claude/session-metrics.js';import { grepGraph } from '../search/grep.js';import { formatGrepResult, zeroHitNote } from '../search/grep-cli.js';import { buildRepoMap, formatRepoMap } from '../graph/map.js';@@ -224,6 +225,9 @@ export async function callTool(// Freshness first: an answer that cites file:line has to be about the code as// it is right now, including edits nobody has committed (or even saved through// this agent). ~3ms when nothing moved; a structural, $0 rebuild when it did.+ // Same reason as the CLI's `noteQuery`: price this session's tokens once,+ // here, so the formatters downstream can put a dollar figure in the nudge.+ setInputRate(sessionInputRate(root));let note: string | null = null;if (!NO_REFRESH_TOOLS.has(name)) {const r = wsdiff --git a/test/claude-format.test.ts b/test/claude-format.test.tsindex 2b91a0ca..1d52ea37 100644--- a/test/claude-format.test.ts+++ b/test/claude-format.test.ts@@ -180,7 +180,11 @@ test('formatOrientation labels and truncates to budget', () => {assert.match(out, /Already know the file or symbol to change\?/, 'known-target edit guidance present');// index truncated to budget (1500) + the fixed usage directive (per-tool descriptions + discipline).assert.match(out, /Refactor, rename, or multi-file change?/, 'refactor blast-radius nudge present');- assert.ok(out.length < 3700, 'index trimmed to budget; only the fixed directive adds to it');+ // The guard is on the INDEX being trimmed, not on the directive's exact byte+ // count: an untrimmed 3000-char index would land near 5200. The ceiling has+ // deliberate slack so teaching the directive one more thing (dollar values,+ // 0.7.x) doesn't fail a test that is watching something else.+ assert.ok(out.length < 4000, 'index trimmed to budget; only the fixed directive adds to it');// Regression: `graft impact` was folded into `graft callers --depth` in 0.6.0 —// the always-on directive must teach the current command, not a dead one.assert.doesNotMatch(out, /graft impact\b/, 'does not teach the removed `graft impact` command');@@ -207,3 +211,20 @@ test('renderSubagent without a query still shows the agent', () => {const out = strip(renderSubagent('Plan', null));assert.match(out, /Plan/);});++test('renderStatusline carries the dollar value once the session has been billed', () => {+ const stats = { ...emptyStats(), nodeCount: 1, edgeCount: 0, totalCount: 1 };+ const s = { ...freshSession(), savedTokens: 100_000, inputCostMicros: 600_000, inputTokensBilled: 1_000_000 };+ const line = strip(renderStatusline(stats, s as any, { ctxPct: null })[0]);+ assert.match(line, /~100,000 tok saved · ~\$0\.06/);+});++test('renderStatusline shows tokens alone until a turn has been billed', () => {+ // Turn one of every session, and every turn on a host that exposes no+ // transcript. Tokens are still true; a price nobody measured is not.+ const stats = { ...emptyStats(), nodeCount: 1, edgeCount: 0, totalCount: 1 };+ const s = { ...freshSession(), savedTokens: 100_000 };+ const line = strip(renderStatusline(stats, s as any, { ctxPct: null })[0]);+ assert.match(line, /~100,000 tok saved/);+ assert.doesNotMatch(line, /\$/);+});diff --git a/test/claude-tally.test.ts b/test/claude-tally.test.tsindex 64ed0819..f492674d 100644--- a/test/claude-tally.test.ts+++ b/test/claude-tally.test.ts@@ -8,7 +8,7 @@ import assert from 'node:assert/strict';import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { hasSavingsTally, lastAssistantTurn } from '../src/claude/tally.js';+import { hasSavingsTally, lastAssistantTurn, lastTurnBilling } from '../src/claude/tally.js';import { main } from '../src/claude/hooks.js';import { readSession, writeSession } from '../src/claude/state.js';@@ -166,3 +166,87 @@ test('a pre-existing session file with none of these fields still parses', asyncassert.equal(s.savedTokens, 1000, 'the existing counter is preserved');assert.equal(s.graftTurns, 1);});++/** An assistant entry carrying usage, as Claude Code writes it: one API+ * response is split across several lines that all repeat the same `message.id`+ * and the same `usage`. */+function billed(+ uuid: string,+ msgId: string,+ part: unknown,+ usage: { input: number; cacheCreate: number; cacheRead: number },+ model = 'claude-opus-5',+): string {+ return JSON.stringify({+ type: 'assistant',+ uuid,+ message: {+ role: 'assistant',+ id: msgId,+ model,+ content: [part],+ usage: {+ input_tokens: usage.input,+ cache_creation_input_tokens: usage.cacheCreate,+ cache_read_input_tokens: usage.cacheRead,+ output_tokens: 100,+ },+ },+ });+}++test('lastTurnBilling: one API response split across lines is billed once', () => {+ // The trap this exists for: Claude Code writes a thinking block and a tool_use+ // block of the SAME response as two entries, each repeating the same usage.+ // Summing lines would bill this turn twice and halve every dollar figure.+ const usage = { input: 10, cacheCreate: 1_000, cacheRead: 100_000 };+ const p = transcript([+ userPrompt('a question'),+ billed('a1', 'msg_1', { type: 'thinking', thinking: '...' }, usage),+ billed('a2', 'msg_1', { type: 'tool_use', name: 'Bash', input: {} }, usage),+ ]);+ const b = lastTurnBilling(p)!;+ assert.equal(b.uuid, 'a2');+ assert.equal(b.tokens, 101_010, 'the response is counted once, not twice');+ // 10 fresh + 1,000 written at 1.25x + 100,000 read at 0.1x, at $5/Mtok.+ assert.equal(b.costMicros, Math.round((10 + 1_250 + 10_000) * 5));+});++test('lastTurnBilling: distinct responses in one turn are summed', () => {+ const p = transcript([+ userPrompt('a question'),+ billed('a1', 'msg_1', { type: 'text', text: 'first' }, { input: 100, cacheCreate: 0, cacheRead: 0 }),+ billed('a2', 'msg_2', { type: 'text', text: 'second' }, { input: 200, cacheCreate: 0, cacheRead: 0 }),+ ]);+ const b = lastTurnBilling(p)!;+ assert.equal(b.tokens, 300);+});++test('lastTurnBilling: the previous turn is not billed again', () => {+ const p = transcript([+ userPrompt('older question'),+ billed('a1', 'msg_1', { type: 'text', text: 'old' }, { input: 9_999, cacheCreate: 0, cacheRead: 0 }),+ userPrompt('current question'),+ billed('a2', 'msg_2', { type: 'text', text: 'new' }, { input: 100, cacheCreate: 0, cacheRead: 0 }),+ ]);+ assert.equal(lastTurnBilling(p)!.tokens, 100);+});++test('lastTurnBilling: an unpriced model is left out of the rate entirely', () => {+ // Not zero-cost — absent. Keeping its tokens in the denominator with no cost+ // in the numerator would drag the blended rate toward zero and quietly+ // under-report every saving after it.+ const p = transcript([+ userPrompt('a question'),+ billed('a1', 'msg_1', { type: 'text', text: 'x' }, { input: 500, cacheCreate: 0, cacheRead: 0 }, 'some-future-model'),+ billed('a2', 'msg_2', { type: 'text', text: 'y' }, { input: 100, cacheCreate: 0, cacheRead: 0 }),+ ]);+ assert.equal(lastTurnBilling(p)!.tokens, 100);+});++test('lastTurnBilling: null when there is nothing to bill', () => {+ assert.equal(lastTurnBilling(undefined), null, 'a host whose Stop hook names no transcript');+ assert.equal(lastTurnBilling('/no/such/file.jsonl'), null, 'unreadable');+ const noUsage = transcript([userPrompt('q'), assistant('a1', 'a reply with no usage recorded')]);+ assert.equal(lastTurnBilling(noUsage), null, 'entries carrying no usage');+});diff --git a/test/price.test.ts b/test/price.test.tsnew file mode 100644index 00000000..37c27816--- /dev/null+++ b/test/price.test.ts@@ -0,0 +1,92 @@+/**+ * Tests for the dollar half of the savings estimate ({@link turnInputCostMicros}+ * + {@link dollarsSaved}). The token half lives in savings.test.ts.+ *+ * The property under test throughout is that nothing is ever invented: an+ * unknown model, an unbilled session and a zero saving all produce null, and+ * null renders as "tokens only" rather than as "$0.00".+ */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import {+ inputUsdPerMtok,+ turnInputCostMicros,+ turnInputTokens,+ dollarsSaved,+ formatDollars,+} from '../src/context/price.js';++test('inputUsdPerMtok: known families are priced, anything else is null', () => {+ assert.equal(inputUsdPerMtok('claude-opus-5'), 5);+ assert.equal(inputUsdPerMtok('claude-opus-4-8'), 5);+ assert.equal(inputUsdPerMtok('claude-sonnet-5'), 2);+ assert.equal(inputUsdPerMtok('claude-sonnet-4-6'), 3);+ assert.equal(inputUsdPerMtok('claude-haiku-4-5'), 1);+ assert.equal(inputUsdPerMtok('claude-fable-5-1'), 10);+ assert.equal(inputUsdPerMtok('gpt-5'), null);+ assert.equal(inputUsdPerMtok(undefined), null);+});++test('turnInputCostMicros: fresh tokens cost list price', () => {+ // 1M fresh input tokens on a $5/Mtok model = $5.00 = 5,000,000 micro-dollars.+ const cost = turnInputCostMicros({+ model: 'claude-opus-5', input: 1_000_000, cacheCreate: 0, cacheRead: 0,+ });+ assert.equal(cost, 5_000_000);+});++test('turnInputCostMicros: cache writes cost 1.25x and reads a tenth', () => {+ const write = turnInputCostMicros({+ model: 'claude-opus-5', input: 0, cacheCreate: 1_000_000, cacheRead: 0,+ });+ const read = turnInputCostMicros({+ model: 'claude-opus-5', input: 0, cacheCreate: 0, cacheRead: 1_000_000,+ });+ assert.equal(write, 6_250_000);+ assert.equal(read, 500_000);+});++test('turnInputCostMicros: a cache-heavy turn is an order of magnitude cheaper than list', () => {+ // The shape of a real turn deep in a session: almost everything served from+ // cache. This is the whole reason the rate is measured rather than assumed —+ // pricing these tokens at list would overstate the saving roughly 10x.+ const usage = {+ model: 'claude-opus-5', input: 2, cacheCreate: 2_451, cacheRead: 132_972,+ };+ const cost = turnInputCostMicros(usage)!;+ const perMtok = cost / turnInputTokens(usage);+ assert.ok(perMtok > 0.5 && perMtok < 0.7, `blended rate was $${perMtok}/Mtok`);+});++test('turnInputCostMicros: an unpriced model yields null, never a guess', () => {+ assert.equal(+ turnInputCostMicros({ model: 'some-future-model', input: 100, cacheCreate: 0, cacheRead: 0 }),+ null,+ );+});++test('dollarsSaved: prices a saving at the session\'s blended rate', () => {+ // A session billed $0.60 for 1M input tokens pays $0.60/Mtok; 100k saved+ // tokens are therefore worth $0.06.+ const usd = dollarsSaved(100_000, 600_000, 1_000_000);+ assert.ok(usd !== null);+ assert.ok(Math.abs(usd - 0.06) < 1e-9, `got ${usd}`);+});++test('dollarsSaved: null until something has actually been billed', () => {+ assert.equal(dollarsSaved(100_000, undefined, undefined), null, 'turn one of a session');+ assert.equal(dollarsSaved(100_000, 0, 0), null, 'a host that exposes no transcript');+ assert.equal(dollarsSaved(0, 600_000, 1_000_000), null, 'nothing saved, nothing to price');+});++test('formatDollars: a real sub-cent saving is not rounded away to zero', () => {+ assert.equal(formatDollars(1.234), '$1.23');+ assert.equal(formatDollars(0.005), '<$0.01');+ assert.match(formatDollars(0.0001), /^<\$0\.01$/);+});++test('dollarsSaved: a non-finite accumulator never reaches a rendered surface', () => {+ assert.equal(dollarsSaved(100_000, Number.NaN, 1_000_000), null);+ assert.equal(dollarsSaved(100_000, 600_000, Number.NaN), null);+ assert.equal(dollarsSaved(Number.POSITIVE_INFINITY, 600_000, 1_000_000), null);+});diff --git a/test/savings.test.ts b/test/savings.test.tsindex cb287b8e..4a9596bf 100644--- a/test/savings.test.ts+++ b/test/savings.test.ts@@ -4,7 +4,8 @@*/import { test } from 'node:test';import assert from 'node:assert/strict';-import { savingsFor, savingsLine, withSavings, toTokens } from '../src/context/savings.js';+import { savingsFor, savingsLine, withSavings, toTokens, setInputRate } from '../src/context/savings.js';+import { hasSavingsTally } from '../src/claude/tally.js';import type { GraphV1, NodeV1 } from '../src/graph/types.js';function fileNode(path: string, chars?: number): NodeV1 {@@ -78,3 +79,45 @@ test('withSavings: puts the line on top so `head -N` and host truncation keep ittest('withSavings: returns the body untouched when there is nothing to claim', () => {assert.equal(withSavings('body', undefined), 'body');});++test('the turn nudge carries no dollar figure until a rate is set', () => {+ setInputRate(null);+ const footer = savingsLine('body', { files: 2, baselineChars: 8000 });+ assert.match(footer, /graft saved ~N tokens this turn/);+ assert.doesNotMatch(footer, /\$/, 'no rate measured, so nothing is priced');+});++test('the turn nudge prices this call once a rate is set', () => {+ // $5/Mtok: a 1,000-token saving is worth half a cent, which must read as+ // "<$0.01" rather than "$0.00" — see formatDollars.+ setInputRate(5);+ const footer = savingsLine('x'.repeat(400), { files: 2, baselineChars: 8000 });+ assert.match(footer, /worth <\$0\.01/);+ assert.match(footer, /~\$X.*this turn/, 'the example shows the dollar-bearing form');+ setInputRate(null);+});++test('a priced nudge still leaves exactly one number for the accumulator', () => {+ // The nudge must never grow a second `[graft] tokens saved ≈ <n>` — the+ // PostToolUse accumulator sums every match, so an example carrying the+ // pattern would double-count the call.+ setInputRate(5);+ const footer = savingsLine('x'.repeat(400), { files: 2, baselineChars: 8000 });+ assert.equal((footer.match(/\[graft\] tokens saved ≈ [\d,]+/g) ?? []).length, 1);+ setInputRate(null);+});++test('a priced nudge still matches the reported-turns tally regex', () => {+ // Adding money to the example must not quietly zero `reportedTurns`, which+ // measures whether the agent told the user anything at all.+ assert.equal(hasSavingsTally('🌱 graft saved ~12,400 tokens (~$0.04) this turn'), true);+});++test('setInputRate refuses a rate that would render as $NaN', () => {+ for (const bad of [Number.NaN, Number.POSITIVE_INFINITY, 0, -1]) {+ setInputRate(bad);+ const footer = savingsLine('x'.repeat(400), { files: 2, baselineChars: 8000 });+ assert.doesNotMatch(footer, /\$/, `rate ${bad} must price nothing`);+ }+ setInputRate(null);+});diff --git a/test/session-metrics.test.ts b/test/session-metrics.test.tsindex a2706b1e..5027cf8d 100644--- a/test/session-metrics.test.ts+++ b/test/session-metrics.test.ts@@ -183,3 +183,28 @@ test('formatSessionStats renders the mix, savings and last query', () => {test('formatSessionStats has a friendly empty state', () => {assert.match(formatSessionStats(null), /no session recorded yet/);});++test('formatSessionStats prices the saving once the session has been billed', () => {+ // Billed $0.60 for 1M input tokens = $0.60/Mtok, so 100k saved is worth $0.06 —+ // which formats as <$0.01? No: $0.06. The point is that it is the MEASURED+ // rate, an order of magnitude under this model's $5/Mtok list price.+ const out = formatSessionStats({+ id: 'abc', lastQuery: null, perAgentQuery: {},+ graftReads: 8, sourceReads: 2, savedTokens: 100_000,+ inputCostMicros: 600_000, inputTokensBilled: 1_000_000,+ });+ assert.match(out, /tokens saved:\s+~100,000/);+ assert.match(out, /value saved:\s+~\$0\.06/);+});++test('formatSessionStats omits the dollar line rather than claiming zero', () => {+ // Cursor: its hooks name no transcript, so nothing has ever been billed. The+ // token count still stands; a "$0.00" next to it would be a false claim.+ const out = formatSessionStats({+ id: 'abc', lastQuery: null, perAgentQuery: {},+ graftReads: 8, sourceReads: 2, savedTokens: 100_000,+ });+ assert.match(out, /tokens saved:\s+~100,000/);+ assert.doesNotMatch(out, /value saved/);+ assert.doesNotMatch(out, /\$/);+});