Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix(cli): re-anchor stale `ix context` next rows and flag them stale (CL-20F) (#834)

Ian Hock43a7206ab309
diff --git a/ix-cli/src/cli/__tests__/context-range-first.test.ts b/ix-cli/src/cli/__tests__/context-range-first.test.ts
index 89f9b95b..505144d3 100644
--- a/ix-cli/src/cli/__tests__/context-range-first.test.ts
+++ b/ix-cli/src/cli/__tests__/context-range-first.test.ts
@@ -1,8 +1,31 @@
// Copyright 2026 Ix Infrastructure Inc.
-import { describe, expect, it } from "vitest";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
-import { nextReads } from "../commands/context.js";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { nextReads, renderBundle, renderedNextReads } from "../commands/context.js";
+import { readsOneSymbol, symbolReadChecker } from "../commands/read.js";
+
+// renderBundle vets each symbol read against the file on disk (symbolReadChecker).
+// The bundles here name files that do not exist, so the check is stubbed for
+// the render tests; the real one is tested against a temp tree at the end.
+vi.mock("../commands/read.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../commands/read.js")>()),
+ symbolReadChecker: vi.fn(() => () => true),
+}));
+
+// renderBundle keeps one on-disk check per workspace root for a few seconds.
+// Each test starts a minute later on a fake clock, so none inherits another's.
+let clock = Date.UTC(2026, 0, 1);
+beforeEach(() => {
+ clock += 60_000;
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(clock);
+});
+afterEach(() => vi.useRealTimers());
function bundleWith(evidence: Array<Record<string, unknown>>): never {
return { evidence } as never;
@@ -23,8 +46,8 @@ describe("nextReads", () => {
row("caller", "src/b.ts", 17, 145),
])),
).toEqual([
- "ix read src/a.ts:15-27",
- "ix read src/b.ts:17-145",
+ { cmd: "ix read src/a.ts:15-27", stale: false },
+ { cmd: "ix read src/b.ts:17-145", stale: false },
]);
});
@@ -44,8 +67,8 @@ describe("nextReads", () => {
row("member parse", "src/c.ts", 4, 9),
])),
).toEqual([
- "ix read src/b.ts:17-145",
- "ix read src/c.ts:4-9",
+ { cmd: "ix read src/b.ts:17-145", stale: false },
+ { cmd: "ix read src/c.ts:4-9", stale: false },
]);
});
@@ -58,10 +81,373 @@ describe("nextReads", () => {
row("container config.ts (file)", "src/huge.ts"),
row("member parse", "src/c.ts", 4, 9),
])),
- ).toEqual(["ix read src/c.ts:4-9"]);
+ ).toEqual([{ cmd: "ix read src/c.ts:4-9", stale: false }]);
});
it("says nothing when nothing in the bundle is ranged", () => {
expect(nextReads(bundleWith([row("a"), row("b", "src/x.ts")]))).toEqual([]);
});
});
+
+type Entity = { id: string; name: string; kind: string; path?: string; stale: boolean };
+
+function entity(id: string, name: string, kind: string, path: string, stale = false): Entity {
+ return { id, name, kind, path, stale };
+}
+
+function refRow(title: string, ref: string, path: string, lineStart: number, lineEnd: number, kind = "structural") {
+ return { ...row(title, path, lineStart, lineEnd), kind, refs: [ref] };
+}
+
+const TARGET = { id: "s-list", name: "listByKind", kind: "method", resolutionMode: "exact", path: "src/client/api.ts" };
+
+function fullBundle(
+ evidence: Array<Record<string, unknown>>,
+ entities: Entity[],
+ targetStale = false,
+): never {
+ return { target: TARGET, evidence, entities, freshness: { stale: targetStale, classification: "current" } } as never;
+}
+
+describe("nextReads re-anchors a stale row through the symbol", () => {
+ it("names the symbol and pins its file when the file changed", () => {
+ expect(
+ nextReads(fullBundle(
+ [refRow("member parse", "f-parse", "src/c.ts", 4, 9)],
+ [entity("f-parse", "parse", "function", "src/c.ts", true)],
+ )),
+ ).toEqual([{ cmd: "ix read parse --path src/c.ts", stale: true }]);
+ });
+
+ // The range is exact in a fresh file and never fails; a symbol read can
+ // (live: `ix read add --path core-ingestion/src/role-classifier.ts` exit 1).
+ it("keeps the exact range for a symbol in a fresh file", () => {
+ expect(
+ nextReads(fullBundle(
+ [refRow("member parse", "f-parse", "src/c.ts", 4, 9)],
+ [entity("f-parse", "parse", "function", "src/c.ts")],
+ ), 3, () => {
+ throw new Error("a fresh row needs no disk check");
+ }),
+ ).toEqual([{ cmd: "ix read src/c.ts:4-9", stale: false }]);
+ });
+
+ it("takes the target row's name from the bundle's target", () => {
+ expect(
+ nextReads(fullBundle([refRow("listByKind (method)", "s-list", "src/client/api.ts", 141, 152, "target")], [], true)),
+ ).toEqual([{ cmd: "ix read listByKind --path src/client/api.ts", stale: true }]);
+ });
+
+ it("keeps the target row's range when the target is fresh", () => {
+ expect(
+ nextReads(fullBundle([refRow("listByKind (method)", "s-list", "src/client/api.ts", 141, 152, "target")], [])),
+ ).toEqual([{ cmd: "ix read src/client/api.ts:141-152", stale: false }]);
+ });
+
+ it("keeps the range for a file or module, an unsafe name, or a name used twice in one file", () => {
+ expect(
+ nextReads(fullBundle(
+ [
+ refRow("file", "d-file", "src/f.ts", 1, 50),
+ refRow("module", "d-mod", "src/m.ts", 1, 60),
+ refRow("odd name", "d-odd", "src/o.ts", 3, 8),
+ refRow("first constructor", "k-1", "src/k.ts", 10, 20),
+ ],
+ [
+ entity("d-file", "f.ts", "file", "src/f.ts", true),
+ entity("d-mod", "m", "Module", "src/m.ts", true),
+ entity("d-odd", "operator ==", "method", "src/o.ts", true),
+ entity("k-1", "constructor", "method", "src/k.ts", true),
+ entity("k-2", "constructor", "method", "src/k.ts", true),
+ ],
+ ), 4),
+ ).toEqual([
+ { cmd: "ix read src/f.ts:1-50", stale: true },
+ { cmd: "ix read src/m.ts:1-60", stale: true },
+ { cmd: "ix read src/o.ts:3-8", stale: true },
+ { cmd: "ix read src/k.ts:10-20", stale: true },
+ ]);
+ });
+
+ it("still collapses a caller and a dependent naming the same range", () => {
+ expect(
+ nextReads(fullBundle(
+ [
+ refRow("caller handleLogin", "f-login", "src/b.ts", 17, 145),
+ refRow("dependent handleLogin", "f-login", "src/b.ts", 17, 145),
+ ],
+ [entity("f-login", "handleLogin", "function", "src/b.ts", true)],
+ )),
+ ).toEqual([{ cmd: "ix read handleLogin --path src/b.ts", stale: true }]);
+ });
+
+ it("flags a row whose file changed since the last ingest", () => {
+ const reads = nextReads(fullBundle(
+ [
+ refRow("listByKind (method)", "s-list", "src/client/api.ts", 141, 152, "target"),
+ refRow("member parse", "f-parse", "src/c.ts", 4, 9),
+ refRow("caller run", "f-run", "src/d.ts", 30, 40),
+ refRow("calls helper", "f-help", "src/e.ts", 1, 5),
+ ],
+ [
+ entity("f-parse", "parse", "function", "src/c.ts", true),
+ entity("f-run", "run", "function", "src/d.ts"),
+ entity("f-other", "other", "function", "src/d.ts", true),
+ entity("f-help", "helper", "function", "src/e.ts"),
+ ],
+ true,
+ ), 4);
+ expect(reads).toEqual([
+ { cmd: "ix read listByKind --path src/client/api.ts", stale: true },
+ { cmd: "ix read parse --path src/c.ts", stale: true },
+ // Stale by a sibling entity in the same file.
+ { cmd: "ix read run --path src/d.ts", stale: true },
+ { cmd: "ix read src/e.ts:1-5", stale: false },
+ ]);
+ });
+});
+
+describe("renderBundle prints the stale flag on next rows", () => {
+ function captureLog(fn: () => void): string[] {
+ const lines: string[] = [];
+ const orig = console.log;
+ console.log = (...a: unknown[]) => void lines.push(a.map(String).join(" "));
+ try {
+ fn();
+ } finally {
+ console.log = orig;
+ }
+ return lines.join("\n").split("\n");
+ }
+
+ function renderable(): never {
+ const base = fullBundle(
+ [
+ refRow("member parse", "f-parse", "src/c.ts", 4, 9),
+ refRow("calls helper", "f-help", "src/e.ts", 1, 5),
+ ],
+ [entity("f-parse", "parse", "function", "src/c.ts", true), entity("f-help", "helper", "function", "src/e.ts")],
+ ) as Record<string, unknown>;
+ return {
+ ...base,
+ relationships: [], claims: [], decisions: [], conflicts: [], intents: [],
+ provenance: { historyLength: 0, stale: false },
+ truncation: { entitiesTruncated: 0, relationshipsTruncated: 0, evidenceTruncated: 0, conflictsTruncated: 0, charsTruncated: 0 },
+ budgets: { maxChars: 10000, maxEvidence: 20, maxEntities: 20, maxRelationships: 20 },
+ } as never;
+ }
+
+ it("emits stale=true in llm records, and no stale key on a fresh row", () => {
+ const next = captureLog(() => renderBundle(renderable(), "llm")).filter((l) => l.startsWith("next "));
+ expect(next).toEqual([
+ 'next cmd="ix read parse --path src/c.ts" stale=true',
+ 'next cmd="ix read src/e.ts:1-5"',
+ ]);
+ });
+
+ // A budget-fitting loop re-renders the bundle, or prefix copies of it; the
+ // on-disk check (file reads plus a workspace walk) must be built once per
+ // workspace root for all of them, not per render or per bundle object.
+ it("builds the on-disk check once per workspace root, across renders and bundle copies", () => {
+ vi.mocked(symbolReadChecker).mockClear();
+ const bundle = renderable();
+ for (let i = 0; i < 5; i++) captureLog(() => renderBundle(bundle, "llm"));
+ renderedNextReads(bundle);
+ for (let i = 0; i < 4; i++) captureLog(() => renderBundle({ ...(renderable() as object) } as never, "llm"));
+ captureLog(() => renderBundle(renderable(), "text"));
+ expect(vi.mocked(symbolReadChecker)).toHaveBeenCalledTimes(1);
+ // A later render (an `ix mcp` process minutes on) walks afresh.
+ vi.setSystemTime(clock + 30_000);
+ captureLog(() => renderBundle(renderable(), "llm"));
+ expect(vi.mocked(symbolReadChecker)).toHaveBeenCalledTimes(2);
+ });
+
+ // Maintainer decision: MCP callers get the stale flag too, additively. The
+ // range call is unchanged; a stale read adds stale=true and the symbol form.
+ it("adds stale and the re-anchored ix_read to the MCP read step, leaving cmd as it was", () => {
+ const prev = process.env.IX_CALLER;
+ process.env.IX_CALLER = "mcp";
+ try {
+ const next = captureLog(() => renderBundle(renderable(), "llm")).filter((l) => l.startsWith("next "));
+ const read = next.find((l) => l.includes("ix_read"))!;
+ expect(read).toBe(
+ 'next cmd="ix_read symbol=src/c.ts:4-9" why="the top-ranked evidence" stale=true reanchor="ix_read symbol=parse path=src/c.ts"',
+ );
+ for (const line of next.filter((l) => !l.includes("ix_read"))) expect(line).not.toMatch(/stale|reanchor/);
+ } finally {
+ if (prev === undefined) delete process.env.IX_CALLER;
+ else process.env.IX_CALLER = prev;
+ }
+ });
+
+ it("ends a stale row with the note in text", () => {
+ const lines = captureLog(() => renderBundle(renderable(), "text"));
+ expect(lines.find((l) => l.includes("ix read parse --path src/c.ts"))).toMatch(
+ /\(stale: changed since last ingest; ix map to update\)$/,
+ );
+ expect(lines.find((l) => l.includes("ix read src/e.ts:1-5"))).not.toMatch(/stale/);
+ });
+});
+
+describe("nextReads keeps the range form where the symbol read could miss", () => {
+ const ev = [refRow("member parse", "f-parse", "src/c.ts", 4, 9)];
+ const ents = [entity("f-parse", "parse", "function", "src/c.ts", true)];
+
+ it("asks the check with the name and the row's file, and falls back when it says no", () => {
+ const asked: Array<[string, string]> = [];
+ const reads = nextReads(fullBundle(ev, ents), 3, (name, path) => {
+ asked.push([name, path]);
+ return false;
+ });
+ expect(asked).toEqual([["parse", "src/c.ts"]]);
+ expect(reads).toEqual([{ cmd: "ix read src/c.ts:4-9", stale: true }]);
+ });
+
+ it("renderBundle falls back when the file on disk does not vouch for the name", () => {
+ vi.mocked(symbolReadChecker).mockReturnValue(() => false);
+ try {
+ const lines: string[] = [];
+ const orig = console.log;
+ console.log = (...a: unknown[]) => void lines.push(a.map(String).join(" "));
+ try {
+ renderBundle({
+ ...(fullBundle(ev, ents) as object),
+ relationships: [], claims: [], decisions: [], conflicts: [], intents: [],
+ provenance: { historyLength: 0, stale: false },
+ truncation: { entitiesTruncated: 0, relationshipsTruncated: 0, evidenceTruncated: 0, conflictsTruncated: 0, charsTruncated: 0 },
+ budgets: { maxChars: 10000, maxEvidence: 20, maxEntities: 20, maxRelationships: 20 },
+ } as never, "llm");
+ } finally {
+ console.log = orig;
+ }
+ expect(lines.join("\n").split("\n").filter((l) => l.startsWith("next "))).toEqual([
+ 'next cmd="ix read src/c.ts:4-9" stale=true',
+ ]);
+ } finally {
+ vi.mocked(symbolReadChecker).mockReturnValue(() => true);
+ }
+ });
+});
+
+describe("readsOneSymbol asks the file, not the bundle", () => {
+ let root: string;
+ let real: typeof readsOneSymbol;
+
+ beforeEach(async () => {
+ root = mkdtempSync(join(tmpdir(), "ix-next-reads-"));
+ mkdirSync(join(root, "src"));
+ real = (await vi.importActual<typeof import("../commands/read.js")>("../commands/read.js")).readsOneSymbol;
+ });
+
+ afterEach(() => rmSync(root, { recursive: true, force: true }));
+
+ it("says yes to a name declared once", () => {
+ writeFileSync(join(root, "src/x.ts"), "export function parse(s: string) {\n return s;\n}\n");
+ expect(real(root, "parse", "src/x.ts")).toBe(true);
+ });
+
+ // The review case: the bundle for A.save lists one `save` (B.save is not a
+ // neighbour), but `ix read save --path src/x.ts` would find both.
+ it("says no to a name declared twice in the file, whatever the bundle lists", () => {
+ writeFileSync(
+ join(root, "src/x.ts"),
+ "class A {\n save(x: number) {\n return x;\n }\n}\nclass B {\n save(y: number) {\n return y;\n }\n}\n",
+ );
+ expect(real(root, "save", "src/x.ts")).toBe(false);
+ const ev = [refRow("A.save (method)", "a-save", "src/x.ts", 2, 4, "target")];
+ const target = { id: "a-save", name: "save", kind: "method", resolutionMode: "exact", path: "src/x.ts" };
+ const bundle = { target, evidence: ev, entities: [], freshness: { stale: true } } as never;
+ expect(nextReads(bundle, 3, (name, path) => real(root, name, path)))
+ .toEqual([{ cmd: "ix read src/x.ts:2-4", stale: true }]);
+ });
+
+ it("says no when no line declares the name, or the file is missing", () => {
+ writeFileSync(join(root, "src/x.ts"), "const y = parse(1);\n");
+ expect(real(root, "parse", "src/x.ts")).toBe(false);
+ expect(real(root, "parse", "src/missing.ts")).toBe(false);
+ });
+
+ // ix read hides test and fixture symbols when a production one shares the
+ // name, before --path narrows: `ix read bundle --path x.test.ts` exits 1.
+ it("says no for a file ingest may have filed as a test or fixture", () => {
+ const decl = "export function parse(s: string) {\n return s;\n}\n";
+ mkdirSync(join(root, "src/__tests__"));
+ mkdirSync(join(root, "src/fixtures"));
+ writeFileSync(join(root, "src/__tests__/x.ts"), decl);
+ writeFileSync(join(root, "src/fixtures/x.ts"), decl);
+ writeFileSync(join(root, "src/x.test.ts"), decl);
+ writeFileSync(join(root, "src/XTest.java"), decl);
+ writeFileSync(join(root, "src/helpers.ts"), `import { it } from "vitest";\n${decl}`);
+ writeFileSync(join(root, "src/latest.ts"), decl);
+ for (const file of ["src/__tests__/x.ts", "src/fixtures/x.ts", "src/x.test.ts", "src/XTest.java", "src/helpers.ts"]) {
+ expect(real(root, "parse", file), file).toBe(false);
+ }
+ expect(real(root, "parse", "src/latest.ts")).toBe(true);
+ });
+
+ it("says no when a file has the name as its basename, since ix read opens it first", () => {
+ writeFileSync(join(root, "src/x.ts"), "export function parse(s: string) {\n return s;\n}\n");
+ writeFileSync(join(root, "src/parse.ts"), "export {};\n");
+ expect(real(root, "parse", "src/x.ts")).toBe(false);
+ });
+
+ // --path is a substring test on the source path, so `--path src/util.ts`
+ // also keeps lib/src/util.ts and src/util.tsx, and a `parse` there makes
+ // the read ambiguous. The range form reads the right file whatever else exists.
+ it("says no when another file's path contains the suggested path", () => {
+ const decl = "export function parse(s: string) {\n return s;\n}\n";
+ writeFileSync(join(root, "src/util.ts"), decl);
+ expect(real(root, "parse", "src/util.ts")).toBe(true);
+ mkdirSync(join(root, "lib/src"), { recursive: true });
+ writeFileSync(join(root, "lib/src/util.ts"), decl);
+ expect(real(root, "parse", "src/util.ts")).toBe(false);
+ rmSync(join(root, "lib"), { recursive: true });
+ writeFileSync(join(root, "src/util.tsx"), decl);
+ expect(real(root, "parse", "src/util.ts")).toBe(false);
+ rmSync(join(root, "src/util.tsx"));
+ // A path that does not contain the suggested one is no collision.
+ writeFileSync(join(root, "src/my-util.ts"), decl);
+ expect(real(root, "parse", "src/util.ts")).toBe(true);
+ });
+
+ it("says no for a path that escapes the workspace with ..", () => {
+ const outside = mkdtempSync(join(tmpdir(), "ix-next-reads-outside-"));
+ try {
+ writeFileSync(join(outside, "x.ts"), "export function parse(s: string) {\n return s;\n}\n");
+ const rel = join("..", outside.split(/[\\/]/).pop()!, "x.ts").replace(/\\/g, "/");
+ expect(real(root, "parse", rel)).toBe(false);
+ } finally {
+ rmSync(outside, { recursive: true, force: true });
+ }
+ });
+
+ it("walks the workspace once for every row it vets, and answers repeats from memory", async () => {
+ const actual = await vi.importActual<typeof import("../commands/read.js")>("../commands/read.js");
+ for (const n of ["a", "b", "c"]) {
+ writeFileSync(join(root, `src/${n}.ts`), `export function run_${n}(s: string) {\n return s;\n}\n`);
+ }
+ let walks = 0;
+ const check = actual.symbolReadChecker(root, (r) => {
+ walks++;
+ return actual.listWorkspaceFiles(r);
+ });
+ for (let i = 0; i < 3; i++) {
+ for (const n of ["a", "b", "c"]) expect(check(`run_${n}`, `src/${n}.ts`)).toBe(true);
+ }
+ expect(walks).toBe(1);
+ // An answer is kept: a colliding file added afterwards is not seen by this checker.
+ writeFileSync(join(root, "src/run_a.ts"), "export {};\n");
+ expect(check("run_a", "src/a.ts")).toBe(true);
+ expect(actual.symbolReadChecker(root)("run_a", "src/a.ts")).toBe(false);
+ });
+});
+
+describe("sameFsPath", () => {
+ it("matches a Windows path whatever its drive-letter case and separators", async () => {
+ const actual = await vi.importActual<typeof import("../commands/read.js")>("../commands/read.js");
+ expect(actual.sameFsPath("C:\\Repo\\src\\x.ts", "c:/repo/src/X.ts", "win32")).toBe(true);
+ expect(actual.sameFsPath("C:\\Repo\\src\\x.ts", "C:\\Repo\\src\\y.ts", "win32")).toBe(false);
+ expect(actual.sameFsPath("/repo/src/x.ts", "/repo/src/../src/x.ts", "linux")).toBe(true);
+ expect(actual.sameFsPath("/repo/src/x.ts", "/repo/src/X.ts", "linux")).toBe(false);
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/context-usefulness.test.ts b/ix-cli/src/cli/__tests__/context-usefulness.test.ts
index 544f1d03..daaa5500 100644
--- a/ix-cli/src/cli/__tests__/context-usefulness.test.ts
+++ b/ix-cli/src/cli/__tests__/context-usefulness.test.ts
@@ -193,7 +193,7 @@ describe("ix context usefulness", () => {
const { lines } = render(fixture);
const next = lines.filter((l) => l.startsWith("next "));
expect(next.length).toBeGreaterThan(0);
- for (const line of next) expect(line).toMatch(/^next cmd="ix read \S+:\d+-\d+"$/);
+ for (const line of next) expect(line).toMatch(/^next cmd="ix read (?:\S+ --path \S+|\S+:\d+-\d+)"(?: stale=true)?$/);
});
});
}
diff --git a/ix-cli/src/cli/__tests__/mcp-hints.test.ts b/ix-cli/src/cli/__tests__/mcp-hints.test.ts
index 62dedf44..3752d5c0 100644
--- a/ix-cli/src/cli/__tests__/mcp-hints.test.ts
+++ b/ix-cli/src/cli/__tests__/mcp-hints.test.ts
@@ -136,6 +136,40 @@ describe("hints produced for an MCP caller", () => {
}
});
+ // Maintainer decision: additive stale info for MCP. The range call stays;
+ // a stale read step adds `stale` and, when the name re-anchors, `reanchor`.
+ it("flag a stale read step and offer the re-anchored symbol read beside the range", () => {
+ const stale = {
+ ...(bundle(
+ { name: "verify", kind: "function", path: "src/auth.ts" },
+ [],
+ [{ location: { path: "src/auth.ts", lineStart: 10, lineEnd: 40 }, refs: ["t"] }],
+ ) as object),
+ freshness: { stale: true },
+ } as never;
+ const read = nextToolCalls(stale).find((s) => s.cmd.startsWith("ix_read"))!;
+ expect(read).toEqual({
+ cmd: "ix_read symbol=src/auth.ts:10-40",
+ why: "the top-ranked evidence",
+ stale: true,
+ reanchor: "ix_read symbol=verify path=src/auth.ts",
+ });
+ expectRunnableOverMcp(read.reanchor!);
+ // The on-disk check says no: still flagged stale, no symbol form.
+ expect(nextToolCalls(stale, () => false).find((s) => s.cmd.startsWith("ix_read"))).toEqual({
+ cmd: "ix_read symbol=src/auth.ts:10-40",
+ why: "the top-ranked evidence",
+ stale: true,
+ });
+ // A fresh file carries neither key.
+ const fresh = nextToolCalls(bundle(
+ { name: "verify", kind: "function", path: "src/auth.ts" },
+ [],
+ [{ location: { path: "src/auth.ts", lineStart: 10, lineEnd: 40 }, refs: ["t"] }],
+ ));
+ for (const step of fresh) expect(Object.keys(step).sort()).toEqual(["cmd", "why"]);
+ });
+
it("close a file's bundle with its importers, by path", () => {
const steps = nextToolCalls(bundle({ name: "auth.ts", kind: "file", path: "src/auth.ts" }));
expect(steps[0].cmd).toBe("ix_neighbors symbol=src/auth.ts relation=imported_by");
@@ -224,7 +258,7 @@ describe("hints produced for the CLI", () => {
expect(roleHint(1)).toBe("1 test/fixture candidate hidden. Use --include-tests to include.");
expect(disambiguationHint("Use --pick <n> or --path to disambiguate.")).toBe("Use --pick <n> or --path to disambiguate.");
expect(nextReads({ evidence: [{ location: { path: "src/a.ts", lineStart: 1, lineEnd: 900 } }] } as never)).toEqual([
- "ix read src/a.ts:1-900",
+ { cmd: "ix read src/a.ts:1-900", stale: false },
]);
});
});
diff --git a/ix-cli/src/cli/__tests__/resolver-definitions-first.test.ts b/ix-cli/src/cli/__tests__/resolver-definitions-first.test.ts
index 60b44b1c..e88a1550 100644
--- a/ix-cli/src/cli/__tests__/resolver-definitions-first.test.ts
+++ b/ix-cli/src/cli/__tests__/resolver-definitions-first.test.ts
@@ -156,3 +156,52 @@ describe("scoreCandidate", () => {
expect(mod).toBeLessThan(fn);
});
});
+
+describe("resolver: --path finds a common name past a full window", () => {
+ /** A fake backend: weight order is array order; `scope` (if honoured) filters source_uri before `limit`. */
+ function scopedClient(nodes: ReturnType<typeof n>[], honoursScope: boolean) {
+ return {
+ search: vi.fn(async (_term: string, opts: { limit?: number; kind?: string; scope?: string }) => {
+ let matching = opts.kind ? nodes.filter((x) => x.kind === opts.kind) : nodes;
+ if (honoursScope && opts.scope) {
+ const want = opts.scope.toLowerCase();
+ matching = matching.filter((x) => x.provenance.sourceUri.toLowerCase().includes(want));
+ }
+ return matching.slice(0, opts.limit);
+ }),
+ workspaceSystem: vi.fn(async () => null),
+ } as any;
+ }
+
+ // 250 other files each declare an `add` that outweighs the one under --path,
+ // so the 200-row window is full before it arrives (the CL-20F stale `next`
+ // row `ix read add --path core-ingestion/src/role-classifier.ts`).
+ const crowd = Array.from({ length: 250 }, (_, i) => n(`other${i}`, "add", "function", `src/m${i}/util.ts`));
+ const wanted = n("wanted", "add", "function", "core-ingestion/src/role-classifier.ts");
+ const nodes = [...crowd, wanted];
+
+ it("resolves the declaration under --path when the backend applies scope before its limit", async () => {
+ const c = scopedClient(nodes, true);
+ const result = await resolveEntityFull(c, "add", ALL_KINDS, {
+ format: "json", path: "core-ingestion/src/role-classifier.ts",
+ } as any);
+ expect(result.resolved && result.entity.id).toBe("wanted");
+ expect(c.search).toHaveBeenCalledWith("add", expect.objectContaining({ scope: "core-ingestion/src/role-classifier.ts" }));
+ });
+
+ it("still misses cleanly on a backend that ignores scope", async () => {
+ const result = await resolveEntityFull(scopedClient(nodes, false), "add", ALL_KINDS, {
+ format: "json", path: "core-ingestion/src/role-classifier.ts",
+ } as any);
+ expect(result.resolved).toBe(false);
+ });
+
+ it("asks only once when the window is not full", async () => {
+ const c = scopedClient([crowd[0], wanted], true);
+ const result = await resolveEntityFull(c, "add", ALL_KINDS, {
+ format: "json", path: "core-ingestion/src/role-classifier.ts",
+ } as any);
+ expect(result.resolved && result.entity.id).toBe("wanted");
+ expect(c.search).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.ts
index 938c77ac..006c61ea 100644
--- a/ix-cli/src/cli/commands/context.ts
+++ b/ix-cli/src/cli/commands/context.ts
@@ -36,6 +36,7 @@ import {
type StartingPoint,
type SymbolHit,
} from "../explain/issue.js";
+import { symbolReadChecker } from "./read.js";
import { collectRelatedFiles, MAX_RELATED, type RelatedRef } from "../explain/related-files.js";
import { cachedBm25Ranker } from "../explain/bm25-cache.js";
import { collectTextReferences, gitRepoAccess, type TextSource } from "../explain/text-references.js";
@@ -2654,8 +2655,9 @@ function issueEvidence(issue: IssueBundleInput): EvidenceItem[] {
*/
export function llmNextLines(bundle: ContextBundle): string[] {
return forMcp()
- ? nextToolCalls(bundle).map((step) => llmLine("next", { cmd: step.cmd, why: step.why }))
- : nextReads(bundle).map((cmd) => llmLine("next", { cmd }));
+ ? nextToolCalls(bundle, onDiskSymbolCheck())
+ .map((step) => llmLine("next", { cmd: step.cmd, why: step.why, stale: step.stale, reanchor: step.reanchor }))
+ : renderedNextReads(bundle).map((row) => llmLine("next", { cmd: row.cmd, stale: row.stale || undefined }));
}
/**
@@ -2821,10 +2823,12 @@ export function renderBundle(bundle: ContextBundle, format: string): void {
}
}
- const reads = nextReads(bundle);
+ const reads = renderedNextReads(bundle);
if (reads.length > 0) {
renderSection("Next");
- for (const cmd of reads) console.log(` ${cmd}`);
+ for (const row of reads) {
+ console.log(` ${row.cmd}${row.stale ? " (stale: changed since last ingest; ix map to update)" : ""}`);
+ }
}
const trunc = bundle.truncation;
@@ -2987,6 +2991,56 @@ function targetLocation(facts: ContextFacts): Located | undefined {
return { path: facts.path, lineStart: facts.lineStart, lineEnd: facts.lineEnd };
}
+/** One suggested read: the command, and whether its file changed since the last ingest. */
+export interface NextRead {
+ cmd: string;
+ stale: boolean;
+}
+
+/**
+ * A name or path a shell passes through unquoted and unsplit. No `$` (it
+ * expands), no leading `#` (it starts a comment) and no leading `-` (it reads
+ * as an option); anything else falls back to the range form.
+ */
+const SHELL_SAFE_NAME = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
+const SHELL_SAFE_PATH = /^[A-Za-z0-9_./][A-Za-z0-9_./-]*$/;
+
+/** Whether `ix read <name> --path <file>` reads `name` and nothing else; see `readsOneSymbol`. */
+export type SymbolReadCheck = (name: string, path: string) => boolean;
+
+/**
+ * One on-disk check per workspace root (`symbolReadChecker`: one workspace
+ * walk, each row's answer kept), shared by every bundle rendered against that
+ * root within SYMBOL_CHECK_TTL_MS. Keyed on the root, not the bundle object,
+ * so a render that sizes several copies of a bundle (a budget-fitting loop
+ * measuring prefixes) still walks once. The short lifetime keeps a long-lived
+ * `ix mcp` process from answering from a stale walk after files change.
+ */
+const SYMBOL_CHECK_TTL_MS = 5_000;
+const symbolChecksByRoot = new Map<string, { check: SymbolReadCheck; at: number }>();
+
+/** `readsOneSymbol` against this workspace's files, as they are on disk now, memoised per root. */
+function onDiskSymbolCheck(): SymbolReadCheck {
+ // Lazy: the workspace root is resolved only when a stale row asks, so a
+ // bundle with no stale rows never loads workspace config for this.
+ let check: SymbolReadCheck | undefined;
+ return (name, path) => (check ??= checkerForRoot(resolveWorkspaceRoot()))(name, path);
+}
+
+function checkerForRoot(root: string): SymbolReadCheck {
+ const now = Date.now();
+ const cached = symbolChecksByRoot.get(root);
+ if (cached && now - cached.at < SYMBOL_CHECK_TTL_MS) return cached.check;
+ const check = symbolReadChecker(root);
+ symbolChecksByRoot.set(root, { check, at: now });
+ return check;
+}
+
+/** The `next` rows renderBundle prints: `nextReads` with the on-disk check, cheap to call again. */
+export function renderedNextReads(bundle: ContextBundle): NextRead[] {
+ return nextReads(bundle, 3, onDiskSymbolCheck());
+}
+
/**
* The reads worth making next, most valuable first.
*
@@ -2997,25 +3051,99 @@ function targetLocation(facts: ContextFacts): Located | undefined {
* byte the bundle spends, and an agent handed a path with no range opens the
* file.
*
+ * `stale` says the row's file changed since the last ingest, from the flags
+ * the bundle already carries. There the range is from the last ingest and
+ * points at the wrong lines, so a stale row that names a symbol is suggested
+ * as `ix read <name> --path <file>`, which re-anchors to where the name is
+ * declared on disk now. A fresh row keeps the range: it is exact, and it never
+ * fails, where a symbol read can (live, `ix read add --path
+ * core-ingestion/src/role-classifier.ts` exited 1: the resolver's name search
+ * never returned that `add`). The range form also stays for a row with no
+ * named symbol, a file or module, a name the shell would split, a name the
+ * bundle shows twice in one file, and a name `symbolRead` rejects. The bundle's
+ * entities are only the target's neighbours, so a second `save` in the same
+ * file need not be among them: renderBundle passes `onDiskSymbolCheck`, which
+ * asks the file itself (see `readsOneSymbol`), once per workspace root.
+ *
* Deduped, because a caller and a dependent are frequently the same function,
* and taken in evidence order, which is already the ranking — the target first,
* then its members, what it reaches, and what reaches it.
*/
-export function nextReads(bundle: ContextBundle, limit = 3): string[] {
+export function nextReads(
+ bundle: ContextBundle,
+ limit = 3,
+ symbolRead: SymbolReadCheck = () => true,
+): NextRead[] {
+ const rows = rowFreshness(bundle);
const seen = new Set<string>();
- const reads: string[] = [];
+ const reads: NextRead[] = [];
for (const item of bundle.evidence) {
const loc = item.location;
if (!loc?.path || loc.lineStart === undefined || loc.lineEnd === undefined) continue;
const range = `${loc.path}:${loc.lineStart}-${loc.lineEnd}`;
if (seen.has(range)) continue;
seen.add(range);
- reads.push(`ix read ${range}`);
+ const { stale, symbol } = rows(item, loc.path, symbolRead);
+ reads.push({ cmd: symbol ? `ix read ${symbol} --path ${loc.path}` : `ix read ${range}`, stale });
if (reads.length === limit) break;
}
return reads;
}
+/**
+ * For one evidence row at `path`: whether its file changed since the last
+ * ingest, and, for a stale row, the symbol name `read <name> --path <path>`
+ * re-anchors to — undefined wherever the range form must stand (see
+ * {@link nextReads} for each condition). Shared by the CLI and MCP closes.
+ */
+function rowFreshness(
+ bundle: ContextBundle,
+): (item: EvidenceItem, path: string, symbolRead: SymbolReadCheck) => { stale: boolean; symbol?: string } {
+ // `?? []`: a bundle restored from an older save, or built by hand, may carry
+ // evidence alone.
+ const entities = bundle.entities ?? [];
+ const byId = new Map<string, { id: string; name: string; kind: string; path?: string; stale?: boolean }>();
+ for (const e of entities) byId.set(e.id, e);
+ const target = bundle.target;
+ if (target?.id && !byId.has(target.id)) byId.set(target.id, target);
+ const stalePaths = new Set<string>();
+ for (const e of entities) if (e.stale && e.path) stalePaths.add(e.path);
+ const sameNameInFile = new Map<string, number>();
+ for (const e of byId.values()) {
+ if (!e.path) continue;
+ const key = `${e.path}\n${e.name}`;
+ sameNameInFile.set(key, (sameNameInFile.get(key) ?? 0) + 1);
+ }
+ return (item, path, symbolRead) => {
+ const ref = item.refs?.[0];
+ const entity = ref ? byId.get(ref) : undefined;
+ const stale = entity?.stale === true
+ || stalePaths.has(path)
+ || (path === target?.path && bundle.freshness?.stale === true);
+ const kind = entity?.kind.toLowerCase();
+ const named = stale
+ && entity !== undefined
+ && entity.name !== ""
+ && kind !== "file"
+ && kind !== "module"
+ && entity.path === path
+ && SHELL_SAFE_NAME.test(entity.name)
+ && SHELL_SAFE_PATH.test(path)
+ && sameNameInFile.get(`${path}\n${entity.name}`) === 1
+ // Last: the only check that may touch the disk.
+ && symbolRead(entity.name, path);
+ return named ? { stale, symbol: entity.name } : { stale };
+ };
+}
+
+/** One MCP next step; `stale` and `reanchor` appear only on a stale read (see {@link nextToolCalls}). */
+export interface NextToolCall {
+ cmd: string;
+ why: string;
+ stale?: true;
+ reanchor?: string;
+}
+
/** Longest range a suggested read may span; past it the read covers its head only. */
export const NEXT_READ_MAX_LINES = 120;
@@ -3032,10 +3160,18 @@ export const NEXT_READ_MAX_LINES = 120;
*
* Every call names core tools only, and pins the target's file with `path=` so
* an ambiguous name resolves to the entity this bundle was built for.
+ *
+ * The read step carries `stale: true` when its file changed since the last
+ * ingest (its range is from the last ingest), and then, if the symbol re-anchors
+ * safely (the same checks as {@link nextReads}), `reanchor`: an `ix_read
+ * symbol=<name> path=<file>` call that lands on where the name is now.
*/
-export function nextToolCalls(bundle: ContextBundle): Array<{ cmd: string; why: string }> {
+export function nextToolCalls(
+ bundle: ContextBundle,
+ symbolRead: SymbolReadCheck = () => true,
+): NextToolCall[] {
const { name, kind, path } = bundle.target;
- const steps: Array<{ cmd: string; why: string }> = [];
+ const steps: NextToolCall[] = [];
const isFile = kind.toLowerCase() === "file";
// A file resolves by its path; a symbol by name, pinned to its file.
const symbol = isFile ? (path ?? name) : name;
@@ -3048,16 +3184,22 @@ export function nextToolCalls(bundle: ContextBundle): Array<{ cmd: string; why:
);
steps.push({ cmd: suggest.impact(symbol, pin), why: "what a change here reaches, before you edit it" });
- const read = bundle.evidence.find(
+ const readItem = bundle.evidence.find(
(item) => item.location?.path && item.location.lineStart !== undefined && item.location.lineEnd !== undefined,
- )?.location;
- if (read?.lineStart !== undefined && read.lineEnd !== undefined) {
+ );
+ const read = readItem?.location;
+ if (readItem && read?.lineStart !== undefined && read.lineEnd !== undefined) {
const end = Math.min(read.lineEnd, read.lineStart + NEXT_READ_MAX_LINES - 1);
+ // Additive: the range call is unchanged; a stale file adds `stale` and,
+ // where the name re-anchors safely, the symbol form beside it.
+ const { stale, symbol } = rowFreshness(bundle)(readItem, read.path, symbolRead);
steps.push({
cmd: toolCall("ix_read", { symbol: `${read.path}:${read.lineStart}-${end}` }),
why: end < read.lineEnd
? `first ${NEXT_READ_MAX_LINES} of ${read.lineEnd - read.lineStart + 1} lines of the top-ranked evidence`
: "the top-ranked evidence",
+ ...(stale ? { stale: true as const } : {}),
+ ...(symbol ? { reanchor: toolCall("ix_read", { symbol, path: read.path }) } : {}),
});
}
return steps;
diff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.ts
index 617f9f5a..1d38e580 100644
--- a/ix-cli/src/cli/commands/read.ts
+++ b/ix-cli/src/cli/commands/read.ts
@@ -10,7 +10,8 @@ import { absoluteFromSourceUri, isReadablePath, readableRoots, resolveWorkspaceR
import { resolveEntityFull, activeReadScope, ensureReadScope } from "../resolve.js";
import { stderr } from "../stderr.js";
import { isFileStale } from "../stale.js";
-import { anchorSpan, bareName } from "../edge-sites.js";
+import { anchorSpan, bareName, countDeclarations } from "../edge-sites.js";
+import { readBoundedFile } from "../bounded-read.js";
import { relativePath, printJson } from "../format.js";
import { llmError, llmLine, llmShortId, printLlmLines } from "../llm.js";
import { parsePickOption } from "../options.js";
@@ -707,8 +708,7 @@ interface LocalMatches {
* that distinction to decide whether it may skip the backend fallback.
*/
function findLocalBasenameMatches(root: string, target: string, limit = 25): LocalMatches {
- const wanted = path.basename(target);
- const wantedNoExt = wanted.replace(/\.[^.]+$/, "");
+ const matches = basenameMatcher(target);
const paths: string[] = [];
const stack = [root];
let budget = WALK_ENTRY_BUDGET;
@@ -729,8 +729,7 @@ function findLocalBasenameMatches(root: string, target: string, limit = 25): Loc
continue;
}
if (!entry.isFile()) continue; // symlinks are not followed
- const nameNoExt = entry.name.replace(/\.[^.]+$/, "");
- if (entry.name === wanted || nameNoExt === wanted || nameNoExt === wantedNoExt) {
+ if (matches(entry.name)) {
paths.push(path.join(current, entry.name));
if (paths.length >= limit) return { paths, exhaustive: true };
}
@@ -739,6 +738,181 @@ function findLocalBasenameMatches(root: string, target: string, limit = 25): Loc
return { paths, exhaustive: stack.length === 0 };
}
+/** Whether a file named `entryName` is one `read` would open for `target`. */
+function basenameMatcher(target: string): (entryName: string) => boolean {
+ const wanted = path.basename(target);
+ const wantedNoExt = wanted.replace(/\.[^.]+$/, "");
+ return (entryName) => {
+ const nameNoExt = entryName.replace(/\.[^.]+$/, "");
+ return entryName === wanted || nameNoExt === wanted || nameNoExt === wantedNoExt;
+ };
+}
+
+/** The workspace's files, from one walk; `exhaustive` is false when it ran out of budget. */
+export interface WorkspaceFiles {
+ paths: string[];
+ exhaustive: boolean;
+}
+
+/**
+ * Every file under `root`, by the walk `findLocalBasenameMatches` makes (same
+ * ignored directories, same entry budget, symlinks not followed). Listed once
+ * so one bundle's symbol suggestions share a single walk instead of one each.
+ */
+export function listWorkspaceFiles(root: string): WorkspaceFiles {
+ const paths: string[] = [];
+ const stack = [root];
+ let budget = WALK_ENTRY_BUDGET;
+ while (stack.length > 0) {
+ const current = stack.pop()!;
+ let entries: fs.Dirent[];
+ try {
+ entries = fs.readdirSync(current, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const entry of entries) {
+ if (--budget <= 0) return { paths, exhaustive: false };
+ if (entry.isDirectory()) {
+ if (entry.name.startsWith(".") || WALK_IGNORE_DIRS.has(entry.name)) continue;
+ stack.push(path.join(current, entry.name));
+ continue;
+ }
+ if (!entry.isFile()) continue;
+ paths.push(path.join(current, entry.name));
+ }
+ }
+ return { paths, exhaustive: true };
+}
+
+/**
+ * Whether `a` and `b` name the same file. Resolved first, and compared without
+ * case on Windows, where `C:\Repo\x.ts` and `c:/repo/x.ts` are one file: a
+ * plain `!==` there made a file collide with itself, so the symbol form was
+ * never suggested.
+ */
+export function sameFsPath(a: string, b: string, platform: NodeJS.Platform = process.platform): boolean {
+ if (platform === "win32") {
+ return path.win32.resolve(a).toLowerCase() === path.win32.resolve(b).toLowerCase();
+ }
+ return path.posix.resolve(a) === path.posix.resolve(b);
+}
+
+/**
+ * Whether the workspace holds a file that would turn `ix read <name> --path
+ * <file>` away from the `name` declared in `file` (at `abs`):
+ *
+ * - a file named `name`: Step 3 above opens it before any symbol lookup, and
+ * --path does not stop it;
+ * - another file whose path contains `file`: --path is a substring test on the
+ * graph's source path (resolve.ts), so `src/util.ts` also keeps
+ * `lib/src/util.ts` and `src/util.tsx`, and a `name` declared there too
+ * leaves the lookup to return candidates or the wrong one.
+ *
+ * Says yes when the walk ran out of budget, since then neither is ruled out.
+ * Files outside the workspace (another repo in the same system) are not seen.
+ */
+function suggestionCollides(files: WorkspaceFiles, name: string, abs: string, file: string): boolean {
+ if (!files.exhaustive) return true;
+ const named = basenameMatcher(name);
+ const needle = file.replace(/\\/g, "/").replace(/^\.\//, "").toLowerCase();
+ for (const other of files.paths) {
+ if (named(path.basename(other))) return true;
+ if (other.replace(/\\/g, "/").toLowerCase().includes(needle) && !sameFsPath(other, abs)) return true;
+ }
+ return false;
+}
+
+/** Past this a file is not read just to vet a suggestion; the range form stands. */
+const SUGGEST_MAX_FILE_BYTES = 2 * 1024 * 1024;
+
+/**
+ * A superset of what ingest's role classifier (core-ingestion
+ * role-classifier.ts) calls test or fixture: any one signal counts here, where
+ * the classifier weighs them. Too broad only costs a symbol suggestion.
+ */
+const TEST_LIKE_DIR = /(?:^|\/)(?:__tests__|__fixtures__|tests?|specs?|fixtures?|testdata|[^/]*\.tests?)(?:\/)/i;
+const TEST_LIKE_FILE = /(?:^|[._-])(?:tests?|spec|fixtures?|mocks?|stubs?|fakes?|samples?|conftest)(?:[._-]|$)/i;
+/** Case-sensitive, as in the classifier: `FooTest.java`, `FakeClock.java`, but not `latest.ts`. */
+const TEST_LIKE_CLASS_FILE = /(?:Tests?|Spec)\.[^.]+$|^(?:Stub|Fake|Mock)[A-Z]/;
+const TEST_LIKE_IMPORT = new RegExp([
+ /from ['"](?:jest|vitest|mocha|chai|sinon|jasmine|@testing-library)/.source,
+ /require\(['"](?:jest|vitest|mocha|chai|sinon|jasmine)['"]\)/.source,
+ /(?:import|from)\s+(?:unittest|pytest)/.source,
+ /import\s+(?:org\.junit|org\.testng|io\.mockk|org\.mockito|org\.scalatest|munit|zio\.test)/.source,
+ /require\s+['"](?:rspec|minitest)['"]/.source,
+ /using\s+(?:NUnit\.Framework|Xunit|Microsoft\.VisualStudio\.TestTools\.UnitTesting)/.source,
+ /^import\s*(?:\([^)]*"testing"|"testing")/.source,
+].join("|"), "m");
+
+/** Whether ingest may have filed `file` as a test or a fixture. */
+function mayBeTestOrFixture(file: string, source: string): boolean {
+ const normalized = file.replace(/\\/g, "/");
+ return TEST_LIKE_DIR.test(normalized)
+ || TEST_LIKE_FILE.test(path.posix.basename(normalized))
+ || TEST_LIKE_CLASS_FILE.test(path.posix.basename(normalized))
+ || TEST_LIKE_IMPORT.test(source);
+}
+
+/**
+ * Whether `ix read <name> --path <file>` would show the one declaration of
+ * `name` in `file`, so `ix context` may suggest it instead of a line range.
+ *
+ * No when `file` resolves outside every readable workspace root (`ix read`
+ * would refuse it, and a `..` in a graph path must not make this open it).
+ * No when a workspace file has `name` as its basename, or another workspace
+ * file's path contains `file` (see `suggestionCollides`). No unless the
+ * file on disk declares `name` exactly once: two (`save` in two classes) leave
+ * the lookup to return candidates or the other one, and none leaves the stale
+ * re-anchor nothing to find. A bundle's entities are only the target's graph
+ * neighbours, so they cannot answer this; the file can. No for a test or
+ * fixture file: the resolver drops test and fixture symbols whenever a
+ * production one shares the name, before --path is applied, so the read finds
+ * nothing and exits 1. Unreadable, missing or oversized files say no.
+ *
+ * One-off; a caller vetting several rows should use `symbolReadChecker`, which
+ * walks the workspace once for all of them.
+ */
+export function readsOneSymbol(root: string, name: string, file: string): boolean {
+ return symbolReadChecker(root)(name, file);
+}
+
+/**
+ * `readsOneSymbol` for many rows against one workspace: the workspace is
+ * walked at most once (lazily, only when a row gets past the per-file checks),
+ * and each (name, file) is answered once, so calling it again — from a
+ * budget-fitting loop that re-renders the same bundle — costs a map lookup.
+ * `listFiles` is injectable for tests.
+ */
+export function symbolReadChecker(
+ root: string,
+ listFiles: (root: string) => WorkspaceFiles = listWorkspaceFiles,
+): (name: string, file: string) => boolean {
+ let files: WorkspaceFiles | undefined;
+ const answers = new Map<string, boolean>();
+ const check = (name: string, file: string): boolean => {
+ const abs = absoluteFromSourceUri(file, root);
+ if (!isReadablePath(abs, root)) return false;
+ // One open, fstat and read on the same handle (CodeQL js/file-system-race).
+ const text = readBoundedFile(abs, { maxBytes: SUGGEST_MAX_FILE_BYTES });
+ if (text === null) return false;
+ if (mayBeTestOrFixture(file, text)) return false;
+ if (countDeclarations(text.split("\n"), bareName(name)) !== 1) return false;
+ // Last: the file read above is cheaper than the walk of the workspace.
+ files ??= listFiles(root);
+ return !suggestionCollides(files, name, abs, file);
+ };
+ return (name, file) => {
+ const key = `${name}\n${file}`;
+ let answer = answers.get(key);
+ if (answer === undefined) {
+ answer = check(name, file);
+ answers.set(key, answer);
+ }
+ return answer;
+ };
+}
+
/** Filter nodes to those whose filename actually matches the target basename. */
function filterMatches(
nodes: any[],
diff --git a/ix-cli/src/cli/edge-sites.ts b/ix-cli/src/cli/edge-sites.ts
index b7f2d1b8..9c820c64 100644
--- a/ix-cli/src/cli/edge-sites.ts
+++ b/ix-cli/src/cli/edge-sites.ts
@@ -107,6 +107,18 @@ function declRe(name: string): RegExp {
);
}
+/**
+ * How many lines look like they declare `name`, by the same test `anchorSpan`
+ * re-anchors with. More than one means a re-anchor could land on the wrong
+ * one; none means it has nothing to land on.
+ */
+export function countDeclarations(lines: string[], name: string): number {
+ const def = declRe(name);
+ let count = 0;
+ for (const line of lines) if (def.test(line)) count++;
+ return count;
+}
+
const COMMENT_ONLY = /^\s*(?:\/\/|\/\*|\*|#(?!include|import)|--|;)/;
/** The site's text: its line, plus the lines of a call left open across them. */
diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.ts
index e362524e..ac1d5560 100644
--- a/ix-cli/src/cli/resolve.ts
+++ b/ix-cli/src/cli/resolve.ts
@@ -489,6 +489,25 @@ export async function resolveEntityFull(
});
const windowFull = nodes.length >= searchLimit;
+ // `--path` is applied client-side, after the backend has cut its
+ // weight-ordered window. A common name (`add`, `get`) declared in hundreds
+ // of files can fill that window before the row under --path arrives, and
+ // the read then misses a name the file plainly declares. Only when the
+ // window came back full, ask again with the path as `scope`, which the
+ // backend applies before its limit. An older backend ignores `scope` and
+ // returns the same window, so the merge changes nothing there.
+ if (effectivePath && windowFull) {
+ const scoped = await client.search(symbol, {
+ limit: searchLimit,
+ kind: kindFilter,
+ nameOnly: true,
+ workspaceId,
+ systemId,
+ scope: effectivePath.replace(/\\/g, "/"),
+ });
+ nodes = mergeById(nodes, scoped);
+ }
+
// The backend orders its window by weight — every exact name before every
// partial one — so when a name is imported in dozens of files, the window is
// all imports and the file that DEFINES it (`borderStylesReset.js`, a