Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

feat(cli): ix hook claude-post-edit -- dependents after every edit

KageBinarya7a2af72b2e2
diff --git a/ix-cli/src/cli/__tests__/claude-post-edit.test.ts b/ix-cli/src/cli/__tests__/claude-post-edit.test.ts
new file mode 100644
index 00000000..4cd8af47
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/claude-post-edit.test.ts
@@ -0,0 +1,226 @@
+// 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";
+
+const ORIGINAL = [
+ "export function add(a, b) {", // 1
+ " return a + b;", // 2
+ "}", // 3
+ "", // 4
+ "export function sub(a, b) {", // 5
+ " return a - b;", // 6
+ "}", // 7
+].join("\n");
+const UPDATED = ORIGINAL.replace(" return a + b;", " const s = a + b;\n return s;");
+
+const EDIT_PATCH = [{
+ oldStart: 1, oldLines: 3, newStart: 1, newLines: 4,
+ lines: [" export function add(a, b) {", "- return a + b;", "+ const s = a + b;", "+ return s;", " }"],
+}];
+
+function editInput(over: Partial<PostToolUseInput> = {}): PostToolUseInput {
+ return {
+ hook_event_name: "PostToolUse",
+ cwd: "/ws",
+ tool_name: "Edit",
+ tool_input: { file_path: "/ws/src/math.ts", old_string: " return a + b;", new_string: " const s = a + b;\n return s;" },
+ tool_response: { filePath: "/ws/src/math.ts", originalFile: ORIGINAL, structuredPatch: EDIT_PATCH },
+ ...over,
+ };
+}
+
+describe("patchRanges", () => {
+ it("locates a replacement on both sides of the patch", () => {
+ expect(patchRanges(EDIT_PATCH, "old")).toEqual([{ start: 2, end: 2 }]);
+ expect(patchRanges(EDIT_PATCH, "new")).toEqual([{ start: 2, end: 3 }]);
+ });
+
+ it("locates a pure insertion on the old side as the two lines it went between", () => {
+ const hunk = [{ oldStart: 1, newStart: 1, lines: [" a", "+b", " c"] }];
+ expect(patchRanges(hunk, "old")).toEqual([{ start: 1, end: 2, insertion: true }]);
+ expect(patchRanges(hunk, "new")).toEqual([{ start: 2, end: 2 }]);
+ });
+
+ it("locates a pure deletion on the new side as the two lines it closed up", () => {
+ const hunk = [{ oldStart: 4, newStart: 4, lines: [" a", "-b", " c"] }];
+ expect(patchRanges(hunk, "old")).toEqual([{ start: 5, end: 5 }]);
+ expect(patchRanges(hunk, "new")).toEqual([{ start: 4, end: 5, insertion: true }]);
+ });
+});
+
+describe("locateText", () => {
+ it("finds the lines a new_string occupies", () => {
+ expect(locateText(UPDATED, " const s = a + b;\n return s;")).toEqual([{ start: 2, end: 3 }]);
+ });
+
+ it("matches across CRLF line endings", () => {
+ expect(locateText(UPDATED.replace(/\n/g, "\r\n"), " const s = a + b;\n return s;")).toEqual([{ start: 2, end: 3 }]);
+ });
+
+ it("gives up on an empty or ubiquitous string", () => {
+ expect(locateText(UPDATED, "")).toEqual([]);
+ expect(locateText("x\nx\nx\nx\nx", "x")).toEqual([]);
+ });
+});
+
+describe("locateEdit", () => {
+ it("Edit with a patch and the original file: old-side lines, anchored in the original", () => {
+ const at = locateEdit(editInput(), UPDATED)!;
+ expect(at.ranges).toEqual([{ start: 2, end: 2 }]);
+ expect(at.anchorLines).toEqual(ORIGINAL.split("\n"));
+ });
+
+ it("Edit with a patch but no original: new-side lines in the file now", () => {
+ const at = locateEdit(editInput({ tool_response: { structuredPatch: EDIT_PATCH } }), UPDATED)!;
+ expect(at.ranges).toEqual([{ start: 2, end: 3 }]);
+ expect(at.anchorLines).toEqual(UPDATED.split("\n"));
+ });
+
+ it("Edit with no tool_response: finds new_string in the file now", () => {
+ const at = locateEdit(editInput({ tool_response: undefined }), UPDATED)!;
+ expect(at.ranges).toEqual([{ start: 2, end: 3 }]);
+ });
+
+ it("MultiEdit: every edit's new_string", () => {
+ const input = editInput({
+ tool_name: "MultiEdit",
+ tool_input: { file_path: "/ws/src/math.ts", edits: [{ old_string: "x", new_string: " return s;" }, { old_string: "y", new_string: " return a - b;" }] },
+ tool_response: undefined,
+ });
+ expect(locateEdit(input, UPDATED)!.ranges).toEqual([{ start: 3, end: 3 }, { start: 7, end: 7 }]);
+ });
+
+ it("Write: nothing for a new file or a no-op, the whole file without a response", () => {
+ const write = (resp: PostToolUseInput["tool_response"]) => editInput({
+ tool_name: "Write", tool_input: { file_path: "/ws/src/math.ts", content: UPDATED }, tool_response: resp,
+ });
+ expect(locateEdit(write({ type: "create", originalFile: null, structuredPatch: [] }), UPDATED)).toBeUndefined();
+ expect(locateEdit(write({ type: "update", originalFile: ORIGINAL, structuredPatch: [] }), UPDATED)).toBeUndefined();
+ expect(locateEdit(write({ type: "update", originalFile: ORIGINAL, structuredPatch: EDIT_PATCH }), UPDATED)!.ranges)
+ .toEqual([{ start: 2, end: 2 }]);
+ expect(locateEdit(write(undefined), UPDATED)).toEqual({ anchorLines: UPDATED.split("\n") });
+ });
+});
+
+// ── 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/commands/hook.ts b/ix-cli/src/cli/commands/hook.ts
new file mode 100644
index 00000000..6748e630
--- /dev/null
+++ b/ix-cli/src/cli/commands/hook.ts
@@ -0,0 +1,58 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+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";
+
+/**
+ * `ix hook <agent-event>`: entry points an agent harness runs on its own
+ * events. One subcommand per (harness, event), because each harness has its
+ * own stdin and stdout contract; `claude-post-edit` is Claude Code's
+ * PostToolUse for Edit / MultiEdit / Write.
+ */
+export function registerHookCommand(program: Command): void {
+ const hook = program
+ .command("hook")
+ .description("Entry points for agent hooks (Claude Code PostToolUse: claude-post-edit)");
+
+ hook
+ .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("--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,
+{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"..."}},
+naming the changed symbols' callers, importers that use them, and tests that
+reach them -- or prints nothing. Always exits 0: a backend that is down, an
+unmapped workspace, a file not in the graph or a non-code file all print
+nothing. Gives up after IX_HOOK_TIMEOUT_MS (default 3000). IX_HOOK_DEBUG=1
+says why on stderr.
+
+.claude/settings.json:
+ {"hooks":{"PostToolUse":[{"matcher":"Edit|MultiEdit|Write",
+ "hooks":[{"type":"command","command":"ix hook claude-post-edit"}]}]}}`)
+ .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);
+ });
+}
diff --git a/ix-cli/src/cli/hook/claude-post-edit.ts b/ix-cli/src/cli/hook/claude-post-edit.ts
new file mode 100644
index 00000000..c2151c20
--- /dev/null
+++ b/ix-cli/src/cli/hook/claude-post-edit.ts
@@ -0,0 +1,330 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import * as fs from "node:fs";
+import * as path from "node:path";
+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 {
+ DEFAULT_TOKEN_BUDGET, 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.
+ *
+ * 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
+ * at the moment it matters: right after an edit, who calls or imports what was
+ * just changed, and which tests reach it -- the other places the fix may have
+ * to touch.
+ *
+ * It must never get in the agent's way. Any failure -- no backend, an unmapped
+ * workspace, a file the graph does not hold, a non-code file, a slow answer --
+ * prints nothing and exits 0. `IX_HOOK_DEBUG=1` says why on stderr.
+ */
+
+export interface PatchHunk {
+ oldStart: number;
+ oldLines?: number;
+ newStart: number;
+ newLines?: number;
+ lines: string[];
+}
+
+/** The fields of Claude Code's PostToolUse input this hook reads. */
+export interface PostToolUseInput {
+ hook_event_name?: string;
+ cwd?: string;
+ tool_name?: string;
+ tool_input?: {
+ file_path?: string;
+ old_string?: string;
+ new_string?: string;
+ replace_all?: boolean;
+ edits?: Array<{ old_string?: string; new_string?: string; replace_all?: boolean }>;
+ content?: string;
+ };
+ tool_response?: {
+ filePath?: string;
+ type?: string;
+ originalFile?: string | null;
+ structuredPatch?: PatchHunk[];
+ } | null;
+}
+
+export interface HookOptions {
+ /** The mapped workspace to query, when the agent edits a different checkout of it. */
+ graphRoot?: string;
+ /** The root the agent's `file_path` is under; mapped onto `graphRoot`. */
+ worktree?: string;
+ budget?: number;
+ env?: NodeJS.ProcessEnv;
+}
+
+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[] {
+ const sorted = [...new Set(lines)].sort((a, b) => a - b);
+ const out: LineRange[] = [];
+ for (const l of sorted) {
+ const last = out[out.length - 1];
+ if (last && l === last.end + 1) last.end = l;
+ else out.push({ start: l, end: l });
+ }
+ return out;
+}
+
+/**
+ * The lines a patch changed, on one side of it.
+ *
+ * `old`: the removed lines, in the file before the edit, plus each pure
+ * insertion as the pair of old lines it went between. `new`: the added lines
+ * in the file after it, plus each pure deletion as the pair it closed up.
+ */
+export function patchRanges(hunks: PatchHunk[], side: "old" | "new"): LineRange[] {
+ const changed: number[] = [];
+ const gaps: LineRange[] = [];
+ for (const h of hunks) {
+ let o = h.oldStart;
+ let n = h.newStart;
+ let removedInRun = false;
+ let addedInRun = false;
+ for (const line of h.lines ?? []) {
+ const c = line[0];
+ if (c === "-") {
+ if (side === "old") changed.push(o);
+ removedInRun = true;
+ o++;
+ } else if (c === "+") {
+ if (side === "new") changed.push(n);
+ else if (!removedInRun && !addedInRun) gaps.push({ start: Math.max(1, o - 1), end: Math.max(1, o), insertion: true });
+ addedInRun = true;
+ n++;
+ } else if (c === "\\") {
+ continue;
+ } else {
+ if (side === "new" && removedInRun && !addedInRun) gaps.push({ start: Math.max(1, n - 1), end: Math.max(1, n), insertion: true });
+ removedInRun = false;
+ addedInRun = false;
+ o++;
+ n++;
+ }
+ }
+ if (side === "new" && removedInRun && !addedInRun) gaps.push({ start: Math.max(1, n - 1), end: Math.max(1, n), insertion: true });
+ }
+ return [...toRanges(changed), ...gaps];
+}
+
+/** The line ranges `text` occupies in `content`, at most {@link MAX_OCCURRENCES} of them. */
+export function locateText(content: string, text: string): LineRange[] {
+ if (!text) return [];
+ const variants = content.includes("\r\n") && !text.includes("\r\n") ? [text, text.replace(/\n/g, "\r\n")] : [text];
+ for (const t of variants) {
+ const out: LineRange[] = [];
+ let from = 0;
+ for (;;) {
+ const at = content.indexOf(t, from);
+ if (at < 0) break;
+ const start = lineOf(content, at);
+ const trimmed = t.replace(/\r?\n$/, "");
+ out.push({ start, end: start + (trimmed.match(/\n/g)?.length ?? 0) });
+ if (out.length > MAX_OCCURRENCES) return [];
+ from = at + Math.max(1, t.length);
+ }
+ if (out.length > 0) return out;
+ }
+ return [];
+}
+
+function lineOf(content: string, offset: number): number {
+ let line = 1;
+ for (let i = 0; i < offset; i++) if (content.charCodeAt(i) === 10) line++;
+ return line;
+}
+
+export interface EditLocation {
+ /** None: the whole file. */
+ ranges?: LineRange[];
+ /** The text `ranges` index into. */
+ anchorLines: string[];
+}
+
+/**
+ * Where the edit is, and in which text.
+ *
+ * The graph's spans were recorded before the edit, and the edit itself can
+ * move or rename the declaration it changed. So the pre-edit side of the
+ * patch is the anchor whenever the pre-edit text is there (`originalFile`):
+ * the declaration the graph recorded is still in it, by its recorded name,
+ * and the spans are re-anchored to that text for whatever earlier edits moved
+ * it. When the edit runs in a different checkout from the graph's, this is
+ * the only side that matches the graph at all. Without the pre-edit text the
+ * new side is used, re-anchored to the file as it is now -- the same step
+ * `ix around` takes for a line typed by hand.
+ *
+ * Undefined means there is nothing to report on: a new file, a no-op write,
+ * an edit whose text cannot be found.
+ */
+export function locateEdit(input: PostToolUseInput, current: string): EditLocation | undefined {
+ const tool = input.tool_name ?? "";
+ const resp = input.tool_response ?? undefined;
+ const currentLines = current.split("\n");
+ if (tool === "Write" && resp?.type === "create") return undefined;
+
+ const hunks = Array.isArray(resp?.structuredPatch) ? resp!.structuredPatch! : undefined;
+ if (hunks && hunks.length > 0) {
+ if (typeof resp?.originalFile === "string") {
+ const ranges = patchRanges(hunks, "old");
+ return ranges.length > 0 ? { ranges, anchorLines: resp.originalFile.split("\n") } : undefined;
+ }
+ const ranges = patchRanges(hunks, "new");
+ return ranges.length > 0 ? { ranges, anchorLines: currentLines } : undefined;
+ }
+
+ if (tool === "Write") {
+ // An empty patch on an update is a write that changed nothing; with no
+ // response at all, all that is known is that the whole file was written.
+ if (resp && hunks) return undefined;
+ return { anchorLines: currentLines };
+ }
+
+ const ti = input.tool_input ?? {};
+ const news = tool === "MultiEdit" ? (ti.edits ?? []).map((e) => e?.new_string ?? "") : [ti.new_string ?? ""];
+ const ranges = news.flatMap((t) => locateText(current, t));
+ return ranges.length > 0 ? { ranges, anchorLines: currentLines } : undefined;
+}
+
+export interface HookDeps {
+ gather?: (req: AroundRequest) => Promise<AroundResult>;
+ readFile?: (abs: 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;
+}
+
+function defaultReadFile(abs: string): string | undefined {
+ try {
+ const stat = fs.statSync(abs);
+ if (!stat.isFile() || stat.size > 2 * 1024 * 1024) return undefined;
+ return fs.readFileSync(abs, "utf-8");
+ } catch {
+ return undefined;
+ }
+}
+
+const isInside = (rel: string) => rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
+
+/**
+ * The hook, minus stdin and the process: the stdout it should print, or
+ * undefined to print nothing. Never throws.
+ */
+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);
+
+ // 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);
+ }
+ (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; }
+
+ 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")}`);
+
+ // 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),
+ });
+ 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));
+ } catch (err) {
+ debug(`failed: ${err instanceof Error ? err.message : String(err)}`);
+ return undefined;
+ }
+}
+
+/** 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/main.ts b/ix-cli/src/cli/main.ts
index b66bc323..3de4b538 100644
--- a/ix-cli/src/cli/main.ts
+++ b/ix-cli/src/cli/main.ts
@@ -86,8 +86,13 @@ registerOssCommands(program);
// 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 {
- proLoaded = await tryLoadProCommands(program);
+ if (!isHook) proLoaded = await tryLoadProCommands(program);
} catch (err) {
if (!isRepairInvocation(process.argv)) {
renderCliError(err, debug, safeEndpoint()); // exits 1
diff --git a/ix-cli/src/cli/register/oss.ts b/ix-cli/src/cli/register/oss.ts
index 2461ee88..5ad5508b 100644
--- a/ix-cli/src/cli/register/oss.ts
+++ b/ix-cli/src/cli/register/oss.ts
@@ -40,6 +40,7 @@ import { registerPatchesCommand } from "../commands/patches.js";
import { registerMcpCommand } from "../commands/mcp.js";
import { registerContextCommand } from "../commands/context.js";
import { registerAroundCommand } from "../commands/around.js";
+import { registerHookCommand } from "../commands/hook.js";
import { validateCliOptions } from "../options.js";
import { setPrettyJson } from "../format.js";
import { setOutputShape } from "../output-shape.js";
@@ -76,6 +77,8 @@ const ADVANCED_COMMANDS = [
"depends", "entity", "text", "conflicts", "query",
// init is deprecated; ingest is now an implementation detail
"init", "ingest",
+ // run by an agent harness, not typed
+ "hook",
];
const OPTION_CHOICES: Record<string, Record<string, string[]>> = {
@@ -218,6 +221,7 @@ export function registerOssCommands(program: Command): void {
registerMcpCommand(program);
registerContextCommand(program);
registerAroundCommand(program);
+ registerHookCommand(program);
configureOssOptions(program);
diff --git a/skills/ix/references/commands.md b/skills/ix/references/commands.md
index fa35d8ca..d790ecd1 100644
--- a/skills/ix/references/commands.md
+++ b/skills/ix/references/commands.md
@@ -58,6 +58,18 @@ The graph's spans are re-anchored to the file on disk first, so a file edited
since 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`):
+
+```json
+{"hooks":{"PostToolUse":[{"matcher":"Edit|MultiEdit|Write",
+ "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>`.
+
## History, Diffs & Contradictions
| Goal | Command | Example |
diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.md
index 72a64604..fa34f5a4 100644
--- a/skills/ix/references/flags.md
+++ b/skills/ix/references/flags.md
@@ -382,6 +382,22 @@ Show provenance chain for a file or entity.
| `--quiet` | — | off | Drop headers, section titles and advisory hints |
| `--fields` | `<list>` | — | Keep only these fields on each row, in this order (e.g. `name,path,lines`) |
+### `ix hook`
+
+Entry points an agent harness runs on its own events; not typed by hand. One subcommand per (harness, event), since each has its own stdin/stdout contract.
+
+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.
+
+| 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` |
+| `--budget` | `<tokens>` | `300` | Token budget for the context it adds (~4 chars a token) |
+
### `ix impact <target>`
System risk analysis — what behavior is at risk if this changes.