Skip to content

Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.

feat(metrics): score Cursor sessions like Claude Code (#265)

Anthony Feddersend89583d2c3f6
diff --git a/.gitignore b/.gitignore
index e5685282..32e11a89 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,3 +21,7 @@ transcripts/
# and never part of a PR diff (the hook helpers/skills alongside them stay tracked).
.claude/settings.json
.claude/settings.local.json
+
+# Cursor project config — written per machine by `graft init` (hooks, MCP, rule),
+# a personal setup like the Claude settings above, not a shared artifact.
+.cursor/
diff --git a/scripts/run-tests.mjs b/scripts/run-tests.mjs
index f8418123..63dfd00b 100644
--- a/scripts/run-tests.mjs
+++ b/scripts/run-tests.mjs
@@ -30,9 +30,23 @@ if (files.length === 0) {
process.exit(1);
}
+// Several tests `git init` a scratch repo and `git commit` into it to exercise the
+// incremental/submodule/ingest git paths. Those commits inherit the developer's
+// global git config — so a contributor who signs commits (gpg, or gitsign, whose
+// x509 flow opens a browser for OIDC on EVERY commit) gets a signing storm from a
+// run that has nothing to do with their identity. Inject config via GIT_CONFIG_*
+// (git merges these over the user's config for this process tree only) so test
+// commits never sign, without touching anyone's global settings.
+const gitEnv = {
+ GIT_CONFIG_COUNT: "2",
+ GIT_CONFIG_KEY_0: "commit.gpgsign", GIT_CONFIG_VALUE_0: "false",
+ GIT_CONFIG_KEY_1: "tag.gpgsign", GIT_CONFIG_VALUE_1: "false",
+};
+
const result = spawnSync(process.execPath, ["--import", "tsx", "--test", ...files], {
cwd: repoRoot,
stdio: "inherit",
+ env: { ...process.env, ...gitEnv },
});
if (result.error) {
diff --git a/src/claude/hooks.ts b/src/claude/hooks.ts
index bc6da71c..cf45867e 100644
--- a/src/claude/hooks.ts
+++ b/src/claude/hooks.ts
@@ -9,9 +9,10 @@ import { patchStats, readStats, acquireLock, readSession, writeSession, resolveC
import { graftCliPath, claudeScriptPath } from './paths.js';
import { runUpkeep } from '../upkeep-run.js';
import { runningVersion } from '../upkeep.js';
-import { flushClosedSessions } from '../telemetry/sessions.js';
+import { flushClosedSessions, summarizeSession } from '../telemetry/sessions.js';
import { hasSavingsTally, lastAssistantTurn } from './tally.js';
import { scopeOf, scopesOfGraph } from '../graph/scopes.js';
+import { classifyToolUse, isMcpToolName, isGraftMcpTool, parseSavings, recordToolUse, type ToolKind } from './session-metrics.js';
/** Prompts shorter than this never trigger retrieval — they are almost always
* conversational ("yes go ahead", "thanks") and the coverage gate can't judge
@@ -230,26 +231,86 @@ 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;
- // This turn used graft, so it is owed a tally in the reply. countTallyTurn()
- // at Stop resolves whether it got one; a flag rather than a count because a
- // turn with four graft calls is still one reply to the user.
- s.turnUsedGraft = true;
- writeSession(dir, id, s);
+/**
+ * PostToolUse on a retrieval tool. Two jobs, both a pure parse of the payload the
+ * hook already received (no re-run):
+ *
+ * 1. Score the usage mix: classify the tool as a graft retrieval or a source
+ * read (Read/Grep/Glob) and bump the session's `graftReads`/`sourceReads`.
+ * Until this ran, those counters were never incremented, so
+ * `session_summary` telemetry shipped 0/0 for every session.
+ * 2. Sum any `[graft] tokens saved ≈ N` footers in the output into the running
+ * `savedTokens` total, so the statusline's `~N tok saved` reflects the
+ * session across CLI and MCP.
+ *
+ * A `[graft]` footer is itself proof graft ran, so it also counts as a graft
+ * read even when the tool name alone (a bare `Bash`) couldn't say so. A graft use
+ * also flags the turn (`turnUsedGraft`) so the Stop hook's tally can resolve
+ * whether the reply told the user what it saved. Stays a no-op on the
+ * Write/Edit/unrelated-Bash majority: nothing to classify and no footer means
+ * nothing is written.
+ */
+function handleToolUse(input: any, dir: string): void {
+ recordToolUse(dir, input?.session_id || 'default',
+ { ...classifyAndScore(input?.tool_name, input?.tool_input?.command, () => input?.tool_response ?? input), host: 'claude-code' });
+}
+
+/**
+ * Classify a tool use and, only when it could carry a graft footer, parse the
+ * savings out of its (lazily-serialised) output.
+ *
+ * Source reads (Read/Grep/Glob) never print a `[graft]` footer, and their output
+ * is a whole file or every match — serialising and regexing that on every read
+ * is the expensive, pointless case the widened PostToolUse matcher would
+ * otherwise hit. So skip `payload()` entirely for them. For anything else, a
+ * footer is itself proof graft ran (a bare `Bash graft …` the name couldn't
+ * classify), so its presence upgrades the kind to 'graft'.
+ */
+function classifyAndScore(
+ toolName: string | undefined,
+ command: string | undefined,
+ payload: () => unknown,
+): { kind: ToolKind | null; savedTokens: number } {
+ let kind = classifyToolUse(toolName, command);
+ if (kind === 'source') return { kind, savedTokens: 0 };
+ const savedTokens = parseSavings(JSON.stringify(payload() ?? ''));
+ if (savedTokens > 0) kind = 'graft';
+ return { kind, savedTokens };
+}
+
+/**
+ * Cursor `postToolUse` (https://cursor.com/docs/hooks). Same job as
+ * {@link handleToolUse} but over Cursor's payload shape: `tool_output` holds the
+ * JSON-stringified result (a Shell `graft …` call's footer lives in its stdout),
+ * and the session key is `conversation_id`. MCP graft calls are skipped here —
+ * `afterMCPExecution` owns them, and counting both would double the graft tally.
+ * The skip covers both the prefixed (`MCP:graft_find_code`) and bare
+ * (`graft_find_code`) tool-name shapes, so the guard — not just the installed
+ * matcher — is what prevents the double count.
+ */
+function handleCursorPostTool(input: any, dir: string): void {
+ const toolName = String(input?.tool_name ?? '');
+ if (isMcpToolName(toolName) || isGraftMcpTool(toolName)) return; // handled by handleCursorMcp
+ const command = input?.tool_input?.command ?? input?.tool_input?.cmd;
+ recordToolUse(dir, cursorSessionId(input),
+ { ...classifyAndScore(toolName, command, () => input?.tool_output ?? input?.tool_response ?? input), host: 'cursor' });
+}
+
+/**
+ * Cursor `afterMCPExecution`: fires only for MCP tools, so a graft tool is
+ * recognised by its name and its savings read out of `result_json`. This is the
+ * one place graft MCP calls are counted for Cursor.
+ */
+function handleCursorMcp(input: any, dir: string): void {
+ const toolName = String(input?.tool_name ?? '');
+ if (!isGraftMcpTool(toolName)) return;
+ const savedTokens = parseSavings(JSON.stringify(input?.result_json ?? input?.result ?? input ?? ''));
+ recordToolUse(dir, cursorSessionId(input), { kind: 'graft', savedTokens, host: 'cursor' });
+}
+
+/** Cursor keys a chat by `conversation_id` (its `session_id` equivalent). */
+function cursorSessionId(input: any): string {
+ return input?.conversation_id || input?.session_id || 'default';
}
/**
@@ -328,7 +389,17 @@ 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 === 'tool-savings') { handleToolUse(input, dir); return; }
+
+ if (event === 'cursor-post-tool') { handleCursorPostTool(input, dir); return; }
+
+ if (event === 'cursor-mcp') { handleCursorMcp(input, dir); return; }
+
+ // Cursor closes a chat: force-close THIS conversation into a bucketed
+ // `session_summary` now (its file's mtime is fresh, so the idle sweep would
+ // skip it). Attributed to Cursor. The idle sweep stays on Claude's
+ // session-start, whose Stop fires per turn and so has no real end signal.
+ if (event === 'cursor-session-end') { summarizeSession(dir, cursorSessionId(input), { host: 'cursor' }); return; }
if (event === 'stop') { handleStop(input, dir); return; }
diff --git a/src/claude/session-metrics.ts b/src/claude/session-metrics.ts
new file mode 100644
index 00000000..211b902d
--- /dev/null
+++ b/src/claude/session-metrics.ts
@@ -0,0 +1,187 @@
+/**
+ * Session usage accounting, shared across every host (Claude Code, Cursor, and
+ * plain MCP). It answers the one question the README rests on: when an agent had
+ * both graft and grep in front of it, which did it reach for, and how much did
+ * that save?
+ *
+ * The counters (`graftReads`, `sourceReads`, `savedTokens`) already live on
+ * {@link SessionState}; before this module nothing ever incremented the first
+ * two, so `session_summary` telemetry shipped 0/0 for every session. Everything
+ * here is a pure classify + read-modify-write over `graft/.cache/session/`, so a
+ * host adapter is a few lines: parse its payload, call {@link recordToolUse}.
+ *
+ * Two payload shapes feed it, confirmed against the vendor docs rather than
+ * guessed (the matcher depends on getting the names right):
+ *
+ * - Claude Code `PostToolUse` — `{ tool_name, tool_input: { command }, tool_response }`.
+ * A graft retrieval prints a `[graft] tokens saved ≈ N` footer into
+ * `tool_response`, which is itself proof graft ran.
+ * - Cursor `postToolUse` — `{ tool_name, tool_input, tool_output, conversation_id }`
+ * (https://cursor.com/docs/hooks). `tool_output` is the JSON-stringified
+ * result; a Shell `graft …` call carries the same footer inside its stdout.
+ * - Cursor `afterMCPExecution` — `{ tool_name, tool_input, result_json, duration }`.
+ * Fires only for MCP tools, so a graft tool is recognised by its name and
+ * its savings read out of `result_json`.
+ *
+ * MCP tool names arrive host-prefixed in different shapes (`graft_find_code`,
+ * `MCP:graft_find_code`, `mcp__graft__graft_find_code`). {@link isGraftMcpTool}
+ * strips the prefix to the last delimited segment and checks it against the real
+ * name list (`GRAFT_MCP_TOOL_NAMES`), so a graft tool is recognised across every
+ * host format while a third-party tool that merely contains "graft" is not.
+ */
+import { statSync } from 'node:fs';
+import { join } from 'node:path';
+import { sumSavingsFooters } from '../context/savings.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';
+
+export type ToolKind = 'graft' | 'source';
+
+/** Native tools that mean "the agent went to read source itself" — the grep/read
+ * path graft is meant to replace. These are the host tool NAMES (Claude Code and
+ * Cursor both use Read/Grep/Glob; Cursor adds Search); shell builtins like `ls`
+ * are commands, never tool names, so they belong to the Shell branch, not here.
+ * Compared lower-cased. */
+const SOURCE_TOOLS = new Set(['read', 'grep', 'glob', 'search']);
+
+/** The host's shell tool, whose `command` we then inspect for a graft invocation. */
+function isShellTool(t: string): boolean {
+ return t === 'bash' || t === 'shell';
+}
+
+/** An MCP-style tool name (server-prefixed), as opposed to a native Read/Shell.
+ * Used to hand graft MCP calls to the dedicated MCP hook so a host that fires
+ * BOTH a generic post-tool hook and an MCP hook can't double-count them. */
+export function isMcpToolName(toolName: string): boolean {
+ const t = toolName.toLowerCase();
+ return t.startsWith('mcp') || t.includes(':') || t.includes('__');
+}
+
+/**
+ * Whether a tool name is one of graft's MCP tools, across every host prefix.
+ * Anchored on the real name list (`graft_find_code`, its legacy aliases, …), not
+ * a loose `includes('graft')`: a third-party MCP tool whose name merely contains
+ * "graft" (or a repo working on graft itself) must not count as a graft read —
+ * the same care `commandInvokesGraft` takes for the CLI side. Strips the host
+ * prefix first (`mcp__graft__graft_find_code`, `MCP:graft_find_code`) by taking
+ * the last delimited segment. */
+export function isGraftMcpTool(toolName: string): boolean {
+ const t = toolName.toLowerCase();
+ const bare = t.split(/[:./]|__/).pop() ?? t;
+ return GRAFT_MCP_TOOL_NAMES.has(bare);
+}
+
+/** Whether a shell command line invokes the graft CLI (any of its install shapes). */
+export function commandInvokesGraft(command: string): boolean {
+ const c = command.trim();
+ if (/dist[/\\]cli\.js/.test(c)) return true; // running from a source checkout
+ // `graft …`, `graft-dev …`, `npx [-y] [@nanonets/]graft …`, at the start of the
+ // line or of a &&/;/| segment — not "mygraft" or a path that merely contains it.
+ return /(^|[|&;]\s*)(npx\s+(-y\s+)?(@nanonets\/)?)?graft(-dev)?\b/i.test(c);
+}
+
+/**
+ * Classify one tool use as a graft retrieval, a source read, or neither
+ * (an edit, a task spawn, an unrelated shell command — no retrieval signal).
+ * `command` is the shell command line when `toolName` is the host's shell tool.
+ */
+export function classifyToolUse(toolName?: string, command?: string): ToolKind | null {
+ const t = (toolName ?? '').toLowerCase();
+ if (!t) return null;
+ if (isGraftMcpTool(t)) return 'graft';
+ if (SOURCE_TOOLS.has(t)) return 'source';
+ if (isShellTool(t) && command && commandInvokesGraft(command)) return 'graft';
+ return null;
+}
+
+/** Sum every `[graft] tokens saved ≈ N` footer in a blob of tool output. Thin
+ * alias over {@link sumSavingsFooters}, which lives next to the code that writes
+ * the footer so the two can't drift. */
+export function parseSavings(blob: string): number {
+ return sumSavingsFooters(blob);
+}
+
+export interface ToolUse {
+ /** 'graft' → graftReads++, 'source' → sourceReads++, null/absent → neither. */
+ kind?: ToolKind | null;
+ /** Tokens the retrieval saved, parsed from its footer. Added to the running total. */
+ savedTokens?: number;
+ /** The host recording this use. Stamped on the session file (once) so the
+ * `session_summary` is attributed correctly no matter which host later flushes it. */
+ host?: AgentHost;
+}
+
+/**
+ * Fold one tool use into a session's counters. A no-op when there is nothing to
+ * record (kind null and no savings), so a host can call it unconditionally after
+ * every tool without first checking whether the tool was interesting — the
+ * no-write path is what keeps it cheap on the Write/Edit/Task majority.
+ *
+ * Best-effort read-modify-write, not locked — mirroring `patchStats` in
+ * util/state.ts. Two tool-use hooks racing on the same session file can lose a
+ * count; that is acceptable for an episodic usage estimate (worst case is an
+ * undercount by one, never corruption thanks to the atomic write), and a lock
+ * here would contend with the build lock these hooks also touch.
+ */
+export function recordToolUse(dir: string, sessionId: string, use: ToolUse): void {
+ const saved = use.savedTokens ?? 0;
+ if (!use.kind && saved <= 0) return;
+ const id = sessionId || 'default';
+ const s = readSession(dir, id);
+ if (use.kind === 'graft') s.graftReads = (s.graftReads ?? 0) + 1;
+ else if (use.kind === 'source') s.sourceReads = (s.sourceReads ?? 0) + 1;
+ if (saved > 0) s.savedTokens = (s.savedTokens ?? 0) + saved;
+ // A graft use owes a tally in this turn's reply; the Stop hook (countTallyTurn)
+ // resolves whether it got one and clears the flag. A flag, not a count — a turn
+ // with several graft calls is still one reply to the user.
+ if (use.kind === 'graft') s.turnUsedGraft = true;
+ // Stamp the host once; the first tool use that lands owns the attribution.
+ if (use.host && !s.host) s.host = use.host;
+ writeSession(dir, id, s);
+}
+
+export interface SessionSummary extends SessionState {
+ id: string;
+}
+
+/** The most-recently-touched session file for a repo, or null when none exist —
+ * what `graft stats` shows by default: the session you were just in. */
+export function latestSession(dir: string): SessionSummary | null {
+ const sdir = sessionDir(dir);
+ let bestId: string | null = null;
+ let bestMtime = -Infinity;
+ for (const id of listSessionIds(dir)) {
+ let mtime: number;
+ try { mtime = statSync(join(sdir, `${id}.json`)).mtimeMs; } catch { continue; }
+ if (mtime > bestMtime) { bestMtime = mtime; bestId = id; }
+ }
+ if (bestId === null) return null;
+ return { id: bestId, ...readSession(dir, bestId) };
+}
+
+/**
+ * A one-line-per-fact readout of a session's usage mix — Cursor has no
+ * statusline, so this is how you see the numbers the Claude Code bar would show.
+ * Reads local JSON only; sends nothing.
+ */
+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.';
+ }
+ const graft = s.graftReads ?? 0;
+ const source = s.sourceReads ?? 0;
+ const saved = s.savedTokens ?? 0;
+ const total = graft + source;
+ const mix =
+ total === 0 ? 'no retrieval yet' : `${Math.round((graft / total) * 100)}% graft`;
+ const lines = [
+ `graft stats — session ${s.id}`,
+ ` graft reads: ${graft}`,
+ ` source reads: ${source} (Read / Grep / Glob)`,
+ ` mix: ${mix}`,
+ ` tokens saved: ~${saved.toLocaleString()}`,
+ ];
+ if (s.lastQuery) lines.push(` last query: ${s.lastQuery}`);
+ return lines.join('\n');
+}
diff --git a/src/claude/settings-merge.ts b/src/claude/settings-merge.ts
index 9b886eeb..6571d4c7 100644
--- a/src/claude/settings-merge.ts
+++ b/src/claude/settings-merge.ts
@@ -1,3 +1,5 @@
+import { isGraftEntry } from '../hosts/config-write.js';
+
type Json = Record<string, any>;
const SL_CMD = 'node "${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-statusline.cjs"';
@@ -23,11 +25,14 @@ function graftBlocks(): Record<string, Json[]> {
return {
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 }] },
+ // Score the usage mix and sum token savings. A graft retrieval (CLI `graft …`
+ // via Bash, or the `graft_*` MCP tools) prints a `[graft] tokens saved ≈ N`
+ // footer this hook sums into the session total; the same hook classifies
+ // Read/Grep/Glob as source reads vs graft as graft reads, which is what feeds
+ // `graft stats` and the `session_summary` graft-vs-grep ratio. Broad matcher,
+ // but the handler no-ops instantly unless there is something to record, so an
+ // unrelated Bash or a plain Read costs only a stdin read.
+ { matcher: 'Bash|mcp__graft__|Read|Grep|Glob', hooks: [{ type: 'command', command: hookCmd('tool-savings'), timeout: 8000 }] },
],
// Longer budget than the other hooks: its `graft ask` is a real query, and a
// query now brings the graph up to date first (graph/refresh.ts) — usually
@@ -42,10 +47,6 @@ function graftBlocks(): Record<string, Json[]> {
Stop: [{ hooks: [{ type: 'command', command: hookCmd('stop'), timeout: 8000 }] }],
};
}
-function isGraftHookEntry(entry: Json): boolean {
- return JSON.stringify(entry ?? '').includes('graft-hooks.cjs');
-}
-
/**
* Is this allowlist entry one graft wrote?
*
@@ -120,7 +121,7 @@ export function mergeGraftSettings(
merged.hooks = { ...(merged.hooks ?? {}) };
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
+ const foreign = prior.filter((e: Json) => !isGraftEntry(e)); // drop old Graft entries → idempotent
merged.hooks[event] = [...foreign, ...blocks];
}
diff --git a/src/claude/state.ts b/src/claude/state.ts
index 8a142546..832793bf 100644
--- a/src/claude/state.ts
+++ b/src/claude/state.ts
@@ -4,8 +4,10 @@
* pre-query auto-refresh can take the same lock; they are re-exported here so
* every existing import path keeps working.
*/
+import { readdirSync } from 'node:fs';
import { join } from 'node:path';
import { cacheDir, readJson, writeJsonAtomic } from '../util/state.js';
+import type { AgentHost } from '../telemetry/contract.js';
export {
LOCK_STALE_MS,
@@ -54,13 +56,30 @@ export interface SessionState {
* A flag rather than deleting the file: the file still holds `lastQuery` and
* `injectedPointers`, which a resumed session needs. */
summarized?: boolean;
+ /** Which host recorded this session, stamped on the first tool use. Lets the
+ * `session_summary` be attributed correctly even when Claude Code's idle sweep
+ * is what finally flushes a Cursor session. Optional: files written before
+ * host-stamping (or an empty session never touched by a tool) fall back to the
+ * flushing host. */
+ host?: AgentHost;
}
function emptySession(): SessionState {
return { lastQuery: null, perAgentQuery: {}, graftReads: 0, sourceReads: 0, savedTokens: 0, injectedPointers: [], nudges: 0 };
}
-function sessionPath(d: string, id: string): string { return join(cacheDir(d), 'session', `${id}.json`); }
+/** The per-repo session directory holding one `<id>.json` per agent session. */
+export function sessionDir(d: string): string { return join(cacheDir(d), 'session'); }
+
+function sessionPath(d: string, id: string): string { return join(sessionDir(d), `${id}.json`); }
+
+/** Every session id with a file on disk, or `[]` when none exist (never throws).
+ * Shared by the telemetry rollup and `graft stats` so they agree on the set. */
+export function listSessionIds(d: string): string[] {
+ try {
+ return readdirSync(sessionDir(d)).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -'.json'.length));
+ } catch { return []; }
+}
export function readSession(d: string, id: string): SessionState {
return readJson<SessionState>(sessionPath(d, id)) ?? emptySession();
diff --git a/src/cli.ts b/src/cli.ts
index da6c6332..afeb81da 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -40,6 +40,7 @@ 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 { formatUpdateNudge, maybeRefreshInBackground, readUpdateCache, refreshUpdateCache, writeStamp } from "./upkeep.js";
import {
errorCode,
@@ -661,6 +662,24 @@ program
if (bothMissing || markdownFail || wiringFail) process.exit(1);
});
+program
+ .command("stats")
+ .description("Show this agent session's graft-vs-source usage mix and tokens saved")
+ .argument(...DIR_ARG)
+ .option("--json", "output the session stats as JSON")
+ .action((dirArg: string | undefined, opts: { json?: boolean }) => {
+ // Reads local session JSON only — no graph, no network. This is how a Cursor
+ // user (no statusline) sees the numbers the Claude Code bar would show, and it
+ // works under DO_NOT_TRACK because it never touches telemetry.
+ const dir = queryRoot(dirArg);
+ const s = latestSession(dir);
+ if (opts.json) {
+ console.log(JSON.stringify(s, null, 2));
+ return;
+ }
+ console.log(formatSessionStats(s));
+ });
+
program
.command("viz")
.description("Serve an interactive visualization of the context graph (and graph.json when present)")
diff --git a/src/context/savings.ts b/src/context/savings.ts
index 2848352b..e1cddb93 100644
--- a/src/context/savings.ts
+++ b/src/context/savings.ts
@@ -81,6 +81,21 @@ 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
+ * text is not miscounted here.
+ */
+export function sumSavingsFooters(text: string): number {
+ let total = 0;
+ for (const m of text.matchAll(/\[graft\] tokens saved ≈ ([\d,]+)/g)) {
+ total += Number(m[1].replace(/,/g, '')) || 0;
+ }
+ return total;
+}
+
/** Render `body` with the savings line on TOP.
*
* Deliberately a header, not a footer: agents routinely pipe graft through
diff --git a/src/hosts/antigravity.ts b/src/hosts/antigravity.ts
index 8e51b8b2..5fc2da05 100644
--- a/src/hosts/antigravity.ts
+++ b/src/hosts/antigravity.ts
@@ -14,7 +14,7 @@ import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { skillTemplate } from '../claude/skill-template.js';
import type { PlannedWrite } from './plan.js';
-import type { HookWrite } from './codex-hooks.js';
+import type { ConfigWrite } from './config-write.js';
/** The skill file path, under the user's global Antigravity skills dir. */
function skillPath(home: string): string {
@@ -33,7 +33,7 @@ export function antigravitySkillTargets(home: string): PlannedWrite[] {
}
/** Write graft's skill into `~/.gemini/skills/graft/SKILL.md`, idempotently. */
-export function installAntigravitySkill(home: string): HookWrite[] {
+export function installAntigravitySkill(home: string): ConfigWrite[] {
const path = skillPath(home);
const content = skillTemplate();
const existed = existsSync(path);
diff --git a/src/hosts/codex-hooks.ts b/src/hosts/codex-hooks.ts
index c5f545a8..46bd9198 100644
--- a/src/hosts/codex-hooks.ts
+++ b/src/hosts/codex-hooks.ts
@@ -3,17 +3,12 @@
* PostToolUse semantics. Writes the shared hook shim and one PostToolUse
* entry that runs post-edit + background sync after every file edit.
*/
-import { readFileSync, writeFileSync, mkdirSync, existsSync, chmodSync, statSync } from 'node:fs';
-import { dirname, join } from 'node:path';
+import { writeFileSync, statSync } from 'node:fs';
+import { join } from 'node:path';
import { hooksShim } from '../claude/shim-template.js';
import { claudeDistDir } from '../claude/paths.js';
import type { PlannedWrite } from './plan.js';
-
-export interface HookWrite {
- id: string;
- path: string;
- action: 'created' | 'updated' | 'unchanged' | 'skipped-unparseable';
-}
+import { writeOwned, isGraftEntry, readJsonObject, type ConfigWrite } from './config-write.js';
function dirExists(p: string): boolean {
try { return statSync(p).isDirectory(); } catch { return false; }
@@ -42,22 +37,6 @@ export function hookTargets(home: string): PlannedWrite[] {
];
}
-function writeOwned(id: string, path: string, content: string, mode?: number): HookWrite {
- const existed = existsSync(path);
- if (existed && readFileSync(path, 'utf8') === content) {
- if (mode !== undefined && (statSync(path).mode & 0o777) !== mode) chmodSync(path, mode);
- return { id, path, action: 'unchanged' };
- }
- mkdirSync(dirname(path), { recursive: true });
- writeFileSync(path, content);
- if (mode !== undefined) chmodSync(path, mode);
- return { id, path, action: existed ? 'updated' : 'created' };
-}
-
-function isGraftEntry(entry: unknown): boolean {
- return JSON.stringify(entry).includes('graft-hooks.cjs');
-}
-
/**
* The graft hook entries Codex should carry, mirroring the Claude Code set:
* - SessionStart → orientation from `graft/INDEX.md`
@@ -79,21 +58,18 @@ function desiredEntries(): DesiredEntry[] {
];
}
-export function installCodexHooks(home: string): HookWrite[] {
+export function installCodexHooks(home: string): ConfigWrite[] {
const targets = hookTargets(home);
if (targets.length === 0) return [];
const shimPath = targets[0].path;
const shimWrite = writeOwned('codex-hook-shim', shimPath, hooksShim(claudeDistDir()), 0o755);
- const skipped: HookWrite = { id: 'codex-hooks', path: targets[1].path, action: 'skipped-unparseable' };
-
const cfgPath = targets[1].path;
- let root: Record<string, any> = {};
- const existed = existsSync(cfgPath);
- if (existed) {
- try { root = JSON.parse(readFileSync(cfgPath, 'utf8')); } catch { return [shimWrite, skipped]; }
- }
- if (typeof root !== 'object' || root === null || Array.isArray(root)) return [shimWrite, skipped];
+ const skipped: ConfigWrite = { id: 'codex-hooks', path: cfgPath, action: 'skipped-unparseable' };
+
+ const loaded = readJsonObject(cfgPath);
+ if (loaded === 'unparseable') return [shimWrite, skipped];
+ const { root, existed } = loaded;
const before = JSON.stringify(root);
const hooks = (root.hooks ??= {});
if (typeof hooks !== 'object' || hooks === null || Array.isArray(hooks)) return [shimWrite, skipped];
diff --git a/src/hosts/config-write.ts b/src/hosts/config-write.ts
new file mode 100644
index 00000000..e83d7439
--- /dev/null
+++ b/src/hosts/config-write.ts
@@ -0,0 +1,70 @@
+/**
+ * Shared helpers for the host config writers. Both the hook installers (Codex,
+ * user-level under `~/.codex`; Cursor, repo-local under `.cursor`) and the MCP
+ * registration merge graft entries into a JSON config, own a generated shim, and
+ * describe the outcome with the same little result record. The file-owning write,
+ * the graft-entry test, and the load-or-skip JSON open are identical across them;
+ * the merge itself differs per host, so only the genuinely-shared pieces live here.
+ */
+import { readFileSync, writeFileSync, mkdirSync, existsSync, chmodSync, statSync } from 'node:fs';
+import { dirname } from 'node:path';
+
+/** The result of one config/shim write, reported by every installer and by MCP
+ * registration so they speak the same vocabulary. `McpWrite` aliases this. */
+export interface ConfigWrite {
+ id: string;
+ path: string;
+ action: 'created' | 'updated' | 'unchanged' | 'skipped-unparseable';
+}
+
+/**
+ * Write a graft-owned file, idempotently: unchanged when the content already
+ * matches (only re-applying `mode` if it drifted), else created/updated. `mode`
+ * is applied on POSIX; on Windows the exec bit does not exist and is skipped by
+ * the caller's expectations.
+ */
+export function writeOwned(id: string, path: string, content: string, mode?: number): ConfigWrite {
+ const existed = existsSync(path);
+ if (existed && readFileSync(path, 'utf8') === content) {
+ if (mode !== undefined && (statSync(path).mode & 0o777) !== mode) chmodSync(path, mode);
+ return { id, path, action: 'unchanged' };
+ }
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, content);
+ if (mode !== undefined) chmodSync(path, mode);
+ return { id, path, action: existed ? 'updated' : 'created' };
+}
+
+/** Whether a hooks-config entry is one graft installed (so an upgrade replaces
+ * it in place instead of stacking a second copy next to the stale one). The
+ * `?? ''` guards a stray `undefined` entry: `JSON.stringify(undefined)` is
+ * `undefined`, whose `.includes` would throw. */
+export function isGraftEntry(entry: unknown): boolean {
+ return JSON.stringify(entry ?? '').includes('graft-hooks.cjs');
+}
+
+/**
+ * Load a JSON config that graft is about to merge into, distinguishing the three
+ * outcomes an installer must treat differently:
+ * - missing → `{ root: {}, existed: false }`: start fresh, this is a create.
+ * - a plain object → `{ root, existed: true }`: merge into it.
+ * - anything else (parse error, or a top-level array/null/primitive) →
+ * `'unparseable'`: leave the file exactly as the user left it.
+ *
+ * Deliberately NOT `readJson` from `util/state.ts`, which returns `null` for both
+ * missing and unparseable — collapsing those two would let a create silently
+ * clobber a hand-edited broken `hooks.json`.
+ */
+export function readJsonObject(
+ path: string,
+): { root: Record<string, any>; existed: boolean } | 'unparseable' {
+ if (!existsSync(path)) return { root: {}, existed: false };
+ let root: unknown;
+ try {
+ root = JSON.parse(readFileSync(path, 'utf8'));
+ } catch {
+ return 'unparseable';
+ }
+ if (typeof root !== 'object' || root === null || Array.isArray(root)) return 'unparseable';
+ return { root: root as Record<string, any>, existed: true };
+}
diff --git a/src/hosts/cursor-hooks.ts b/src/hosts/cursor-hooks.ts
new file mode 100644
index 00000000..8f431173
--- /dev/null
+++ b/src/hosts/cursor-hooks.ts
@@ -0,0 +1,109 @@
+/**
+ * Cursor project hooks (https://cursor.com/docs/hooks) — the adapter that lets
+ * Cursor produce the same session usage mix Claude Code does (graft reads vs
+ * Read/Grep, plus token savings), which Cursor otherwise has no way to record.
+ *
+ * Unlike the Codex hooks (which live under `~/.codex` and fire in every repo),
+ * Cursor project hooks are **repo-local**: `.cursor/hooks.json` + a shim under
+ * `.cursor/hooks/`. That matches graft's Cursor-only posture — a `--no-global`
+ * init that never writes outside the repo — so these are scoped 'repo' and are
+ * NOT suppressed by `--global false`; only `--no-hooks` skips them.
+ *
+ * The shim is the same one Claude Code and Codex use (`hooksShim`): it locates
+ * the installed `@nanonets/graft` package and calls `hooks.js`' `main(argv[2])`,
+ * so the sub-command in each entry (`cursor-post-tool`, `cursor-mcp`,
+ * `cursor-session-end`) routes to the matching handler in `../claude/hooks.ts`.
+ *
+ * Events, confirmed against the Cursor hooks docs (the matcher/tool-name shape
+ * is load-bearing, so it is read from the docs, not guessed):
+ * - `postToolUse` (matcher `Read|Grep|Glob|Search|Shell`) → classify a source read
+ * vs a graft-CLI Shell call; MCP tools are skipped here so they aren't
+ * double-counted against `afterMCPExecution`.
+ * - `afterMCPExecution` → the graft MCP calls, savings parsed from `result_json`.
+ * - `sessionEnd` → roll the closed session up into `session_summary` as Cursor.
+ */
+import { writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { hooksShim } from '../claude/shim-template.js';
+import { claudeDistDir } from '../claude/paths.js';
+import type { PlannedWrite } from './plan.js';
+import { writeOwned, isGraftEntry, readJsonObject, type ConfigWrite } from './config-write.js';
+
+/** The Cursor hooks.json schema version graft writes. */
+const CURSOR_HOOKS_VERSION = 1;
+
+function shimPathFor(repo: string): string {
+ return join(repo, '.cursor', 'hooks', 'graft-hooks.cjs');
+}
+function configPathFor(repo: string): string {
+ return join(repo, '.cursor', 'hooks.json');
+}
+
+/**
+ * The files a Cursor-hooks install would touch — pure, no writes. Both are
+ * repo-local, so both are scoped 'repo' (they fire only in this repo, matching
+ * the Cursor-only, no-global init). Always returns the pair: unlike Codex there
+ * is no "is the CLI installed" gate — the repo's own `.cursor/` is what we write.
+ */
+export function cursorHookTargets(repo: string): PlannedWrite[] {
+ return [
+ {
+ hostId: 'cursor', id: 'cursor-hook-shim',
+ path: shimPathFor(repo),
+ scope: 'repo', kind: 'hook', what: 'session-scoring hook shim',
+ },
+ {
+ hostId: 'cursor', id: 'cursor-hooks',
+ path: configPathFor(repo),
+ scope: 'repo', kind: 'hook', what: 'postToolUse / afterMCPExecution / sessionEnd',
+ },
+ ];
+}
+
+/**
+ * The graft hook entries Cursor should carry. `matcher` is set only where Cursor
+ * filters by tool (postToolUse); `afterMCPExecution` fires for every MCP tool and
+ * `sessionEnd` for none, so they carry no matcher.
+ */
+interface DesiredEntry { event: string; matcher?: string; sub: string; }
+function desiredEntries(): DesiredEntry[] {
+ return [
+ { event: 'postToolUse', matcher: 'Read|Grep|Glob|Search|Shell', sub: 'cursor-post-tool' },
+ { event: 'afterMCPExecution', sub: 'cursor-mcp' },
+ { event: 'sessionEnd', sub: 'cursor-session-end' },
+ ];
+}
+
+/**
+ * Install (or refresh) graft's Cursor project hooks in `repo`. Idempotent, and
+ * conservative with a hand-edited config: an unparseable or wrong-shaped
+ * `hooks.json` is left exactly as-is (reported `skipped-unparseable`) rather than
+ * clobbered. Foreign hook entries are preserved; a stale graft entry is replaced
+ * so an upgrade re-points to the current shim/sub-command instead of stacking.
+ */
+export function installCursorHooks(repo: string): ConfigWrite[] {
+ const shimPath = shimPathFor(repo);
+ const shimWrite = writeOwned('cursor-hook-shim', shimPath, hooksShim(claudeDistDir()), 0o755);
+ const cfgPath = configPathFor(repo);
+ const skipped: ConfigWrite = { id: 'cursor-hooks', path: cfgPath, action: 'skipped-unparseable' };
+
+ const loaded = readJsonObject(cfgPath);
+ if (loaded === 'unparseable') return [shimWrite, skipped];
+ const { root, existed } = loaded;
+ const before = JSON.stringify(root);
+ if (root.version === undefined) root.version = CURSOR_HOOKS_VERSION;
+ const hooks = (root.hooks ??= {});
+ if (typeof hooks !== 'object' || hooks === null || Array.isArray(hooks)) return [shimWrite, skipped];
+
+ for (const d of desiredEntries()) {
+ if (hooks[d.event] !== undefined && !Array.isArray(hooks[d.event])) return [shimWrite, skipped];
+ const prior: unknown[] = Array.isArray(hooks[d.event]) ? hooks[d.event] : [];
+ const command = `node "${shimPath}" ${d.sub}`;
+ const entry = d.matcher ? { matcher: d.matcher, command } : { command };
+ hooks[d.event] = [...prior.filter((e) => !isGraftEntry(e)), entry];
+ }
+
+ if (JSON.stringify(root) === before) return [shimWrite, { id: 'cursor-hooks', path: cfgPath, action: 'unchanged' }];
+ writeFileSync(cfgPath, `${JSON.stringify(root, null, 2)}\n`);
+ return [shimWrite, { id: 'cursor-hooks', path: cfgPath, action: existed ? 'updated' : 'created' }];
+}
diff --git a/src/hosts/init.ts b/src/hosts/init.ts
index 834cd4dc..12b73d5a 100644
--- a/src/hosts/init.ts
+++ b/src/hosts/init.ts
@@ -9,7 +9,9 @@ import { homedir } from 'node:os';
import { HOSTS, detectHosts, type DetectProbe, type HostTarget } from './registry.js';
import { upsertSection } from './sections.js';
import { registerMcpConfigs, type McpWrite } from './mcp-config.js';
-import { installCodexHooks, type HookWrite } from './codex-hooks.js';
+import { installCodexHooks } from './codex-hooks.js';
+import { installCursorHooks } from './cursor-hooks.js';
+import type { ConfigWrite } from './config-write.js';
import { installAntigravitySkill } from './antigravity.js';
export interface HostsInitResult {
@@ -17,7 +19,7 @@ export interface HostsInitResult {
skipped: string[];
unknown: string[];
mcp: McpWrite[];
- hooks: HookWrite[];
+ hooks: ConfigWrite[];
}
function probeFor(home: string, repo: string): DetectProbe {
@@ -76,15 +78,21 @@ export function runHostsInit(
opts.mcp === false
? []
: registerMcpConfigs(repo, selected.map((h) => h.id), { home, global: opts.global });
- // Every hook target is user-level, so --no-global suppresses the lot.
+ // The Codex hook targets are user-level (~/.codex), so --no-global suppresses them.
const hooks =
opts.hooks === false || opts.global === false || !selected.some((h) => h.id === 'agents')
? []
: installCodexHooks(home);
+ // Cursor's hooks are repo-local (.cursor/hooks.json), matching the Cursor-only,
+ // no-global posture — so --no-global does NOT suppress them; only --no-hooks does.
+ const cursorHooks =
+ opts.hooks === false || !selected.some((h) => h.id === 'cursor')
+ ? []
+ : installCursorHooks(repo);
// Antigravity's skill is a global write too, so --no-global suppresses it as well.
const antigravitySkill =
opts.global === false || !selected.some((h) => h.id === 'antigravity')
? []
: installAntigravitySkill(home);
- return { written, skipped, unknown, mcp, hooks: [...hooks, ...antigravitySkill] };
+ return { written, skipped, unknown, mcp, hooks: [...hooks, ...cursorHooks, ...antigravitySkill] };
}
diff --git a/src/hosts/mcp-config.ts b/src/hosts/mcp-config.ts
index cabe60ed..111da50f 100644
--- a/src/hosts/mcp-config.ts
+++ b/src/hosts/mcp-config.ts
@@ -12,12 +12,10 @@ import { spawnSync } from 'node:child_process';
import { dirname, join } from 'node:path';
import { homedir } from 'node:os';
import type { PlannedWrite } from './plan.js';
+import { readJsonObject, type ConfigWrite } from './config-write.js';
-export interface McpWrite {
- id: string;
- path: string;
- action: 'created' | 'updated' | 'unchanged' | 'skipped-unparseable';
-}
+/** MCP registration reports the same write-result record every installer does. */
+export type McpWrite = ConfigWrite;
/** A planned MCP write, plus the detail needed to actually perform it. */
export interface McpTarget extends PlannedWrite {
@@ -78,15 +76,9 @@ function dirExists(p: string): boolean {
}
export function mergeJsonKey(id: string, path: string, topKey: string, entry: object): McpWrite {
- let root: Record<string, any> = {};
- const existed = existsSync(path);
- if (existed) {
- try {
- root = JSON.parse(readFileSync(path, 'utf8'));
- } catch {
- return { id, path, action: 'skipped-unparseable' };
- }
- }
+ const loaded = readJsonObject(path);
+ if (loaded === 'unparseable') return { id, path, action: 'skipped-unparseable' };
+ const { root, existed } = loaded;
const bucket = (root[topKey] ??= {});
if (typeof bucket !== 'object' || bucket === null || Array.isArray(bucket)) {
return { id, path, action: 'skipped-unparseable' };
diff --git a/src/hosts/plan.ts b/src/hosts/plan.ts
index 10385203..991b97f9 100644
--- a/src/hosts/plan.ts
+++ b/src/hosts/plan.ts
@@ -13,6 +13,7 @@ import { statSync } from 'node:fs';
import { HOSTS, detectHosts, type DetectProbe, type HostTarget } from './registry.js';
import { mcpTargets } from './mcp-config.js';
import { hookTargets } from './codex-hooks.js';
+import { cursorHookTargets } from './cursor-hooks.js';
import { antigravitySkillTargets } from './antigravity.js';
import { claudeTargets } from '../claude/init.js';
@@ -78,6 +79,7 @@ export function planInit(repo: string, opts: { home?: string; ids?: string[] } =
instructionTarget(repo, host),
...mcpTargets(repo, [host.id], { home }),
...(host.id === 'agents' ? hookTargets(home) : []),
+ ...(host.id === 'cursor' ? cursorHookTargets(repo) : []),
...(host.id === 'antigravity' ? antigravitySkillTargets(home) : []),
],
})),
diff --git a/src/mcp/tool-names.ts b/src/mcp/tool-names.ts
new file mode 100644
index 00000000..23ac2eb5
--- /dev/null
+++ b/src/mcp/tool-names.ts
@@ -0,0 +1,41 @@
+/**
+ * The graft MCP tool names, kept in a zero-import module so both the MCP server
+ * (which also pulls in the whole engine) and the session-scoring hooks (which must
+ * stay cheap and engine-free) can share one list. Adding a dependency here would
+ * drag it into every hook invocation, so this file imports nothing.
+ */
+
+/** The tools graft advertises today, as their canonical names. */
+export const GRAFT_MCP_TOOL_CANONICAL = [
+ 'graft_find_code',
+ 'graft_find_all',
+ 'graft_trace_calls',
+ 'graft_file_api',
+ 'graft_repo_map',
+ 'graft_check_freshness',
+] as const;
+
+/**
+ * The pre-0.8.1 tool names, still accepted. A name is an API: skills, saved
+ * prompts and other people's notes reference the old ones, so they map to the
+ * canonical name rather than 404.
+ */
+export const GRAFT_MCP_TOOL_ALIASES: Record<string, string> = {
+ graft_ask: 'graft_find_code',
+ graft_grep: 'graft_find_all',
+ graft_callers: 'graft_trace_calls',
+ graft_skeleton: 'graft_file_api',
+ graft_map: 'graft_repo_map',
+ graft_check: 'graft_check_freshness',
+};
+
+/** Every name graft answers to (canonical + legacy), lower-cased, for a membership
+ * test that anchors on the real vocabulary instead of a loose `includes('graft')`. */
+export const GRAFT_MCP_TOOL_NAMES: ReadonlySet<string> = new Set(
+ [...GRAFT_MCP_TOOL_CANONICAL, ...Object.keys(GRAFT_MCP_TOOL_ALIASES)].map((n) => n.toLowerCase()),
+);
+
+/** Canonical name for a requested tool: itself, or what it was renamed to. */
+export function canonicalToolName(name: string): string {
+ return GRAFT_MCP_TOOL_ALIASES[name] ?? name;
+}
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index 8e6e1d89..5b4ba5b4 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -24,6 +24,7 @@ import {
readWorkspace,
} from '../graph/workspace.js';
import type { NodeV1 } from '../graph/types.js';
+import { canonicalToolName } from './tool-names.js';
export interface ToolDef {
name: string;
@@ -201,29 +202,15 @@ async function callWorkspaceTool(
const NO_REFRESH_TOOLS = new Set(['graft_check_freshness']);
/**
- * The pre-0.8.1 tool names, still accepted.
- *
- * The names were the reason for renaming: when a host defers graft's schemas it
- * shows the model the *names alone* — no descriptions — so `graft_ask` had to
- * compete with `Grep` on 9 characters of self-description. The new names say what
- * they do. But a name is an API: skills, saved prompts, scripts and other people's
- * notes reference the old ones, and silently 404-ing on them would be a worse
- * outcome than an ugly name. Not advertised in {@link TOOLS} — the roster stays six
- * — so this costs nothing in the payload and only ever rescues an old caller.
+ * The pre-0.8.1 tool names, still accepted, live in the dependency-free
+ * `tool-names.ts` (shared with the engine-free session hooks). The names were the
+ * reason for renaming: when a host defers graft's schemas it shows the model the
+ * *names alone* — no descriptions — so `graft_ask` had to compete with `Grep` on
+ * 9 characters. The new names say what they do; the aliases keep old callers
+ * (skills, saved prompts, notes) from 404-ing. Re-exported here so existing
+ * importers of `canonicalToolName` from this module keep working.
*/
-const TOOL_ALIASES: Record<string, string> = {
- graft_ask: 'graft_find_code',
- graft_grep: 'graft_find_all',
- graft_callers: 'graft_trace_calls',
- graft_skeleton: 'graft_file_api',
- graft_map: 'graft_repo_map',
- graft_check: 'graft_check_freshness',
-};
-
-/** Canonical name for a requested tool: itself, or what it was renamed to. */
-export function canonicalToolName(name: string): string {
- return TOOL_ALIASES[name] ?? name;
-}
+export { canonicalToolName };
export async function callTool(
root: string,
diff --git a/src/telemetry/index.ts b/src/telemetry/index.ts
index 9d7d4e94..eab62bac 100644
--- a/src/telemetry/index.ts
+++ b/src/telemetry/index.ts
@@ -14,4 +14,4 @@ export { telemetryOn, offReason, explainOff } from './gate.js';
export { maybeFlushInBackground, runFlush } from './flush.js';
export { firstRunNotice, formatStatus, formatDebug, NOTICE, TELEMETRY_DOC_URL } from './notice.js';
export { patchState, readState } from './identity.js';
-export { flushClosedSessions } from './sessions.js';
+export { flushClosedSessions, summarizeSession } from './sessions.js';
diff --git a/src/telemetry/sessions.ts b/src/telemetry/sessions.ts
index 126ba6a0..37bcab5b 100644
--- a/src/telemetry/sessions.ts
+++ b/src/telemetry/sessions.ts
@@ -9,19 +9,22 @@
* session into `graft/.cache/session/` since well before telemetry did. Nothing
* new is measured here; a closed session is simply bucketed and queued.
*
- * "Closed" is inferred from mtime rather than observed, because there is no
- * reliable end-of-session hook — `Stop` fires per turn, and an editor that
- * crashes fires nothing at all. A session untouched for two hours is over.
+ * "Closed" is inferred from mtime by the idle sweep ({@link flushClosedSessions})
+ * because Claude Code has no reliable end-of-session hook — `Stop` fires per
+ * turn, and an editor that crashes fires nothing at all. A session untouched for
+ * two hours is over. Cursor DOES have `sessionEnd`, so it force-closes the exact
+ * conversation that just ended via {@link summarizeSession}, skipping the idle
+ * gate that would otherwise ignore the file the last tool use just wrote.
*
- * Called from the session-start hook, which is the one place guaranteed to run
- * again after a session ends. A hook must never touch the network (see the note
- * atop upkeep.ts) and this doesn't: it only appends to the local queue.
+ * Called from the session-start hook (the sweep) and the Cursor sessionEnd hook
+ * (the force-close) — both places guaranteed to run at the right moment. A hook
+ * must never touch the network (see the note atop upkeep.ts) and this doesn't:
+ * it only appends to the local queue.
*/
-import { readdirSync, statSync } from 'node:fs';
+import { statSync } from 'node:fs';
import { join } from 'node:path';
-import { cacheDir } from '../util/state.js';
-import { readSession, writeSession } from '../claude/state.js';
-import { countBucket, savedTokensBucket } from './contract.js';
+import { readSession, writeSession, sessionDir, listSessionIds } from '../claude/state.js';
+import { countBucket, savedTokensBucket, type AgentHost } from './contract.js';
import { track } from './track.js';
import { telemetryOn } from './gate.js';
@@ -32,52 +35,75 @@ export const SESSION_IDLE_MS = 2 * 60 * 60 * 1000;
* session files must not slow down a session start. The rest wait for the next. */
const MAX_PER_RUN = 20;
+/**
+ * Roll one session up into a `session_summary`, ignoring the idle gate — for a
+ * host with a real end-of-session signal (Cursor's `sessionEnd`). Returns 1 if
+ * queued, 0 if already summarised or telemetry is off. Never throws.
+ *
+ * The event is attributed to the host stamped on the session file when there is
+ * one (a session used from Cursor stays Cursor even if Claude's idle sweep is
+ * what finally flushes it); `opts.host` is only the fallback for a file written
+ * before host-stamping, or by a path that didn't stamp.
+ */
+export function summarizeSession(
+ repo: string,
+ id: string,
+ opts: { host?: AgentHost; home?: string; env?: NodeJS.ProcessEnv } = {},
+): number {
+ try {
+ const { host = 'claude-code', home, env } = opts;
+ if (!telemetryOn(home, env)) return 0;
+
+ const s = readSession(repo, id);
+ if (s.summarized) return 0;
+
+ // An empty session — opened, nothing asked — is still a fact worth having:
+ // it is the difference between "graft is installed" and "graft is used".
+ track(
+ 'session_summary',
+ {
+ graft_reads_bucket: countBucket(s.graftReads ?? 0),
+ source_reads_bucket: countBucket(s.sourceReads ?? 0),
+ saved_tokens_bucket: savedTokensBucket(s.savedTokens ?? 0),
+ // Saved vs *said*: the gap between these two is value the user never
+ // heard about. Only turns whose reply was actually readable are in
+ // either count (claude/tally.ts), so a host that exposes no transcript
+ // reports 0/0 rather than a misleading 0-out-of-many.
+ graft_turns_bucket: countBucket(s.graftTurns ?? 0),
+ reported_turns_bucket: countBucket(s.reportedTurns ?? 0),
+ },
+ { repo, host: s.host ?? host, home, env },
+ );
+ writeSession(repo, id, { ...s, summarized: true });
+ return 1;
+ } catch {
+ return 0;
+ }
+}
+
/**
* Queue a `session_summary` for every closed, not-yet-summarised session in this
- * repo. Returns how many were queued (for tests). Never throws.
+ * repo. "Closed" = untouched for {@link SESSION_IDLE_MS}. Returns how many were
+ * queued (for tests). Never throws.
*/
export function flushClosedSessions(
repo: string,
now = Date.now(),
home?: string,
env?: NodeJS.ProcessEnv,
+ host: AgentHost = 'claude-code',
): number {
try {
if (!telemetryOn(home, env)) return 0;
- const dir = join(cacheDir(repo), 'session');
- let files: string[];
- try { files = readdirSync(dir).filter((f) => f.endsWith('.json')); } catch { return 0; }
+ const dir = sessionDir(repo);
let queued = 0;
- for (const file of files.sort()) {
+ for (const id of listSessionIds(repo).sort()) {
if (queued >= MAX_PER_RUN) break;
let mtime: number;
- try { mtime = statSync(join(dir, file)).mtimeMs; } catch { continue; }
+ try { mtime = statSync(join(dir, `${id}.json`)).mtimeMs; } catch { continue; }
if (now - mtime < SESSION_IDLE_MS) continue;
-
- const id = file.slice(0, -'.json'.length);
- const s = readSession(repo, id);
- if (s.summarized) continue;
-
- // An empty session — opened, nothing asked — is still a fact worth having:
- // it is the difference between "graft is installed" and "graft is used".
- track(
- 'session_summary',
- {
- graft_reads_bucket: countBucket(s.graftReads ?? 0),
- source_reads_bucket: countBucket(s.sourceReads ?? 0),
- saved_tokens_bucket: savedTokensBucket(s.savedTokens ?? 0),
- // Saved vs *said*: the gap between these two is value the user never
- // heard about. Only turns whose reply was actually readable are in
- // either count (claude/tally.ts), so a host that exposes no transcript
- // reports 0/0 rather than a misleading 0-out-of-many.
- graft_turns_bucket: countBucket(s.graftTurns ?? 0),
- reported_turns_bucket: countBucket(s.reportedTurns ?? 0),
- },
- { repo, host: 'claude-code', home, env },
- );
- writeSession(repo, id, { ...s, summarized: true });
- queued++;
+ queued += summarizeSession(repo, id, { host, home, env });
}
return queued;
} catch {
diff --git a/test/claude-hooks.test.ts b/test/claude-hooks.test.ts
index ab9cc9f3..08279e35 100644
--- a/test/claude-hooks.test.ts
+++ b/test/claude-hooks.test.ts
@@ -466,6 +466,109 @@ test('tool-savings counts a REAL savings line (with the turn nudge) exactly once
}
});
+// ── the usage-mix counters: graft vs source (both hosts) ───────────────────
+
+test('tool-savings now scores the mix: a Read is a source read, a graft footer is a graft read', async () => {
+ const d = mkdtempSync(join(tmpdir(), 'graft-mix-'));
+ process.env.CLAUDE_PROJECT_DIR = d;
+ try {
+ await runWithStdin(JSON.stringify({ session_id: 'm', tool_name: 'Read', tool_input: { file_path: '/x' } }), () => main('tool-savings'));
+ assert.equal(readSession(d, 'm').sourceReads, 1, 'Read counted as a source read');
+ assert.equal(readSession(d, 'm').graftReads, 0);
+
+ await runWithStdin(JSON.stringify({
+ session_id: 'm', tool_name: 'Bash',
+ tool_response: { stdout: '[graft] tokens saved ≈ 500 — …' },
+ }), () => main('tool-savings'));
+ assert.equal(readSession(d, 'm').graftReads, 1, 'a graft footer counts as a graft read');
+ assert.equal(readSession(d, 'm').savedTokens, 500);
+ } finally {
+ delete process.env.CLAUDE_PROJECT_DIR;
+ }
+});
+
+// ── Cursor hook adapters ────────────────────────────────────────────────────
+
+test('cursor-post-tool: Read → source read, Shell graft → graft read + savings, keyed by conversation_id', async () => {
+ const d = mkdtempSync(join(tmpdir(), 'graft-cursor-pt-'));
+ process.env.CLAUDE_PROJECT_DIR = d;
+ try {
+ await runWithStdin(JSON.stringify({ conversation_id: 'c1', tool_name: 'Read', tool_input: {} }), () => main('cursor-post-tool'));
+ assert.equal(readSession(d, 'c1').sourceReads, 1);
+
+ await runWithStdin(JSON.stringify({
+ conversation_id: 'c1', tool_name: 'Shell',
+ tool_input: { command: 'graft ask "x"' },
+ tool_output: JSON.stringify({ stdout: '…\n[graft] tokens saved ≈ 900 — …' }),
+ }), () => main('cursor-post-tool'));
+ assert.equal(readSession(d, 'c1').graftReads, 1, 'Shell graft CLI is a graft read');
+ assert.equal(readSession(d, 'c1').savedTokens, 900, 'savings parsed out of tool_output');
+ } finally {
+ delete process.env.CLAUDE_PROJECT_DIR;
+ }
+});
+
+test('cursor-post-tool skips graft MCP tools — prefixed AND bare — so afterMCPExecution is the only counter', async () => {
+ const d = mkdtempSync(join(tmpdir(), 'graft-cursor-skip-'));
+ process.env.CLAUDE_PROJECT_DIR = d;
+ try {
+ // prefixed shape
+ await runWithStdin(JSON.stringify({ conversation_id: 'c1', tool_name: 'MCP:graft_find_code', tool_output: '{}' }), () => main('cursor-post-tool'));
+ assert.equal(existsSync(join(d, 'graft', '.cache', 'session', 'c1.json')), false, 'prefixed MCP tool not counted here');
+ // bare shape — the guard, not just the installed matcher, must catch this or it double-counts
+ await runWithStdin(JSON.stringify({ conversation_id: 'c2', tool_name: 'graft_find_code', tool_output: '{}' }), () => main('cursor-post-tool'));
+ assert.equal(existsSync(join(d, 'graft', '.cache', 'session', 'c2.json')), false, 'bare graft MCP tool not counted here');
+ } finally {
+ delete process.env.CLAUDE_PROJECT_DIR;
+ }
+});
+
+test('cursor-mcp: a graft MCP tool is a graft read with savings from result_json; a foreign MCP tool is a no-op', async () => {
+ const d = mkdtempSync(join(tmpdir(), 'graft-cursor-mcp-'));
+ process.env.CLAUDE_PROJECT_DIR = d;
+ try {
+ await runWithStdin(JSON.stringify({
+ conversation_id: 'c1', tool_name: 'graft_find_code',
+ result_json: JSON.stringify({ text: '…\n[graft] tokens saved ≈ 1,200 — …' }),
+ }), () => main('cursor-mcp'));
+ assert.equal(readSession(d, 'c1').graftReads, 1);
+ assert.equal(readSession(d, 'c1').savedTokens, 1200);
+
+ await runWithStdin(JSON.stringify({ conversation_id: 'c2', tool_name: 'some_other_server_tool', result_json: '{}' }), () => main('cursor-mcp'));
+ assert.equal(existsSync(join(d, 'graft', '.cache', 'session', 'c2.json')), false, 'foreign MCP tool ignored');
+ } finally {
+ delete process.env.CLAUDE_PROJECT_DIR;
+ }
+});
+
+test('cursor-session-end force-closes THIS conversation even though its file was just touched (idle gate skipped)', async () => {
+ const d = mkdtempSync(join(tmpdir(), 'graft-cursor-end-'));
+ const home = mkdtempSync(join(tmpdir(), 'graft-cursor-end-home-'));
+ mkdirSync(join(d, 'graft', '.cache', 'session'), { recursive: true });
+ const sfile = join(d, 'graft', '.cache', 'session', 'c1.json');
+ // mtime = now: the idle sweep would skip this, but the end hook must summarize it.
+ writeFileSync(sfile, JSON.stringify({ graftReads: 8, sourceReads: 2, savedTokens: 7400 }));
+
+ // Turn telemetry on against a scratch $HOME so the rollup actually queues (and
+ // marks the file), the observable proof the force-close ran — not just no-throw.
+ const saved = {
+ HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE,
+ KEY: process.env.GRAFT_POSTHOG_KEY, CI: process.env.CI, DNT: process.env.DO_NOT_TRACK,
+ };
+ process.env.HOME = home; process.env.USERPROFILE = home;
+ process.env.GRAFT_POSTHOG_KEY = 'phc_test_key';
+ delete process.env.CI; delete process.env.DO_NOT_TRACK;
+ process.env.CLAUDE_PROJECT_DIR = d;
+ try {
+ await runWithStdin(JSON.stringify({ conversation_id: 'c1' }), () => main('cursor-session-end'));
+ assert.equal(readSession(d, 'c1').summarized, true, 'the just-ended conversation was rolled up');
+ } finally {
+ delete process.env.CLAUDE_PROJECT_DIR;
+ for (const [k, v] of Object.entries({ HOME: saved.HOME, USERPROFILE: saved.USERPROFILE, GRAFT_POSTHOG_KEY: saved.KEY, CI: saved.CI, DO_NOT_TRACK: saved.DNT }))
+ if (v === undefined) delete (process.env as any)[k]; else (process.env as any)[k] = v;
+ }
+});
+
/**
* The prompt hook's `graft ask` child must stay inside the budget THIS repo has
* installed, not the one the current source would install. `mergeGraftSettings` runs
diff --git a/test/claude-settings-merge.test.ts b/test/claude-settings-merge.test.ts
index 0e5cae4e..ad424557 100644
--- a/test/claude-settings-merge.test.ts
+++ b/test/claude-settings-merge.test.ts
@@ -13,10 +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).
+ // PostToolUse carries a second graft block: the usage-mix + tokens-saved
+ // accumulator over the retrieval tools (Bash `graft …`, the graft_* MCP tools)
+ // and the source-read tools (Read/Grep/Glob) it scores against.
const savings = merged.hooks.PostToolUse[1];
- assert.equal(savings.matcher, 'Bash|mcp__graft__');
+ assert.equal(savings.matcher, 'Bash|mcp__graft__|Read|Grep|Glob');
assert.ok(savings.hooks[0].command.includes('tool-savings'), 'savings hook wired');
assert.ok(merged.footerLinksRegexes.includes('graft/[\\w./-]+\\.md'));
assert.deepEqual(warnings, []);
diff --git a/test/hosts-config-write.test.ts b/test/hosts-config-write.test.ts
new file mode 100644
index 00000000..dae92e6b
--- /dev/null
+++ b/test/hosts-config-write.test.ts
@@ -0,0 +1,59 @@
+/**
+ * The shared config-writer helpers. `readJsonObject` is the load-or-skip half of
+ * every installer, so its three outcomes are pinned here: a missing file is a
+ * fresh create, a plain object is merged into, and anything else is left exactly
+ * as the user wrote it (never clobbered).
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtempSync, writeFileSync, readFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { readJsonObject, isGraftEntry, writeOwned } from '../src/hosts/config-write.js';
+
+function fresh(): string { return mkdtempSync(join(tmpdir(), 'graft-config-write-')); }
+
+test('readJsonObject: a missing file is a fresh create, not unparseable', () => {
+ const r = readJsonObject(join(fresh(), 'nope.json'));
+ assert.notEqual(r, 'unparseable');
+ assert.deepEqual(r, { root: {}, existed: false });
+});
+
+test('readJsonObject: a plain object is returned for merging', () => {
+ const p = join(fresh(), 'hooks.json');
+ writeFileSync(p, JSON.stringify({ version: 1, hooks: {} }));
+ const r = readJsonObject(p);
+ assert.notEqual(r, 'unparseable');
+ assert.deepEqual(r, { root: { version: 1, hooks: {} }, existed: true });
+});
+
+test('readJsonObject: invalid JSON is unparseable (distinct from missing, so a broken file is never overwritten)', () => {
+ const p = join(fresh(), 'hooks.json');
+ writeFileSync(p, '{ not json');
+ assert.equal(readJsonObject(p), 'unparseable');
+});
+
+test('readJsonObject: a top-level array or primitive is unparseable — we only merge into an object', () => {
+ const dir = fresh();
+ const arr = join(dir, 'arr.json'); writeFileSync(arr, '[1,2,3]');
+ const num = join(dir, 'num.json'); writeFileSync(num, '42');
+ const nul = join(dir, 'nul.json'); writeFileSync(nul, 'null');
+ assert.equal(readJsonObject(arr), 'unparseable');
+ assert.equal(readJsonObject(num), 'unparseable');
+ assert.equal(readJsonObject(nul), 'unparseable');
+});
+
+test('isGraftEntry matches graft-owned entries and tolerates undefined', () => {
+ assert.ok(isGraftEntry({ command: 'node /x/graft-hooks.cjs post-edit' }));
+ assert.ok(!isGraftEntry({ command: 'other-tool.sh' }));
+ assert.doesNotThrow(() => isGraftEntry(undefined));
+ assert.equal(isGraftEntry(undefined), false);
+});
+
+test('writeOwned is idempotent: created, then unchanged', () => {
+ const p = join(fresh(), 'shim.cjs');
+ assert.equal(writeOwned('x', p, 'hello').action, 'created');
+ assert.equal(writeOwned('x', p, 'hello').action, 'unchanged');
+ assert.equal(writeOwned('x', p, 'world').action, 'updated');
+ assert.equal(readFileSync(p, 'utf8'), 'world');
+});
diff --git a/test/hosts-cursor-hooks.test.ts b/test/hosts-cursor-hooks.test.ts
new file mode 100644
index 00000000..2a480095
--- /dev/null
+++ b/test/hosts-cursor-hooks.test.ts
@@ -0,0 +1,105 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, existsSync, statSync, readdirSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { installCursorHooks, cursorHookTargets } from '../src/hosts/cursor-hooks.js';
+import { runHostsInit } from '../src/hosts/init.js';
+
+function fresh(): string { return mkdtempSync(join(tmpdir(), 'graft-cursorhooks-')); }
+
+const HAS_EXEC_BIT = process.platform !== 'win32';
+function assertRunnableShim(shim: string, note: string): void {
+ assert.ok(existsSync(shim), `${note}: shim missing at ${shim}`);
+ if (HAS_EXEC_BIT) assert.ok(statSync(shim).mode & 0o111, note);
+}
+
+const shimPath = (repo: string) => join(repo, '.cursor', 'hooks', 'graft-hooks.cjs');
+const cfgPath = (repo: string) => join(repo, '.cursor', 'hooks.json');
+
+test('cursorHookTargets are repo-local and always present (no CLI-home gate)', () => {
+ const repo = fresh();
+ const t = cursorHookTargets(repo);
+ assert.equal(t.length, 2);
+ assert.ok(t.every((w) => w.scope === 'repo' && w.hostId === 'cursor'));
+ assert.deepEqual(t.map((w) => w.path).sort(), [cfgPath(repo), shimPath(repo)].sort());
+});
+
+test('writes shim + hooks.json (version 1), idempotent on re-run', () => {
+ const repo = fresh();
+ const w = installCursorHooks(repo);
+ assert.equal(w.length, 2);
+ assertRunnableShim(shimPath(repo), 'shim is executable');
+ const cfg = JSON.parse(readFileSync(cfgPath(repo), 'utf8'));
+ assert.equal(cfg.version, 1, 'Cursor hooks.json carries a schema version');
+ const sub = (event: string) => cfg.hooks[event][0].command.match(/cjs" (\S+)$/)?.[1];
+ assert.equal(sub('postToolUse'), 'cursor-post-tool');
+ assert.equal(sub('afterMCPExecution'), 'cursor-mcp');
+ assert.equal(sub('sessionEnd'), 'cursor-session-end');
+ // postToolUse filters to the read/shell tools; the MCP + end hooks take every event.
+ assert.match(cfg.hooks.postToolUse[0].matcher, /Read\|Grep\|Glob\|Search\|Shell/);
+ assert.ok(!('matcher' in cfg.hooks.afterMCPExecution[0]), 'no matcher on afterMCPExecution');
+ assert.ok(!('matcher' in cfg.hooks.sessionEnd[0]), 'no matcher on sessionEnd');
+
+ const again = installCursorHooks(repo);
+ assert.deepEqual(again.map((x) => x.action), ['unchanged', 'unchanged'], 'idempotent');
+ const after = JSON.parse(readFileSync(cfgPath(repo), 'utf8'));
+ for (const ev of ['postToolUse', 'afterMCPExecution', 'sessionEnd'])
+ assert.equal(after.hooks[ev].length, 1, `${ev} not duplicated on re-run`);
+});
+
+test('foreign hook entries and a pre-existing version are preserved; stale graft entries replaced', () => {
+ const repo = fresh();
+ mkdirSync(join(repo, '.cursor'), { recursive: true });
+ writeFileSync(cfgPath(repo), JSON.stringify({
+ version: 1,
+ hooks: {
+ postToolUse: [
+ { command: 'other-tool.sh' },
+ { command: 'node /old/graft-hooks.cjs cursor-post-tool' },
+ ],
+ },
+ }));
+ installCursorHooks(repo);
+ const entries = JSON.parse(readFileSync(cfgPath(repo), 'utf8')).hooks.postToolUse;
+ assert.equal(entries.length, 2, 'foreign kept, stale graft replaced by fresh');
+ assert.ok(entries.some((e: any) => e.command === 'other-tool.sh'), 'foreign entry preserved');
+ assert.ok(entries.some((e: any) => /graft-hooks\.cjs" cursor-post-tool$/.test(e.command)), 'fresh graft entry present');
+ assert.ok(!JSON.stringify(entries).includes('/old/'), 'stale graft entry removed');
+});
+
+test('unparseable hooks.json is never rewritten', () => {
+ const repo = fresh();
+ mkdirSync(join(repo, '.cursor'), { recursive: true });
+ writeFileSync(cfgPath(repo), '{ nope');
+ const w = installCursorHooks(repo);
+ assert.ok(w.some((x) => x.action === 'skipped-unparseable'));
+ assert.equal(readFileSync(cfgPath(repo), 'utf8'), '{ nope');
+});
+
+// ── runHostsInit wiring ─────────────────────────────────────────────────────
+
+test('runHostsInit --agents cursor writes repo-local hooks and never touches ~/.cursor', () => {
+ const home = fresh(); const repo = fresh();
+ const r = runHostsInit(repo, { home, agents: ['cursor'] });
+ assert.ok(existsSync(cfgPath(repo)), 'hooks.json written in the repo');
+ assert.ok(existsSync(shimPath(repo)), 'shim written in the repo');
+ assert.ok(r.hooks.some((h) => h.id === 'cursor-hooks'), 'reported in result.hooks');
+ // Nothing user-level: the home dir stays empty.
+ assert.ok(!existsSync(join(home, '.cursor')), 'no ~/.cursor writes');
+});
+
+test('cursor hooks are repo-local, so --no-global does NOT suppress them', () => {
+ const home = fresh(); const repo = fresh();
+ runHostsInit(repo, { home, agents: ['cursor'], global: false });
+ assert.ok(existsSync(cfgPath(repo)), '--no-global keeps the repo-local Cursor hooks');
+});
+
+test('--no-hooks skips the Cursor hook files (rule file still written)', () => {
+ const home = fresh(); const repo = fresh();
+ const r = runHostsInit(repo, { home, agents: ['cursor'], hooks: false });
+ assert.ok(!existsSync(cfgPath(repo)), 'no hooks.json under --no-hooks');
+ assert.ok(!existsSync(shimPath(repo)), 'no shim under --no-hooks');
+ assert.ok(!r.hooks.some((h) => h.id?.startsWith('cursor')), 'no cursor hook writes reported');
+ assert.ok(existsSync(join(repo, '.cursor', 'rules', 'graft.mdc')), 'the rule file is still written');
+});
diff --git a/test/session-metrics.test.ts b/test/session-metrics.test.ts
new file mode 100644
index 00000000..a2706b1e
--- /dev/null
+++ b/test/session-metrics.test.ts
@@ -0,0 +1,185 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtempSync, mkdirSync, writeFileSync, utimesSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ classifyToolUse,
+ commandInvokesGraft,
+ isGraftMcpTool,
+ isMcpToolName,
+ parseSavings,
+ recordToolUse,
+ latestSession,
+ formatSessionStats,
+} from '../src/claude/session-metrics.js';
+import { readSession } from '../src/claude/state.js';
+
+function fresh(): string { return mkdtempSync(join(tmpdir(), 'graft-metrics-')); }
+
+// ── the classifier: the load-bearing table ────────────────────────────────
+
+/**
+ * Every host names its tools differently; this is the one place those names are
+ * mapped to graft / source / neither. The MCP rows cover the three prefixes a
+ * graft tool arrives under across hosts (bare, `MCP:`, `mcp__…__`) — the matcher
+ * must recognise all three, since it is what decides whether a call is counted.
+ */
+const CASES: Array<{ name: string; command?: string; want: 'graft' | 'source' | null }> = [
+ // graft MCP tools, every host prefix
+ { name: 'graft_find_code', want: 'graft' },
+ { name: 'MCP:graft_find_code', want: 'graft' },
+ { name: 'mcp__graft__graft_find_code', want: 'graft' },
+ { name: 'graft_repo_map', want: 'graft' },
+ // native source-read tools (Claude + Cursor)
+ { name: 'Read', want: 'source' },
+ { name: 'Grep', want: 'source' },
+ { name: 'Glob', want: 'source' },
+ { name: 'Search', want: 'source' },
+ // shell running the graft CLI → graft
+ { name: 'Bash', command: 'graft ask "how does auth work"', want: 'graft' },
+ { name: 'Shell', command: 'graft map', want: 'graft' },
+ { name: 'Shell', command: 'npx -y @nanonets/graft callers foo', want: 'graft' },
+ { name: 'Bash', command: 'node dist/cli.js grep bar', want: 'graft' },
+ // shell running something else → neither
+ { name: 'Bash', command: 'ls -la', want: null },
+ { name: 'Shell', command: 'git status', want: null },
+ // a path that merely contains "graft" is not an invocation
+ { name: 'Bash', command: './mygraft/run.sh', want: null },
+ // a third-party MCP tool whose NAME merely contains "graft" is NOT a graft read —
+ // the name test is anchored on the real vocabulary, not a loose substring
+ { name: 'mygraft_search', want: null },
+ { name: 'graft-adjacent-tool', want: null },
+ { name: 'some__graft__tool', want: null },
+ // edits / spawns / unknown → neither
+ { name: 'Write', want: null },
+ { name: 'Edit', want: null },
+ { name: 'Task', want: null },
+ { name: '', want: null },
+];
+
+for (const c of CASES) {
+ test(`classifyToolUse(${c.name || '∅'}${c.command ? ` :: ${c.command}` : ''}) → ${c.want}`, () => {
+ assert.equal(classifyToolUse(c.name, c.command), c.want);
+ });
+}
+
+test('isGraftMcpTool recognises graft tools across prefixes, and rejects lookalikes', () => {
+ // every host prefix, canonical and legacy names
+ assert.ok(isGraftMcpTool('MCP:graft_find_code'));
+ assert.ok(isGraftMcpTool('mcp__graft__graft_find_code'));
+ assert.ok(isGraftMcpTool('graft_trace_calls'));
+ assert.ok(isGraftMcpTool('graft_ask'), 'a legacy alias still counts');
+ // anchored on the real name list — a third-party tool that merely CONTAINS
+ // "graft" must not be counted as a graft read
+ assert.ok(!isGraftMcpTool('Read'));
+ assert.ok(!isGraftMcpTool('mygraft_search'));
+ assert.ok(!isGraftMcpTool('graft-adjacent-tool'));
+ assert.ok(!isGraftMcpTool('mcp__other__graft_helper'));
+});
+
+test('isMcpToolName recognises the server-prefixed shapes', () => {
+ assert.ok(isMcpToolName('MCP:graft_find_code'));
+ assert.ok(isMcpToolName('mcp__graft__graft_find_code'));
+ assert.ok(!isMcpToolName('Read'));
+ assert.ok(!isMcpToolName('Shell'));
+});
+
+test('commandInvokesGraft is anchored — not fooled by a substring path', () => {
+ assert.ok(commandInvokesGraft('graft ask x'));
+ assert.ok(commandInvokesGraft('cd repo && graft map'));
+ assert.ok(!commandInvokesGraft('cat mygraft.txt'));
+ assert.ok(!commandInvokesGraft('echo upgraft'));
+});
+
+// ── parseSavings ───────────────────────────────────────────────────────────
+
+test('parseSavings sums every footer, tolerant of commas', () => {
+ assert.equal(parseSavings('nothing here'), 0);
+ assert.equal(parseSavings('[graft] tokens saved ≈ 2,181 (89%) — …'), 2181);
+ assert.equal(
+ parseSavings('a\n[graft] tokens saved ≈ 100 — …\nb\n[graft] tokens saved ≈ 1,000 — …'),
+ 1100,
+ );
+});
+
+// ── recordToolUse ──────────────────────────────────────────────────────────
+
+test('recordToolUse increments the right counter and accumulates savings', () => {
+ const d = fresh();
+ recordToolUse(d, 's1', { kind: 'graft', savedTokens: 500 });
+ recordToolUse(d, 's1', { kind: 'graft' });
+ recordToolUse(d, 's1', { kind: 'source' });
+ const s = readSession(d, 's1');
+ assert.equal(s.graftReads, 2);
+ assert.equal(s.sourceReads, 1);
+ assert.equal(s.savedTokens, 500);
+});
+
+test('recordToolUse is a no-op when there is nothing to record (no file written)', () => {
+ const d = fresh();
+ recordToolUse(d, 's1', { kind: null, savedTokens: 0 });
+ recordToolUse(d, 's1', {});
+ // readSession returns the empty default without a file; the proof it never
+ // wrote is that a fresh empty session equals what we read.
+ const s = readSession(d, 's1');
+ assert.equal(s.graftReads, 0);
+ assert.equal(s.sourceReads, 0);
+ assert.equal(s.savedTokens, 0);
+});
+
+test('recordToolUse can log savings on a graft read with no explicit kind classification', () => {
+ const d = fresh();
+ recordToolUse(d, 's1', { kind: 'graft', savedTokens: 1990 });
+ assert.equal(readSession(d, 's1').savedTokens, 1990);
+ assert.equal(readSession(d, 's1').graftReads, 1);
+});
+
+test('recordToolUse stamps the host once — the first tool use owns the attribution', () => {
+ const d = fresh();
+ recordToolUse(d, 's1', { kind: 'graft', host: 'cursor' });
+ assert.equal(readSession(d, 's1').host, 'cursor');
+ // a later use from a different host must not overwrite the stamp
+ recordToolUse(d, 's1', { kind: 'source', host: 'claude-code' });
+ assert.equal(readSession(d, 's1').host, 'cursor', 'host is not re-stamped');
+});
+
+// ── latestSession + formatSessionStats (what `graft stats` reads) ──────────
+
+function writeSession(d: string, id: string, body: object, ageMs = 0): void {
+ const dir = join(d, 'graft', '.cache', 'session');
+ mkdirSync(dir, { recursive: true });
+ const p = join(dir, `${id}.json`);
+ writeFileSync(p, JSON.stringify(body));
+ if (ageMs) { const w = new Date(Date.now() - ageMs); utimesSync(p, w, w); }
+}
+
+test('latestSession returns null when no session exists', () => {
+ assert.equal(latestSession(fresh()), null);
+});
+
+test('latestSession picks the most recently touched session file', () => {
+ const d = fresh();
+ writeSession(d, 'old', { graftReads: 1, sourceReads: 9 }, 60_000);
+ writeSession(d, 'new', { graftReads: 8, sourceReads: 2 }, 0);
+ const s = latestSession(d)!;
+ assert.equal(s.id, 'new');
+ assert.equal(s.graftReads, 8);
+});
+
+test('formatSessionStats renders the mix, savings and last query', () => {
+ const out = formatSessionStats({
+ id: 'abc', lastQuery: 'where is auth', perAgentQuery: {},
+ graftReads: 8, sourceReads: 2, savedTokens: 12345,
+ });
+ assert.match(out, /session abc/);
+ assert.match(out, /graft reads:\s+8/);
+ assert.match(out, /source reads:\s+2/);
+ assert.match(out, /80% graft/);
+ assert.match(out, /12,345/);
+ assert.match(out, /where is auth/);
+});
+
+test('formatSessionStats has a friendly empty state', () => {
+ assert.match(formatSessionStats(null), /no session recorded yet/);
+});
diff --git a/test/telemetry-sessions.test.ts b/test/telemetry-sessions.test.ts
index 37f06f46..46cc3975 100644
--- a/test/telemetry-sessions.test.ts
+++ b/test/telemetry-sessions.test.ts
@@ -6,7 +6,7 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import { mkdirSync, utimesSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
-import { SESSION_IDLE_MS, flushClosedSessions } from '../src/telemetry/sessions.js';
+import { SESSION_IDLE_MS, flushClosedSessions, summarizeSession } from '../src/telemetry/sessions.js';
import { peek } from '../src/telemetry/queue.js';
import { readSession } from '../src/claude/state.js';
import { tmpRepo } from './helpers.js';
@@ -48,6 +48,61 @@ test('a closed session is rolled up into one bucketed event', () => {
}
});
+test('the rollup is attributed to the host that flushed it (Cursor, not the hardcoded default)', () => {
+ const { repo, home } = fixture('sess-host');
+ writeSessionFile(repo, 's1', { graftReads: 4, sourceReads: 1 }, SESSION_IDLE_MS + 1000);
+ assert.equal(flushClosedSessions(repo, Date.now(), home, OPEN, 'cursor'), 1);
+ const [ev] = peek(home) as { properties: Record<string, string> }[];
+ assert.equal(ev.properties.agent_host, 'cursor');
+});
+
+test('the default host stays claude-code when none is passed', () => {
+ const { repo, home } = fixture('sess-host-default');
+ writeSessionFile(repo, 's1', { graftReads: 1 }, SESSION_IDLE_MS + 1000);
+ assert.equal(flushClosedSessions(repo, Date.now(), home, OPEN), 1);
+ const [ev] = peek(home) as { properties: Record<string, string> }[];
+ assert.equal(ev.properties.agent_host, 'claude-code');
+});
+
+test('a session stamped with a host is attributed to it, even when the idle sweep (claude-code default) flushes it', () => {
+ const { repo, home } = fixture('sess-host-stamp');
+ writeSessionFile(repo, 's1', { graftReads: 4, host: 'cursor' }, SESSION_IDLE_MS + 1000);
+ // the flusher passes no host → default claude-code; the file's stamp must win.
+ assert.equal(flushClosedSessions(repo, Date.now(), home, OPEN), 1);
+ const [ev] = peek(home) as { properties: Record<string, string> }[];
+ assert.equal(ev.properties.agent_host, 'cursor');
+});
+
+test('summarizeSession force-closes a just-touched session — the idle gate is skipped', () => {
+ const { repo, home } = fixture('sess-force');
+ // mtime = now: flushClosedSessions would skip this, but the end-of-session hook must not.
+ writeSessionFile(repo, 's1', { graftReads: 8, sourceReads: 2, savedTokens: 7400 }, 0);
+ assert.equal(flushClosedSessions(repo, Date.now(), home, OPEN), 0, 'the idle sweep skips a fresh file');
+ assert.equal(summarizeSession(repo, 's1', { host: 'cursor', home, env: OPEN }), 1);
+ const [ev] = peek(home) as { event: string; properties: Record<string, string> }[];
+ assert.equal(ev.event, 'session_summary');
+ assert.equal(ev.properties.agent_host, 'cursor');
+ assert.equal(ev.properties.graft_reads_bucket, '5-19');
+ // and it is marked, so a later idle sweep can't double-count it
+ assert.equal(readSession(repo, 's1').summarized, true);
+});
+
+test('summarizeSession counts a session exactly once', () => {
+ const { repo, home } = fixture('sess-force-once');
+ writeSessionFile(repo, 's1', { graftReads: 1 }, 0);
+ assert.equal(summarizeSession(repo, 's1', { host: 'cursor', home, env: OPEN }), 1);
+ assert.equal(summarizeSession(repo, 's1', { host: 'cursor', home, env: OPEN }), 0, 'already summarized');
+ assert.equal(peek(home).length, 1);
+});
+
+test('summarizeSession prefers the file stamp over the passed host', () => {
+ const { repo, home } = fixture('sess-force-stamp');
+ writeSessionFile(repo, 's1', { graftReads: 1, host: 'cursor' }, 0);
+ assert.equal(summarizeSession(repo, 's1', { host: 'claude-code', home, env: OPEN }), 1);
+ const [ev] = peek(home) as { properties: Record<string, string> }[];
+ assert.equal(ev.properties.agent_host, 'cursor');
+});
+
test('a live session is left alone', () => {
const { repo, home } = fixture('sess-live');
writeSessionFile(repo, 's1', { graftReads: 3 }, 60_000);