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
feat(claude): post-edit hook — drift flag + blast-radius injection
Shrish Dwivedi7097dc5e75e1
diff --git a/.claude/helpers/graft-hooks.cjs b/.claude/helpers/graft-hooks.cjsnew file mode 100644index 00000000..ea2108c1--- /dev/null+++ b/.claude/helpers/graft-hooks.cjs@@ -0,0 +1,6 @@+#!/usr/bin/env node+const path = require('path');+const dir = process.env.CLAUDE_PROJECT_DIR || process.cwd();+import(path.join(dir, 'dist', 'claude', 'hooks.js'))+ .then((m) => m.main(process.argv[2]))+ .catch(() => { /* best-effort: never disrupt the session */ });diff --git a/.claude/settings.json b/.claude/settings.jsonindex 93fae57e..30d18a2d 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -2,5 +2,15 @@"statusLine": {"type": "command","command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-statusline.cjs\""+ },+ "hooks": {+ "PostToolUse": [+ {+ "matcher": "Write|Edit|MultiEdit",+ "hooks": [+ { "type": "command", "command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-hooks.cjs\" post-edit", "timeout": 10000 }+ ]+ }+ ]}}diff --git a/src/claude/format.ts b/src/claude/format.tsindex 3c37463e..98abfba1 100644--- a/src/claude/format.ts+++ b/src/claude/format.ts@@ -1,5 +1,6 @@import { basename } from 'node:path';import type { Stats, SessionState } from './state.js';+import type { GraphV1, EdgeV1 } from '../graph/types.js';const C = {indigo: (s: string) => `\x1b[38;2;84;111;255m${s}\x1b[0m`,@@ -43,3 +44,30 @@ export function renderStatusline(if (bottom.length) lines.push(C.muted('▸ ') + bottom.join(SEP));return lines;}++function nodeIdsInFile(w: GraphV1, filePath: string): Set<string> {+ const nodes = w.nodes ?? [];+ return new Set(+ nodes.filter((n) => n.path && (filePath === n.path || filePath.endsWith(`/${n.path}`) || filePath.endsWith(n.path)))+ .map((n) => n.id),+ );+}++export function incomingEdges(w: GraphV1, filePath: string): EdgeV1[] {+ const ids = nodeIdsInFile(w, filePath);+ if (!ids.size) return [];+ return (w.edges ?? []).filter((e) => ids.has(e.target) && !ids.has(e.source));+}++export function formatBlastRadius(w: GraphV1, filePath: string, cap = 8): string | null {+ const edges = incomingEdges(w, filePath);+ if (!edges.length) return null;+ const byId = new Map((w.nodes ?? []).map((n) => [n.id, n]));+ const items = edges.slice(0, cap).map((e) => {+ const n = byId.get(e.source);+ const label = n ? `${n.name} (${basename(n.path)})` : e.source;+ return ` • ${e.relation} ← ${label}`;+ });+ const more = edges.length > cap ? `\n • +${edges.length - cap} more` : '';+ return `[graft] blast radius for ${basename(filePath)} — who depends on it:\n${items.join('\n')}${more}`;+}diff --git a/src/claude/hooks.ts b/src/claude/hooks.tsnew file mode 100644index 00000000..5cb0a793--- /dev/null+++ b/src/claude/hooks.ts@@ -0,0 +1,61 @@+import { readFileSync } from 'node:fs';+import { execFileSync, spawn } from 'node:child_process';+import { join, basename } from 'node:path';+import { readWiring } from './stats.js';+import { formatBlastRadius } from './format.js';+import { patchStats, readStats, acquireLock } from './state.js';++function readStdin(): any {+ const seam = process.env.GRAFT_TEST_STDIN;+ const raw = seam !== undefined ? seam : safeReadFd0();+ try { return JSON.parse(raw); } catch { return {}; }+}+function safeReadFd0(): string { try { return readFileSync(0, 'utf8'); } catch { return ''; } }++function projectDir(input: any): string {+ return process.env.CLAUDE_PROJECT_DIR || input.cwd || process.cwd();+}+export function underGraft(dir: string, file: string): boolean {+ const rel = file.startsWith(dir) ? file.slice(dir.length) : file;+ return rel.replace(/^[/\\]+/, '').replace(/\\/g, '/').startsWith('graft/');+}+function graftJson(dir: string, args: string[]): any | null {+ try {+ const out = execFileSync(process.execPath, [join(dir, 'dist', 'cli.js'), ...args],+ { cwd: dir, encoding: 'utf8', timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'] });+ return JSON.parse(out);+ } catch { return null; }+}+function checkStaleCount(dir: string): number {+ const r = graftJson(dir, ['check', '.', '--json']);+ const g = r?.graph ?? {};+ return (g.changed?.length ?? 0) + (g.added?.length ?? 0) + (g.removed?.length ?? 0);+}+function emit(eventName: string, additionalContext: string): void {+ process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: eventName, additionalContext } }));+}++export async function main(event: string): Promise<void> {+ const input = readStdin();+ const dir = projectDir(input);++ if (event === 'post-edit') {+ const file: string | undefined = input?.tool_input?.file_path;+ if (!file || underGraft(dir, file)) return;+ patchStats(dir, { dirty: true, staleCount: checkStaleCount(dir), lastFile: basename(file) });+ const w = readWiring(dir);+ if (w) { const br = formatBlastRadius(w, file); if (br) emit('PostToolUse', br); }+ return;+ }++ if (event === 'stop') {+ const stats = readStats(dir);+ if (stats?.dirty && acquireLock(dir)) {+ patchStats(dir, { syncing: true });+ const child = spawn(process.execPath, [join(dir, 'dist', 'claude', 'sync-run.js'), dir],+ { detached: true, stdio: 'ignore' });+ child.unref();+ }+ return;+ }+}diff --git a/test/claude-format.test.ts b/test/claude-format.test.tsindex be2e74cb..f5374238 100644--- a/test/claude-format.test.ts+++ b/test/claude-format.test.ts@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { renderStatusline, enrichedSegment } from '../src/claude/format.js';+import { renderStatusline, enrichedSegment, incomingEdges, formatBlastRadius } from '../src/claude/format.js';import { emptyStats } from '../src/claude/state.js';const strip = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, '');@@ -36,3 +36,29 @@ test('syncing overrides stale; synced when clean', () => {assert.match(strip(renderStatusline({ ...base, syncing: true, dirty: true }, null, { ctxPct: null })[0]), /syncing/);assert.match(strip(renderStatusline(base, null, { ctxPct: null })[0]), /✓ synced/);});++const wiring2 = {+ meta: { nodeCount: 3, edgeCount: 2, languages: ['typescript'] },+ nodes: [+ { id: 'src/pkce.ts#verify', name: 'verify', path: 'src/pkce.ts', summary_state: 'ready' },+ { id: 'src/client.ts#exchange', name: 'exchange', path: 'src/client.ts', summary_state: 'ready' },+ { id: 'src/pkce.ts#gen', name: 'gen', path: 'src/pkce.ts', summary_state: 'ready' },+ ],+ edges: [+ { source: 'src/client.ts#exchange', target: 'src/pkce.ts#verify', relation: 'calls', confidence: 'extracted' },+ { source: 'src/pkce.ts#gen', target: 'src/pkce.ts#verify', relation: 'calls', confidence: 'extracted' },+ ],+} as any;++test('incomingEdges: external callers of nodes in the edited file', () => {+ const e = incomingEdges(wiring2, '/abs/repo/src/pkce.ts');+ assert.equal(e.length, 1, 'same-file edge (gen→verify) excluded');+ assert.equal(e[0].source, 'src/client.ts#exchange');+});++test('formatBlastRadius renders callers or null', () => {+ const txt = formatBlastRadius(wiring2, '/abs/repo/src/pkce.ts');+ assert.match(strip(txt!), /blast radius for pkce\.ts/);+ assert.match(strip(txt!), /exchange \(client\.ts\)/);+ assert.equal(formatBlastRadius(wiring2, '/abs/repo/src/unknown.ts'), null);+});diff --git a/test/claude-hooks.test.ts b/test/claude-hooks.test.tsnew file mode 100644index 00000000..2678298b--- /dev/null+++ b/test/claude-hooks.test.ts@@ -0,0 +1,39 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { underGraft, main } from '../src/claude/hooks.js';+import { readStats } from '../src/claude/state.js';++test('underGraft detects edits inside graft/', () => {+ assert.equal(underGraft('/repo', '/repo/graft/x.md'), true);+ assert.equal(underGraft('/repo', '/repo/src/cli.ts'), false);+});++test('post-edit marks dirty and records lastFile', async () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-hooks-'));+ mkdirSync(join(d, 'graft', '.graph'), { recursive: true });+ writeFileSync(join(d, 'graft', '.graph', 'wiring.json'),+ JSON.stringify({ meta: { nodeCount: 0, edgeCount: 0, languages: [] }, nodes: [], edges: [] }));+ // graft check will fail (no dist/cli.js here) → staleCount falls back to 0, but dirty must still be set.+ process.env.CLAUDE_PROJECT_DIR = d;+ const stdin = JSON.stringify({ tool_input: { file_path: join(d, 'src', 'auth.ts') } });+ await runWithStdin(stdin, () => main('post-edit'));+ const s = readStats(d)!;+ assert.equal(s.dirty, true);+ assert.equal(s.lastFile, 'auth.ts');+});++test('post-edit ignores edits inside graft/', async () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-hooks-'));+ process.env.CLAUDE_PROJECT_DIR = d;+ await runWithStdin(JSON.stringify({ tool_input: { file_path: join(d, 'graft', 'a.md') } }), () => main('post-edit'));+ assert.equal(readStats(d), null, 'no state written for graft/ edits');+});++// helper: hooks.ts reads process.env.GRAFT_TEST_STDIN first (test seam), else fd 0.+async function runWithStdin(text: string, fn: () => Promise<void>): Promise<void> {+ process.env.GRAFT_TEST_STDIN = text;+ try { await fn(); } finally { delete process.env.GRAFT_TEST_STDIN; }+}