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
Retrieval + steering fixes: staleness, test de-rank, known-target/refactor guidance, callers --depth all
Shrish Dwivedi7d74ecde6ccd
diff --git a/package-lock.json b/package-lock.jsonindex 965b8439..8c9858da 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "@nanonets/graft",- "version": "0.7.0",+ "version": "0.8.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@nanonets/graft",- "version": "0.7.0",+ "version": "0.8.0","hasInstallScript": true,"license": "MIT","dependencies": {diff --git a/package.json b/package.jsonindex c6a6e2e3..5040181a 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "@nanonets/graft",- "version": "0.7.1",+ "version": "0.8.0","description": "Build a repo's context graph as a folder of linked markdown files that live in the repo and stay in sync with the code through git.","keywords": ["ai",diff --git a/src/ask/ask.ts b/src/ask/ask.tsindex a4ba6a63..fe41bd7d 100644--- a/src/ask/ask.ts+++ b/src/ask/ask.ts@@ -134,6 +134,17 @@ function loadCorpus(outDir: string): Corpus {* far less than a rare, discriminating identifier ("scrolling"). Without idf,* pure term-frequency lets an incidental common word dominate the ranking; this* is the lexical half of the keyword-collision fix (graph-rank is the other). */+/** Test files rarely answer "how does X work" / "where is Y" — they mirror the+ * real symbol's tokens, so a test can out-score the definition on a lexical tie+ * and land as the top hit (observed: an `ask` returning a `Test…` function first,+ * sending the agent to the wrong file). A multiplicative de-rank keeps tests in+ * the results (they still matter for "where are the tests") but below the real+ * definition. Covers Go (`_test.go`), JS/TS (`.test.` / `.spec.`), and test dirs. */+export function isTestPath(path: string): boolean {+ return /(^|\/)(tests?|__tests__|spec)\/|(_test|\.test|\.spec)\.[a-z]+$/i.test(path || "");+}+const TEST_RANK_PENALTY = 0.35;+function score(query: Map<string, number>,doc: Map<string, number>,@@ -253,7 +264,7 @@ type StructuralOutcome = { result: AskResult } | { fallthroughNote: string } | nfunction fallthroughNoteFor(subject: string): string {return (`structural index: no entries for '${subject}' — showing lexical matches; ` +- `for exhaustive callers use grep -rn '${subject}'`+ `for precise edges try graft callers '${subject}', or graft grep '${subject}' for every reference (loosen the pattern if it returns nothing)`);}@@ -378,6 +389,14 @@ function lexical(query: string, corpus: Corpus, limit: number, graphRank: booleaconst q = new Map([...counts(tokenize(query)).keys()].map((t) => [t, 1]));const graph = corpus.graph;+ // Test-file de-ranking is query-aware: a query that ASKS about tests wants test+ // files on top, so it gets no penalty; every other query wants the real+ // definition first. This stops a test that merely contains the query's literals+ // (e.g. `TestDownloadStall` matching "download stall") from outranking the+ // source it exercises — the "tests ranked above the actual code" trap.+ const wantsTests = /\b(tests?|specs?|coverage|assert(?:ion)?s?|fixtures?|mocks?)\b/i.test(query);+ const testFactor = (path: string): number => (!wantsTests && isTestPath(path) ? TEST_RANK_PENALTY : 1);+// ── Pass 1: tokenize every scored field once, and collect per-document token// bags so IDF can down-weight words that occur across the whole corpus. `--in`// drops a concept unless at least one of its sources falls under the prefix —@@ -536,9 +555,10 @@ function lexical(query: string, corpus: Corpus, limit: number, graphRank: booleaconst out = new Map<string, number>();for (const { n, name, path, body } of docs) {const total =- score(q, name, sIdf) * 3 +- score(q, path, sIdf) * 2 +- bm25(q, body, sIdf, bodyLen(body), avg);+ (score(q, name, sIdf) * 3 ++ score(q, path, sIdf) * 2 ++ bm25(q, body, sIdf, bodyLen(body), avg)) *+ testFactor(n.path);if (total > 0) out.set(n.id, total);}return out;@@ -609,9 +629,10 @@ function lexical(query: string, corpus: Corpus, limit: number, graphRank: boolea// Name and path are short identifiers → plain idf-weighted overlap; the body// is length-normalized via BM25 so long definitions don't win on bulk.const total =- score(q, name, idf) * 3 +- score(q, path, idf) * 2 +- bm25(q, body, idf, bodyLen(body), avgBodyLen);+ (score(q, name, idf) * 3 ++ score(q, path, idf) * 2 ++ bm25(q, body, idf, bodyLen(body), avgBodyLen)) *+ testFactor(n.path);if (total > 0) {lex.set(n.id, total);maxLex = Math.max(maxLex, total);diff --git a/src/claude/format.ts b/src/claude/format.tsindex d6a3a010..727d6e78 100644--- a/src/claude/format.ts+++ b/src/claude/format.ts@@ -154,7 +154,7 @@ export function relevantRetrieval(ask: AskJson, s: SessionState, cap = 3): strinreturn txt;}-export function formatOrientation(indexMd: string, budgetBytes = 1500): string {+export function formatOrientation(indexMd: string, budgetBytes = 1500, staleNote?: string): string {// Always-on directive (cached, seen turn 0) so the agent reaches for graft's// commands without waiting for the discretionary skill to load. This is the// reliable steering channel (fires every session, unlike the discretionary@@ -166,11 +166,14 @@ export function formatOrientation(indexMd: string, budgetBytes = 1500): string {` • graft ask "<task>" --source: locate + understand. Ranked nodes with the code inlined at each file:line (the ≤8-line crux; add --full for the whole span). The default for "how does X work" / "where is Y".\n` +` • graft grep "<literal>": exhaustive find. Every occurrence, grouped by enclosing symbol; use when you need them ALL (ask is ranked top-N and misses instances).\n` +` • graft skeleton <file>: a file's whole API in ~200 tokens, every signature + span, ~10x cheaper than reading the file.\n` +- ` • graft callers <sym> [--direction out] [--depth N]: exact edges. Who calls it (default), what it calls (--direction out), or the full blast radius (--depth 2). Run before you change a symbol.\n` ++ ` • graft callers <sym> [--direction out] [--depth N|all]: exact edges. Who calls it (default), what it calls (--direction out), or the full blast radius (--depth 2, or --depth all for every connected source). Run before you change a symbol.\n` +` • graft map: orientation for an unfamiliar repo, directory clusters, hubs, hotspots. map alone is the answer; don't then skeleton every subsystem it names.\n` +` In a monorepo, add --in <path>/ to ask/grep/callers to scope to one sub-project; hits are labeled [scope/].\n` ++ ` Already know the file or symbol to change? Go straight to it: graft grep "<symbol>", read the span, edit. Save ask for when you don't yet know where the code lives.\n` ++ ` Refactor, rename, or multi-file change? Run graft callers <sym> --depth all FIRST to map every connected file; editing the primary file and stopping is the classic miss (platform siblings, a new file to extract).\n` +`Each tool prints a "[graft] tokens saved ≈ N" footer; when you used graft this turn, close your reply with a one-line tally of the total saved (e.g. 🌱 graft saved ~12k tokens this turn, 3 calls).\n`;- return `${directive}\nrepo map (graft/INDEX.md):\n${indexMd.slice(0, budgetBytes)}`;+ const banner = staleNote ? `${staleNote}\n\n` : "";+ return `${banner}${directive}\nrepo map (graft/INDEX.md):\n${indexMd.slice(0, budgetBytes)}`;}export function renderSubagent(agentName: string, session: SessionState | null): string {diff --git a/src/claude/hooks.ts b/src/claude/hooks.tsindex 046e0605..205c59fc 100644--- a/src/claude/hooks.ts+++ b/src/claude/hooks.ts@@ -3,6 +3,7 @@ import { execFileSync, spawn } from 'node:child_process';import { join, basename } from 'node:path';import { readWiring } from './stats.js';import { formatBlastRadius, relevantRetrieval, formatOrientation } from './format.js';+import { indexFreshness, staleBanner } from '../context/check.js';import { patchStats, readStats, acquireLock, readSession, writeSession } from './state.js';import { graftCliPath, claudeScriptPath } from './paths.js';import { scopeOf, scopesOfGraph } from '../graph/scopes.js';@@ -145,7 +146,8 @@ export async function main(event: string): Promise<void> {if (event === 'session-start') {try {const idx = readFileSync(join(dir, 'graft', 'INDEX.md'), 'utf8');- emit('SessionStart', formatOrientation(idx));+ const banner = staleBanner(indexFreshness(dir)) ?? undefined;+ emit('SessionStart', formatOrientation(idx, undefined, banner));} catch { /* no INDEX.md — skip */ }return;}diff --git a/src/claude/skill-template.ts b/src/claude/skill-template.tsindex 8da65e40..2791310d 100644--- a/src/claude/skill-template.ts+++ b/src/claude/skill-template.ts@@ -44,8 +44,13 @@ enclosing symbol** and ranked by coupling; it also reports files it couldn't rea- **Use it when** you need every occurrence: all call sites, all uses of aconstant, all providers. \`ask\` is ranked top-N and *will* miss instances;grep won't. One grep replaces a spray of asks.-- \`-i\` case-insensitive; \`--in <path>\` scopes to a subtree. Fall back to raw- \`grep -rn\` only for files graft doesn't index (docs, configs, new files).+- Search a **short symbol name or literal**, not a full guessed signature: an+ over-specific regex (\`func (s *Server) GenerateHandler\`) returns nothing even+ when the code is indexed. If a grep misses, **loosen it** (drop the receiver+ and signature, keep the bare name) and retry \`graft grep\` — do NOT switch to+ raw \`grep -rn\`, which is slower and unranked.+- \`-i\` case-insensitive; \`--in <path>\` scopes to a subtree. Raw \`grep -rn\` is+ only for files graft genuinely doesn't index (docs, configs, brand-new files).### 3 · \`graft skeleton <file>\`: a file's API at a glanceSignatures-only view of one file (every function / method / type with its span)@@ -62,6 +67,10 @@ Precomputed call/reference edges, not a text search. Symbol can be bare- \`--direction out\`: **what this symbol itself calls/depends on** (the old \`callees\`).- \`--depth N\`: walk transitively N hops for the **full blast radius** (the old\`impact\`); \`--depth 2\` is the usual "what breaks if I touch this".+- \`--depth all\`: the **entire connected closure** — every source reachable+ through the edges. Reach for this before a **refactor, rename, or any+ multi-file change**: it surfaces the sibling and downstream files (platform+ variants, a module you must split out) that a single-file edit would miss.### 5 · \`graft map\`: orientation for an unfamiliar repo or areaA token-budgeted tour: directory clusters, per-directory hubs, and global@@ -82,8 +91,9 @@ You rarely touch these mid-task; the graph is already built and committed.| Onboarding / "explain this codebase" | \`graft map\`, then read the named hub cards | 1 || Understanding a flow ("how does X work") | \`graft ask "<flow>" --source\` | 1 || Finding where a change belongs | \`graft ask "where is <behavior>" --source\` | 1 |-| Editing a known symbol | \`graft ask "<symbol>" --source\`, edit at the \`file:line\` | 1 |+| Editing a symbol you can already name | \`graft grep "<symbol>"\`, edit at the \`file:line\` (skip \`ask\` — you know where it is) | 1 || Renaming / deleting / changing a signature | \`graft callers <sym> --depth 2\` first | 1 |+| Refactor / multi-file change (before editing) | \`graft callers <sym> --depth all\` — map every connected file, don't stop at the first | 1 || "What does this depend on?" | \`graft callers <sym> --direction out\` | 1 || Finding every occurrence of a pattern | \`graft grep "<literal>"\` | 1 || "What's the API of this file?" | \`graft skeleton <file>\` | 1 |@@ -99,10 +109,15 @@ you already know where you're working, narrow with \`graft ask "<task>" --in <sc- A node's \`covers:\` list already gives exact \`file:line\` for every symbol, socite straight from it. The spans are generated from source and authoritative;don't re-open or re-grep files to "double-check".-- When editing, pull the span with \`graft ask "<symbol>" --source\` and edit at- that \`file:line\`; never read the whole file to orient, the pack did that.+- When the task already names the file or symbol to change, go straight there:+ \`graft grep "<symbol>"\` for the exact \`file:line\`, then edit. Reserve+ \`graft ask\` for when you don't yet know where the code lives — an \`ask\`+ round-trip is wasted on a target you can already name.- Trust the answer and act. Reach for a second tool only when the first genuinelyfell short: weak hits, a truncated span, or a need to be exhaustive.+- If graft names a path that isn't on disk, its index is ahead of your checkout+ (a branch switch or unpulled move). Don't read the missing file — \`graft grep\`+ the symbol to find where it lives now, or run \`graft build\` to refresh.## Report what graft saved, every turnEach retrieval tool ends its output with a \`[graft] tokens saved ≈ N\` line: thediff --git a/src/cli.ts b/src/cli.tsindex 5116f7d3..16161bc4 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -311,12 +311,12 @@ programprogram.command("callers").description(- "Who calls/references a symbol ($0, no LLM). --direction out gives callees (what it calls); --depth N walks transitively for full blast radius",+ "Who calls/references a symbol ($0, no LLM). --direction out gives callees (what it calls); --depth N (or all) walks transitively for full blast radius",).argument("<symbol>", "bare name, qualified (Class.method), or package-qualified (pkg.Fn)").argument("[dir]", "repository root", ".").option("--direction <in|out>", 'edge direction: "in" = callers (default), "out" = callees')- .option("-d, --depth <n>", "walk transitively up to N hops for blast radius (default 1)")+ .option("-d, --depth <n>", 'walk transitively up to N hops for blast radius, or "all" for the full connected closure (default 1)').option("--in <path>", "narrow matches to nodes whose path contains this substring").option("--json", "output as JSON").action(@@ -329,7 +329,9 @@ programif (!opts.json && readWorkspace(resolve(dir), globalOpts.dir)) {runWorkspaceCallers(resolve(dir), globalOpts.dir, symbol, {direction: opts.direction === "out" ? "out" : "in",- depth: opts.depth ? Number(opts.depth) : undefined,+ depth: opts.depth+ ? (/^(all|full|max)$/i.test(opts.depth) ? Number.POSITIVE_INFINITY : Number(opts.depth))+ : undefined,in: opts.in,});return;diff --git a/src/context/check.ts b/src/context/check.tsindex 327a5a35..237d46aa 100644--- a/src/context/check.ts+++ b/src/context/check.ts@@ -106,6 +106,47 @@ export function checkContext(dir: string, opts: CheckOptions = {}): CheckResultreturn result;}+/** A cheap, query-time staleness signal (unlike {@link checkContext}, which+ * re-hashes every file for CI). */+export interface FreshnessResult {+ /** Recorded source files that are no longer on disk. */+ missing: number;+ /** Total source files the manifest recorded. */+ total: number;+}++/**+ * How many recorded source files have vanished from disk — an existence-only+ * check (stat, never a read or a hash), safe to call on a hot path like session+ * start. This catches the common "index built on a different tree" case: a+ * branch switch, a `git checkout` to an older commit, an unpulled move — states+ * where graft would otherwise confidently point at files that aren't there and+ * send the agent chasing them. Returns null when there's no graph at all.+ */+export function indexFreshness(dir: string, opts: CheckOptions = {}): FreshnessResult | null {+ const root = resolve(dir);+ const outDir = contextDirFor(root, opts.contextDir);+ const manifest = readManifest(outDir);+ if (!manifest) return null;+ let missing = 0;+ for (const ref of manifest.files) {+ if (!existsSync(resolve(root, ref.path))) missing++;+ }+ return { missing, total: manifest.files.length };+}++/** One-line staleness banner for orientation/query output, or null when the+ * index is fresh (or absent). Terse on purpose — it rides atop the orientation+ * the agent reads first, so it must earn its tokens. */+export function staleBanner(f: FreshnessResult | null): string | null {+ if (!f || f.missing === 0) return null;+ return (+ `⚠ graft's index may be ahead of your working tree: ${f.missing} of ${f.total} indexed ` ++ `files are not on disk (branch switch or uncommitted move?). If graft names a path that ` ++ `isn't there, don't chase it — \`graft grep\` the symbol to find where it lives now; run \`graft build\` to refresh.`+ );+}+/** Render a check result as a human-readable report. */export function formatCheckReport(r: CheckResult): string {if (r.missing) {diff --git a/src/graph/traverse-cli.ts b/src/graph/traverse-cli.tsindex 5c8559f5..2ec2f2ff 100644--- a/src/graph/traverse-cli.ts+++ b/src/graph/traverse-cli.ts@@ -68,7 +68,7 @@ export function callersSavings(export function looseNoteFor(direction: Direction, name: string): string {const label = direction === "out" ? "callees" : "callers";const dir = direction === "out" ? "outgoing" : "incoming";- return ` no indexed ${label} — the graph has no ${dir} call/reference edges for this symbol; try grep -rn "${name}"`;+ return ` no indexed ${label} — the graph has no ${dir} call/reference edges for this symbol as written. Check the name (try the bare symbol, or "Type.method"), or find its uses with graft grep "${name}". Fall back to raw grep -rn only for unindexed files`;}interface SymbolJson {@@ -142,12 +142,21 @@ export function runCallersCommand(query: string, dir: string, opts: CallersCliOpconst direction = resolveDirection(opts.direction);let depth = DEFAULT_DEPTH;if (opts.depth !== undefined) {- const d = Number(opts.depth);- if (!Number.isFinite(d) || d < 1) {- console.error(`✗ --depth must be a positive number, got "${opts.depth}"`);- process.exit(1);+ // `all` (aka full/max) = the whole transitive closure: walk until no new+ // node is reached. The BFS's visited-set makes this cycle-safe, and it+ // terminates when the frontier empties. This is the "show me every+ // connected source" mode — the right first move before a multi-file+ // refactor, where stopping at direct edges misses sibling/downstream files.+ if (/^(all|full|max)$/i.test(opts.depth)) {+ depth = Number.POSITIVE_INFINITY;+ } else {+ const d = Number(opts.depth);+ if (!Number.isFinite(d) || d < 1) {+ console.error(`✗ --depth must be a positive number or "all", got "${opts.depth}"`);+ process.exit(1);+ }+ depth = Math.floor(d);}- depth = Math.floor(d);}const showDepth = depth > 1;diff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex 2eee807b..5637a153 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -78,7 +78,7 @@ export const TOOLS: ToolDef[] = [{name: 'graft_callers',description:- 'Structural edges for a symbol, over call/reference/import/implements/extends ($0, no LLM). Defaults to direct callers (who depends on it). Set direction:"out" for callees (what it calls); set depth>1 to walk transitively for the full blast radius — who breaks if it changes.',+ 'Structural edges for a symbol, over call/reference/import/implements/extends ($0, no LLM). Defaults to direct callers (who depends on it). Set direction:"out" for callees (what it calls); set depth>1 (or depth:"all" for the full closure) to walk transitively for the full blast radius — every source that breaks if it changes. Run before a multi-file refactor to find ALL affected files.',inputSchema: {type: 'object',properties: {@@ -88,7 +88,7 @@ export const TOOLS: ToolDef[] = [enum: ['in', 'out'],description: '"in" (default) = callers/dependents; "out" = callees/dependencies',},- depth: { type: 'number', description: 'transitive walk depth for blast radius (default 1 = direct edges only)' },+ depth: { description: 'transitive walk depth for blast radius (default 1 = direct edges only); pass "all" for the full connected closure — every source that would be affected' },in: { type: 'string', description: 'narrow matches to nodes whose path contains this substring' },},required: ['symbol'],@@ -245,10 +245,14 @@ export function callTool(const matches = resolveSymbol(w, symbol, inOpt);if (matches.length === 0) return { text: unknownSymbolText(symbol), isError: true };const direction: Direction = args.direction === 'out' ? 'out' : 'in';+ // `depth: "all"` (or a huge number) walks the full transitive closure —+ // every connected source — terminating when no new node is reached.const depth =- typeof args.depth === 'number' && Number.isFinite(args.depth) && args.depth >= 1- ? Math.floor(args.depth)- : 1;+ args.depth === 'all' || args.depth === 'full'+ ? Number.POSITIVE_INFINITY+ : typeof args.depth === 'number' && Number.isFinite(args.depth) && args.depth >= 1+ ? Math.floor(args.depth)+ : 1;const results = matches.map((m) => ({ symbol: m, hits: edgeWalk(w, m, direction, depth) }));const byId = new Map(results.map((r) => [r.symbol.id, r.hits]));const body = renderMatches(direction, depth > 1, matches, (m) => byId.get(m.id) ?? []);diff --git a/src/search/grep-cli.ts b/src/search/grep-cli.tsindex b0a98a6c..5eb7c5dd 100644--- a/src/search/grep-cli.ts+++ b/src/search/grep-cli.ts@@ -70,7 +70,7 @@ export function formatGrepResult(result: GrepResult): string {* otherwise a zero-hit result on a stale graph or wrong root reads as "no* matches" when really some files were never searched at all. */export function zeroHitNote(result: GrepResult): string {- const base = `no hits for "${result.pattern}" in ${result.filesSearched} indexed files — unindexed files (docs, configs, new files) aren't searched; try grep -rn "${result.pattern}" for those`;+ const base = `no hits for "${result.pattern}" in ${result.filesSearched} indexed files. The pattern may be too specific — retry graft grep with a bare symbol name or short substring (drop the receiver, full signature, and regex anchors). All indexed code was searched; use raw grep -rn only for genuinely unindexed files (docs, configs, brand-new files)`;const { files } = result.truncated;if (files === 0) return base;return `${base} — note: ${files} indexed file${files === 1 ? "" : "s"} could not be read (stale graph? run graft build)`;diff --git a/test/ask.test.ts b/test/ask.test.tsindex 78549d25..de43b353 100644--- a/test/ask.test.ts+++ b/test/ask.test.ts@@ -12,7 +12,46 @@ import { tmpdir } from "node:os";import { readFileSync } from "node:fs";import { execFileSync } from "node:child_process";import { buildGraph } from "../src/graph/build.js";-import { ask, formatAsk, skeleton, formatSkeleton } from "../src/ask/ask.js";+import { ask, formatAsk, skeleton, formatSkeleton, isTestPath } from "../src/ask/ask.js";++test("isTestPath: de-ranks test files, not real source", () => {+ for (const p of ["server/download_test.go", "packages/x/tests/foo.test.tsx", "a/__tests__/b.ts", "src/api.spec.ts", "pkg/foo/bar_test.go"])+ assert.ok(isTestPath(p), `${p} should be a test path`);+ for (const p of ["server/download.go", "packages/element/src/selection.ts", "src/api.ts", "cmd/root.go"])+ assert.ok(!isTestPath(p), `${p} should NOT be a test path`);+});++test("test files rank below the source they exercise for a non-test query, but not for a test-seeking one", async () => {+ const dir = mkdtempSync(join(tmpdir(), "graft-ask-testrank-"));+ try {+ writeFileSync(+ join(dir, "download.ts"),+ `export function downloadChunk(url: string): string {\n` ++ ` // stall detection before the first byte arrives\n` ++ ` return url;\n` ++ `}\n`,+ );+ writeFileSync(+ join(dir, "download.test.ts"),+ `import { downloadChunk } from "./download";\n` ++ `// stall detection test exercising downloadChunk before first byte\n` ++ `export function testDownloadChunkStall(): void { downloadChunk("x"); }\n`,+ );+ await buildGraph(dir);+ // Non-test query: the real source must outrank its mirror test file, even+ // though the test contains the same literals ("download", "stall", "detection").+ const r = ask(dir, "download chunk stall detection first byte");+ const src = r.hits.findIndex((h) => /(^|\/)download\.ts(:|$)/.test(h.pointer));+ const tst = r.hits.findIndex((h) => /download\.test\.ts/.test(h.pointer));+ assert.ok(src >= 0, "source hit present");+ assert.ok(tst === -1 || src < tst, "source ranks above its test for a non-test query");+ // Test-seeking query: the penalty lifts, so the test file surfaces.+ const rt = ask(dir, "tests for downloadChunk stall");+ assert.ok(rt.hits.some((h) => /download\.test\.ts/.test(h.pointer)), "test file surfaces for a test-seeking query");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});function makeFixture(): string {const dir = mkdtempSync(join(tmpdir(), "graft-ask-"));@@ -231,7 +270,7 @@ test("ask: structural subject resolves but has zero edges — falls through to lassert.equal(r.mode, "lexical", "never a bare empty structural result");assert.ok(r.note, "a fallthrough note must be set");assert.match(r.note!, /structural index: no entries for 'unusedHelper'/);- assert.match(r.note!, /grep -rn 'unusedHelper'/);+ assert.match(r.note!, /graft callers 'unusedHelper'/);assert.ok(r.hits.length > 0, "lexical fallback still finds the function by name");} finally {rmSync(dir, { recursive: true, force: true });diff --git a/test/claude-format.test.ts b/test/claude-format.test.tsindex 55abbae9..6282e9db 100644--- a/test/claude-format.test.ts+++ b/test/claude-format.test.ts@@ -131,14 +131,26 @@ test('formatOrientation labels and truncates to budget', () => {const out = strip(formatOrientation(md, 1500));assert.match(out, /repo map/);assert.match(out, /reach for graft first/, 'always-on usage directive present');+ 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.ok(out.length < 3200, 'index trimmed to budget; only the fixed directive adds to it');+ 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');// 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');assert.match(out, /graft callers .*--depth/, 'teaches blast radius via callers --depth instead');});+test('formatOrientation prepends a staleness banner when one is supplied', () => {+ const md = 'repo index';+ const note = '⚠ graft index may be ahead of your working tree: 3 of 40 indexed files are not on disk';+ const out = strip(formatOrientation(md, 1500, note));+ // banner rides ABOVE the directive so it is the first thing the agent reads.+ assert.ok(out.indexOf('ahead of your working tree') < out.indexOf('reach for graft first'), 'banner precedes the directive');+ // absent by default (fresh index) — no banner noise when nothing supplied.+ assert.doesNotMatch(strip(formatOrientation(md, 1500)), /ahead of your working tree/);+});+test('renderSubagent shows agent name and its last query', () => {const out = strip(renderSubagent('Explore', { lastQuery: null, perAgentQuery: { Explore: 'pkce flow' }, graftReads: 0, sourceReads: 0 }));assert.match(out, /Explore/);diff --git a/test/context.test.ts b/test/context.test.tsindex 73245739..24ca5a33 100644--- a/test/context.test.ts+++ b/test/context.test.ts@@ -9,7 +9,7 @@ import { join } from "node:path";import { tmpdir } from "node:os";import { execFileSync } from "node:child_process";import { buildContext } from "../src/context/build.js";-import { checkContext } from "../src/context/check.js";+import { checkContext, indexFreshness, staleBanner } from "../src/context/check.js";import { contextDirFor, ensureGitignored } from "../src/context/node-file.js";import { fakeProviders } from "./helpers.js";@@ -114,6 +114,36 @@ test("check detects content drift when a source file changes", async () => {}});+test("indexFreshness/staleBanner: recorded files gone from disk (the branch-switch / stale-index case)", async () => {+ const dir = makeFixture();+ try {+ await buildContext(dir, buildOpts());+ // Fresh right after build: nothing missing, no banner.+ const fresh = indexFreshness(dir);+ assert.ok(fresh && fresh.missing === 0, "fresh index reports zero missing");+ assert.equal(staleBanner(fresh), null, "no banner when fresh");+ // Simulate a checkout to a tree where a recorded file doesn't exist.+ rmSync(join(dir, "auth.ts"), { force: true });+ const stale = indexFreshness(dir);+ assert.ok(stale && stale.missing >= 1, "missing count rises when a recorded file vanishes");+ const banner = staleBanner(stale);+ assert.match(banner ?? "", /ahead of your working tree/, "banner fires when stale");+ assert.match(banner ?? "", /graft grep/, "banner steers to graft grep, not raw grep");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});++test("indexFreshness returns null when there is no graph", () => {+ const dir = mkdtempSync(join(tmpdir(), "graft-fresh-nograph-"));+ try {+ assert.equal(indexFreshness(dir), null);+ assert.equal(staleBanner(null), null);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});+test("check detects a new file not yet in the graph (coverage drift)", async () => {const dir = makeFixture();try {diff --git a/test/graph-traverse-cli.test.ts b/test/graph-traverse-cli.test.tsindex 6787a039..a8b6bf64 100644--- a/test/graph-traverse-cli.test.ts+++ b/test/graph-traverse-cli.test.ts@@ -92,7 +92,7 @@ test('graft callers --direction out: zero-edge symbol prints a loud callees noteassert.equal(r.status, 0);assert.match(r.stdout, /add · function · src\/math\.ts:/);assert.match(r.stdout, /no indexed callees/);- assert.match(r.stdout, /grep -rn "add"/);+ assert.match(r.stdout, /graft grep "add"/);});test('graft callers --direction out --json: zero-edge symbol includes a note field', () => {@@ -106,7 +106,7 @@ test('graft callers --direction out --json: zero-edge symbol includes a note fieassert.equal(m.symbol.name, 'add');assert.equal(m.hits.length, 0);assert.ok(m.note, 'zero-edge match must have a note field');- assert.match(m.note, /try grep -rn/);+ assert.match(m.note, /graft grep "add"/);});test('graft callers --depth: depth flag walks the BFS transitively (blast radius)', () => {@@ -127,6 +127,25 @@ test('graft callers --depth: depth flag walks the BFS transitively (blast radiusassert.match(deeper.stdout, /\[depth 2\]/);});+test('graft callers --depth all: walks the entire connected closure', () => {+ const d = builtRepo();+ // compute -> sub -> add. `all` must reach BOTH hops (the full closure),+ // like an unbounded depth, terminating when no new node is found.+ const all = runCli(['callers', 'add', d, '--depth', 'all']);+ assert.equal(all.status, 0);+ assert.match(all.stdout, /← sub \(/);+ assert.match(all.stdout, /\[depth 1\]/);+ assert.match(all.stdout, /← compute \(/);+ assert.match(all.stdout, /\[depth 2\]/);+});++test('graft callers --depth: rejects a non-numeric, non-"all" value with exit 1', () => {+ const d = builtRepo();+ const r = runCli(['callers', 'add', d, '--depth', 'banana']);+ assert.equal(r.status, 1);+ assert.match(r.stderr, /--depth must be a positive number or "all"/);+});+test('graft callers --direction: rejects a bad value with exit 1', () => {const d = builtRepo();const r = runCli(['callers', 'add', d, '--direction', 'sideways']);diff --git a/test/mcp-tools.test.ts b/test/mcp-tools.test.tsindex e26ca8b4..737de550 100644--- a/test/mcp-tools.test.ts+++ b/test/mcp-tools.test.ts@@ -165,7 +165,7 @@ test('graft_callers direction:out round-trips a callee, and reports a loud noteconst empty = callTool(d, 'graft_callers', { symbol: 'add', direction: 'out' });assert.equal(empty.isError, false);assert.match(empty.text, /no indexed callees/);- assert.match(empty.text, /grep -rn "add"/);+ assert.match(empty.text, /graft grep "add"/);});test('graft_callers: unknown symbol / missing symbol are soft isErrors', () => {@@ -227,7 +227,7 @@ test('graft_grep: no hits is a soft (non-error) result with the loud fallback noconst r = callTool(d, 'graft_grep', { pattern: 'noSuchPatternAnywhere' });assert.equal(r.isError, false);assert.match(r.text, /no hits for "noSuchPatternAnywhere"/);- assert.match(r.text, /grep -rn "noSuchPatternAnywhere"/);+ assert.match(r.text, /retry graft grep/);});test('graft_grep: missing pattern and unbuilt repo are soft errors', () => {