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
fix(claude): hooks, sync-run, and statusline respect GRAFT_DIR (#147)
bhavesh-gupta-investis91ee6fca53f2
diff --git a/src/claude/hooks.ts b/src/claude/hooks.tsindex 00381a72..6160ab0c 100644--- a/src/claude/hooks.ts+++ b/src/claude/hooks.ts@@ -4,7 +4,7 @@ import { join, basename, isAbsolute } 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 { patchStats, readStats, acquireLock, readSession, writeSession, resolveContextDir } from './state.js';import { graftCliPath, claudeScriptPath } from './paths.js';import { runUpkeep } from '../upkeep-run.js';import { runningVersion } from '../upkeep.js';@@ -79,6 +79,18 @@ function installedHookTimeout(dir: string, event: string): number | null {}}+/**+ * Append `--dir <contextDir>` for the hooks' own `graft ask`/`graft check`+ * children — the one place in this file that spawns the CLI itself rather+ * than reading `graft/` off disk (which already resolves through+ * `resolveContextDir` inside `util/state.ts` and `claude/stats.ts`). A no-op+ * when `GRAFT_DIR` isn't set, so an unconfigured repo's spawned CLI sees+ * byte-identical argv to before this existed.+ */+function withContextDirArg(dir: string, args: string[]): string[] {+ return process.env.GRAFT_DIR ? [...args, '--dir', resolveContextDir(dir)] : args;+}+function graftJson(dir: string, args: string[], timeout: number = CHILD_TIMEOUT_MS): any | null {try {// GRAFT_TEST_CLI is a test seam (mirrors GRAFT_TEST_STDIN/GRAFT_TEST_SYNC_RUN) so@@ -99,7 +111,7 @@ function graftJson(dir: string, args: string[], timeout: number = CHILD_TIMEOUT_}}function checkStaleCount(dir: string): number {- const r = graftJson(dir, ['check', '.', '--json']);+ const r = graftJson(dir, withContextDirArg(dir, ['check', '.', '--json']));const g = r?.graph ?? {};return (g.changed?.length ?? 0) + (g.added?.length ?? 0) + (g.removed?.length ?? 0);}@@ -228,7 +240,7 @@ export async function main(event: string): Promise<void> {// hook still touches no network; the CLI or the MCP server sends it later.flushClosedSessions(dir);try {- const idx = readFileSync(join(dir, 'graft', 'INDEX.md'), 'utf8');+ const idx = readFileSync(join(resolveContextDir(dir), 'INDEX.md'), 'utf8');const banner = staleBanner(indexFreshness(dir)) ?? undefined;const orientation = formatOrientation(idx, undefined, banner);emit('SessionStart', upkeep.length ? `${upkeep.join('\n')}\n\n${orientation}` : orientation);@@ -256,7 +268,7 @@ export async function main(event: string): Promise<void> {// pulls spans itself via `graft ask --source` when a pointer looks right.// relevantRetrieval then drops the pack entirely when the prompt barely// overlaps the top hit or when every hit was already injected this session.- const askArgs = ['ask', prompt, '.', '--json', '-n', '3'];+ const askArgs = withContextDirArg(dir, ['ask', prompt, '.', '--json', '-n', '3']);// "You're working in backend/, weight it": only fires on a multi-scope// repo whose lastFile resolves cleanly to one scope — see lastFileScopeHint.const scopeHint = lastFileScopeHint(dir, readStats(dir)?.lastFile);diff --git a/src/claude/state.ts b/src/claude/state.tsindex ef8b8f0a..45d9f252 100644--- a/src/claude/state.ts+++ b/src/claude/state.ts@@ -17,6 +17,7 @@ export {patchStats,readStats,releaseLock,+ resolveContextDir,writeJsonAtomic,writeStats,} from '../util/state.js';diff --git a/src/claude/stats.ts b/src/claude/stats.tsindex 6d85f1ac..92f9d7d8 100644--- a/src/claude/stats.ts+++ b/src/claude/stats.ts@@ -2,10 +2,11 @@ import { readFileSync } from 'node:fs';import { join } from 'node:path';import type { GraphV1 } from '../graph/types.js';import type { Stats } from './state.js';+import { resolveContextDir } from '../util/state.js';export function readWiring(projectDir: string): GraphV1 | null {try {- return JSON.parse(readFileSync(join(projectDir, 'graft', '.graph', 'wiring.json'), 'utf8')) as GraphV1;+ return JSON.parse(readFileSync(join(resolveContextDir(projectDir), '.graph', 'wiring.json'), 'utf8')) as GraphV1;} catch { return null; }}diff --git a/src/claude/sync-run.ts b/src/claude/sync-run.tsindex 8c0e6262..e07acb8e 100644--- a/src/claude/sync-run.ts+++ b/src/claude/sync-run.ts@@ -1,13 +1,19 @@import { execFileSync } from 'node:child_process';import { pathToFileURL } from 'node:url';import { readWiring, computeStats } from './stats.js';-import { patchStats, releaseLock } from './state.js';+import { patchStats, releaseLock, resolveContextDir } from './state.js';import { graftCliPath } from './paths.js';/** MONEY GUARD: plain `graft build` only — structural, $0, offline. Never --deep. */function realBuild(dir: string): void {- execFileSync(process.execPath, [graftCliPath(), 'build', '.'],- { cwd: dir, stdio: 'ignore', timeout: 120000 });+ // GRAFT_TEST_CLI is the same seam hooks.ts's graftJson uses, so a test can+ // point this at a stub and inspect the exact argv it was invoked with.+ const cliPath = process.env.GRAFT_TEST_CLI ?? graftCliPath();+ const args = [cliPath, 'build', '.'];+ // Mirrors `withContextDirArg` in hooks.ts: a no-op unless GRAFT_DIR is set, so an+ // unconfigured repo's rebuild sees byte-identical argv to before this existed.+ if (process.env.GRAFT_DIR) args.push('--dir', resolveContextDir(dir));+ execFileSync(process.execPath, args, { cwd: dir, stdio: 'ignore', timeout: 120000 });}export function runSync(dir: string, build: (d: string) => void = realBuild): void {diff --git a/src/util/state.ts b/src/util/state.tsindex 8011a946..24888710 100644--- a/src/util/state.ts+++ b/src/util/state.ts@@ -10,7 +10,7 @@* outside had to change when it moved.*/import { readFileSync, writeFileSync, mkdirSync, renameSync, rmSync, statSync } from 'node:fs';-import { join, dirname } from 'node:path';+import { join, dirname, isAbsolute } from 'node:path';export interface Stats {nodeCount: number; edgeCount: number; languages: string[];@@ -28,7 +28,25 @@ export function emptyStats(): Stats {const LOCK_FILE = '.sync.lock';-export function cacheDir(projectDir: string): string { return join(projectDir, 'graft', '.cache'); }+/**+ * Where the pieces this module manages (the stats cache, the sync lock,+ * per-session state, the upkeep stamp) actually live when no caller-supplied+ * override is available. The Claude Code hooks, `sync-run`, the statusline,+ * and `upkeep` all resolve a bare project dir and never see an explicit+ * `--dir` — unlike a direct CLI invocation, which threads one through+ * `contextDirFor` (`context/node-file.ts`). This mirrors that same override+ * precedence for those entry points: `GRAFT_DIR` wins over the default+ * `<projectDir>/graft`, the same env var `resolveConfig` already honors for+ * the `--deep` LLM path. A relative `GRAFT_DIR` resolves against `projectDir`+ * so it holds regardless of the caller's cwd.+ */+export function resolveContextDir(projectDir: string): string {+ const override = process.env.GRAFT_DIR;+ if (!override) return join(projectDir, 'graft');+ return isAbsolute(override) ? override : join(projectDir, override);+}++export function cacheDir(projectDir: string): string { return join(resolveContextDir(projectDir), '.cache'); }function statsPath(d: string): string { return join(cacheDir(d), 'stats.json'); }export function readJson<T>(p: string): T | null {diff --git a/test/claude-hooks.test.ts b/test/claude-hooks.test.tsindex a9ae6355..f214a067 100644--- a/test/claude-hooks.test.ts+++ b/test/claude-hooks.test.ts@@ -7,7 +7,7 @@ import { underGraft, main, lastFileScopeHint, promptAskTimeout } from '../src/climport { readStats, readSession } from '../src/claude/state.js';import { runSync } from '../src/claude/sync-run.js';import { savingsLine } from '../src/context/savings.js';-import { writeStats, emptyStats, acquireLock } from '../src/claude/state.js';+import { writeStats, emptyStats, acquireLock, resolveContextDir } from '../src/claude/state.js';test('underGraft detects edits inside graft/', () => {assert.equal(underGraft('/repo', '/repo/graft/x.md'), true);@@ -97,6 +97,31 @@ test('runSync clears dirty/syncing, recomputes stats, releases lock', () => {assert.equal(acquireLock(d), true, 'lock released, so reacquire succeeds');});+test("runSync's default build passes --dir <resolved> to graft build when GRAFT_DIR is set", () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-sync-dir-'));+ mkdirSync(join(d, 'elsewhere', '.graph'), { recursive: true });+ const argsFile = join(d, 'args-seen.json');+ const stub = join(d, 'build-stub.cjs');+ writeFileSync(+ stub,+ `const fs = require('fs');\n` ++ `fs.writeFileSync(${JSON.stringify(argsFile)}, JSON.stringify(process.argv.slice(2)));\n` ++ `fs.writeFileSync(${JSON.stringify(join(d, 'elsewhere', '.graph', 'wiring.json'))}, JSON.stringify({ meta: { nodeCount: 0, edgeCount: 0, languages: [] }, nodes: [], edges: [] }));\n`,+ );+ process.env.GRAFT_TEST_CLI = stub;+ process.env.GRAFT_DIR = 'elsewhere';+ try {+ runSync(d); // exercises the real (non-injected) build path+ const argsSeen: string[] = JSON.parse(readFileSync(argsFile, 'utf8'));+ const dirIdx = argsSeen.indexOf('--dir');+ assert.ok(dirIdx !== -1, 'the build call carries --dir when GRAFT_DIR is set');+ assert.equal(argsSeen[dirIdx + 1], resolveContextDir(d));+ } finally {+ delete process.env.GRAFT_TEST_CLI;+ delete process.env.GRAFT_DIR;+ }+});+test('runSync clears syncing even if build throws (money-safe failure)', () => {const d = mkdtempSync(join(tmpdir(), 'graft-sync-'));writeStats(d, { ...emptyStats(), dirty: true, syncing: true });@@ -471,3 +496,103 @@ test('promptAskTimeout is derived from the installed hook budget', () => {assert.equal(promptAskTimeout(withSettings('nonsense')), 6000);assert.equal(promptAskTimeout(mkdtempSync(join(tmpdir(), 'graft-nosettings-'))), 6000);});++// ── GRAFT_DIR: the hooks' own `graft ask`/`graft check` children, and the+// SessionStart INDEX.md read, must land on the same relocated context dir+// that readWiring/readStats/patchStats/acquireLock/session state already+// resolve through resolveContextDir. ──────────────────────────────────────++test('prompt hook passes --dir <resolved> to graft ask when GRAFT_DIR is set', async () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-prompt-dir-'));+ mkdirSync(join(d, 'elsewhere', '.graph'), { recursive: true });+ writeFileSync(join(d, 'elsewhere', '.graph', 'wiring.json'),+ JSON.stringify({ meta: { nodeCount: 0, edgeCount: 0, languages: [] }, nodes: [], edges: [] }));+ const { stub, argsFile } = writeAskArgsStub(d);+ process.env.CLAUDE_PROJECT_DIR = d;+ process.env.GRAFT_TEST_CLI = stub;+ process.env.GRAFT_DIR = 'elsewhere';+ try {+ await runWithStdin(+ JSON.stringify({ session_id: 'p-dir', prompt: 'how does the relocated graph get queried' }),+ () => main('prompt'),+ );+ const argsSeen: string[] = JSON.parse(readFileSync(argsFile, 'utf8'));+ const dirIdx = argsSeen.indexOf('--dir');+ assert.ok(dirIdx !== -1, 'the ask call carries --dir when GRAFT_DIR is set');+ assert.equal(argsSeen[dirIdx + 1], resolveContextDir(d));+ } finally {+ delete process.env.GRAFT_TEST_CLI;+ delete process.env.CLAUDE_PROJECT_DIR;+ delete process.env.GRAFT_DIR;+ }+});++test('prompt hook omits --dir when GRAFT_DIR is unset (byte-identical argv to before)', async () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-prompt-dir-'));+ mkdirSync(join(d, 'graft', '.graph'), { recursive: true });+ writeFileSync(join(d, 'graft', '.graph', 'wiring.json'),+ JSON.stringify({ meta: { nodeCount: 0, edgeCount: 0, languages: [] }, nodes: [], edges: [] }));+ const { stub, argsFile } = writeAskArgsStub(d);+ process.env.CLAUDE_PROJECT_DIR = d;+ process.env.GRAFT_TEST_CLI = stub;+ try {+ await runWithStdin(+ JSON.stringify({ session_id: 'p-nodir', prompt: 'how does the default graph get queried' }),+ () => main('prompt'),+ );+ const argsSeen: string[] = JSON.parse(readFileSync(argsFile, 'utf8'));+ assert.equal(argsSeen.indexOf('--dir'), -1, 'unconfigured repo: no --dir added');+ } finally {+ delete process.env.GRAFT_TEST_CLI;+ delete process.env.CLAUDE_PROJECT_DIR;+ }+});++test('post-edit passes --dir <resolved> to graft check when GRAFT_DIR is set', async () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-postedit-dir-'));+ mkdirSync(join(d, 'elsewhere', '.graph'), { recursive: true });+ writeFileSync(join(d, 'elsewhere', '.graph', 'wiring.json'),+ JSON.stringify({ meta: { nodeCount: 0, edgeCount: 0, languages: [] }, nodes: [], edges: [] }));+ const stub = join(d, 'check-stub.cjs');+ const argsFile = join(d, 'args-seen.json');+ writeFileSync(+ stub,+ `const fs = require('fs');\n` ++ `fs.writeFileSync(${JSON.stringify(argsFile)}, JSON.stringify(process.argv.slice(2)));\n` ++ `process.stdout.write(JSON.stringify({ graph: { changed: [], added: [], removed: [] } }));\n`,+ );+ process.env.CLAUDE_PROJECT_DIR = d;+ process.env.GRAFT_TEST_CLI = stub;+ process.env.GRAFT_DIR = 'elsewhere';+ try {+ const stdin = JSON.stringify({ tool_input: { file_path: join(d, 'src', 'auth.ts') } });+ await runWithStdin(stdin, () => main('post-edit'));+ const argsSeen: string[] = JSON.parse(readFileSync(argsFile, 'utf8'));+ const dirIdx = argsSeen.indexOf('--dir');+ assert.ok(dirIdx !== -1, 'the check call carries --dir when GRAFT_DIR is set');+ assert.equal(argsSeen[dirIdx + 1], resolveContextDir(d));+ } finally {+ delete process.env.GRAFT_TEST_CLI;+ delete process.env.CLAUDE_PROJECT_DIR;+ delete process.env.GRAFT_DIR;+ }+});++test('session-start reads INDEX.md from a GRAFT_DIR-relocated context dir', async () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-session-start-dir-'));+ mkdirSync(join(d, 'elsewhere'), { recursive: true });+ writeFileSync(join(d, 'elsewhere', 'INDEX.md'), '# repo map (relocated)\n');+ process.env.CLAUDE_PROJECT_DIR = d;+ process.env.GRAFT_DIR = 'elsewhere';+ const chunks: string[] = [];+ const orig = process.stdout.write.bind(process.stdout);+ (process.stdout as any).write = (s: any) => { chunks.push(String(s)); return true; };+ try {+ await runWithStdin('{}', () => main('session-start'));+ } finally {+ (process.stdout as any).write = orig;+ delete process.env.CLAUDE_PROJECT_DIR;+ delete process.env.GRAFT_DIR;+ }+ assert.match(chunks.join(''), /repo map \(relocated\)/, 'orientation was built from the relocated INDEX.md');+});diff --git a/test/claude-stats.test.ts b/test/claude-stats.test.tsindex 4122cd0a..6b444a0b 100644--- a/test/claude-stats.test.ts+++ b/test/claude-stats.test.ts@@ -1,6 +1,9 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { computeStats } from '../src/claude/stats.js';+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { computeStats, readWiring } from '../src/claude/stats.js';const wiring = {meta: { version: 1, nodeCount: 3, edgeCount: 2, languages: ['typescript'] },@@ -27,3 +30,15 @@ test('computeStats tolerates missing meta by counting arrays', () => {assert.equal(s.edgeCount, 0);assert.equal(s.readyCount, 0);});++test('readWiring reads from a GRAFT_DIR-relocated context dir instead of <projectDir>/graft', () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-stats-dir-'));+ mkdirSync(join(d, 'elsewhere', '.graph'), { recursive: true });+ writeFileSync(join(d, 'elsewhere', '.graph', 'wiring.json'), JSON.stringify(wiring));+ process.env.GRAFT_DIR = 'elsewhere';+ try {+ assert.deepEqual(readWiring(d), wiring);+ } finally {+ delete process.env.GRAFT_DIR;+ }+});diff --git a/test/util-state.test.ts b/test/util-state.test.tsindex 818010c1..da6e75ea 100644--- a/test/util-state.test.ts+++ b/test/util-state.test.ts@@ -12,10 +12,12 @@ import { tmpdir } from "node:os";import { join } from "node:path";import {buildConfigPath,+ cacheDir,patchBuildConfig,readBuildConfig,readFollowSubmodules,readIncludeDirs,+ resolveContextDir,writeBuildConfig,} from "../src/util/state.js";@@ -79,3 +81,42 @@ test("patchBuildConfig preserves unrelated persisted build choices", () => {followSubmodules: false,});});++// ── resolveContextDir / GRAFT_DIR ──────────────────────────────────────────+//+// Everything in this module keyed only by a project dir (stats cache, sync+// lock, session state, the upkeep stamp) resolves its `graft/` subpath+// through resolveContextDir, so hooks/sync-run/statusline honor GRAFT_DIR+// the same way a direct `--dir` CLI call already does via contextDirFor.++function withGraftDir<T>(value: string | undefined, fn: () => T): T {+ const prev = process.env.GRAFT_DIR;+ if (value === undefined) delete process.env.GRAFT_DIR; else process.env.GRAFT_DIR = value;+ try { return fn(); }+ finally { if (prev === undefined) delete process.env.GRAFT_DIR; else process.env.GRAFT_DIR = prev; }+}++test("resolveContextDir defaults to <projectDir>/graft when GRAFT_DIR is unset", () => {+ const d = fresh();+ withGraftDir(undefined, () => {+ assert.equal(resolveContextDir(d), join(d, "graft"));+ assert.equal(cacheDir(d), join(d, "graft", ".cache"));+ });+});++test("resolveContextDir resolves a relative GRAFT_DIR against projectDir", () => {+ const d = fresh();+ withGraftDir(".repo-docs/graft", () => {+ assert.equal(resolveContextDir(d), join(d, ".repo-docs", "graft"));+ assert.equal(cacheDir(d), join(d, ".repo-docs", "graft", ".cache"));+ });+});++test("resolveContextDir takes an absolute GRAFT_DIR verbatim", () => {+ const d = fresh();+ const abs = join(tmpdir(), "graft-context-elsewhere");+ withGraftDir(abs, () => {+ assert.equal(resolveContextDir(d), abs);+ assert.equal(cacheDir(d), join(abs, ".cache"));+ });+});