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 only what a query reads, and parse the gitdir pointer without a regex
anirudhkumar-nanonetsdc6b1e7cd930
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 12d71391..46527251 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -67,12 +67,14 @@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.+ A query in a worktree now copies the parent checkout's graph and query sidecars in, 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 — and it is what writes the worktree's+ cards and `INDEX.md`, generated from *this* checkout's code rather than copied from the+ parent's branch. A query still writes only what a query reads.Reads the parent, never writes to it. No-ops unless there is genuinely a built parentcheckout on disk — a fresh clone, CI, or a cloned (rather than worktree'd) cloud sessiondiff --git a/src/ask/index-file.ts b/src/ask/index-file.tsindex 6d414bbe..a418620d 100644--- a/src/ask/index-file.ts+++ b/src/ask/index-file.ts@@ -68,7 +68,7 @@ export interface AskIndex {docs: AskIndexDoc[];}-const ASK_INDEX_FILE = "ask-index.json";+export const ASK_INDEX_FILE = "ask-index.json";/** Absolute path to the ask sidecar for a context dir: `<dir>/.cache/ask-index.json`.* `.cache/` is the established uncommitted-cache location — this sidecar is adiff --git a/src/graph/extract-cache.ts b/src/graph/extract-cache.tsindex ccd5cc1c..2acf8b25 100644--- a/src/graph/extract-cache.ts+++ b/src/graph/extract-cache.ts@@ -34,7 +34,7 @@ import type { NodeV1 } from "./types.js";/** Bump when the on-disk shape below changes. */const CACHE_VERSION = 1;-const EXTRACT_CACHE_PREFIX = "extract";+export const EXTRACT_CACHE_PREFIX = "extract";export interface ExtractEntry {size: number;diff --git a/src/graph/fingerprint.ts b/src/graph/fingerprint.tsindex 7de3928b..e01c525c 100644--- a/src/graph/fingerprint.ts+++ b/src/graph/fingerprint.ts@@ -26,7 +26,7 @@ import { readJson, writeJsonAtomic } from "../util/state.js";import { extractorStamp, pruneSidecars, type ExtractEntry } from "./extract-cache.js";import { listSourceStats } from "./source-files.js";-const FINGERPRINT_PREFIX = "fingerprint";+export const FINGERPRINT_PREFIX = "fingerprint";const FINGERPRINT_VERSION = 1;/** The identity this graft's prints are filed under. Unlike the extract memo, adiff --git a/src/graph/refresh.ts b/src/graph/refresh.tsindex 0fd0d3e8..7140ce8a 100644--- a/src/graph/refresh.ts+++ b/src/graph/refresh.ts@@ -121,9 +121,16 @@ async function waitForLock(cache: string): Promise<boolean> {* 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> {+async function seedUnderLock(+ dir: string,+ outDir: string,+ contextDir?: string,+): Promise<SeedResult & { busy?: boolean }> {const lockCache = join(outDir, CACHE_DIR);- if (!(await waitForLock(lockCache))) return { seeded: false };+ // `busy` matters: with no graph on disk there is nothing to fall back to, so a+ // caller that stayed silent here would emit the bare "no matching nodes" this whole+ // mechanism exists to remove. Say what happened instead.+ if (!(await waitForLock(lockCache))) return { seeded: false, busy: true };const unhook = releaseOnSignal(lockCache);try {return seedGraph(dir, { contextDir });@@ -151,13 +158,18 @@ export async function ensureFreshGraph(root: string, opts: RefreshOptions = {}):// 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;+ const seed = await seedUnderLock(dir, outDir, opts.contextDir);+ seededFrom = seed.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;+ if (!existsSync(wiringPath(outDir))) {+ return seed.busy+ ? { refreshed: false, note: "another process is still copying the graph into this worktree — retry the query in a moment" }+ : CLEAN;+ }}const seedNote = seededFrom ? `copied the graph from the main checkout (${seededFrom})` : undefined;diff --git a/src/graph/seed.ts b/src/graph/seed.tsindex b0fcbeb3..d5ddd12a 100644--- a/src/graph/seed.ts+++ b/src/graph/seed.ts@@ -7,6 +7,9 @@* 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.*+ * What travels is the graph and the sidecars a query reads — never the markdown; see+ * `seedable` for why the cards are the parent's branch and not this one's.+ ** 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@@ -42,8 +45,14 @@ import {statSync,} from "node:fs";import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";+import { ASK_INDEX_FILE } from "../ask/index-file.js";import { CACHE_DIR, contextDirFor } from "../context/node-file.js";-import { GRAPH_DIR, GRAPH_FILE, wiringPath } from "./write.js";+import { EXTRACT_CACHE_PREFIX } from "./extract-cache.js";+import { FINGERPRINT_PREFIX } from "./fingerprint.js";+import { GRAPH_DIR, wiringPath } from "./write.js";++/** The one line a linked worktree's `.git` file carries. */+const GITDIR_KEY = "gitdir:";/** Env kill switch, mirroring `GRAFT_NO_REFRESH` in ./refresh.ts. */export function seedDisabled(): boolean {@@ -72,9 +81,17 @@ 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]);+ // Read the pointer without a regex. `/^gitdir:[ \t]*(.+?)[ \t]*$/m` is the+ // polynomial-ReDoS shape CodeQL flagged on `ensureSearchable` (`js/polynomial-redos`,+ // fixed in 44a191e): `.` also matches space and tab, so the lazy group and the+ // trailing `[ \t]*` overlap and a line of blanks costs O(n²). Same conclusion as+ // that fix — the ambiguity buys nothing, and split/startsWith/trim is linear and+ // plainer. `trim` also absorbs the `\r` of a CRLF checkout.+ const line = readFileSync(dot, "utf8").split("\n").find((l) => l.startsWith(GITDIR_KEY));+ if (line === undefined) return null;+ const target = line.slice(GITDIR_KEY.length).trim();+ if (!target) return null;+ const gitdir = isAbsolute(target) ? target : resolve(root, target);if (basename(dirname(gitdir)) !== "worktrees") return null;const rel = readFileSync(join(gitdir, "commondir"), "utf8").trim();if (!rel) return null;@@ -99,25 +116,42 @@ export interface SeedResult {const NOT_SEEDED: SeedResult = { seeded: false };/**- * Repo-relative paths (posix) that a seed deliberately leaves behind.+ * An allowlist, not a skip list: is this repo-relative path (posix) one of the few+ * files a seed may bring across?+ *+ * The gate that calls this promises "writes only what a query reads — the graph, the+ * `ask` sidecar, the freshness record" (see the header of ./refresh.ts). A copy that+ * wrote anything else would turn a read into a write of the repo, so the copy honours+ * the same list. The extraction memo is on it because the refresh immediately after+ * rewrites that file anyway, and replaying it is what keeps the repair cheap.*- * `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.+ * **Deliberately absent: the cards and `INDEX.md`.** They would land as this+ * checkout's documentation while describing the *parent's* branch, and nothing on the+ * query path rewrites them (`writeCards`/`writeIndex` sit behind `!graphOnly`), so they+ * would stay wrong indefinitely. An explicit `graft build` regenerates them from this+ * checkout's own graph — and prunes the ones that no longer apply — which is both+ * correct and nearly free once the graph is here.+ *+ * Also absent, because it belongs to the checkout that produced it: `.cache/session/`+ * (another session's transcripts), `.sync.lock` (another process's lock), and+ * `stats.json` (this checkout earns its own savings and dirty flag).*/-const SKIP = new Set([- `${GRAPH_DIR}/${GRAPH_FILE}`,- `${CACHE_DIR}/.sync.lock`,- `${CACHE_DIR}/session`,- `${CACHE_DIR}/stats.json`,-]);+function seedable(rel: string): boolean {+ // The dirs themselves, or cpSync would never look inside them.+ if (rel === "" || rel === GRAPH_DIR || rel === CACHE_DIR) return true;+ if (!rel.startsWith(`${CACHE_DIR}/`)) return false; // incl. the graph: `installGraph` places it+ const name = rel.slice(CACHE_DIR.length + 1);+ return (+ name === ASK_INDEX_FILE ||+ name.startsWith(`${EXTRACT_CACHE_PREFIX}.`) ||+ name.startsWith(`${FINGERPRINT_PREFIX}.`)+ );+}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("/")),+ filter: (src) => seedable(relative(srcDir, src).split(sep).join("/")),});}diff --git a/test/graph-seed.test.ts b/test/graph-seed.test.tsindex e947a8a5..bca1bf56 100644--- a/test/graph-seed.test.ts+++ b/test/graph-seed.test.ts@@ -14,7 +14,16 @@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 {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ realpathSync,+ rmSync,+ writeFileSync,+} from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { buildGraph } from "../src/graph/build.js";@@ -71,6 +80,22 @@ test("mainWorktreeRoot refuses a submodule", () => {assert.equal(mainWorktreeRoot(sub), null);});+test("mainWorktreeRoot reads the pointer whatever whitespace it arrives with", () => {+ // No regex does this parsing (a lazy group next to a trailing `[ \t]*` is the+ // polynomial-ReDoS shape CodeQL flagged in 44a191e), so the padding cases are worth+ // pinning: a CRLF checkout, tabs, and a `.git` file with other lines in it.+ for (const suffix of ["\n", "\r\n", " \n", "\t\t\n", "\n# a stray line\n"]) {+ const { main, wt } = fakePair();+ const gitdir = join(main, ".git", "worktrees", "w");+ writeFileSync(join(wt, ".git"), `gitdir:\t ${gitdir}${suffix}`);+ assert.equal(mainWorktreeRoot(wt), main, `suffix ${JSON.stringify(suffix)}`);+ }++ const { wt: empty } = fakePair();+ writeFileSync(join(empty, ".git"), "gitdir: \n");+ assert.equal(mainWorktreeRoot(empty), null, "a pointer to nowhere is not a worktree");+});+test("mainWorktreeRoot survives every broken .git it can be handed", () => {const d = tmp("broken");assert.equal(mainWorktreeRoot(d), null, "no .git at all");@@ -164,12 +189,27 @@ test("a git worktree starts with no graph, and one query gives it a correct one");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);+ // A query writes only what a query reads (the rule in refresh.ts's header). The+ // parent's cards describe the parent's *branch*, and nothing on the query path would+ // ever correct them, so they must not travel — `graft build` regenerates them below.+ assert.equal(existsSync(join(outOf(wt), "INDEX.md")), false, "a query writes no markdown");+ assert.equal(existsSync(join(outOf(wt), "graph-extraction-and-loading.md")), false, "nor cards");++ // What did travel is what makes the repair cheap and the answer correct.+ assert.equal(existsSync(join(outOf(wt), ".cache", "ask-index.json")), true, "the ask sidecar");+ assert.ok(+ readdirSync(join(outOf(wt), ".cache")).some((f) => f.startsWith("extract.")),+ "the extraction memo, or every file would be re-parsed",+ );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");+ // …and an explicit build is what produces this checkout's own passive surface.+ const built = await buildGraph(wt);+ assert.ok(built.cards > 0, "the build writes cards for this checkout");+ assert.equal(existsSync(join(outOf(wt), "INDEX.md")), true);+// Seeding reads the parent; it must never write to it.assert.equal(readFileSync(wiringPath(outOf(main)), "utf8"), parentGraph, "parent graph untouched");