Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
feat(hook): report edits from the working tree's diff, once per session
KageBinaryfde36c690641
diff --git a/CLAUDE.md b/CLAUDE.mdindex 2ee6b3da..f8d32d12 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -45,7 +45,7 @@ ix map --silent # refresh the graph after code chang`ix reset --workspace` (the registered workspace containing cwd, nothingelse). After a global reset, re-map each workspace.- **The OSS↔Pro command boundary is derived at runtime, not declared.**- `main.ts` snapshots `ossCmdNames` right after `registerOssCommands()`; the+ `cli.ts` snapshots `ossCmdNames` right after `registerOssCommands()`; thePro probe diffs against it. Adding a command to `oss.ts` silently makes itOSS; removing one makes Pro own it. `registerProCommands` is async and MUSTbe awaited.diff --git a/ix-cli/scripts/dump-cli-surface.mjs b/ix-cli/scripts/dump-cli-surface.mjsindex 36196cec..d790d663 100644--- a/ix-cli/scripts/dump-cli-surface.mjs+++ b/ix-cli/scripts/dump-cli-surface.mjs@@ -39,8 +39,8 @@ try {}const program = new Command();-// Mirror main.ts's root registration. `--version` / `-V` is declared on the-// program itself (main.ts:64), not on any subcommand, so without this the one+// Mirror cli.ts's root registration. `--version` / `-V` is declared on the+// program itself (cli.ts), not on any subcommand, so without this the one// place a flag can be added with no per-command file changing is also the one// place this inventory cannot see it.const pkg = createRequire(import.meta.url)("../package.json");diff --git a/ix-cli/src/cli/__tests__/claude-post-edit.test.ts b/ix-cli/src/cli/__tests__/claude-post-edit.test.tsindex 4cd8af47..574cef49 100644--- a/ix-cli/src/cli/__tests__/claude-post-edit.test.ts+++ b/ix-cli/src/cli/__tests__/claude-post-edit.test.ts@@ -1,12 +1,7 @@// Copyright 2026 Ix Infrastructure Inc.-import { describe, expect, it, vi } from "vitest";-import {- locateEdit, locateText, patchRanges, postToolUseOutput, runClaudePostEdit, withDeadline,- type HookDeps, type PostToolUseInput,-} from "../hook/claude-post-edit.js";-import { estimateTokens, type AroundRequest, type AroundResult } from "../around.js";-import { WorkspaceNotMappedError } from "../errors.js";+import { describe, expect, it } from "vitest";+import { locateEdit, locateText, patchRanges, type PostToolUseInput } from "../hook/claude-post-edit.js";const ORIGINAL = ["export function add(a, b) {", // 1@@ -108,119 +103,3 @@ describe("locateEdit", () => {});});-// ── The whole hook, with the graph read injected ─────────────────────────────--function result(over: Partial<AroundResult> = {}): AroundResult {- return {- path: "src/math.ts",- symbols: [{- id: "1", name: "add", kind: "function", path: "src/math.ts", lineStart: 1, lineEnd: 4,- callers: { total: 1, rows: [{ path: "src/calc.ts", line: 9, snippet: "return add(x, y);", name: "calc" }] },- users: { total: 0, rows: [] },- tests: { total: 1, rows: [{ path: "src/__tests__/calc.test.ts", line: 4, snippet: "expect(calc(1, 2)).toBe(3);", via: "calc" }] },- sameName: [],- }],- importers: { total: 2, tests: 1, rows: [] },- ...over,- };-}--function deps(over: Partial<HookDeps> = {}): HookDeps & { gather: ReturnType<typeof vi.fn> } {- const gather = vi.fn(async (_req: AroundRequest) => result());- return {- gather,- readFile: () => UPDATED,- chdir: () => {},- workspaceRoot: () => "/ws",- ...over,- } as HookDeps & { gather: ReturnType<typeof vi.fn> };-}--describe("runClaudePostEdit", () => {- it("prints exactly the PostToolUse JSON, naming the symbol, its callers and tests", async () => {- const out = await runClaudePostEdit(JSON.stringify(editInput()), {}, deps());- const parsed = JSON.parse(out!);- expect(Object.keys(parsed)).toEqual(["hookSpecificOutput"]);- expect(Object.keys(parsed.hookSpecificOutput)).toEqual(["hookEventName", "additionalContext"]);- expect(parsed.hookSpecificOutput.hookEventName).toBe("PostToolUse");- expect(parsed.hookSpecificOutput.additionalContext).toBe([- "Ix: you changed `add` (src/math.ts:1-4).",- "callers (1):",- " src/calc.ts:9 return add(x, y);",- "tests (1):",- " src/__tests__/calc.test.ts:4 (via calc) expect(calc(1, 2)).toBe(3);",- "math.ts is imported by 2 files (1 test).",- "These may need updating to match your edit.",- ].join("\n"));- expect(out).toBe(postToolUseOutput(parsed.hookSpecificOutput.additionalContext));- });-- it("asks about the old-side lines in the original text, and reports in the file now", async () => {- const d = deps();- await runClaudePostEdit(JSON.stringify(editInput()), {}, d);- const req = d.gather.mock.calls[0][0] as AroundRequest;- expect(req.relPath).toBe("src/math.ts");- expect(req.ranges).toEqual([{ start: 2, end: 2 }]);- expect(req.anchorLines).toEqual(ORIGINAL.split("\n"));- expect(req.currentLines).toEqual(UPDATED.split("\n"));- });-- it("maps a file in --worktree onto the same path under --graph-root", async () => {- const d = deps({ workspaceRoot: () => "/graph" });- const input = editInput({ tool_input: { file_path: "/run/wt/src/math.ts" } });- const chdir = vi.fn();- await runClaudePostEdit(JSON.stringify(input), { graphRoot: "/graph", worktree: "/run/wt" }, { ...d, chdir });- expect(chdir).toHaveBeenCalledWith("/graph");- expect((d.gather.mock.calls[0][0] as AroundRequest).relPath).toBe("src/math.ts");- });-- it("stays under the token budget on a large answer", async () => {- const many = (n: number, p: string) => Array.from({ length: n }, (_, i) => ({- path: `src/some/deeply/nested/${p}${i}.ts`, line: 10 + i, snippet: `return await computeSomethingLong(${i}, alpha, beta, gamma, delta);`,- }));- const big = result();- big.symbols = ["a", "b", "c"].map((name) => ({- ...big.symbols[0], name,- callers: { total: 30, rows: many(8, `${name}c`) },- users: { total: 6, rows: many(5, `${name}u`) },- tests: { total: 9, rows: many(5, `${name}t`) },- }));- const out = await runClaudePostEdit(JSON.stringify(editInput()), {}, deps({ gather: vi.fn(async () => big) }));- const text = JSON.parse(out!).hookSpecificOutput.additionalContext as string;- expect(estimateTokens(text)).toBeLessThanOrEqual(300);- expect(text.split("\n")[0]).toMatch(/^Ix: you changed `a`/);- });-- describe("prints nothing", () => {- const silent: Array<[string, () => Promise<string | undefined>]> = [- ["for input that is not JSON", () => runClaudePostEdit("not json", {}, deps())],- ["for a tool that is not an edit", () => runClaudePostEdit(JSON.stringify(editInput({ tool_name: "Read" })), {}, deps())],- ["for a non-code file", () => runClaudePostEdit(JSON.stringify(editInput({ tool_input: { file_path: "/ws/README.md", new_string: "x" } })), {}, deps())],- ["for a lockfile", () => runClaudePostEdit(JSON.stringify(editInput({ tool_input: { file_path: "/ws/package-lock.json", new_string: "x" } })), {}, deps())],- ["for a file outside the workspace", () => runClaudePostEdit(JSON.stringify(editInput({ tool_input: { file_path: "/elsewhere/a.ts" } })), {}, deps())],- ["for a file outside --worktree", () => runClaudePostEdit(JSON.stringify(editInput()), { graphRoot: "/graph", worktree: "/run/wt" }, deps())],- ["for a new file", () => runClaudePostEdit(JSON.stringify(editInput({ tool_name: "Write", tool_response: { type: "create", originalFile: null, structuredPatch: [] } })), {}, deps())],- ["when the backend is down", () => runClaudePostEdit(JSON.stringify(editInput()), {}, deps({ gather: vi.fn(async () => { throw new TypeError("fetch failed"); }) }))],- ["when the workspace is not mapped", () => runClaudePostEdit(JSON.stringify(editInput()), {}, deps({ gather: vi.fn(async () => { throw new WorkspaceNotMappedError("/ws"); }) }))],- ["when the file is not in the graph", () => runClaudePostEdit(JSON.stringify(editInput()), {}, deps({ gather: vi.fn(async () => { throw Object.assign(new Error("not in graph"), { code: "file_not_in_graph" }); }) }))],- ["when no definition covers the edit", () => runClaudePostEdit(JSON.stringify(editInput()), {}, deps({ gather: vi.fn(async () => result({ symbols: [] })) }))],- ["when nothing depends on it", () => runClaudePostEdit(JSON.stringify(editInput()), {}, deps({- gather: vi.fn(async () => result({ symbols: [{ ...result().symbols[0], callers: { total: 0, rows: [] }, tests: { total: 0, rows: [] } }] })),- }))],- ["when the file cannot be read", () => runClaudePostEdit(JSON.stringify(editInput()), {}, deps({ readFile: () => undefined }))],- ["when chdir throws", () => runClaudePostEdit(JSON.stringify(editInput()), {}, deps({ chdir: () => { throw new Error("ENOENT"); } }))],- ];- for (const [name, run] of silent) {- it(name, async () => {- expect(await run()).toBeUndefined();- });- }-- it("when the answer misses the deadline", async () => {- const slow = new Promise<string>((resolve) => setTimeout(() => resolve("late"), 200));- expect(await withDeadline(slow, 10)).toBeUndefined();- expect(await withDeadline(Promise.reject(new Error("x")), 50)).toBeUndefined();- expect(await withDeadline(Promise.resolve("ok"), 50)).toBe("ok");- });- });-});diff --git a/ix-cli/src/cli/__tests__/post-edit-hook.test.ts b/ix-cli/src/cli/__tests__/post-edit-hook.test.tsnew file mode 100644index 00000000..db5878cd--- /dev/null+++ b/ix-cli/src/cli/__tests__/post-edit-hook.test.ts@@ -0,0 +1,347 @@+// Copyright 2026 Ix Infrastructure Inc.++import { execFileSync } from "node:child_process";+import { mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { parseHookArgs, runPostEditHook, type EntryDeps } from "../hook/entry.js";+import { postToolUseOutput, withDeadline } from "../hook/io.js";+import { fingerprint, loadState, parseUnifiedDiff, statePath } from "../hook/session.js";+import { reportToolEdit, summarize, type PostToolUseInput } from "../hook/claude-post-edit.js";+import { estimateTokens, type AroundRequest, type AroundResult, type AroundSymbol } from "../around.js";+import { WorkspaceNotMappedError } from "../errors.js";++// ── Diff parsing ────────────────────────────────────────────────────────────++describe("parseUnifiedDiff", () => {+ const diff = [+ "diff --git a/src/a.ts b/src/a.ts",+ "index 1..2 100644",+ "--- a/src/a.ts",+ "+++ b/src/a.ts",+ "@@ -2 +2 @@ export function a() {",+ "- return 1;",+ "+ return 2;",+ "@@ -10,0 +11,2 @@",+ "+x",+ "+y",+ "@@ -20,3 +21,0 @@",+ "-p",+ "-q",+ "-r",+ "diff --git a/src/gone.ts b/src/gone.ts",+ "deleted file mode 100644",+ "--- a/src/gone.ts",+ "+++ /dev/null",+ "@@ -1,2 +0,0 @@",+ "-a",+ "-b",+ "diff --git a/src/new.ts b/src/new.ts",+ "new file mode 100644",+ "--- /dev/null",+ "+++ b/src/new.ts",+ "@@ -0,0 +1 @@",+ "+n",+ "diff --git \"a/src/sp\\303\\251cial.ts\" \"b/src/sp\\303\\251cial.ts\"",+ "--- \"a/src/sp\\303\\251cial.ts\"",+ "+++ \"b/src/sp\\303\\251cial.ts\"",+ "@@ -1 +1 @@",+ "-a",+ "+b",+ ].join("\n");++ it("reads each hunk's old side: replacements, insertion points and deletions", () => {+ const files = parseUnifiedDiff(diff);+ expect(files[0]).toEqual({+ oldPath: "src/a.ts", newPath: "src/a.ts",+ oldRanges: [{ start: 2, end: 2 }, { start: 10, end: 11, insertion: true }, { start: 20, end: 22 }],+ });+ });++ it("keeps a deleted file (its symbols had dependents) and a new file without an old path", () => {+ const files = parseUnifiedDiff(diff);+ expect(files[1]).toEqual({ oldPath: "src/gone.ts", newPath: undefined, oldRanges: [{ start: 1, end: 2 }] });+ expect(files[2].oldPath).toBeUndefined();+ });++ it("parses a quoted path", () => {+ expect(parseUnifiedDiff(diff)[3].oldPath).toMatch(/^src\/sp.*cial\.ts$/);+ });+});++describe("parseHookArgs", () => {+ it("reads both flag spellings and ignores the rest", () => {+ expect(parseHookArgs(["--graph-root", "/g", "--worktree=/w", "--budget", "200", "--other"]))+ .toEqual({ graphRoot: "/g", worktree: "/w", budget: 200 });+ expect(parseHookArgs(["--budget", "abc"])).toEqual({});+ });+});++// ── The diff-based hook over a real git repository ──────────────────────────++const LIB = [+ "export function alpha(x) {", // 1+ " return x + 1;", // 2+ "}", // 3+ "", // 4+ "export function beta(y) {", // 5+ " return y * 2;", // 6+ "}", // 7+ "", // 8+ "export function gamma() {", // 9+ " return 0;", // 10+ "}", // 11+].join("\n");++const SYMBOLS: Array<[string, number, number]> = [["alpha", 1, 3], ["beta", 5, 7], ["gamma", 9, 11]];++/** The graph, mocked: every symbol whose span the ranges touch, unless excluded, with one caller. */+function fakeGather(calls: AroundRequest[], opts: { noDependents?: string[] } = {}) {+ return vi.fn(async (req: AroundRequest): Promise<AroundResult> => {+ calls.push(req);+ const symbols: AroundSymbol[] = SYMBOLS+ .filter(([name, s, e]) => !req.exclude?.has(name) && (req.ranges ?? []).some((r) => r.start <= e && r.end >= s))+ .map(([name, s, e]) => ({+ id: name, name, kind: "function", path: req.relPath, lineStart: s, lineEnd: e,+ callers: opts.noDependents?.includes(name)+ ? { total: 0, rows: [] }+ : { total: 1, rows: [{ path: "src/app.js", line: 3, snippet: `${name}(1);` }] },+ users: { total: 0, rows: [] }, tests: { total: 0, rows: [] }, sameName: [],+ }));+ return { path: req.relPath, symbols, importers: { total: 1, tests: 0, rows: [] } };+ });+}++let repo: string;+let stateDir: string;++function git(...args: string[]): void {+ execFileSync("git", ["-C", repo, ...args], { stdio: "ignore" });+}++beforeEach(() => {+ repo = mkdtempSync(join(tmpdir(), "ix-hook-repo-"));+ stateDir = mkdtempSync(join(tmpdir(), "ix-hook-state-"));+ mkdirSync(join(repo, "src"));+ writeFileSync(join(repo, "src/lib.js"), LIB);+ writeFileSync(join(repo, "README.md"), "# r\n");+ git("init", "-q");+ git("-c", "user.email=t@t", "-c", "user.name=t", "add", ".");+ git("-c", "user.email=t@t", "-c", "user.name=t", "-c", "commit.gpgsign=false", "commit", "-q", "-m", "base");+});++afterEach(() => {+ rmSync(repo, { recursive: true, force: true });+ rmSync(stateDir, { recursive: true, force: true });+});++const bash = (session = "s1"): string => JSON.stringify({+ session_id: session, hook_event_name: "PostToolUse", cwd: repo, tool_name: "Bash",+ tool_input: { command: "python3 - <<'E'\n...\nE" }, tool_response: { stdout: "", stderr: "" },+});++function deps(calls: AroundRequest[], over: Partial<EntryDeps> = {}): EntryDeps {+ return { gather: fakeGather(calls), chdir: () => {}, workspaceRoot: () => repo, ...over };+}++const run = (raw: string, d: EntryDeps) => runPostEditHook(raw, { env: { IX_HOOK_STATE_DIR: stateDir } }, d);+const context = (out: string | undefined) => JSON.parse(out!).hookSpecificOutput.additionalContext as string;+const edit = (from: string, to: string) => writeFileSync(join(repo, "src/lib.js"), LIB.replace(from, to));++describe("runPostEditHook: the diff path", () => {+ it("reports an edit made through Bash, located by the old side in HEAD's text", async () => {+ edit(" return y * 2;", " const z = y * 2;\n return z;");+ const calls: AroundRequest[] = [];+ const out = await run(bash(), deps(calls));+ expect(context(out)).toBe([+ "Ix: you changed `beta` (src/lib.js:5-7).",+ "callers (1):",+ " src/app.js:3 beta(1);",+ "lib.js is imported by 1 file.",+ "These may need updating to match your edit.",+ ].join("\n"));+ expect(calls).toHaveLength(1);+ expect(calls[0].relPath).toBe("src/lib.js");+ expect(calls[0].ranges).toEqual([{ start: 6, end: 6 }]);+ expect(calls[0].anchorLines).toEqual(LIB.split("\n"));+ expect(calls[0].currentLines).toContain(" const z = y * 2;");+ });++ it("reports a symbol once per session, across repeated calls and repeat edits", async () => {+ const calls: AroundRequest[] = [];+ const d = deps(calls);+ edit(" return y * 2;", " return y * 3;");+ expect(await run(bash(), d)).toBeDefined();+ // The same diff again: answered from the fingerprint, without the graph.+ expect(await run(bash(), d)).toBeUndefined();+ expect(calls).toHaveLength(1);+ // Editing the same function again: the graph is asked, the symbol excluded.+ edit(" return y * 2;", " return y * 4;");+ expect(await run(bash(), d)).toBeUndefined();+ expect(calls[1].exclude).toEqual(new Set(["beta"]));+ // A newly edited function is reported.+ writeFileSync(join(repo, "src/lib.js"), LIB.replace(" return y * 2;", " return y * 4;").replace(" return x + 1;", " return x + 2;"));+ expect(context(await run(bash(), d))).toMatch(/^Ix: you changed `alpha`/);+ });++ it("keys its memory by session", async () => {+ edit(" return y * 2;", " return y * 3;");+ const calls: AroundRequest[] = [];+ expect(await run(bash("s1"), deps(calls))).toBeDefined();+ expect(await run(bash("s1"), deps(calls))).toBeUndefined();+ expect(await run(bash("s2"), deps(calls))).toBeDefined();+ expect(statePath("s1", repo, { IX_HOOK_STATE_DIR: stateDir })).not.toBe(statePath("s2", repo, { IX_HOOK_STATE_DIR: stateDir }));+ });++ it("prints nothing, without loading the graph, for a Bash call that changed nothing", async () => {+ const calls: AroundRequest[] = [];+ const started = Date.now();+ expect(await run(bash(), deps(calls))).toBeUndefined();+ expect(Date.now() - started).toBeLessThan(500);+ expect(calls).toHaveLength(0);+ });++ it("prints nothing for a new untracked file, or a changed non-code file", async () => {+ writeFileSync(join(repo, "src/fresh.js"), "export function fresh() {}\n");+ writeFileSync(join(repo, "README.md"), "# changed\n");+ const calls: AroundRequest[] = [];+ expect(await run(bash(), deps(calls))).toBeUndefined();+ expect(calls).toHaveLength(0);+ });++ it("locates deleted lines, and a deleted file", async () => {+ edit(" return 0;\n", "");+ const calls: AroundRequest[] = [];+ expect(context(await run(bash(), deps(calls)))).toMatch(/^Ix: you changed `gamma`/);+ expect(calls[0].ranges).toEqual([{ start: 10, end: 10 }]);++ unlinkSync(join(repo, "src/lib.js"));+ expect(context(await run(bash("s2"), deps(calls)))).toMatch(/`alpha`.*`beta`.*`gamma`/);+ expect(calls[1].currentLines).toEqual([""]);+ });++ it("remembers a symbol with nothing depending on it, without reporting it", async () => {+ writeFileSync(join(repo, "src/lib.js"), LIB.replace("x + 1", "x + 9").replace("y * 2", "y * 9").replace("return 0", "return 9"));+ const calls: AroundRequest[] = [];+ const out = context(await run(bash(), deps(calls, { gather: fakeGather(calls, { noDependents: ["gamma"] }) })));+ expect(out).toMatch(/`alpha`.*`beta`/s);+ expect(out).not.toMatch(/gamma/);+ expect(loadState(statePath("s1", repo, { IX_HOOK_STATE_DIR: stateDir })).reported.sort())+ .toEqual(["src/lib.js#alpha", "src/lib.js#beta", "src/lib.js#gamma"]);+ });++ it("caps the symbols per call and reports the rest on the next, even if nothing else changed", async () => {+ SYMBOLS.push(["delta", 1, 11]);+ try {+ writeFileSync(join(repo, "src/lib.js"), LIB.replace("x + 1", "x + 9").replace("y * 2", "y * 9").replace("return 0", "return 9"));+ const calls: AroundRequest[] = [];+ const first = context(await run(bash(), deps(calls)));+ expect(first).toMatch(/`alpha`.*`beta`.*`gamma`/s);+ expect(first).not.toMatch(/delta/);+ expect(context(await run(bash(), deps(calls)))).toMatch(/^Ix: you changed `delta`/);+ expect(await run(bash(), deps(calls))).toBeUndefined();+ } finally {+ SYMBOLS.pop();+ }+ });++ it("prints nothing when the backend is down, the workspace unmapped, or the file not in the graph", async () => {+ edit(" return y * 2;", " return y * 3;");+ for (const err of [new TypeError("fetch failed"), new WorkspaceNotMappedError(repo), new Error("not in graph")]) {+ const out = await runPostEditHook(bash(`s-${err.message}`), { env: { IX_HOOK_STATE_DIR: stateDir } },+ { chdir: () => {}, workspaceRoot: () => repo, gather: vi.fn(async () => { throw err; }) });+ expect(out).toBeUndefined();+ }+ });++ it("prints nothing for input that is not JSON, or outside a mapped workspace", async () => {+ expect(await run("not json", deps([]))).toBeUndefined();+ edit(" return y * 2;", " return y * 3;");+ expect(await run(bash(), deps([], { workspaceRoot: () => join(repo, "elsewhere") }))).toBeUndefined();+ });++ it("maps --worktree onto --graph-root", async () => {+ edit(" return y * 2;", " return y * 3;");+ const calls: AroundRequest[] = [];+ const chdir = vi.fn();+ const out = await runPostEditHook(bash(), { graphRoot: "/graph", worktree: repo, env: { IX_HOOK_STATE_DIR: stateDir } },+ { ...deps(calls), chdir, workspaceRoot: () => "/graph" });+ expect(out).toBeDefined();+ expect(chdir).toHaveBeenCalledWith("/graph");+ expect(calls[0].relPath).toBe("src/lib.js");+ });++ it("stores the diff's fingerprint once everything in it was reported", async () => {+ edit(" return y * 2;", " return y * 3;");+ await run(bash(), deps([]));+ const diff = execFileSync("git", ["-C", repo, "diff", "-U0", "--no-color", "--no-ext-diff", "--no-renames", "HEAD", "--"], { encoding: "utf-8" });+ expect(loadState(statePath("s1", repo, { IX_HOOK_STATE_DIR: stateDir })).fingerprint).toBe(fingerprint(diff));+ });+});++// ── Outside git: the Edit tool's own patch ──────────────────────────────────++describe("reportToolEdit (no git repository)", () => {+ const input: PostToolUseInput = {+ session_id: "s", cwd: "/ws", tool_name: "Edit",+ tool_input: { file_path: "/ws/src/lib.js", old_string: " return y * 2;", new_string: " return y * 3;" },+ tool_response: {+ originalFile: LIB,+ structuredPatch: [{ oldStart: 6, oldLines: 1, newStart: 6, newLines: 1, lines: ["- return y * 2;", "+ return y * 3;"] }],+ },+ };+ const d = (calls: AroundRequest[]) => ({+ gather: fakeGather(calls), chdir: () => {}, workspaceRoot: () => "/ws", readFile: () => LIB.replace("y * 2", "y * 3"),+ });++ it("reports from the old side of the tool's patch, and remembers what it reported", async () => {+ const calls: AroundRequest[] = [];+ const outcome = await reportToolEdit(input, new Set(), {}, d(calls));+ expect(context(outcome.output)).toMatch(/^Ix: you changed `beta` \(src\/lib\.js:5-7\)/);+ expect(calls[0].ranges).toEqual([{ start: 6, end: 6 }]);+ expect(outcome.reported).toEqual(["src/lib.js#beta"]);+ });++ it("prints nothing for a non-edit tool, a non-code file, or a symbol already reported", async () => {+ expect((await reportToolEdit({ ...input, tool_name: "Read" }, new Set(), {}, d([]))).output).toBeUndefined();+ expect((await reportToolEdit({ ...input, tool_input: { file_path: "/ws/README.md" } }, new Set(), {}, d([]))).output).toBeUndefined();+ expect((await reportToolEdit(input, new Set(["src/lib.js#beta"]), {}, d([]))).output).toBeUndefined();+ });+});++// ── Output ──────────────────────────────────────────────────────────────────++describe("output", () => {+ it("is exactly the PostToolUse shape", () => {+ expect(JSON.parse(postToolUseOutput("ctx"))).toEqual({+ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: "ctx" },+ });+ });++ it("stays under the token budget across several large files", () => {+ const many = (n: number, p: string) => Array.from({ length: n }, (_, i) => ({+ path: `src/some/deeply/nested/${p}${i}.ts`, line: 10 + i, snippet: `return await computeSomethingLong(${i}, alpha, beta, gamma);`,+ }));+ const results: AroundResult[] = ["a", "b"].map((f) => ({+ path: `src/${f}.ts`,+ symbols: ["x", "y"].map((name) => ({+ id: `${f}${name}`, name, kind: "function", path: `src/${f}.ts`, lineStart: 1, lineEnd: 9,+ callers: { total: 30, rows: many(8, `${f}${name}c`) }, users: { total: 6, rows: many(5, `${f}${name}u`) },+ tests: { total: 9, rows: many(5, `${f}${name}t`) }, sameName: [],+ })),+ importers: { total: 40, tests: 3, rows: many(5, `${f}i`) },+ }));+ const outcome = summarize(results, 300);+ expect(estimateTokens(context(outcome.output))).toBeLessThanOrEqual(300);+ expect(outcome.complete).toBe(false); // four symbols, three shown+ expect(outcome.reported).toEqual(["src/a.ts#ax", "src/a.ts#ay", "src/b.ts#bx"]);+ });++ it("drops an answer that misses the deadline", async () => {+ expect(await withDeadline(new Promise((r) => setTimeout(() => r("late"), 200)), 10)).toBeUndefined();+ expect(await withDeadline(Promise.reject(new Error("x")), 50)).toBeUndefined();+ expect(await withDeadline(Promise.resolve("ok"), 50)).toBe("ok");+ });+});diff --git a/ix-cli/src/cli/around.ts b/ix-cli/src/cli/around.tsindex 762e79dc..b31da2b0 100644--- a/ix-cli/src/cli/around.ts+++ b/ix-cli/src/cli/around.ts@@ -328,6 +328,12 @@ export interface AroundRequest {/** Reads the dependents' files for their sites. */files: SourceFiles;caps?: Partial<AroundCaps>;+ /**+ * Ids of definitions not to report: the post-edit hook's "already told this+ * session". Applied after innermost selection, so a class whose method was+ * reported earlier does not take that method's place.+ */+ exclude?: Set<string>;}type AroundClient = Pick<IxClient, "search" | "expand" | "workspaceSystem" | "currentRevision" | "stats"> & { endpoint?: string };@@ -435,11 +441,15 @@ export async function gatherAround(client: AroundClient, req: AroundRequest): Prlet chosen: PlacedDef[];const preloaded = new Map<string, any[]>();if (req.ranges && req.ranges.length > 0) {- chosen = selectEdited(anchorPlaced, req.ranges, caps.symbols);+ chosen = selectEdited(anchorPlaced, req.ranges, Number.MAX_SAFE_INTEGER)+ .filter((d) => !req.exclude?.has(d.id))+ .slice(0, caps.symbols);} else {// The whole file: its outermost definitions, the most-called first, so a// capped answer keeps the ones with dependents.- const candidates = outermostDefs(anchorPlaced).slice(0, WHOLE_FILE_CANDIDATES);+ const candidates = outermostDefs(anchorPlaced)+ .filter((d) => !req.exclude?.has(d.id))+ .slice(0, WHOLE_FILE_CANDIDATES);const counts = await Promise.all(candidates.map(async (d) => {const r = await client.expand(d.id, { direction: "in", predicates: ["CALLS", "REFERENCES"] });preloaded.set(d.id, r.nodes.filter((n: any) => n.id !== d.id));diff --git a/ix-cli/src/cli/cli.ts b/ix-cli/src/cli/cli.tsnew file mode 100644index 00000000..76243ecc--- /dev/null+++ b/ix-cli/src/cli/cli.ts@@ -0,0 +1,139 @@+// Copyright 2026 Ix Infrastructure Inc.++import { Command } from "commander";+import { registerOssCommands, registerProStubs } from "./register/oss.js";+import { tryLoadProCommands } from "./register/pro-loader.js";+import { isRepairInvocation } from "./register/pro-failure.js";+import { buildHelpText } from "./help-text.js";+import { checkForUpdate, updateCheckEnabled } from "./commands/upgrade.js";+import { stderrIsTerminal } from "./stderr.js";+import { detectRequestedFormat, renderCliError, setErrorFormat } from "./errors.js";+import { getEndpoint } from "./config.js";++import { readFileSync } from "fs";+import { join, dirname } from "path";+import { fileURLToPath } from "url";++// Runtime Node version guard. Runs before any command work so users on an+// unsupported Node get an actionable message instead of a cryptic "fetch+// failed" deep inside undici.+const MIN_NODE_MAJOR = 22;+{+ const current = process.versions.node;+ const major = parseInt(current.split(".")[0] ?? "0", 10);+ if (!Number.isFinite(major) || major < MIN_NODE_MAJOR) {+ process.stderr.write(+ `Ix requires Node.js ${MIN_NODE_MAJOR} or newer. You are running v${current}.\n` ++ `Install a supported version from https://nodejs.org/ and re-run.\n`+ );+ process.exit(1);+ }+}++let cliVersion = "0.0.0";+try {+ const __dirname = dirname(fileURLToPath(import.meta.url));+ const pkg = JSON.parse(readFileSync(join(__dirname, "../../package.json"), "utf-8"));+ cliVersion = pkg.version || "0.0.0";+} catch {}++// Set IX_DEBUG=1 to append stack traces to any rendered error.+const debug = process.env.IX_DEBUG === "1";++// Before anything can throw. The handlers below are installed for+// `unhandledRejection` and `uncaughtException`, which can fire before+// commander has parsed a thing, so the error boundary gets the format from+// argv rather than from a parsed command.+setErrorFormat(detectRequestedFormat(process.argv.slice(2)));++// Resolving the endpoint reads config off disk, which can itself fail. An+// error renderer must never throw, so failure here just drops the endpoint+// from the message rather than replacing one crash with another.+function safeEndpoint(): string | undefined {+ try {+ return getEndpoint();+ } catch {+ return undefined;+ }+}++// Last line of defence. Without these, any rejection escaping a command — most+// commonly the backend not running — reaches Node's default handler and prints+// an undici stack trace that exposes internal paths and tells the user nothing.+process.on("unhandledRejection", (err: unknown) => {+ renderCliError(err, debug, safeEndpoint());+});+process.on("uncaughtException", (err: unknown) => {+ renderCliError(err, debug, safeEndpoint());+});++const program = new Command();+program+ .name("ix")+ .version(cliVersion);++// Start with OSS-only help; updated after Pro probe.+program.helpInformation = () => buildHelpText();++registerOssCommands(program);++(async () => {+ const ossCmdNames = new Set(program.commands.map((c: Command) => c.name()));++ // An installed-but-broken Pro throws here rather than reporting absence, so+ // commands never run without its credential guard. Note this call sits+ // OUTSIDE the parseAsync try/catch below — render the failure here rather+ // than letting it reach the unhandledRejection handler by accident.+ let proLoaded = false;+ // `ix hook` runs inside an agent harness after every edit and must exit 0+ // with nothing on stdout whenever it cannot help. A broken Pro install would+ // otherwise make it exit 1 before its action runs, and it needs nothing Pro+ // registers.+ const isHook = process.argv[2] === "hook";+ try {+ if (!isHook) proLoaded = await tryLoadProCommands(program);+ } catch (err) {+ if (!isRepairInvocation(process.argv)) {+ renderCliError(err, debug, safeEndpoint()); // exits 1+ }+ // Repair invocation: continue OSS-only. proLoaded stays false, so the Pro+ // stubs register below and would misreport a broken Pro as absent — the+ // warning here is what distinguishes the two, and no command in the set+ // above reaches a stub.+ console.error(+ "[!!] Ix Pro is installed but failed to initialize; continuing with OSS " ++ "commands only so this one can repair the install.",+ );+ }+ if (proLoaded) {+ // Collect commands that Pro added (weren't in OSS set)+ const proCommands = program.commands+ .filter((c: Command) => !ossCmdNames.has(c.name()))+ .map((c: Command) => ({ name: c.name(), desc: c.description() }));++ program.helpInformation = () => buildHelpText(proCommands);+ } else {+ registerProStubs(program);+ }++ // Check for updates (non-blocking, cached 1hr). Only when a person is+ // watching stderr — see updateCheckEnabled for why, and for the+ // IX_NO_UPDATE_CHECK opt-out.+ const args = process.argv.slice(2);+ if (updateCheckEnabled(args, process.env, stderrIsTerminal())) {+ // Deliberately not awaited — but it must still be caught here. The catch+ // inside checkForUpdate only guards its inner fetch chain; the function's+ // own promise covers the synchronous cached-read path, and a corrupt+ // ~/.ix/.version-check.json makes that throw. Uncaught, the new+ // unhandledRejection handler then aborts a command that already succeeded.+ checkForUpdate().catch(() => {});+ }++ // parseAsync (not parse) so rejections from async action handlers surface+ // here instead of floating off as unhandled rejections.+ try {+ await program.parseAsync();+ } catch (err) {+ renderCliError(err, debug, safeEndpoint());+ }+})();diff --git a/ix-cli/src/cli/commands/hook.ts b/ix-cli/src/cli/commands/hook.tsindex 6748e630..3d549a7b 100644--- a/ix-cli/src/cli/commands/hook.ts+++ b/ix-cli/src/cli/commands/hook.ts@@ -3,7 +3,7 @@import type { Command } from "commander";import { parseBudgetOption } from "../options.js";import { DEFAULT_TOKEN_BUDGET } from "../around.js";-import { hookTimeoutMs, readStdin, runClaudePostEdit, withDeadline } from "../hook/claude-post-edit.js";+import { runHookProcess } from "../hook/entry.js";/*** `ix hook <agent-event>`: entry points an agent harness runs on its own@@ -20,10 +20,14 @@ export function registerHookCommand(program: Command): void {.command("claude-post-edit").description("Claude Code PostToolUse hook: after an edit, tell the agent who depends on what it changed").option("--graph-root <dir>", "Mapped workspace to query (default: the one containing the edited file)")- .option("--worktree <dir>", "Root the edited file_path is under; mapped to the same relative path in --graph-root")+ .option("--worktree <dir>", "Checkout the agent edits (default: git root of the hook cwd); mapped to the same relative paths in --graph-root").option("--budget <tokens>", "Token budget for the context it adds (~4 chars a token)", (v: string) => parseBudgetOption(v, String(DEFAULT_TOKEN_BUDGET)), DEFAULT_TOKEN_BUDGET).addHelpText("after", `-Reads Claude Code's PostToolUse JSON on stdin. Prints one JSON object,+Reads Claude Code's PostToolUse JSON on stdin and the working tree's diff+against HEAD, so an edit made through Bash counts as much as one made with+Edit or Write. Each edited symbol is reported once per session (state in+IX_HOOK_STATE_DIR, default <tmp>/ix-hook); a call that edited nothing new+prints nothing. Prints one JSON object,{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"..."}},naming the changed symbols' callers, importers that use them, and tests thatreach them -- or prints nothing. Always exits 0: a backend that is down, an@@ -32,27 +36,12 @@ nothing. Gives up after IX_HOOK_TIMEOUT_MS (default 3000). IX_HOOK_DEBUG=1says why on stderr..claude/settings.json:- {"hooks":{"PostToolUse":[{"matcher":"Edit|MultiEdit|Write",+ {"hooks":{"PostToolUse":[{"matcher":"Edit|MultiEdit|Write|Bash","hooks":[{"type":"command","command":"ix hook claude-post-edit"}]}]}}`)+ // Normally never reached: main.ts dispatches this invocation before the+ // CLI loads. Kept so the command is registered, documented and runnable+ // through the full CLI too..action(async (opts: { graphRoot?: string; worktree?: string; budget: number }) => {- const started = Date.now();- const timeout = hookTimeoutMs();- const debugOn = process.env.IX_HOOK_DEBUG === "1";- const debug = (msg: string) => { if (debugOn) process.stderr.write(`[ix hook] ${msg}\n`); };- let out: string | undefined;- try {- const raw = await readStdin(timeout);- const left = Math.max(0, timeout - (Date.now() - started));- out = await withDeadline(runClaudePostEdit(raw, opts, { debug }), left);- if (out === undefined) debug("no output");- } catch (err) {- debug(`failed: ${err instanceof Error ? err.message : String(err)}`);- out = undefined;- }- debug(`${Date.now() - started} ms`);- // Exit at once: a request still in flight past the deadline must not- // keep the agent waiting, or surface later as an unhandled rejection.- if (out) process.stdout.write(`${out}\n`, () => process.exit(0));- else process.exit(0);+ await runHookProcess(opts);});}diff --git a/ix-cli/src/cli/errors.ts b/ix-cli/src/cli/errors.tsindex 20cf6451..788cd5a2 100644--- a/ix-cli/src/cli/errors.ts+++ b/ix-cli/src/cli/errors.ts@@ -18,7 +18,7 @@ import { llmError } from "./llm.js";*/let requestedFormat: string | undefined;-/** Record the format for the error boundary. Called once, from `main.ts`. */+/** Record the format for the error boundary. Called once, from `cli.ts`. */export function setErrorFormat(format: string | undefined): void {requestedFormat = format;}diff --git a/ix-cli/src/cli/hook/claude-post-edit.ts b/ix-cli/src/cli/hook/claude-post-edit.tsindex c2151c20..e4923857 100644--- a/ix-cli/src/cli/hook/claude-post-edit.ts+++ b/ix-cli/src/cli/hook/claude-post-edit.ts@@ -6,14 +6,18 @@ import { IxClient } from "../../client/api.js";import { getEndpoint, resolveWorkspaceRoot } from "../config.js";import { SourceFiles } from "../edge-sites.js";import { isSourcePath } from "../explain/issue.js";+import type { FileDiff } from "./session.js";+import { gitShowHead, symbolKey } from "./session.js";+import { hookTimeoutMs, postToolUseOutput } from "./io.js";import {- DEFAULT_TOKEN_BUDGET, fitToBudget, gatherAround, hasDependents, type AroundRequest, type AroundResult, type LineRange,+ DEFAULT_TOKEN_BUDGET, estimateTokens, fitToBudget, gatherAround, hasDependents, type AroundRequest, type AroundResult, type LineRange,} from "../around.js";import { renderAroundText } from "../around-render.js";/**- * `ix hook claude-post-edit`: Claude Code's PostToolUse hook for Edit,- * MultiEdit and Write.+ * `ix hook claude-post-edit`: Claude Code's PostToolUse hook, the part that+ * reads the graph. `entry.ts` decides cheaply whether anything new was edited+ * and loads this module only when something was.** Agents never call Ix on their own, and context handed to them up front did* not change whether they solved an issue. This pushes one fact into the loop@@ -36,6 +40,7 @@ export interface PatchHunk {/** The fields of Claude Code's PostToolUse input this hook reads. */export interface PostToolUseInput {+ session_id?: string;hook_event_name?: string;cwd?: string;tool_name?: string;@@ -67,23 +72,6 @@ export interface HookOptions {export const EDIT_TOOLS = new Set(["Edit", "MultiEdit", "Write"]);/** Where a `new_string` occurs more often than this, it says nothing about where the edit was. */const MAX_OCCURRENCES = 3;-export const DEFAULT_HOOK_TIMEOUT_MS = 3000;--/**- * The one place the hook's stdout contract lives: Claude Code reads- * `hookSpecificOutput.additionalContext` off a PostToolUse hook's JSON and- * hands it to the model after the tool result.- */-export function postToolUseOutput(additionalContext: string): string {- return JSON.stringify({- hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext },- });-}--export function hookTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {- const raw = Number(env.IX_HOOK_TIMEOUT_MS);- return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_HOOK_TIMEOUT_MS;-}/** Runs of consecutive line numbers as ranges. */function toRanges(lines: number[]): LineRange[] {@@ -220,12 +208,32 @@ export function locateEdit(input: PostToolUseInput, current: string): EditLocatiexport interface HookDeps {gather?: (req: AroundRequest) => Promise<AroundResult>;readFile?: (abs: string) => string | undefined;+ /** A file's content in HEAD; the default asks git. */+ showHead?: (repoRoot: string, repoPath: string) => string | undefined;/** Moves the read scope to a directory; the default is `process.chdir`. */chdir?: (dir: string) => void;workspaceRoot?: () => string;debug?: (msg: string) => void;}+/** What one run told the agent, and what it now counts as told. */+export interface HookOutcome {+ /** The stdout to print, if any. */+ output?: string;+ /** `path#id` keys of the symbols this run covered: shown, or found to have no dependents. */+ reported: string[];+ /** False when edited symbols were left for a later call by the symbol cap. */+ complete: boolean;+}++const NOTHING: HookOutcome = { reported: [], complete: true };+/** Changed files looked at per run; a diff touching more is mostly not code anyway. */+const MAX_FILES = 8;+/** Symbols reported per run, across all files. */+const MAX_SYMBOLS = 3;+const LEAD = "Ix: you changed";+const FOOTER = "These may need updating to match your edit.";+function defaultReadFile(abs: string): string | undefined {try {const stat = fs.statSync(abs);@@ -238,93 +246,173 @@ function defaultReadFile(abs: string): string | undefined {const isInside = (rel: string) => rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);+interface Roots {+ /** Where the agent's files are. */+ worktree: string;+ /** The checkout the graph was built from. */+ graphRoot: string;+ /** The mapped workspace root (graph source_uris are relative to it). */+ workspaceRoot: string;+ /** The workspace root's counterpart in the worktree, for reading dependents' sites. */+ sourceRoot: string;+}++function resolveRoots(worktree: string, opts: HookOptions, deps: HookDeps): Roots {+ const graphRoot = path.resolve(opts.graphRoot ?? worktree);+ (deps.chdir ?? process.chdir)(graphRoot);+ const workspaceRoot = path.resolve((deps.workspaceRoot ?? resolveWorkspaceRoot)());+ return {+ worktree: path.resolve(worktree),+ graphRoot,+ workspaceRoot,+ sourceRoot: path.join(path.resolve(worktree), path.relative(graphRoot, workspaceRoot)),+ };+}++/** A worktree file as the graph spells it, or undefined when it is outside the workspace or not code. */+function graphPath(roots: Roots, worktreeFile: string): string | undefined {+ const rel = path.relative(roots.worktree, worktreeFile);+ if (!isInside(rel)) return undefined;+ const relPath = path.relative(roots.workspaceRoot, path.join(roots.graphRoot, rel)).split(path.sep).join("/");+ return isInside(relPath) && isSourcePath(relPath) ? relPath : undefined;+}++function gatherWith(deps: HookDeps, opts: HookOptions): (req: AroundRequest) => Promise<AroundResult> {+ if (deps.gather) return deps.gather;+ const timeoutMs = hookTimeoutMs(opts.env);+ return (req) => gatherAround(new IxClient(getEndpoint(), AbortSignal.timeout(timeoutMs)), req);+}+/**- * The hook, minus stdin and the process: the stdout it should print, or- * undefined to print nothing. Never throws.+ * The context for a set of answers: one `Ix: you changed ...` block per file,+ * the budget shared by symbol count, one closing line.*/-export async function runClaudePostEdit(raw: string, opts: HookOptions = {}, deps: HookDeps = {}): Promise<string | undefined> {- const debug = deps.debug ?? (() => {});- try {- let input: PostToolUseInput;- try { input = JSON.parse(raw) as PostToolUseInput; } catch { debug("stdin is not JSON"); return undefined; }- if (!input || typeof input !== "object") return undefined;- if (!EDIT_TOOLS.has(input.tool_name ?? "")) { debug(`tool ${input.tool_name} is not an edit`); return undefined; }-- const filePathRaw = input.tool_input?.file_path ?? input.tool_response?.filePath;- if (!filePathRaw) { debug("no file_path"); return undefined; }- const base = input.cwd && path.isAbsolute(input.cwd) ? input.cwd : process.cwd();- const filePath = path.resolve(base, filePathRaw);+export function renderHookText(results: AroundResult[], budget: number): string {+ const total = results.reduce((n, r) => n + r.symbols.length, 0);+ const room = Math.max(40, budget - Math.ceil(FOOTER.length / 4) - 1);+ const render = (x: AroundResult) => renderAroundText(x, { lead: LEAD });+ const fit = (r: AroundResult, tokens: number) => render(fitToBudget(r, render, tokens));+ // Each file gets its share by symbol count; what a small answer leaves+ // unused goes to the next one that was cut.+ const blocks = results.map((r) => fit(r, Math.max(30, Math.floor((room * r.symbols.length) / Math.max(1, total)))));+ let spare = room - blocks.reduce((n, b) => n + estimateTokens(b) + 1, 0);+ for (let i = 0; i < blocks.length && spare > 0; i++) {+ const used = estimateTokens(blocks[i]);+ const wider = fit(results[i], used + spare);+ spare -= estimateTokens(wider) - used;+ blocks[i] = wider;+ }+ return [...blocks, FOOTER].join("\n");+}- // The edited file, mapped into the checkout the graph was built from.- let graphFile = filePath;- if (opts.worktree) {- const rel = path.relative(path.resolve(opts.worktree), filePath);- if (!isInside(rel)) { debug(`${filePath} is not under --worktree`); return undefined; }- graphFile = path.join(path.resolve(opts.graphRoot ?? opts.worktree), rel);+/**+ * Turn per-file answers into what to print and what to remember. A symbol+ * with no dependents counts as told (there is nothing to tell); one with+ * dependents past the cap does not, so a later call reports it.+ */+export function summarize(results: AroundResult[], budget: number): HookOutcome {+ const reported: string[] = [];+ const shown: AroundResult[] = [];+ let slots = MAX_SYMBOLS;+ let complete = true;+ for (const r of results) {+ const keep = [];+ for (const s of r.symbols) {+ const deps = s.callers.total + s.users.total + s.tests.total;+ if (deps === 0) { reported.push(symbolKey(r.path, s.id)); continue; }+ if (slots === 0) { complete = false; continue; }+ slots--;+ keep.push(s);+ reported.push(symbolKey(r.path, s.id));}- (deps.chdir ?? process.chdir)(opts.graphRoot ? path.resolve(opts.graphRoot) : path.dirname(graphFile));- const workspaceRoot = path.resolve((deps.workspaceRoot ?? resolveWorkspaceRoot)());- const relPath = path.relative(workspaceRoot, graphFile).split(path.sep).join("/");- if (!isInside(relPath)) { debug(`${graphFile} is outside workspace ${workspaceRoot}`); return undefined; }- if (!isSourcePath(relPath)) { debug(`${relPath} is not a source file`); return undefined; }+ if (keep.length > 0) shown.push({ ...r, symbols: keep });+ }+ if (shown.length === 0) return { reported, complete };+ return { output: postToolUseOutput(renderHookText(shown, budget)), reported, complete };+}+/**+ * The diff path: every tracked file changed against HEAD, located by its+ * hunks' old side in HEAD's text -- the text the graph indexed, and what an+ * unedited `--graph-root` checkout holds -- and re-anchored from there.+ * Symbols in `already` are skipped. Never throws.+ */+export async function reportChangedFiles(+ ctx: { repoRoot: string; files: FileDiff[]; already: Set<string> },+ opts: HookOptions = {},+ deps: HookDeps = {},+): Promise<HookOutcome> {+ const debug = deps.debug ?? (() => {});+ try {+ const roots = resolveRoots(opts.worktree ?? ctx.repoRoot, opts, deps);const read = deps.readFile ?? defaultReadFile;- const current = read(filePath) ?? (typeof input.tool_input?.content === "string" ? input.tool_input.content : undefined);- if (current === undefined) { debug(`cannot read ${filePath}`); return undefined; }- const where = locateEdit(input, current);- if (!where) { debug("edit not located"); return undefined; }- debug(`${relPath} ranges=${JSON.stringify(where.ranges ?? "file")}`);+ const showHead = deps.showHead ?? gitShowHead;+ const gather = gatherWith(deps, opts);+ const files = new SourceFiles(roots.sourceRoot);- // Dependents' files are read where the agent sees them.- const sourceRoot = opts.worktree- ? path.join(path.resolve(opts.worktree), path.relative(path.resolve(opts.graphRoot ?? opts.worktree), workspaceRoot))- : workspaceRoot;- const timeoutMs = hookTimeoutMs(opts.env);- const gather = deps.gather ?? ((req: AroundRequest) =>- gatherAround(new IxClient(getEndpoint(), AbortSignal.timeout(timeoutMs)), req));- const result = await gather({- relPath,- ranges: where.ranges,- anchorLines: where.anchorLines,- currentLines: current.split("\n"),- files: new SourceFiles(sourceRoot),+ const requests: AroundRequest[] = [];+ for (const f of ctx.files) {+ if (requests.length >= MAX_FILES) break;+ if (!f.oldPath) continue; // new file: nothing in the graph+ const relPath = graphPath(roots, path.join(ctx.repoRoot, f.oldPath));+ if (!relPath) { debug(`skip ${f.oldPath}`); continue; }+ const head = showHead(ctx.repoRoot, f.oldPath);+ if (head === undefined) continue;+ const current = f.newPath ? read(path.join(ctx.repoRoot, f.newPath)) ?? "" : "";+ const exclude = new Set([...ctx.already].filter((k) => k.startsWith(`${relPath}#`)).map((k) => k.slice(relPath.length + 1)));+ requests.push({+ relPath, ranges: f.oldRanges, anchorLines: head.split("\n"), currentLines: current.split("\n"), files, exclude,+ });+ debug(`${relPath} old-side ${JSON.stringify(f.oldRanges)}`);+ }+ if (requests.length === 0) return NOTHING;+ const settled = await Promise.allSettled(requests.map((r) => gather(r)));+ const results = settled.flatMap((s, i) => {+ if (s.status === "fulfilled") return [s.value];+ debug(`${requests[i].relPath}: ${s.reason instanceof Error ? s.reason.message : String(s.reason)}`);+ return [];});- if (result.symbols.length === 0) { debug("no graph definition covers the edit"); return undefined; }- if (!hasDependents(result)) { debug("no dependents"); return undefined; }-- const textOpts = { lead: "Ix: you changed", footer: "These may need updating to match your edit." };- const budget = opts.budget ?? DEFAULT_TOKEN_BUDGET;- const fitted = fitToBudget(result, (r) => renderAroundText(r, textOpts), budget);- return postToolUseOutput(renderAroundText(fitted, textOpts));+ return summarize(results, opts.budget ?? DEFAULT_TOKEN_BUDGET);} catch (err) {debug(`failed: ${err instanceof Error ? err.message : String(err)}`);- return undefined;+ return NOTHING;}}-/** All of stdin, or "" when there is none or it does not arrive in time. */-export function readStdin(timeoutMs: number, stdin: NodeJS.ReadStream = process.stdin): Promise<string> {- if (stdin.isTTY) return Promise.resolve("");- return new Promise((resolve) => {- const chunks: Buffer[] = [];- const done = (value: string) => { clearTimeout(timer); resolve(value); };- const timer = setTimeout(() => done(""), timeoutMs);- stdin.on("data", (c: Buffer) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));- stdin.on("end", () => done(Buffer.concat(chunks).toString("utf-8")));- stdin.on("error", () => done(""));- });-}-/**- * Race the hook against its deadline. A late answer is dropped, not waited- * for: an agent's next turn is worth more than the dependents of its last one.+ * Outside a git repository there is no diff, and only an Edit / MultiEdit /+ * Write says what changed: located from its own patch, the pre-edit side when+ * the pre-edit text is there (see {@link locateEdit}). Never throws.*/-export async function withDeadline<T>(work: Promise<T>, ms: number): Promise<T | undefined> {- let timer: NodeJS.Timeout | undefined;- const late = new Promise<undefined>((resolve) => { timer = setTimeout(() => resolve(undefined), ms); });+export async function reportToolEdit(+ input: PostToolUseInput, already: Set<string>, opts: HookOptions = {}, deps: HookDeps = {},+): Promise<HookOutcome> {+ const debug = deps.debug ?? (() => {});try {- return await Promise.race([work.catch(() => undefined), late]);- } finally {- if (timer) clearTimeout(timer);+ if (!EDIT_TOOLS.has(input.tool_name ?? "")) { debug(`tool ${input.tool_name} is not an edit`); return NOTHING; }+ const filePathRaw = input.tool_input?.file_path ?? input.tool_response?.filePath;+ if (!filePathRaw) { debug("no file_path"); return NOTHING; }+ const base = input.cwd && path.isAbsolute(input.cwd) ? input.cwd : process.cwd();+ const filePath = path.resolve(base, filePathRaw);+ const roots = resolveRoots(opts.worktree ?? path.dirname(filePath), opts, deps);+ const relPath = graphPath(roots, filePath);+ if (!relPath) { debug(`${filePath} is outside the workspace or not a source file`); return NOTHING; }++ const current = (deps.readFile ?? defaultReadFile)(filePath)+ ?? (typeof input.tool_input?.content === "string" ? input.tool_input.content : undefined);+ if (current === undefined) { debug(`cannot read ${filePath}`); return NOTHING; }+ const where = locateEdit(input, current);+ if (!where) { debug("edit not located"); return NOTHING; }++ const exclude = new Set([...already].filter((k) => k.startsWith(`${relPath}#`)).map((k) => k.slice(relPath.length + 1)));+ const result = await gatherWith(deps, opts)({+ relPath, ranges: where.ranges, anchorLines: where.anchorLines, currentLines: current.split("\n"),+ files: new SourceFiles(roots.sourceRoot), exclude,+ });+ if (!hasDependents(result)) debug("no dependents");+ return summarize([result], opts.budget ?? DEFAULT_TOKEN_BUDGET);+ } catch (err) {+ debug(`failed: ${err instanceof Error ? err.message : String(err)}`);+ return NOTHING;}}diff --git a/ix-cli/src/cli/hook/entry.ts b/ix-cli/src/cli/hook/entry.tsnew file mode 100644index 00000000..daa7a91d--- /dev/null+++ b/ix-cli/src/cli/hook/entry.ts@@ -0,0 +1,115 @@+// Copyright 2026 Ix Infrastructure Inc.++import * as path from "node:path";+import { hookTimeoutMs, readStdin, withDeadline } from "./io.js";+import {+ fingerprint, gitDiffHead, gitTopLevel, loadState, parseUnifiedDiff, saveState, statePath,+} from "./session.js";+import type { HookDeps, HookOptions, PostToolUseInput } from "./claude-post-edit.js";++/**+ * The post-edit hook's front door, loaded before -- and instead of -- the+ * CLI: `main.ts` dispatches `ix hook claude-post-edit` here directly.+ *+ * It runs after every hooked tool call, Bash included, because agents edit+ * through Bash scripts as often as through Edit. Most of those calls change+ * nothing new, so the order is cheapest-first:+ *+ * 1. `git diff -U0 HEAD`. Empty: nothing tracked has changed; print nothing.+ * 2. Its fingerprint against the one this session last reported on. Same+ * diff: nothing new; print nothing.+ * 3. Only now load the graph code (`claude-post-edit.ts`) and ask about the+ * edited symbols this session has not been told about yet.+ *+ * Steps 1-2 need node's builtins and one git process. Outside a git+ * repository the Edit / Write tool's own patch is the fallback.+ */++export interface EntryDeps extends HookDeps {+ gitTopLevel?: (dir: string) => string | undefined;+ gitDiffHead?: (repoRoot: string) => string;+}++/** Never throws; undefined means print nothing. */+export async function runPostEditHook(raw: string, opts: HookOptions = {}, deps: EntryDeps = {}): Promise<string | undefined> {+ const debug = deps.debug ?? (() => {});+ const env = opts.env ?? process.env;+ try {+ let input: PostToolUseInput;+ try { input = JSON.parse(raw) as PostToolUseInput; } catch { debug("stdin is not JSON"); return undefined; }+ if (!input || typeof input !== "object") return undefined;+ const base = input.cwd && path.isAbsolute(input.cwd) ? input.cwd : process.cwd();+ const worktree = path.resolve(opts.worktree ?? base);+ const repoRoot = (deps.gitTopLevel ?? gitTopLevel)(worktree);++ if (!repoRoot) {+ const file = statePath(input.session_id, worktree, env);+ const state = loadState(file);+ const heavy = await import("./claude-post-edit.js");+ const outcome = await heavy.reportToolEdit(input, new Set(state.reported), opts, deps);+ if (outcome.reported.length > 0) saveState(file, { ...state, reported: [...state.reported, ...outcome.reported] });+ return outcome.output;+ }++ const diff = (deps.gitDiffHead ?? gitDiffHead)(repoRoot);+ if (!diff.trim()) { debug("no tracked changes"); return undefined; }+ const fp = fingerprint(diff);+ const file = statePath(input.session_id, repoRoot, env);+ const state = loadState(file);+ if (state.fingerprint === fp) { debug("diff unchanged since last report"); return undefined; }++ const files = parseUnifiedDiff(diff);+ const heavy = await import("./claude-post-edit.js");+ const outcome = await heavy.reportChangedFiles({ repoRoot, files, already: new Set(state.reported) }, opts, deps);+ saveState(file, {+ // Keep the old fingerprint while edited symbols wait behind the cap, so+ // the next call -- even one that edits nothing -- reports them.+ fingerprint: outcome.complete ? fp : state.fingerprint,+ reported: [...new Set([...state.reported, ...outcome.reported])],+ });+ return outcome.output;+ } catch (err) {+ debug(`failed: ${err instanceof Error ? err.message : String(err)}`);+ return undefined;+ }+}++/** `--graph-root <dir>`, `--worktree=<dir>`, `--budget <n>`; anything else is ignored. */+export function parseHookArgs(argv: string[]): HookOptions {+ const opts: HookOptions = {};+ for (let i = 0; i < argv.length; i++) {+ const [flag, inline] = argv[i].split(/=(.*)/s, 2);+ const value = () => inline ?? argv[++i];+ if (flag === "--graph-root") opts.graphRoot = value();+ else if (flag === "--worktree") opts.worktree = value();+ else if (flag === "--budget") {+ const n = Number(value());+ if (Number.isSafeInteger(n) && n > 0) opts.budget = n;+ }+ }+ return opts;+}++/**+ * The whole process: read stdin, answer within the deadline, print, exit 0.+ * Exits at once so a request still in flight past the deadline can neither+ * hold the agent nor surface later as an unhandled rejection.+ */+export async function runHookProcess(opts: HookOptions): Promise<void> {+ const started = Date.now();+ const timeout = hookTimeoutMs();+ const debugOn = process.env.IX_HOOK_DEBUG === "1";+ const debug = (msg: string) => { if (debugOn) process.stderr.write(`[ix hook] ${msg}\n`); };+ let out: string | undefined;+ try {+ const raw = await readStdin(timeout);+ const left = Math.max(0, timeout - (Date.now() - started));+ out = await withDeadline(runPostEditHook(raw, opts, { debug }), left);+ } catch (err) {+ debug(`failed: ${err instanceof Error ? err.message : String(err)}`);+ out = undefined;+ }+ debug(`${out ? "reported" : "nothing"} in ${Date.now() - started} ms`);+ if (out) process.stdout.write(`${out}\n`, () => process.exit(0));+ else process.exit(0);+}diff --git a/ix-cli/src/cli/hook/io.ts b/ix-cli/src/cli/hook/io.tsnew file mode 100644index 00000000..46b56657--- /dev/null+++ b/ix-cli/src/cli/hook/io.ts@@ -0,0 +1,51 @@+// Copyright 2026 Ix Infrastructure Inc.++/**+ * The hook's process contract, kept free of the CLI's imports: this module is+ * loaded on every hooked tool call, most of which change nothing.+ */++export const DEFAULT_HOOK_TIMEOUT_MS = 3000;++/**+ * The one place the hook's stdout contract lives: Claude Code reads+ * `hookSpecificOutput.additionalContext` off a PostToolUse hook's JSON and+ * hands it to the model after the tool result.+ */+export function postToolUseOutput(additionalContext: string): string {+ return JSON.stringify({+ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext },+ });+}++export function hookTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {+ const raw = Number(env.IX_HOOK_TIMEOUT_MS);+ return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_HOOK_TIMEOUT_MS;+}++/** All of stdin, or "" when there is none or it does not arrive in time. */+export function readStdin(timeoutMs: number, stdin: NodeJS.ReadStream = process.stdin): Promise<string> {+ if (stdin.isTTY) return Promise.resolve("");+ return new Promise((resolve) => {+ const chunks: Buffer[] = [];+ const done = (value: string) => { clearTimeout(timer); resolve(value); };+ const timer = setTimeout(() => done(""), timeoutMs);+ stdin.on("data", (c: Buffer) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));+ stdin.on("end", () => done(Buffer.concat(chunks).toString("utf-8")));+ stdin.on("error", () => done(""));+ });+}++/**+ * Race the hook against its deadline. A late answer is dropped, not waited+ * for: an agent's next turn is worth more than the dependents of its last one.+ */+export async function withDeadline<T>(work: Promise<T>, ms: number): Promise<T | undefined> {+ let timer: NodeJS.Timeout | undefined;+ const late = new Promise<undefined>((resolve) => { timer = setTimeout(() => resolve(undefined), ms); });+ try {+ return await Promise.race([work.catch(() => undefined), late]);+ } finally {+ if (timer) clearTimeout(timer);+ }+}diff --git a/ix-cli/src/cli/hook/session.ts b/ix-cli/src/cli/hook/session.tsnew file mode 100644index 00000000..966100ae--- /dev/null+++ b/ix-cli/src/cli/hook/session.ts@@ -0,0 +1,164 @@+// Copyright 2026 Ix Infrastructure Inc.++import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import * as fs from "node:fs";+import * as os from "node:os";+import * as path from "node:path";++/**+ * What the post-edit hook knows without the graph: the working tree's diff+ * against HEAD, and what it already told this session.+ *+ * Agents do not only edit with Edit and Write. In benchmark runs they rewrote+ * files with `python3 - <<EOF` through Bash just as often, and a hook keyed on+ * the edit tools never fired. The diff sees every editing path. It also says+ * where each edit is in the base commit -- the hunk's old side -- which is the+ * text the graph indexed.+ *+ * Builtins only: this runs on every hooked tool call, and the common answer is+ * "nothing new", which must cost a git call, not the CLI's module graph.+ */++/** 1-based inclusive range on the old side of a hunk; `insertion` marks a pure insertion point. */+export interface OldRange {+ start: number;+ end: number;+ insertion?: boolean;+}++export interface FileDiff {+ /** Repository-relative path in the base commit; undefined for a new file. */+ oldPath?: string;+ /** Repository-relative path in the working tree; undefined for a deleted file. */+ newPath?: string;+ /** Where the edits are, in the base commit's file. */+ oldRanges: OldRange[];+}++const GIT_TIMEOUT_MS = 2000;++function git(cwd: string, args: string[]): string {+ return execFileSync("git", ["-C", cwd, ...args], {+ encoding: "utf-8",+ stdio: ["ignore", "pipe", "ignore"],+ timeout: GIT_TIMEOUT_MS,+ maxBuffer: 32 * 1024 * 1024,+ });+}++/** The repository's top level, or undefined outside one. */+export function gitTopLevel(dir: string): string | undefined {+ try {+ const out = git(dir, ["rev-parse", "--show-toplevel"]).trim();+ return out ? path.resolve(out) : undefined;+ } catch {+ return undefined;+ }+}++/**+ * The tracked changes against HEAD, with no context lines. Untracked files are+ * not in it, and need not be: a file that is new has no graph facts.+ */+export function gitDiffHead(repoRoot: string): string {+ return git(repoRoot, ["diff", "-U0", "--no-color", "--no-ext-diff", "--no-renames", "HEAD", "--"]);+}++/** A file's content in HEAD, or undefined when HEAD has no such file. */+export function gitShowHead(repoRoot: string, repoPath: string): string | undefined {+ try {+ return git(repoRoot, ["show", `HEAD:${repoPath}`]);+ } catch {+ return undefined;+ }+}++function unquote(p: string): string {+ // git quotes paths with unusual characters: "a/sp\303\251cial.ts"+ if (!p.startsWith("\"")) return p;+ try { return JSON.parse(p) as string; } catch { return p.slice(1, -1); }+}++function diffPath(raw: string, prefix: "a/" | "b/"): string | undefined {+ const p = unquote(raw.trim());+ if (p === "/dev/null") return undefined;+ return p.startsWith(prefix) ? p.slice(prefix.length) : p;+}++/**+ * The files of a `git diff -U0` and, for each, where its hunks sit on the old+ * side. A hunk `-a,b +c,d` with `b > 0` replaced or removed old lines+ * `a..a+b-1`; with `b == 0` it inserted after old line `a`, between `a` and+ * `a+1`.+ */+export function parseUnifiedDiff(text: string): FileDiff[] {+ const files: FileDiff[] = [];+ let cur: FileDiff | undefined;+ for (const line of text.split("\n")) {+ if (line.startsWith("diff --git ")) {+ cur = { oldRanges: [] };+ files.push(cur);+ } else if (!cur) {+ continue;+ } else if (line.startsWith("--- ")) {+ cur.oldPath = diffPath(line.slice(4), "a/");+ } else if (line.startsWith("+++ ")) {+ cur.newPath = diffPath(line.slice(4), "b/");+ } else if (line.startsWith("@@")) {+ const m = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line);+ if (!m) continue;+ const start = Number(m[1]);+ const count = m[2] === undefined ? 1 : Number(m[2]);+ if (count > 0) cur.oldRanges.push({ start, end: start + count - 1 });+ else cur.oldRanges.push({ start: Math.max(1, start), end: start + 1, insertion: true });+ }+ }+ return files.filter((f) => f.oldRanges.length > 0);+}++export function fingerprint(text: string): string {+ return createHash("sha256").update(text).digest("hex").slice(0, 32);+}++// ── Per-session state ───────────────────────────────────────────────────────++export interface HookState {+ /** The diff last fully reported on. The same diff again has nothing new in it. */+ fingerprint?: string;+ /** `path#id` of every symbol this session was already told about. */+ reported: string[];+}++/** One file per (session, worktree), under IX_HOOK_STATE_DIR or the OS temp dir. */+export function statePath(sessionId: string | undefined, worktree: string, env: NodeJS.ProcessEnv = process.env): string {+ const dir = env.IX_HOOK_STATE_DIR || path.join(os.tmpdir(), "ix-hook");+ const key = fingerprint(`${sessionId ?? "no-session"}\0${path.resolve(worktree)}`).slice(0, 24);+ return path.join(dir, `${key}.json`);+}++export function loadState(file: string): HookState {+ try {+ const parsed = JSON.parse(fs.readFileSync(file, "utf-8")) as Partial<HookState>;+ return {+ fingerprint: typeof parsed.fingerprint === "string" ? parsed.fingerprint : undefined,+ reported: Array.isArray(parsed.reported) ? parsed.reported.filter((r): r is string => typeof r === "string") : [],+ };+ } catch {+ return { reported: [] };+ }+}++/** Written whole and renamed into place, so a concurrent reader never sees half a file. */+export function saveState(file: string, state: HookState): void {+ try {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const tmp = `${file}.${process.pid}.tmp`;+ fs.writeFileSync(tmp, JSON.stringify(state));+ fs.renameSync(tmp, file);+ } catch { /* a hook that cannot remember only repeats itself */ }+}++export function symbolKey(relPath: string, id: string): string {+ return `${relPath}#${id}`;+}diff --git a/ix-cli/src/cli/main.ts b/ix-cli/src/cli/main.tsindex 3de4b538..48dc07b1 100644--- a/ix-cli/src/cli/main.ts+++ b/ix-cli/src/cli/main.ts@@ -1,140 +1,22 @@#!/usr/bin/env node// Copyright 2026 Ix Infrastructure Inc.-import { Command } from "commander";-import { registerOssCommands, registerProStubs } from "./register/oss.js";-import { tryLoadProCommands } from "./register/pro-loader.js";-import { isRepairInvocation } from "./register/pro-failure.js";-import { buildHelpText } from "./help-text.js";-import { checkForUpdate, updateCheckEnabled } from "./commands/upgrade.js";-import { stderrIsTerminal } from "./stderr.js";-import { detectRequestedFormat, renderCliError, setErrorFormat } from "./errors.js";-import { getEndpoint } from "./config.js";--import { readFileSync } from "fs";-import { join, dirname } from "path";-import { fileURLToPath } from "url";--// Runtime Node version guard. Runs before any command work so users on an-// unsupported Node get an actionable message instead of a cryptic "fetch-// failed" deep inside undici.-const MIN_NODE_MAJOR = 22;-{- const current = process.versions.node;- const major = parseInt(current.split(".")[0] ?? "0", 10);- if (!Number.isFinite(major) || major < MIN_NODE_MAJOR) {- process.stderr.write(- `Ix requires Node.js ${MIN_NODE_MAJOR} or newer. You are running v${current}.\n` +- `Install a supported version from https://nodejs.org/ and re-run.\n`- );- process.exit(1);- }-}--let cliVersion = "0.0.0";-try {- const __dirname = dirname(fileURLToPath(import.meta.url));- const pkg = JSON.parse(readFileSync(join(__dirname, "../../package.json"), "utf-8"));- cliVersion = pkg.version || "0.0.0";-} catch {}--// Set IX_DEBUG=1 to append stack traces to any rendered error.-const debug = process.env.IX_DEBUG === "1";--// Before anything can throw. The handlers below are installed for-// `unhandledRejection` and `uncaughtException`, which can fire before-// commander has parsed a thing, so the error boundary gets the format from-// argv rather than from a parsed command.-setErrorFormat(detectRequestedFormat(process.argv.slice(2)));--// Resolving the endpoint reads config off disk, which can itself fail. An-// error renderer must never throw, so failure here just drops the endpoint-// from the message rather than replacing one crash with another.-function safeEndpoint(): string | undefined {- try {- return getEndpoint();- } catch {- return undefined;- }+/**+ * The `ix` executable.+ *+ * Everything but one invocation goes straight to the CLI (`cli.ts`). The+ * exception is `ix hook claude-post-edit`, which an agent harness runs after+ * every hooked tool call -- every Bash command included -- and which almost+ * always has nothing to say. Loading the CLI's command tree costs ~140 ms+ * before a single line of it runs; the hook's "nothing changed" answer costs a+ * git call. So the hook is dispatched here, before that tree is loaded, and+ * loads the graph code itself only when there is an edit to report.+ * `--help` still goes through the CLI, where the command is documented.+ */+const args = process.argv.slice(2);+if (args[0] === "hook" && args[1] === "claude-post-edit" && !args.some((a) => a === "-h" || a === "--help")) {+ const { parseHookArgs, runHookProcess } = await import("./hook/entry.js");+ await runHookProcess(parseHookArgs(args.slice(2)));+} else {+ await import("./cli.js");}--// Last line of defence. Without these, any rejection escaping a command — most-// commonly the backend not running — reaches Node's default handler and prints-// an undici stack trace that exposes internal paths and tells the user nothing.-process.on("unhandledRejection", (err: unknown) => {- renderCliError(err, debug, safeEndpoint());-});-process.on("uncaughtException", (err: unknown) => {- renderCliError(err, debug, safeEndpoint());-});--const program = new Command();-program- .name("ix")- .version(cliVersion);--// Start with OSS-only help; updated after Pro probe.-program.helpInformation = () => buildHelpText();--registerOssCommands(program);--(async () => {- const ossCmdNames = new Set(program.commands.map((c: Command) => c.name()));-- // An installed-but-broken Pro throws here rather than reporting absence, so- // commands never run without its credential guard. Note this call sits- // OUTSIDE the parseAsync try/catch below — render the failure here rather- // than letting it reach the unhandledRejection handler by accident.- let proLoaded = false;- // `ix hook` runs inside an agent harness after every edit and must exit 0- // with nothing on stdout whenever it cannot help. A broken Pro install would- // otherwise make it exit 1 before its action runs, and it needs nothing Pro- // registers.- const isHook = process.argv[2] === "hook";- try {- if (!isHook) proLoaded = await tryLoadProCommands(program);- } catch (err) {- if (!isRepairInvocation(process.argv)) {- renderCliError(err, debug, safeEndpoint()); // exits 1- }- // Repair invocation: continue OSS-only. proLoaded stays false, so the Pro- // stubs register below and would misreport a broken Pro as absent — the- // warning here is what distinguishes the two, and no command in the set- // above reaches a stub.- console.error(- "[!!] Ix Pro is installed but failed to initialize; continuing with OSS " +- "commands only so this one can repair the install.",- );- }- if (proLoaded) {- // Collect commands that Pro added (weren't in OSS set)- const proCommands = program.commands- .filter((c: Command) => !ossCmdNames.has(c.name()))- .map((c: Command) => ({ name: c.name(), desc: c.description() }));-- program.helpInformation = () => buildHelpText(proCommands);- } else {- registerProStubs(program);- }-- // Check for updates (non-blocking, cached 1hr). Only when a person is- // watching stderr — see updateCheckEnabled for why, and for the- // IX_NO_UPDATE_CHECK opt-out.- const args = process.argv.slice(2);- if (updateCheckEnabled(args, process.env, stderrIsTerminal())) {- // Deliberately not awaited — but it must still be caught here. The catch- // inside checkForUpdate only guards its inner fetch chain; the function's- // own promise covers the synchronous cached-read path, and a corrupt- // ~/.ix/.version-check.json makes that throw. Uncaught, the new- // unhandledRejection handler then aborts a command that already succeeded.- checkForUpdate().catch(() => {});- }-- // parseAsync (not parse) so rejections from async action handlers surface- // here instead of floating off as unhandled rejections.- try {- await program.parseAsync();- } catch (err) {- renderCliError(err, debug, safeEndpoint());- }-})();diff --git a/ix-cli/src/mcp/runner.ts b/ix-cli/src/mcp/runner.tsindex e029ac60..ef6c504e 100644--- a/ix-cli/src/mcp/runner.ts+++ b/ix-cli/src/mcp/runner.ts@@ -350,7 +350,7 @@ function releaseLocksOf(run: ActiveRun): void {/*** Replace the CLI's fatal error handlers for the lifetime of the server.*- * `main.ts` installs `unhandledRejection`/`uncaughtException` handlers whose+ * `cli.ts` installs `unhandledRejection`/`uncaughtException` handlers whose* every path ends in `process.exit(1)`. That is right for one command in one* process and fatal for a server: a stray rejection from any command's* fire-and-forget work would either exit outright, or — once the in-processdiff --git a/skills/ix/references/commands.md b/skills/ix/references/commands.mdindex d790ecd1..00796734 100644--- a/skills/ix/references/commands.md+++ b/skills/ix/references/commands.md@@ -58,17 +58,20 @@ The graph's spans are re-anchored to the file on disk first, so a file editedsince the last map is still read correctly. Output is held to `--budget` tokens(default 300); lists are cut, never their totals.-The same answer is pushed to Claude Code after every edit by-`ix hook claude-post-edit` (PostToolUse, matcher `Edit|MultiEdit|Write`):+The same answer is pushed to Claude Code after edits by+`ix hook claude-post-edit` (PostToolUse). It reads the working tree's diff+against HEAD rather than the tool's arguments, so match Bash too -- agents+often edit through scripts:```json-{"hooks":{"PostToolUse":[{"matcher":"Edit|MultiEdit|Write",+{"hooks":{"PostToolUse":[{"matcher":"Edit|MultiEdit|Write|Bash","hooks":[{"type":"command","command":"ix hook claude-post-edit"}]}]}}```-It prints nothing and exits 0 whenever it cannot help. When the agent edits a-different checkout from the mapped one, pass `--graph-root <mapped>` and-`--worktree <agent checkout>`.+Each edited symbol is reported once per session; a call that changed nothing+new prints nothing and costs one git call. It prints nothing and exits 0+whenever it cannot help. When the agent edits a different checkout from the+mapped one, pass `--graph-root <mapped>` and `--worktree <agent checkout>`.## History, Diffs & Contradictions@@ -204,7 +207,7 @@ ix inventory --kind function --path auth.pydegraded graph.- **The OSS↔Pro command boundary is derived at runtime, not declared.**- `main.ts` snapshots `ossCmdNames` immediately after `registerOssCommands()`;+ `cli.ts` (which `main.ts` loads) snapshots `ossCmdNames` immediately after `registerOssCommands()`;the Pro probe (`tryLoadProCommands`) then diffs whatever commands existagainst that set to decide which count as "Pro". Consequences:- Adding a `register*Command` call in `oss.ts` silently reclassifies thatdiff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.mdindex fa34f5a4..f21ca0e8 100644--- a/skills/ix/references/flags.md+++ b/skills/ix/references/flags.md@@ -390,12 +390,12 @@ No flags.#### `ix hook claude-post-edit`-Claude Code PostToolUse hook for `Edit|MultiEdit|Write`: reads the hook JSON on stdin and prints `{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"..."}}` naming the changed symbols' callers, importers that use them, and tests that reach them -- or prints nothing. Always exits 0; any failure (backend down, unmapped workspace, file not in the graph, non-code file, `IX_HOOK_TIMEOUT_MS`, default 3000, exceeded) prints nothing. `IX_HOOK_DEBUG=1` says why on stderr.+Claude Code PostToolUse hook, matcher `Edit|MultiEdit|Write|Bash`. Reads the hook JSON on stdin and the working tree's `git diff -U0 HEAD`, so an edit made through a Bash script counts as much as one made with Edit or Write; each hunk's old side locates the edited symbols in HEAD's text, which is what the graph indexed. Prints `{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"..."}}` naming the changed symbols' callers, importers that use them, and tests that reach them -- each symbol once per session (state per `session_id` in `IX_HOOK_STATE_DIR`, default `<tmp>/ix-hook`). A call whose diff is empty or unchanged since the last report answers from one git call, without loading the CLI. Always exits 0; any failure (backend down, unmapped workspace, file not in the graph, non-code or untracked file, `IX_HOOK_TIMEOUT_MS`, default 3000, exceeded) prints nothing. Outside a git repository it falls back to the Edit/Write tool's own patch. `IX_HOOK_DEBUG=1` says why on stderr.| Flag | Value | Default | Effect ||---|---|---|---|| `--graph-root` | `<dir>` | — | Mapped workspace to query (default: the one containing the edited file) |-| `--worktree` | `<dir>` | — | Root the edited `file_path` is under; mapped to the same relative path in `--graph-root` |+| `--worktree` | `<dir>` | — | Checkout the agent edits (default: the git root of the hook's `cwd`); its paths map to the same relative paths in `--graph-root` || `--budget` | `<tokens>` | `300` | Token budget for the context it adds (~4 chars a token) |### `ix impact <target>`