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
Seed a git worktree's graph from its parent checkout
anirudhkumar-nanonets670d37a7a6de
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 16d13e4e..12d71391 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -60,6 +60,24 @@- **`GRAFT_REFRESH=hash`** — confirm every file by hashing its contents instead of trustingsize and mtime, for tooling that rewrites files while preserving both.+### Fixed++- **A git worktree is no longer blind.** `graft/` is gitignored, so `git worktree add`+ never checks it out — and the graph is the only thing the MCP tools read. Every tool in+ a fresh worktree answered `no matching nodes` / `no graph found` for the whole session,+ and `INDEX.md` and the cards were missing too, so `grep` and the repo map came up empty.++ A query in a worktree now copies the parent checkout's `graft/` in and then treats the+ difference between the two checkouts as ordinary drift. The worktree's `.git` is a file+ naming its parent, so there is nothing to configure; the copy is $0 and offline, and the+ Tier-2 meaning layer survives it (a cold rebuild would have thrown away every summary+ you paid for and re-parsed the repo). `graft build` in a worktree starts from the same+ copy, so it is incremental too.++ Reads the parent, never writes to it. No-ops unless there is genuinely a built parent+ checkout on disk — a fresh clone, CI, or a cloned (rather than worktree'd) cloud session+ behaves exactly as before. `GRAFT_NO_SEED=1` turns it off.+## 0.8.0### Changeddiff --git a/src/cli.ts b/src/cli.tsindex 4447f880..573ce5cb 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -192,6 +192,8 @@ programprocess.stderr.write("\n");console.log(`✓ wiring: ${g.nodes} nodes (${fmt(g.byKind)}), ${g.edges} edges, ${g.cards} cards [${g.languages.join(", ")}]`);console.log(` parsed: ${g.parsed} of ${g.files} files (${g.reused} replayed from cache)`);+ // Worth one line: this build started from a graph the user never built *here*.+ if (g.seededFrom) console.log(` seeded: copied a starting graph from ${g.seededFrom} (git worktree)`);if (deep) {const m = g.meaning;console.log(` meaning: ${m.computed} computed, ${m.cached} cached, ${m.stale} stale, ${m.pending} pending`);diff --git a/src/graph/build.ts b/src/graph/build.tsindex af9bc6e6..49a9cd15 100644--- a/src/graph/build.ts+++ b/src/graph/build.ts@@ -26,6 +26,7 @@ import {type ExtractEntry,} from "./extract-cache.js";import { writeFingerprint } from "./fingerprint.js";+import { seedGraph, type SeedResult } from "./seed.js";import { listSourceStats } from "./source-files.js";import { resolveEdges, type GoModule } from "./resolve.js";import { enrichGraph, type EnrichStats } from "./enrich.js";@@ -96,6 +97,9 @@ export interface GraphBuildResult {parsed: number;/** Files replayed from the extraction cache. */reused: number;+ /** The parent checkout this build copied a starting graph from, when it was run in+ * a git worktree that had none of its own. See `./seed.ts`. */+ seededFrom?: string;nodes: number;edges: number;byKind: Record<Kind, number>;@@ -140,6 +144,14 @@ export async function buildGraph(const langs = new Set<Language>();const errors: string[] = [];+ // In a git worktree there is nothing to reuse *yet* — `graft/` is gitignored, so+ // git never checked it out — but the parent checkout's graph is one directory away.+ // Copy it in before reading the priors below and this build is incremental and+ // keeps its paid-for summaries, instead of being a cold parse of the whole repo.+ // No-ops everywhere else, including on an explicit cold build (`reuse: false`).+ const seed: SeedResult =+ opts.reuse === false ? { seeded: false } : seedGraph(root, { contextDir: opts.contextDir });+// Tier-1 memo: unchanged files replay their last parse. `entries` is rebuilt// from scratch each run and keyed only by files currently on disk, so deletions// fall out of both the cache and the fingerprint with no separate pruning pass.@@ -308,6 +320,7 @@ export async function buildGraph(files: files.length,parsed,reused,+ seededFrom: seed.from,nodes: nodes.length,edges: edges.length,byKind,diff --git a/src/graph/refresh.ts b/src/graph/refresh.tsindex 99c78c81..0fd0d3e8 100644--- a/src/graph/refresh.ts+++ b/src/graph/refresh.ts@@ -25,6 +25,11 @@* at the end of a turn — so retrieval stays cheap and a read stays a read. It* also leaves `stats.json` alone, so that same `Stop` hook still sees `dirty` and* still rebuilds the passive surface.+ *+ * One case is not drift but absence: inside a git worktree there is no graph at all,+ * because `graft/` is gitignored and so was never checked out. The gate covers that+ * too — it copies the parent checkout's graph in (`./seed.ts`) and then treats the+ * difference between the two checkouts as ordinary drift, which is exactly what it is.*/import { existsSync } from "node:fs";import { join, resolve } from "node:path";@@ -34,6 +39,7 @@ import { CACHE_DIR } from "../context/node-file.js";import { buildGraph } from "./build.js";import { driftCount, isClean, probeDrift, type Drift } from "./fingerprint.js";import { invalidateGraphCaches } from "./load.js";+import { seedGraph, type SeedResult } from "./seed.js";import { wiringPath } from "./write.js";/** How long to wait for another process's in-flight rebuild before giving up and@@ -107,6 +113,26 @@ async function waitForLock(cache: string): Promise<boolean> {}}+/**+ * Copy a parent checkout's graph in, holding the same lock a rebuild would.+ *+ * Two MCP tool calls in a fresh worktree arrive here at the same moment, and an 8 MB+ * copy is long enough for both to start one. The loser waits, then finds the graph+ * already there and reports nothing — which is why the caller re-checks the file+ * rather than trusting this return value.+ */+async function seedUnderLock(dir: string, outDir: string, contextDir?: string): Promise<SeedResult> {+ const lockCache = join(outDir, CACHE_DIR);+ if (!(await waitForLock(lockCache))) return { seeded: false };+ const unhook = releaseOnSignal(lockCache);+ try {+ return seedGraph(dir, { contextDir });+ } finally {+ unhook();+ releaseLockIn(lockCache);+ }+}+/*** Rebuild `root`'s structural graph if the working tree has moved since the last* build. Cheap and side-effect-free when nothing changed, which is the usual case.@@ -119,26 +145,38 @@ export async function ensureFreshGraph(root: string, opts: RefreshOptions = {}):try {const dir = resolve(root);const outDir = contextDirFor(dir, opts.contextDir);- // Nothing built yet: the caller's own "no graph — run graft build" message is- // the right answer. Auto-building a whole repo under a query is a surprise,- // and it's the one case where the user hasn't opted into graft at all yet.- if (!existsSync(wiringPath(outDir))) return CLEAN;+ let seededFrom: string | undefined;+ if (!existsSync(wiringPath(outDir))) {+ // One case has a graph to work with even though this checkout has none: a git+ // worktree, whose parent checkout's `graft/` git could not check out. Copy it+ // in and carry on — the drift below is then exactly the diff between the two+ // checkouts, and repairing it is what makes the copied graph honest here.+ seededFrom = (await seedUnderLock(dir, outDir, opts.contextDir)).from;+ // Still nothing (not a worktree, parent never built, or a concurrent seed we+ // lost the race for and which we now re-check for): the caller's own "no graph+ // — run graft build" message is the right answer. Auto-building a whole repo+ // under a query is a surprise, and it's the one case where the user hasn't+ // opted into graft at all yet.+ if (!existsSync(wiringPath(outDir))) return CLEAN;+ }+ const seedNote = seededFrom ? `copied the graph from the main checkout (${seededFrom})` : undefined;// null = no fingerprint at all: a graph built before this mechanism existed,// or by a different extractor build. Rebuild once — that lays the fingerprint// down, so it costs exactly one build, not one per query.const drift = probeDrift(dir, outDir);- if (drift && isClean(drift)) return CLEAN;+ if (drift && isClean(drift)) return seedNote ? { refreshed: false, note: seedNote } : CLEAN;// On the default layout this is `<root>/graft/.cache/.sync.lock`, the very file// the Claude Code hooks lock — so this refresh and the background sync can// never rebuild at the same time.const lockCache = join(outDir, CACHE_DIR);if (!(await waitForLock(lockCache))) {+ const busy = "a graph rebuild is already in flight — answering from the current graph";return {refreshed: false,drift: drift ?? undefined,- note: "a graph rebuild is already in flight — answering from the current graph",+ note: seedNote ? `${seedNote}; ${busy}` : busy,};}const unhook = releaseOnSignal(lockCache);@@ -152,7 +190,7 @@ export async function ensureFreshGraph(root: string, opts: RefreshOptions = {}):const now = drift ? probeDrift(dir, outDir) : null;if (now && isClean(now)) {invalidateGraphCaches(outDir);- return CLEAN;+ return seedNote ? { refreshed: false, note: seedNote } : CLEAN;}// Tier-1 only: no summarizer, so no LLM call and no network, ever. And// `graphOnly`: write the graph, the ask sidecar and the fingerprint, nothing@@ -161,7 +199,7 @@ export async function ensureFreshGraph(root: string, opts: RefreshOptions = {}):// card's mtime, and skipping them is most of what keeps this cheap.await buildGraph(dir, { contextDir: opts.contextDir, graphOnly: true });invalidateGraphCaches(outDir);- return { refreshed: true, drift: drift ?? undefined };+ return { refreshed: true, drift: drift ?? undefined, note: seedNote };} finally {unhook();releaseLockIn(lockCache);@@ -209,8 +247,11 @@ export async function ensureFreshChildren(/** The one-line note a CLI/MCP surface prints when a refresh actually happened.* Null when there's nothing to say (the overwhelmingly common case). */export function refreshNote(r: RefreshResult): string | null {- if (r.note) return `[graft] ${r.note}`;- if (!r.refreshed) return null;+ if (!r.refreshed) return r.note ? `[graft] ${r.note}` : null;const n = r.drift ? driftCount(r.drift) : 0;- return `[graft] refreshed the graph (${n || "?"} file${n === 1 ? "" : "s"} changed) before answering`;+ const built = `refreshed the graph (${n || "?"} file${n === 1 ? "" : "s"} changed) before answering`;+ // Both facts, when a worktree was seeded *and* the copy needed repairing: the+ // count is the interesting half (it's the branch diff), the provenance explains+ // where a graph came from in a directory the user knows they never built.+ return r.note ? `[graft] ${built} — ${r.note}` : `[graft] ${built}`;}diff --git a/src/graph/seed.ts b/src/graph/seed.tsnew file mode 100644index 00000000..b0fcbeb3--- /dev/null+++ b/src/graph/seed.ts@@ -0,0 +1,170 @@+/**+ * `seedGraph` — give a linked git worktree the graph its parent checkout already has.+ *+ * `graft/` is a local cache, so it is gitignored, so `git worktree add` never checks+ * it out: a worktree starts with `src/` and `.claude/` and no graph at all. Every+ * MCP tool then answers "no graph found — run graft build first" for the whole+ * session, and the passive surface (`INDEX.md`, the cards) is missing too. The agent+ * that was supposed to be cheapest in a fresh worktree is instead blind in one.+ *+ * The parent checkout has not gone anywhere, though — a worktree's `.git` is a *file*+ * naming it, and the harness that creates these worktrees already reaches back the+ * same way (Claude Code symlinks `node_modules` to the parent's). So: copy the+ * parent's `graft/` in, then let the ordinary refresh gate repair the difference.+ *+ * Copy, not symlink. `node_modules` is the same for every branch; a graph is a set of+ * `file:line` spans for one specific tree, so a shared one would have the worktree+ * rewriting the parent's graph with its own branch's line numbers. What makes the+ * copy worth doing rather than just rebuilding cold:+ *+ * - **The Tier-2 meaning layer survives.** Summaries and cruxes cost real money;+ * `buildGraph` folds a prior `wiring.json` in by `body_hash`, so an unchanged+ * function keeps the summary someone already paid for. A cold build throws them all+ * away and the worktree silently drops to structural-only answers.+ * - **The repair is small.** `probeDrift` confirms a suspect file by content hash, so+ * a fresh checkout's brand-new mtimes cost one hashing pass and nothing more; the+ * drift that survives is exactly the diff between the two checkouts' commits.+ * - **$0 and offline**, like everything else on the query path.+ *+ * Never writes to the parent, never throws, and no-ops unless there is genuinely a+ * built parent checkout on disk — so a fresh clone, CI, or a cloud session whose repo+ * was *cloned* rather than worktree'd behaves exactly as it did before: "run graft+ * build first".+ */+import {+ copyFileSync,+ cpSync,+ existsSync,+ mkdirSync,+ readFileSync,+ renameSync,+ rmSync,+ statSync,+} from "node:fs";+import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";+import { CACHE_DIR, contextDirFor } from "../context/node-file.js";+import { GRAPH_DIR, GRAPH_FILE, wiringPath } from "./write.js";++/** Env kill switch, mirroring `GRAFT_NO_REFRESH` in ./refresh.ts. */+export function seedDisabled(): boolean {+ const v = process.env.GRAFT_NO_SEED;+ return v !== undefined && v !== "" && v !== "0" && v !== "false";+}++/**+ * The main checkout of the repo `root` is a linked worktree of, or null when `root`+ * isn't one (which is the common case, and not an error).+ *+ * Filesystem-only on purpose: no `git` subprocess on a path that runs before every+ * query. The shapes it has to tell apart:+ *+ * - `<root>/.git` is a **directory** → this *is* the main checkout. Nothing to seed.+ * - `gitdir: <main>/.git/worktrees/<name>` → a linked worktree. `commondir` inside+ * that dir points back at the shared `.git` (`../..`), whose parent is the main+ * checkout.+ * - `gitdir: <super>/.git/modules/<name>` → a **submodule**. Identical file shape,+ * completely different thing: a submodule is its own repo and its parent's `graft/`+ * describes different code entirely. The `worktrees` path segment is what rejects it.+ * - A bare repo or `--separate-git-dir` layout, where the resolved common dir isn't+ * named `.git` and there may be no working tree at all → null.+ */+export function mainWorktreeRoot(root: string): string | null {+ try {+ const dot = join(root, ".git");+ if (statSync(dot).isDirectory()) return null;+ const m = /^gitdir:[ \t]*(.+?)[ \t]*$/m.exec(readFileSync(dot, "utf8"));+ if (!m) return null;+ const gitdir = isAbsolute(m[1]) ? m[1] : resolve(root, m[1]);+ if (basename(dirname(gitdir)) !== "worktrees") return null;+ const rel = readFileSync(join(gitdir, "commondir"), "utf8").trim();+ if (!rel) return null;+ const common = isAbsolute(rel) ? rel : resolve(gitdir, rel);+ if (basename(common) !== ".git" || !statSync(common).isDirectory()) return null;+ const main = dirname(common);+ if (resolve(main) === resolve(root)) return null;+ return main;+ } catch {+ // No `.git` at all, an unreadable one, a `commondir` that doesn't exist: all of+ // them mean "can't seed from here", which is the same answer as "not a worktree".+ return null;+ }+}++export interface SeedResult {+ seeded: boolean;+ /** The main checkout the graph came from, when one was used. */+ from?: string;+}++const NOT_SEEDED: SeedResult = { seeded: false };++/**+ * Repo-relative paths (posix) that a seed deliberately leaves behind.+ *+ * `wiring.json` is here because it is copied last and atomically — see `installGraph`.+ * The rest is state that belongs to the checkout that produced it: another process's+ * lock, another session's transcripts, and another checkout's savings/dirty counters.+ */+const SKIP = new Set([+ `${GRAPH_DIR}/${GRAPH_FILE}`,+ `${CACHE_DIR}/.sync.lock`,+ `${CACHE_DIR}/session`,+ `${CACHE_DIR}/stats.json`,+]);++function copyTree(srcDir: string, outDir: string): void {+ cpSync(srcDir, outDir, {+ recursive: true,+ // A directory that returns false is skipped whole, which is what keeps+ // `.cache/session/` (one file per session, forever) out of the copy.+ filter: (src) => !SKIP.has(relative(srcDir, src).split(sep).join("/")),+ });+}++/**+ * Put `wiring.json` in place last, via a temp file and a rename.+ *+ * Its presence is the flag every caller reads to mean "this repo has a graph"+ * (`refresh.ts`, `workspace.ts`, every MCP tool). So it must appear only once the+ * rest of the copy has landed and must never appear half-written: a seed killed+ * midway then leaves no graph, and the next call simply seeds again.+ */+function installGraph(srcGraph: string, destGraph: string): void {+ mkdirSync(dirname(destGraph), { recursive: true });+ const tmp = `${destGraph}.seed.${process.pid}`;+ try {+ copyFileSync(srcGraph, tmp);+ renameSync(tmp, destGraph);+ } catch (err) {+ try { rmSync(tmp, { force: true }); } catch { /* nothing to clean up */ }+ throw err;+ }+}++/**+ * Copy the parent checkout's graph into `root`'s own `graft/`, if all of this holds:+ * `root` is a linked worktree, it has no graph yet, the parent has one, and no `--dir`+ * override is in play (a custom output dir can't be mapped to a sibling checkout —+ * the same conservatism `ensureGitignored` applies).+ *+ * Best-effort by contract: the caller's fallback is the behaviour that existed before+ * this function did, so every failure returns `{ seeded: false }` rather than raising.+ */+export function seedGraph(root: string, opts: { contextDir?: string } = {}): SeedResult {+ if (opts.contextDir || seedDisabled()) return NOT_SEEDED;+ try {+ const dir = resolve(root);+ const outDir = contextDirFor(dir);+ if (existsSync(wiringPath(outDir))) return NOT_SEEDED; // already has its own+ const main = mainWorktreeRoot(dir);+ if (!main) return NOT_SEEDED;+ const srcDir = contextDirFor(main);+ const srcGraph = wiringPath(srcDir);+ if (!existsSync(srcGraph)) return NOT_SEEDED; // parent never built either+ copyTree(srcDir, outDir);+ installGraph(srcGraph, wiringPath(outDir));+ return { seeded: true, from: main };+ } catch {+ return NOT_SEEDED;+ }+}diff --git a/test/graph-seed.test.ts b/test/graph-seed.test.tsnew file mode 100644index 00000000..e947a8a5--- /dev/null+++ b/test/graph-seed.test.ts@@ -0,0 +1,283 @@+/**+ * Seeding a git worktree's graph from its parent checkout.+ *+ * Two things have to hold. The worktree *shape* detection must be exactly right —+ * it decides whether graft reaches into a neighbouring directory at all, and a+ * submodule has the same `.git`-is-a-file shape while being a different repo — and+ * the copy must leave the parent checkout untouched while ending up with a graph+ * that describes *this* checkout's code, not the parent's.+ *+ * The end-to-end test drives real `git init` / `git worktree add` rather than+ * hand-written `.git` files, because the whole feature rests on an assumption about+ * git's on-disk layout and a fixture can't falsify that.+ */+import { test } from "node:test";+import assert from "node:assert/strict";+import { execFileSync } from "node:child_process";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { buildGraph } from "../src/graph/build.js";+import { ensureFreshGraph, refreshNote } from "../src/graph/refresh.js";+import { mainWorktreeRoot, seedGraph } from "../src/graph/seed.js";+import { readGraph, wiringPath } from "../src/graph/write.js";+import { callTool } from "../src/mcp/tools.js";++const MATH = "export function add(a: number, b: number): number {\n return a + b;\n}\n";+const MUL = "export function mul(a: number, b: number): number {\n return a * b;\n}\n";++const outOf = (d: string): string => join(d, "graft");+const tmp = (tag: string): string => mkdtempSync(join(tmpdir(), `graft-seed-${tag}-`));++/* ------------------------------------------------------------------ *+ * mainWorktreeRoot: telling the shapes apart+ * ------------------------------------------------------------------ */++/** A parent checkout with one registered worktree, built by hand. */+function fakePair(): { main: string; wt: string } {+ const box = tmp("shape");+ const main = join(box, "main");+ const wt = join(box, "wt");+ const gitdir = join(main, ".git", "worktrees", "w");+ mkdirSync(gitdir, { recursive: true });+ writeFileSync(join(gitdir, "commondir"), "../..\n");+ mkdirSync(wt, { recursive: true });+ writeFileSync(join(wt, ".git"), `gitdir: ${gitdir}\n`);+ return { main, wt };+}++test("mainWorktreeRoot finds the parent checkout of a linked worktree", () => {+ const { main, wt } = fakePair();+ assert.equal(mainWorktreeRoot(wt), main);+});++test("mainWorktreeRoot returns null for the main checkout itself", () => {+ const d = tmp("plain");+ mkdirSync(join(d, ".git"), { recursive: true });+ assert.equal(mainWorktreeRoot(d), null, "a .git directory means this *is* the checkout");+});++test("mainWorktreeRoot refuses a submodule", () => {+ // Same file shape as a worktree, but `.git/modules/<name>`: a submodule is its own+ // repo, and the superproject's graph describes entirely different code. Treating it+ // as a worktree would seed a repo with a graph full of paths it doesn't contain.+ const box = tmp("submodule");+ const sub = join(box, "sub");+ const gitdir = join(box, "super", ".git", "modules", "sub");+ mkdirSync(gitdir, { recursive: true });+ writeFileSync(join(gitdir, "commondir"), "../..\n");+ mkdirSync(sub, { recursive: true });+ writeFileSync(join(sub, ".git"), `gitdir: ${gitdir}\n`);+ assert.equal(mainWorktreeRoot(sub), null);+});++test("mainWorktreeRoot survives every broken .git it can be handed", () => {+ const d = tmp("broken");+ assert.equal(mainWorktreeRoot(d), null, "no .git at all");++ writeFileSync(join(d, ".git"), "this is not a gitdir line\n");+ assert.equal(mainWorktreeRoot(d), null, "unparseable .git file");++ const { wt } = fakePair();+ rmSync(join(mainWorktreeRoot(wt)!, ".git", "worktrees", "w", "commondir"));+ assert.equal(mainWorktreeRoot(wt), null, "worktree shape but no commondir");++ // A bare repo (`repo.git/worktrees/w`): the common dir isn't named `.git` and there+ // is no working tree above it to hold a graph.+ const box = tmp("bare");+ const gitdir = join(box, "repo.git", "worktrees", "w");+ mkdirSync(gitdir, { recursive: true });+ writeFileSync(join(gitdir, "commondir"), "../..\n");+ const bareWt = join(box, "wt");+ mkdirSync(bareWt, { recursive: true });+ writeFileSync(join(bareWt, ".git"), `gitdir: ${gitdir}\n`);+ assert.equal(mainWorktreeRoot(bareWt), null);+});++/* ------------------------------------------------------------------ *+ * The real thing: git makes the worktree, graft seeds it+ * ------------------------------------------------------------------ */++/** Isolated from the developer's own git config, so CI and a laptop behave alike. */+function git(cwd: string, ...args: string[]): string {+ return execFileSync("git", args, {+ cwd,+ encoding: "utf8",+ stdio: ["ignore", "pipe", "pipe"],+ env: {+ ...process.env,+ GIT_CONFIG_GLOBAL: "/dev/null",+ GIT_CONFIG_SYSTEM: "/dev/null",+ GIT_AUTHOR_NAME: "graft test",+ GIT_AUTHOR_EMAIL: "[email protected]",+ GIT_COMMITTER_NAME: "graft test",+ GIT_COMMITTER_EMAIL: "[email protected]",+ },+ });+}++/** A committed repo with one source file and `graft/` gitignored, as a real repo has. */+function gitRepo(): string {+ const d = tmp("repo");+ git(d, "init", "-b", "main");+ mkdirSync(join(d, "src"), { recursive: true });+ writeFileSync(join(d, "src", "math.ts"), MATH);+ writeFileSync(join(d, ".gitignore"), "graft/\n");+ git(d, "add", "-A");+ git(d, "commit", "-m", "init");+ return d;+}++function addWorktree(main: string, name: string): string {+ const wt = join(mkdtempSync(join(tmpdir(), "graft-seed-wt-")), name);+ git(main, "worktree", "add", "--detach", wt, "HEAD");+ return wt;+}++test("a git worktree starts with no graph, and one query gives it a correct one", async () => {+ const main = gitRepo();+ await buildGraph(main);+ const parentGraph = readFileSync(wiringPath(outOf(main)), "utf8");++ // State that belongs to the checkout that produced it, and must not travel.+ mkdirSync(join(outOf(main), ".cache", "session"), { recursive: true });+ writeFileSync(join(outOf(main), ".cache", "session", "abc.json"), "{}");+ writeFileSync(join(outOf(main), ".cache", "stats.json"), '{"tokens_saved":999}');++ const wt = addWorktree(main, "feature");+ assert.equal(existsSync(outOf(wt)), false, "git does not check out the gitignored cache");+ assert.equal(existsSync(wiringPath(outOf(wt))), false);++ // The worktree's code differs from the parent's — that difference is the whole+ // reason the copied graph can't just be used as-is.+ writeFileSync(join(wt, "src", "math.ts"), `${MATH}${MUL}`);++ const r = await ensureFreshGraph(wt);+ assert.equal(existsSync(wiringPath(outOf(wt))), true, "the worktree now has its own graph");+ assert.match(refreshNote(r) ?? "", /copied the graph from the main checkout/);+ assert.match(refreshNote(r) ?? "", /^\[graft\] refreshed the graph \(1 file changed\)/);++ const graph = readGraph(wiringPath(outOf(wt)));+ assert.ok(+ graph?.nodes.some((n) => n.id === "src/math.ts#mul"),+ "the graph describes the worktree's code, not the parent's",+ );+ assert.ok(graph?.nodes.some((n) => n.id === "src/math.ts#add"), "and kept what didn't change");++ // The passive surface came across too — it's what `grep` and the repo map read.+ assert.equal(existsSync(join(outOf(wt), "INDEX.md")), true);++ assert.equal(existsSync(join(outOf(wt), ".cache", "session")), false, "no session transcripts");+ assert.equal(existsSync(join(outOf(wt), ".cache", "stats.json")), false, "no borrowed savings");++ // Seeding reads the parent; it must never write to it.+ assert.equal(readFileSync(wiringPath(outOf(main)), "utf8"), parentGraph, "parent graph untouched");++ rmSync(main, { recursive: true, force: true });+ rmSync(wt, { recursive: true, force: true });+});++test("a worktree nested inside the repo is seeded too, and isn't double-indexed", async () => {+ // Claude Code's own worktree feature puts them at `<repo>/.claude/worktrees/<name>`+ // rather than off in a temp dir. Same `.git`-file shape, but nested — so the parent's+ // own walk has to keep ignoring it (it does: `walkDir` skips dot-directories), or the+ // parent would index a second copy of its own source.+ const main = gitRepo();+ await buildGraph(main);+ const nested = join(main, ".claude", "worktrees", "inner");+ git(main, "worktree", "add", "--detach", nested, "HEAD");++ assert.equal(existsSync(wiringPath(outOf(nested))), false, "still nothing checked out");+ await ensureFreshGraph(nested);+ assert.equal(existsSync(wiringPath(outOf(nested))), true, "nested worktrees seed the same way");++ await buildGraph(main);+ const parent = readGraph(wiringPath(outOf(main)));+ assert.equal(+ parent?.nodes.filter((n) => n.id.includes(".claude")).length,+ 0,+ "the parent must not index the worktree's copy of its own files",+ );++ rmSync(main, { recursive: true, force: true });+});++test("the MCP tool answers from a seeded worktree instead of refusing", async () => {+ const main = gitRepo();+ await buildGraph(main);+ const wt = addWorktree(main, "mcp");++ const res = await callTool(wt, "graft_find_code", { query: "add two numbers" });+ assert.equal(res.isError, false);+ assert.doesNotMatch(res.text, /no graph found/);+ assert.match(res.text, /math\.ts/);++ rmSync(main, { recursive: true, force: true });+ rmSync(wt, { recursive: true, force: true });+});++test("GRAFT_NO_SEED leaves the worktree exactly as it was", async () => {+ const main = gitRepo();+ await buildGraph(main);+ const wt = addWorktree(main, "off");++ process.env.GRAFT_NO_SEED = "1";+ try {+ const r = await ensureFreshGraph(wt);+ assert.equal(existsSync(wiringPath(outOf(wt))), false, "no graph copied");+ assert.equal(refreshNote(r), null, "and nothing claimed");+ // The pre-seeding symptom, verbatim: `find_code` on an ungraphed checkout doesn't+ // say "no graph", it says "no matching nodes" — which reads like "your question+ // was bad" rather than "there is nothing to search". Worth pinning so the failure+ // mode this feature removes stays recognisable.+ const res = await callTool(wt, "graft_find_code", { query: "add" });+ assert.match(res.text, /no matching nodes/, "back to the pre-seeding behaviour");+ } finally {+ delete process.env.GRAFT_NO_SEED;+ }++ rmSync(main, { recursive: true, force: true });+ rmSync(wt, { recursive: true, force: true });+});++test("seedGraph declines a --dir override and a checkout that already has a graph", async () => {+ const main = gitRepo();+ await buildGraph(main);+ const wt = addWorktree(main, "guards");++ // A custom output dir can't be mapped onto a sibling checkout, so don't guess.+ const elsewhere = tmp("dir");+ assert.deepEqual(seedGraph(wt, { contextDir: elsewhere }), { seeded: false });+ assert.equal(existsSync(wiringPath(elsewhere)), false);++ assert.equal(seedGraph(wt).seeded, true, "first call copies");+ assert.deepEqual(seedGraph(wt), { seeded: false }, "second call has nothing to do");++ rmSync(main, { recursive: true, force: true });+ rmSync(wt, { recursive: true, force: true });+});++test("a plain repo with no parent checkout is left to `graft build`", async () => {+ const solo = gitRepo(); // a main checkout, never built+ const r = await ensureFreshGraph(solo);+ assert.equal(existsSync(wiringPath(outOf(solo))), false, "no surprise full build under a query");+ assert.equal(refreshNote(r), null);+ rmSync(solo, { recursive: true, force: true });+});++test("`graft build` in a worktree starts from the parent's graph, not from scratch", async () => {+ const main = gitRepo();+ await buildGraph(main);+ const wt = addWorktree(main, "build");+ writeFileSync(join(wt, "src", "math.ts"), `${MATH}${MUL}`);++ const g = await buildGraph(wt);+ // `realpathSync`: git writes the canonical path into the worktree's `.git`, and on+ // macOS the temp dir arrives here as the `/var` symlink to `/private/var`.+ assert.equal(g.seededFrom, realpathSync(main), "reported, because the user never built here");+ assert.equal(g.parsed, 1, "only the file this checkout changed was re-parsed");+ assert.ok(g.cards > 0, "and the passive surface is rebuilt for this checkout");++ rmSync(main, { recursive: true, force: true });+ rmSync(wt, { recursive: true, force: true });+});