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): compare paths in one spelling, and keep session state out of the temp dir

KageBinary3a596a7950b2
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 db5878cd..6dbe76e2 100644
--- a/ix-cli/src/cli/__tests__/post-edit-hook.test.ts
+++ b/ix-cli/src/cli/__tests__/post-edit-hook.test.ts
@@ -1,14 +1,14 @@
// Copyright 2026 Ix Infrastructure Inc.
import { execFileSync } from "node:child_process";
-import { mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+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 { postToolUseOutput, withDeadline } from "../hook/io.js";
-import { fingerprint, loadState, parseUnifiedDiff, statePath } from "../hook/session.js";
+import { fingerprint, loadState, parseUnifiedDiff, pruneStates, 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";
@@ -269,16 +269,55 @@ describe("runPostEditHook: the diff path", () => {
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(chdir).toHaveBeenCalledWith(resolve("/graph"));
expect(calls[0].relPath).toBe("src/lib.js");
});
+ // git names the top level with links resolved; the roots the hook is handed
+ // are as someone typed them. macOS's temp directory is such a link.
+ it.skipIf(process.platform === "win32")("reports an edit in a checkout reached through a symlink", async () => {
+ const link = `${repo}-link`;
+ symlinkSync(repo, link, "dir");
+ try {
+ edit(" return y * 2;", " return y * 3;");
+ const calls: AroundRequest[] = [];
+ const input = JSON.stringify({ ...JSON.parse(bash()), cwd: link });
+ const out = await runPostEditHook(input, { env: { IX_HOOK_STATE_DIR: stateDir } },
+ deps(calls, { workspaceRoot: () => link }));
+ expect(context(out)).toMatch(/^Ix: you changed `beta`/);
+ expect(calls[0].relPath).toBe("src/lib.js");
+ // One checkout, one memory, whichever way it was reached.
+ expect(statePath("s1", link, { IX_HOOK_STATE_DIR: stateDir }))
+ .toBe(statePath("s1", repo, { IX_HOOK_STATE_DIR: stateDir }));
+ } finally {
+ unlinkSync(link);
+ }
+ });
+
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));
});
+
+ it("keeps its memory under IX_HOME, not in the shared temp directory", () => {
+ const home = join(stateDir, "home");
+ expect(dirname(statePath("s1", repo, { IX_HOME: home }))).toBe(join(home, "hook-state"));
+ expect(dirname(statePath("s1", repo, { IX_HOME: home, IX_HOOK_STATE_DIR: stateDir }))).toBe(stateDir);
+ });
+
+ it("drops a session's file a week after its last write, and keeps the rest", () => {
+ const fresh = join(stateDir, "fresh.json");
+ const stale = join(stateDir, "stale.json");
+ const other = join(stateDir, "notes.txt");
+ for (const f of [fresh, stale, other]) writeFileSync(f, "{}");
+ const eightDaysAgo = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000);
+ utimesSync(stale, eightDaysAgo, eightDaysAgo);
+ utimesSync(other, eightDaysAgo, eightDaysAgo);
+ pruneStates(stateDir);
+ expect(readdirSync(stateDir).sort()).toEqual(["fresh.json", "notes.txt"]);
+ });
});
// ── Outside git: the Edit tool's own patch ──────────────────────────────────
diff --git a/ix-cli/src/cli/commands/around.ts b/ix-cli/src/cli/commands/around.ts
index ff1b886d..e928c178 100644
--- a/ix-cli/src/cli/commands/around.ts
+++ b/ix-cli/src/cli/commands/around.ts
@@ -28,9 +28,16 @@ function reportError(code: string, message: string, format: string, extra: Array
/** The file's lines, or none when it is not on disk (the graph's spans then stand as recorded). */
export function readLines(abs: string): string[] {
try {
- const stat = fs.statSync(abs);
- if (!stat.isFile() || stat.size > 2 * 1024 * 1024) return [];
- return fs.readFileSync(abs, "utf-8").split("\n");
+ // One descriptor for the checks and the read, so the file measured is the
+ // file read (CodeQL js/file-system-race).
+ const fd = fs.openSync(abs, "r");
+ try {
+ const stat = fs.fstatSync(fd);
+ if (!stat.isFile() || stat.size > 2 * 1024 * 1024) return [];
+ return fs.readFileSync(fd, "utf-8").split("\n");
+ } finally {
+ fs.closeSync(fd);
+ }
} catch {
return [];
}
diff --git a/ix-cli/src/cli/commands/hook.ts b/ix-cli/src/cli/commands/hook.ts
index 3d549a7b..968e5f68 100644
--- a/ix-cli/src/cli/commands/hook.ts
+++ b/ix-cli/src/cli/commands/hook.ts
@@ -26,7 +26,7 @@ export function registerHookCommand(program: Command): void {
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
+IX_HOOK_STATE_DIR, default <IX_HOME>/hook-state); 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 that
diff --git a/ix-cli/src/cli/hook/claude-post-edit.ts b/ix-cli/src/cli/hook/claude-post-edit.ts
index e4923857..ad6f4857 100644
--- a/ix-cli/src/cli/hook/claude-post-edit.ts
+++ b/ix-cli/src/cli/hook/claude-post-edit.ts
@@ -7,7 +7,7 @@ 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 { canonicalPath, gitShowHead, symbolKey } from "./session.js";
import { hookTimeoutMs, postToolUseOutput } from "./io.js";
import {
DEFAULT_TOKEN_BUDGET, estimateTokens, fitToBudget, gatherAround, hasDependents, type AroundRequest, type AroundResult, type LineRange,
@@ -236,9 +236,16 @@ const FOOTER = "These may need updating to match your edit.";
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");
+ // One descriptor for the checks and the read, so the file measured is the
+ // file read (CodeQL js/file-system-race).
+ const fd = fs.openSync(abs, "r");
+ try {
+ const stat = fs.fstatSync(fd);
+ if (!stat.isFile() || stat.size > 2 * 1024 * 1024) return undefined;
+ return fs.readFileSync(fd, "utf-8");
+ } finally {
+ fs.closeSync(fd);
+ }
} catch {
return undefined;
}
@@ -257,21 +264,23 @@ interface Roots {
sourceRoot: string;
}
+/** Every root in its canonical spelling (see `canonicalPath`), so they compare. */
function resolveRoots(worktree: string, opts: HookOptions, deps: HookDeps): Roots {
- const graphRoot = path.resolve(opts.graphRoot ?? worktree);
+ const graphRoot = canonicalPath(opts.graphRoot ?? worktree);
(deps.chdir ?? process.chdir)(graphRoot);
- const workspaceRoot = path.resolve((deps.workspaceRoot ?? resolveWorkspaceRoot)());
+ const workspaceRoot = canonicalPath((deps.workspaceRoot ?? resolveWorkspaceRoot)());
+ const root = canonicalPath(worktree);
return {
- worktree: path.resolve(worktree),
+ worktree: root,
graphRoot,
workspaceRoot,
- sourceRoot: path.join(path.resolve(worktree), path.relative(graphRoot, workspaceRoot)),
+ sourceRoot: path.join(root, 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);
+ const rel = path.relative(roots.worktree, canonicalPath(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;
diff --git a/ix-cli/src/cli/hook/session.ts b/ix-cli/src/cli/hook/session.ts
index 966100ae..eed3c7e9 100644
--- a/ix-cli/src/cli/hook/session.ts
+++ b/ix-cli/src/cli/hook/session.ts
@@ -38,6 +38,23 @@ export interface FileDiff {
const GIT_TIMEOUT_MS = 2000;
+/**
+ * A path with its symlinks -- and, on Windows, its 8.3 short names -- resolved,
+ * as far as it exists: a deleted file takes its directory's spelling.
+ *
+ * git names the repository's top level this way, while `--worktree`,
+ * `--graph-root`, a registered workspace and a tool's `file_path` come as
+ * someone typed them. Compared as given, a checkout reached through a link
+ * (macOS's temp directory, for one) puts every edited file "outside" the
+ * workspace, and the hook says nothing.
+ */
+export function canonicalPath(p: string): string {
+ const resolved = path.resolve(p);
+ try { return fs.realpathSync.native(resolved); } catch { /* does not exist: resolve what does */ }
+ const parent = path.dirname(resolved);
+ return parent === resolved ? resolved : path.join(canonicalPath(parent), path.basename(resolved));
+}
+
function git(cwd: string, args: string[]): string {
return execFileSync("git", ["-C", cwd, ...args], {
encoding: "utf-8",
@@ -51,7 +68,7 @@ function git(cwd: string, args: string[]): string {
export function gitTopLevel(dir: string): string | undefined {
try {
const out = git(dir, ["rev-parse", "--show-toplevel"]).trim();
- return out ? path.resolve(out) : undefined;
+ return out ? canonicalPath(out) : undefined;
} catch {
return undefined;
}
@@ -130,13 +147,44 @@ export interface HookState {
reported: string[];
}
-/** One file per (session, worktree), under IX_HOOK_STATE_DIR or the OS temp dir. */
+/** A session's file is dropped this long after the hook last wrote it. */
+const STATE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
+
+/**
+ * One file per (session, worktree), under IX_HOOK_STATE_DIR or
+ * `<IX_HOME>/hook-state`. The worktree is keyed by its canonical path, so one
+ * checkout is one memory however it was reached.
+ *
+ * Not the OS temp directory: that is shared, the names here are predictable,
+ * and another user could plant a link where the hook is about to write.
+ */
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);
+ const dir = env.IX_HOOK_STATE_DIR || path.join(env.IX_HOME || path.join(os.homedir(), ".ix"), "hook-state");
+ const key = fingerprint(`${sessionId ?? "no-session"}\0${canonicalPath(worktree)}`).slice(0, 24);
return path.join(dir, `${key}.json`);
}
+/**
+ * Sessions end without telling the hook, and nothing else cleans this
+ * directory: drop what has not been written for a week. The age is read off a
+ * descriptor, and a file removed just as its session came back only makes the
+ * hook repeat itself once.
+ */
+export function pruneStates(dir: string, now = Date.now()): void {
+ let names: string[];
+ try { names = fs.readdirSync(dir); } catch { return; }
+ for (const name of names) {
+ if (!name.endsWith(".json") && !name.endsWith(".tmp")) continue;
+ const file = path.join(dir, name);
+ try {
+ const fd = fs.openSync(file, "r");
+ let stale: boolean;
+ try { stale = now - fs.fstatSync(fd).mtimeMs > STATE_MAX_AGE_MS; } finally { fs.closeSync(fd); }
+ if (stale) fs.unlinkSync(file);
+ } catch { /* gone already, or not ours to remove */ }
+ }
+}
+
export function loadState(file: string): HookState {
try {
const parsed = JSON.parse(fs.readFileSync(file, "utf-8")) as Partial<HookState>;
@@ -152,10 +200,12 @@ export function loadState(file: string): HookState {
/** 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 dir = path.dirname(file);
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
const tmp = `${file}.${process.pid}.tmp`;
- fs.writeFileSync(tmp, JSON.stringify(state));
+ fs.writeFileSync(tmp, JSON.stringify(state), { mode: 0o600 });
fs.renameSync(tmp, file);
+ pruneStates(dir);
} catch { /* a hook that cannot remember only repeats itself */ }
}
diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.md
index 649c1db4..7cc5dec8 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 `<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.
+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.
| Flag | Value | Default | Effect |
|---|---|---|---|