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): nearest dependents first, fewer rows, and a log of why it was silent
KageBinarya0b71321614f
diff --git a/ix-cli/src/cli/__tests__/around.test.ts b/ix-cli/src/cli/__tests__/around.test.tsindex 16b22022..58d3cc53 100644--- a/ix-cli/src/cli/__tests__/around.test.ts+++ b/ix-cli/src/cli/__tests__/around.test.ts@@ -11,7 +11,7 @@ vi.mock("../resolve.js", () => ({}));import {- CONTAINER_KINDS, declarationLines, DEFAULT_CAPS, estimateTokens, findUseInImporter, fitToBudget, gatherAround, importStatementText, isTestFile,+ CONTAINER_KINDS, declarationLines, DEFAULT_CAPS, localityRank, estimateTokens, findUseInImporter, fitToBudget, gatherAround, importStatementText, isTestFile,outermostDefs, parseAroundTarget, placeDefs, selectEdited, type AroundResult, type FileDef,} from "../around.js";import { aroundJson, renderAroundLlm, renderAroundText } from "../around-render.js";@@ -369,3 +369,20 @@ describe("renderers", () => {expect(aroundJson(r).graph).toMatchObject({ status: "degraded" });});});++describe("localityRank", () => {+ it("puts the edited file's own directory first, then the nearest", () => {+ const edited = "src/main/java/a/b/Foo.java";+ expect(localityRank(edited, "src/main/java/a/b/Bar.java")).toBe(0);+ expect(localityRank(edited, "src/main/java/a/b/c/Baz.java")).toBe(1);+ expect(localityRank(edited, "src/main/java/a/x/Qux.java")).toBe(2);+ expect(localityRank(edited, "other/module/Z.java")).toBeGreaterThan(localityRank(edited, "src/main/java/a/x/Qux.java"));+ });++ it("orders a list nearest first", () => {+ const edited = "lib/plugins/aws/deploy.js";+ const sorted = ["lib/classes/Service.js", "lib/plugins/aws/package.js", "lib/plugins/print.js"]+ .sort((a, b) => localityRank(edited, a) - localityRank(edited, b));+ expect(sorted).toEqual(["lib/plugins/aws/package.js", "lib/plugins/print.js", "lib/classes/Service.js"]);+ });+});diff --git a/ix-cli/src/cli/__tests__/post-edit-hook.test.ts b/ix-cli/src/cli/__tests__/post-edit-hook.test.tsindex db5878cd..56e4b933 100644--- a/ix-cli/src/cli/__tests__/post-edit-hook.test.ts+++ b/ix-cli/src/cli/__tests__/post-edit-hook.test.ts@@ -1,7 +1,7 @@// Copyright 2026 Ix Infrastructure Inc.import { execFileSync } from "node:child_process";-import { mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, readFileSync, 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";@@ -9,7 +9,7 @@ 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 { HOOK_CAPS, 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";@@ -345,3 +345,49 @@ describe("output", () => {expect(await withDeadline(Promise.resolve("ok"), 50)).toBe("ok");});});++describe("the hook's row caps and its log", () => {+ it("asks for the hook's caps: the nearest two callers and users, one test", async () => {+ edit(" return y * 2;", " return y * 3;");+ const calls: AroundRequest[] = [];+ await run(bash(), deps(calls));+ expect(calls[0].caps).toEqual(HOOK_CAPS);+ expect(HOOK_CAPS).toMatchObject({ callers: 2, users: 2, tests: 1 });+ });++ const logged = (file: string) => readFileSync(file, "utf-8").trim().split("\n").map((l) => JSON.parse(l));++ it("logs one line per call saying why nothing was printed, or what was", async () => {+ const log = join(stateDir, "hook.log");+ const env = { IX_HOOK_STATE_DIR: stateDir, IX_HOOK_LOG: log };+ const calls: AroundRequest[] = [];+ await runPostEditHook(bash(), { env }, deps(calls)); // nothing changed yet+ edit(" return y * 2;", " return y * 3;");+ await runPostEditHook(bash(), { env }, deps(calls)); // reports beta+ await runPostEditHook(bash(), { env }, deps(calls)); // same diff again+ const lines = logged(log);+ expect(lines.map((l) => l.path)).toEqual(["no_changes", "reported", "diff_unchanged"]);+ expect(lines[1].notes).toContain("src/lib.js#beta: reported");+ expect(lines[1].chars).toBeGreaterThan(0);+ expect(lines[1]).toMatchObject({ session: "s1", tool: "Bash", files: 1 });+ expect(typeof lines[1].ms).toBe("number");+ });++ it("logs a symbol with no dependents as the reason for silence", async () => {+ const log = join(stateDir, "hook.log");+ edit(" return y * 2;", " return y * 3;");+ const calls: AroundRequest[] = [];+ const out = await runPostEditHook(bash(), { env: { IX_HOOK_STATE_DIR: stateDir, IX_HOOK_LOG: log } },+ deps(calls, { gather: fakeGather(calls, { noDependents: ["beta"] }) }));+ expect(out).toBeUndefined();+ const [line] = logged(log);+ expect(line.path).toBe("silent");+ expect(line.notes).toContain("src/lib.js#beta: no_dependents");+ });++ it("writes no log without IX_HOOK_LOG", async () => {+ edit(" return y * 2;", " return y * 3;");+ await run(bash(), deps([]));+ expect(() => readFileSync(join(stateDir, "hook.log"))).toThrow();+ });+});diff --git a/ix-cli/src/cli/around.ts b/ix-cli/src/cli/around.tsindex d92d7fad..1cbf14ba 100644--- a/ix-cli/src/cli/around.ts+++ b/ix-cli/src/cli/around.ts@@ -153,6 +153,24 @@ export interface AroundCaps {export const DEFAULT_CAPS: AroundCaps = { symbols: 3, callers: 8, users: 5, tests: 5, importers: 5 };+/**+ * How close `other` is to `edited`, smaller first: 0 for the same directory,+ * then one more for each directory you climb from `edited` to a shared one.+ *+ * Measured on 93 hook runs over SWE-PolyBench multi-file issues: a caller in+ * the edited file's own directory was a file the fix changed 10 times in 16,+ * one elsewhere 19 in 96; for importers that use the name, 5 in 10 against 3+ * in 31.+ */+export function localityRank(edited: string, other: string): number {+ const a = edited.split("/").slice(0, -1);+ const b = other.split("/").slice(0, -1);+ let shared = 0;+ while (shared < a.length && shared < b.length && a[shared] === b[shared]) shared++;+ // Directories climbed from the edited file, plus one if `other` then goes down another.+ return (a.length - shared) + (b.length > shared ? 1 : 0);+}+/** The default token budget for rendered output: it lands in an agent's context after every edit. */export const DEFAULT_TOKEN_BUDGET = 300;@@ -520,8 +538,10 @@ export async function gatherAround(client: AroundClient, req: AroundRequest): Prconst target = { name: d.name, kind: d.kind, path: relPath };const nonTest = hop1.filter((r) => !isTestFile(rowLocation(r).path ?? ""));+ // Other files first (the agent has this one open), the nearest first.+ const near = (r: any) => localityRank(relPath, rowLocation(r).path ?? "");const crossFirst = [...nonTest].sort((a, b) =>- Number(rowLocation(a).path === relPath) - Number(rowLocation(b).path === relPath));+ Number(rowLocation(a).path === relPath) - Number(rowLocation(b).path === relPath) || near(a) - near(b));const callers = crossFirst.slice(0, caps.callers).map((row) => siteRef(row, safeSite("callers", row, target, req.files)));const callerPaths = new Set(hop1.map((r) => rowLocation(r).path));@@ -576,7 +596,10 @@ export async function gatherAround(client: AroundClient, req: AroundRequest): PrlineEnd: here.end,movedFrom: here.start !== d.lineStart ? d.lineStart : undefined,callers: { total: nonTest.length, rows: callers },- users: { total: users.length, rows: users.slice(0, caps.users) },+ users: {+ total: users.length,+ rows: [...users].sort((x, y) => localityRank(relPath, x.path) - localityRank(relPath, y.path)).slice(0, caps.users),+ },tests: { total: testRows.length, rows: testRows.slice(0, caps.tests) },sameName,...(decl ? { declarations: { lineStart: decl.start + shift, lineEnd: decl.end + shift } } : {}),diff --git a/ix-cli/src/cli/hook/claude-post-edit.ts b/ix-cli/src/cli/hook/claude-post-edit.tsindex e4923857..c477512b 100644--- a/ix-cli/src/cli/hook/claude-post-edit.ts+++ b/ix-cli/src/cli/hook/claude-post-edit.ts@@ -224,6 +224,8 @@ export interface HookOutcome {reported: string[];/** False when edited symbols were left for a later call by the symbol cap. */complete: boolean;+ /** What happened to each file and symbol, for `IX_HOOK_LOG`. */+ notes?: string[];}const NOTHING: HookOutcome = { reported: [], complete: true };@@ -232,6 +234,14 @@ const MAX_FILES = 8;/** Symbols reported per run, across all files. */const MAX_SYMBOLS = 3;const LEAD = "Ix: you changed";++/**+ * Rows the hook prints per symbol. In 93 recorded runs the first caller+ * listed was a file the fix changed 24 times in 61, later ones 5 in 51, and+ * no test row ever was (agents are told not to edit tests), so the hook shows+ * the nearest two callers and users and one test, and counts the rest.+ */+export const HOOK_CAPS = { symbols: 3, callers: 2, users: 2, tests: 1, importers: 5 };const FOOTER = "These may need updating to match your edit.";function defaultReadFile(abs: string): string | undefined {@@ -312,14 +322,16 @@ export function renderHookText(results: AroundResult[], budget: number): string*/export function summarize(results: AroundResult[], budget: number): HookOutcome {const reported: string[] = [];+ const notes: string[] = [];const shown: AroundResult[] = [];let slots = MAX_SYMBOLS;let complete = true;for (const r of results) {const keep = [];+ if (r.symbols.length === 0) notes.push(`${r.path}: 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)); continue; }+ if (deps === 0) { reported.push(symbolKey(r.path, s.id)); notes.push(`${r.path}#${s.name}: no_dependents`); continue; }if (slots === 0) { complete = false; continue; }slots--;keep.push(s);@@ -327,8 +339,9 @@ export function summarize(results: AroundResult[], budget: number): HookOutcome}if (keep.length > 0) shown.push({ ...r, symbols: keep });}- if (shown.length === 0) return { reported, complete };- return { output: postToolUseOutput(renderHookText(shown, budget)), reported, complete };+ for (const r of shown) for (const s of r.symbols) notes.push(`${r.path}#${s.name}: reported`);+ if (shown.length === 0) return { reported, complete, notes };+ return { output: postToolUseOutput(renderHookText(shown, budget)), reported, complete, notes };}/**@@ -362,6 +375,7 @@ export async function reportChangedFiles(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,+ caps: HOOK_CAPS,});debug(`${relPath} old-side ${JSON.stringify(f.oldRanges)}`);}@@ -407,7 +421,7 @@ export async function reportToolEdit(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,+ files: new SourceFiles(roots.sourceRoot), exclude, caps: HOOK_CAPS,});if (!hasDependents(result)) debug("no dependents");return summarize([result], opts.budget ?? DEFAULT_TOKEN_BUDGET);diff --git a/ix-cli/src/cli/hook/entry.ts b/ix-cli/src/cli/hook/entry.tsindex daa7a91d..80854a23 100644--- a/ix-cli/src/cli/hook/entry.ts+++ b/ix-cli/src/cli/hook/entry.ts@@ -1,5 +1,6 @@// Copyright 2026 Ix Infrastructure Inc.+import * as fs from "node:fs";import * as path from "node:path";import { hookTimeoutMs, readStdin, withDeadline } from "./io.js";import {@@ -30,14 +31,49 @@ export interface EntryDeps extends HookDeps {gitDiffHead?: (repoRoot: string) => string;}+/**+ * One JSON line per hook call, appended to `IX_HOOK_LOG` when it is set: what+ * the call did and why it printed nothing when it did not. Best-effort.+ */+export function appendHookLog(file: string | undefined, record: Record<string, unknown>): void {+ if (!file) return;+ try { fs.appendFileSync(file, `${JSON.stringify(record)}\n`); } catch { /* never fail the hook over its log */ }+}+/** 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;+ const logFile = env.IX_HOOK_LOG || undefined;+ const started = Date.now();+ const notes: string[] = [];+ const record: Record<string, unknown> = { ts: new Date().toISOString() };+ const outer = deps.debug;+ const debug = (m: string) => { if (logFile) notes.push(m); outer?.(m); };+ deps = { ...deps, debug };+ let output: string | undefined;+ try {+ output = await runPostEditHookInner(raw, opts, deps, env, record, notes);+ return output;+ } finally {+ if (logFile) {+ appendHookLog(logFile, {+ ...record, ms: Date.now() - started, chars: output?.length ?? 0, notes,+ });+ }+ }+}++async function runPostEditHookInner(+ raw: string, opts: HookOptions, deps: EntryDeps, env: NodeJS.ProcessEnv,+ record: Record<string, unknown>, notes: string[],+): 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;+ record.session = input.session_id;+ record.tool = input.tool_name;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);@@ -47,20 +83,25 @@ export async function runPostEditHook(raw: string, opts: HookOptions = {}, deps:const state = loadState(file);const heavy = await import("./claude-post-edit.js");const outcome = await heavy.reportToolEdit(input, new Set(state.reported), opts, deps);+ record.path = "tool-edit";+ notes.push(...(outcome.notes ?? []));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; }+ if (!diff.trim()) { record.path = "no_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; }+ if (state.fingerprint === fp) { record.path = "diff_unchanged"; 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);+ record.path = outcome.output ? "reported" : "silent";+ record.files = files.length;+ notes.push(...(outcome.notes ?? []));saveState(file, {// Keep the old fingerprint while edited symbols wait behind the cap, so// the next call -- even one that edits nothing -- reports them.