Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix(hook): make IX_HOOK_LOG say why for timeouts and repeat edits

KageBinary2d143ad7f426
diff --git a/ix-cli/src/cli/__tests__/around.test.ts b/ix-cli/src/cli/__tests__/around.test.ts
index 0ea74aba..1a70317b 100644
--- a/ix-cli/src/cli/__tests__/around.test.ts
+++ b/ix-cli/src/cli/__tests__/around.test.ts
@@ -302,6 +302,14 @@ describe("gatherAround", () => {
expect(result.importers.total).toBe(2);
});
+ it("counts the edited definitions it was told to leave out", async () => {
+ const req = { relPath: "src/lib.ts", ranges: [{ start: 2, end: 2 }], anchorLines: FILES["src/lib.ts"], files: new SourceFiles(root) };
+ const result = await gatherAround(mockClient() as any, { ...req, exclude: new Set(["d-target"]) });
+ expect(result.symbols).toEqual([]);
+ expect(result.excluded).toBe(1);
+ expect((await gatherAround(mockClient() as any, req)).excluded).toBeUndefined();
+ });
+
it("caps callers and keeps the total", async () => {
const result = await gatherAround(mockClient(20) as any, {
relPath: "src/lib.ts",
diff --git a/ix-cli/src/cli/__tests__/post-edit-hook.test.ts b/ix-cli/src/cli/__tests__/post-edit-hook.test.ts
index 6a36903d..139d4064 100644
--- a/ix-cli/src/cli/__tests__/post-edit-hook.test.ts
+++ b/ix-cli/src/cli/__tests__/post-edit-hook.test.ts
@@ -6,7 +6,7 @@ import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { parseHookArgs, runPostEditHook, type EntryDeps } from "../hook/entry.js";
+import { answerWithin, parseHookArgs, runPostEditHook, type EntryDeps } from "../hook/entry.js";
import { postToolUseOutput, withDeadline } from "../hook/io.js";
import { fingerprint, loadState, parseUnifiedDiff, pruneStates, statePath } from "../hook/session.js";
import { HOOK_CAPS, reportToolEdit, summarize, type PostToolUseInput } from "../hook/claude-post-edit.js";
@@ -447,6 +447,33 @@ describe("the hook's row caps and its log", () => {
expect(line.notes).toContain("src/lib.js#beta: no_dependents");
});
+ it("still says why on IX_HOOK_DEBUG when nothing changed", async () => {
+ const said: string[] = [];
+ await run(bash(), deps([], { debug: (m) => said.push(m) }));
+ edit(" return y * 2;", " return y * 3;");
+ await run(bash(), deps([], { debug: (m) => said.push(m) }));
+ await run(bash(), deps([], { debug: (m) => said.push(m) }));
+ expect(said).toContain("no tracked changes");
+ expect(said).toContain("diff unchanged since last report");
+ });
+
+ it("logs an edit inside a symbol it already reported as that, not as outside every definition", () => {
+ const empty = { symbols: [], importers: { total: 0, tests: 0, rows: [] } };
+ expect(summarize([{ path: "src/a.ts", ...empty, excluded: 1 }], 300).notes).toEqual(["src/a.ts: already_reported"]);
+ expect(summarize([{ path: "src/a.ts", ...empty }], 300).notes).toEqual(["src/a.ts: no_definition_covers"]);
+ });
+
+ it("logs a call the deadline cut off", async () => {
+ const log = join(stateDir, "hook.log");
+ edit(" return y * 2;", " return y * 3;");
+ const never = vi.fn(() => new Promise<AroundResult>(() => {}));
+ const out = await answerWithin(bash(), { env: { IX_HOOK_STATE_DIR: stateDir, IX_HOOK_LOG: log } }, 50,
+ deps([], { gather: never }));
+ expect(out).toBeUndefined();
+ expect(never).toHaveBeenCalled();
+ expect(logged(log).map((l) => l.path)).toEqual(["timeout"]);
+ });
+
it("writes no log without IX_HOOK_LOG", async () => {
edit(" return y * 2;", " return y * 3;");
await run(bash(), deps([]));
diff --git a/ix-cli/src/cli/around.ts b/ix-cli/src/cli/around.ts
index 1cbf14ba..8042fe73 100644
--- a/ix-cli/src/cli/around.ts
+++ b/ix-cli/src/cli/around.ts
@@ -141,6 +141,12 @@ export interface AroundResult {
symbols: AroundSymbol[];
/** Every importer of the file, at its import line. */
importers: AroundSection & { tests: number };
+ /**
+ * Edited definitions left out because the request excluded them (the hook's
+ * "already told"); absent when none were. Lets the hook's log tell an edit
+ * outside every definition from one inside a definition it already reported.
+ */
+ excluded?: number;
}
export interface AroundCaps {
@@ -499,10 +505,12 @@ export async function gatherAround(client: AroundClient, req: AroundRequest): Pr
// Which definitions to report on.
let chosen: PlacedDef[];
const preloaded = new Map<string, any[]>();
+ let alreadyReported = 0;
if (req.ranges && req.ranges.length > 0) {
- chosen = selectEdited(anchorPlaced, req.ranges, Number.MAX_SAFE_INTEGER)
- .filter((d) => !req.exclude?.has(d.id))
- .slice(0, caps.symbols);
+ const edited = selectEdited(anchorPlaced, req.ranges, Number.MAX_SAFE_INTEGER);
+ const fresh = edited.filter((d) => !req.exclude?.has(d.id));
+ alreadyReported = edited.length - fresh.length;
+ chosen = fresh.slice(0, caps.symbols);
} else {
// The whole file: its outermost definitions, the most-called first, so a
// capped answer keeps the ones with dependents.
@@ -626,6 +634,7 @@ export async function gatherAround(client: AroundClient, req: AroundRequest): Pr
graph: isUnhealthy(health) ? health : undefined,
symbols,
importers,
+ ...(alreadyReported > 0 ? { excluded: alreadyReported } : {}),
};
}
diff --git a/ix-cli/src/cli/commands/hook.ts b/ix-cli/src/cli/commands/hook.ts
index 968e5f68..d7c02ac1 100644
--- a/ix-cli/src/cli/commands/hook.ts
+++ b/ix-cli/src/cli/commands/hook.ts
@@ -33,7 +33,9 @@ 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.
+says why on stderr; IX_HOOK_LOG=<file> appends one JSON line per call saying
+what it did (no_changes, diff_unchanged, reported, silent, timeout;
+tool-edit outside git) and why.
.claude/settings.json:
{"hooks":{"PostToolUse":[{"matcher":"Edit|MultiEdit|Write|Bash",
diff --git a/ix-cli/src/cli/hook/claude-post-edit.ts b/ix-cli/src/cli/hook/claude-post-edit.ts
index f56f2ce8..8106e5c3 100644
--- a/ix-cli/src/cli/hook/claude-post-edit.ts
+++ b/ix-cli/src/cli/hook/claude-post-edit.ts
@@ -337,7 +337,7 @@ export function summarize(results: AroundResult[], budget: number): HookOutcome
let complete = true;
for (const r of results) {
const keep = [];
- if (r.symbols.length === 0) notes.push(`${r.path}: no_definition_covers`);
+ if (r.symbols.length === 0) notes.push(`${r.path}: ${r.excluded ? "already_reported" : "no_definition_covers"}`);
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)); notes.push(`${r.path}#${s.name}: no_dependents`); continue; }
diff --git a/ix-cli/src/cli/hook/entry.ts b/ix-cli/src/cli/hook/entry.ts
index 80854a23..3a7f5910 100644
--- a/ix-cli/src/cli/hook/entry.ts
+++ b/ix-cli/src/cli/hook/entry.ts
@@ -90,11 +90,11 @@ async function runPostEditHookInner(
}
const diff = (deps.gitDiffHead ?? gitDiffHead)(repoRoot);
- if (!diff.trim()) { record.path = "no_changes"; return undefined; }
+ if (!diff.trim()) { record.path = "no_changes"; 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) { record.path = "diff_unchanged"; return undefined; }
+ if (state.fingerprint === fp) { record.path = "diff_unchanged"; debug("diff unchanged since last report"); return undefined; }
const files = parseUnifiedDiff(diff);
const heavy = await import("./claude-post-edit.js");
@@ -115,6 +115,26 @@ async function runPostEditHookInner(
}
}
+/**
+ * The hook's answer, or undefined once `ms` have passed. A call the deadline
+ * cuts off never writes its own `IX_HOOK_LOG` line -- the process exits before
+ * `runPostEditHook` finishes -- so it is logged here: a timeout is one of the
+ * reasons the hook is silent, and the log is where that is looked up.
+ */
+export async function answerWithin(raw: string, opts: HookOptions, ms: number, deps: EntryDeps = {}): Promise<string | undefined> {
+ const started = Date.now();
+ let settled = false;
+ const work = runPostEditHook(raw, opts, deps).finally(() => { settled = true; });
+ const out = await withDeadline(work, ms);
+ if (!settled) {
+ deps.debug?.(`no answer within ${ms} ms`);
+ appendHookLog((opts.env ?? process.env).IX_HOOK_LOG || undefined, {
+ ts: new Date(started).toISOString(), path: "timeout", ms: Date.now() - started, chars: 0, notes: [],
+ });
+ }
+ return out;
+}
+
/** `--graph-root <dir>`, `--worktree=<dir>`, `--budget <n>`; anything else is ignored. */
export function parseHookArgs(argv: string[]): HookOptions {
const opts: HookOptions = {};
@@ -145,7 +165,7 @@ export async function runHookProcess(opts: HookOptions): Promise<void> {
try {
const raw = await readStdin(timeout);
const left = Math.max(0, timeout - (Date.now() - started));
- out = await withDeadline(runPostEditHook(raw, opts, { debug }), left);
+ out = await answerWithin(raw, opts, left, { debug });
} catch (err) {
debug(`failed: ${err instanceof Error ? err.message : String(err)}`);
out = undefined;
diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.md
index 7cc5dec8..5997c1c1 100644
--- a/skills/ix/references/flags.md
+++ b/skills/ix/references/flags.md
@@ -395,7 +395,7 @@ No flags.
#### `ix hook claude-post-edit`
-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 `<IX_HOME>/hook-state`, dropped after a week unused). 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.
+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 `<IX_HOME>/hook-state`, dropped after a week unused). 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; `IX_HOOK_LOG=<file>` appends one JSON line per call with what it did (`no_changes`, `diff_unchanged`, `reported`, `silent`, `timeout`; `tool-edit` outside git) and why.
| Flag | Value | Default | Effect |
|---|---|---|---|