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): callers text-search fallback honours --offset (HR-02A)

KageBinary37b8eafe4dc2
diff --git a/ix-cli/src/cli/__tests__/callers-text-fallback-paging.test.ts b/ix-cli/src/cli/__tests__/callers-text-fallback-paging.test.ts
new file mode 100644
index 00000000..c1c54ecc
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/callers-text-fallback-paging.test.ts
@@ -0,0 +1,145 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Command } from "commander";
+
+import { registerCallersCommand, TEXT_FALLBACK_PAGE } from "../commands/callers.js";
+
+/**
+ * With no graph callers, `ix callers` falls back to a text search. That
+ * fallback used to print a fixed first 10 rows whatever --offset said, so a
+ * caller following the paging hint saw page 1 again. It now pages the same
+ * ranked list the way the graph path does.
+ */
+
+const { expand, rgMatches } = vi.hoisted(() => ({ expand: vi.fn(), rgMatches: { value: [] as Array<[string, number, string]> } }));
+
+vi.mock("../../client/factory.js", () => ({
+ createClient: () => ({ expand: (...args: unknown[]) => expand(...args) }),
+}));
+vi.mock("../resolve.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../resolve.js")>(),
+ resolveFileOrReport: async () => ({ id: "11111111-0000-0000-0000-000000000000", kind: "function", name: "foo", resolutionMode: "exact" }),
+ printResolved: () => {},
+}));
+vi.mock("../graph-health.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../graph-health.js")>(),
+ checkGraphHealth: async () => ({ status: "healthy" }),
+}));
+vi.mock("../config.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../config.js")>(),
+ resolveWorkspaceRoot: () => "/ws",
+}));
+vi.mock("node:child_process", async (importOriginal) => ({
+ ...await importOriginal<typeof import("node:child_process")>(),
+ // promisify(execFile) resolves with the callback's value.
+ execFile: (_file: string, _args: string[], _opts: unknown, cb: (err: unknown, out: { stdout: string; stderr: string }) => void) => {
+ // Emitted in reverse order: rg's order varies between runs and the command must not depend on it.
+ const stdout = [...rgMatches.value].reverse().map(([path, line, text]) => JSON.stringify({
+ type: "match", data: { path: { text: path }, line_number: line, lines: { text: `${text}\n` } },
+ })).join("\n");
+ cb(null, { stdout, stderr: "" });
+ },
+}));
+
+/** `count` call sites of foo, one per file. */
+function calls(count: number): Array<[string, number, string]> {
+ return Array.from({ length: count }, (_, i) => [`src/f${String(i).padStart(2, "0")}.ts`, i + 1, `foo(${i});`]);
+}
+
+async function run(args: string[]): Promise<{ out: string[]; err: string[] }> {
+ const program = new Command().name("ix").exitOverride();
+ registerCallersCommand(program);
+ const out: string[] = [];
+ const err: string[] = [];
+ vi.spyOn(console, "log").mockImplementation((...parts) => { out.push(parts.join(" ")); });
+ vi.spyOn(process.stderr, "write").mockImplementation((chunk: string | Uint8Array) => { err.push(String(chunk)); return true; });
+ await program.parseAsync(["callers", "foo", ...args], { from: "user" });
+ return { out, err };
+}
+
+const refs = (out: string[]) => out.filter((l) => l.startsWith("ref "));
+
+describe("ix callers text fallback paging", () => {
+ beforeEach(() => {
+ expand.mockReset();
+ expand.mockResolvedValue({ nodes: [], edges: [] });
+ });
+ afterEach(() => vi.restoreAllMocks());
+
+ it("page 1 and page 2 make up the full list with no overlap", async () => {
+ rgMatches.value = calls(15);
+ const p1 = await run(["--format", "llm"]);
+ const p2 = await run(["--offset", "10", "--format", "llm"]);
+
+ expect(p1.out[0]).toBe("callers target=foo source=text shown=10 total=15");
+ expect(p1.out).toContain(
+ 'diagnostic code=results_truncated next_offset=10 message="15 text candidates; showing 10. next: ix callers --format llm --offset 10 foo"',
+ );
+ expect(p2.out[0]).toBe("callers target=foo source=text offset=10 shown=5 total=15");
+ expect(p2.out.some((l) => l.includes("results_truncated") || l.includes("offset_past_end"))).toBe(false);
+
+ const all = [...refs(p1.out), ...refs(p2.out)];
+ expect(refs(p1.out)).toHaveLength(TEXT_FALLBACK_PAGE);
+ expect(new Set(all).size).toBe(15);
+ expect(all.map((l) => /path=(\S+)/.exec(l)?.[1])).toEqual(calls(15).map(([p]) => p));
+ });
+
+ it("json pages carry offset, truncated and nextOffset", async () => {
+ rgMatches.value = calls(15);
+ const p1 = JSON.parse((await run(["--format", "json"])).out.join("\n"));
+ const p2 = JSON.parse((await run(["--offset", "10", "--format", "json"])).out.join("\n"));
+ expect(p1.summary).toEqual({ candidatesFound: 15, candidatesReturned: 10, truncated: true, nextOffset: 10 });
+ expect(p2.summary).toEqual({ candidatesFound: 15, candidatesReturned: 5, offset: 10 });
+ const lines = [...p1.results, ...p2.results].map((r: { line: number }) => r.line);
+ expect(lines).toEqual(Array.from({ length: 15 }, (_, i) => i + 1));
+ });
+
+ it("text page 1 points at page 2", async () => {
+ rgMatches.value = calls(15);
+ const { err } = await run([]);
+ expect(err.join("")).toContain("(15 total candidates; showing 10) next: ix callers --offset 10 foo");
+ const p2 = await run(["--offset", "10"]);
+ expect(p2.out.filter((l) => l.includes("foo("))).toHaveLength(5);
+ expect(p2.err.join("")).toContain("(15 total candidates; showing 11-15)");
+ });
+
+ it("an offset past the end says so in every format", async () => {
+ rgMatches.value = calls(15);
+ const llm = await run(["--offset", "15", "--format", "llm"]);
+ expect(llm.out[0]).toBe("callers target=foo source=text offset=15 shown=0 total=15");
+ expect(llm.out).toContain('diagnostic code=offset_past_end message="15 text candidates; --offset 15 is past the end."');
+ expect(llm.out.some((l) => l.includes("no_edges") || l.includes("results_truncated"))).toBe(false);
+
+ const json = JSON.parse((await run(["--offset", "40", "--format", "json"])).out.join("\n"));
+ expect(json.results).toEqual([]);
+ expect(json.diagnostics.map((d: { code: string }) => d.code)).toEqual(["text_fallback_used", "offset_past_end"]);
+
+ const text = await run(["--offset", "15"]);
+ expect(text.out).toEqual(["15 text candidates; --offset 15 is past the end."]);
+ });
+
+ it("the last full page is not called past the end", async () => {
+ rgMatches.value = calls(20);
+ const llm = await run(["--offset", "10", "--format", "llm"]);
+ expect(refs(llm.out)).toHaveLength(10);
+ expect(llm.out.some((l) => l.includes("offset_past_end") || l.includes("results_truncated"))).toBe(false);
+ });
+
+ it("output without --offset is unchanged when the list fits one page", async () => {
+ rgMatches.value = calls(3);
+ expect((await run(["--format", "llm"])).out).toEqual([
+ "callers target=foo source=text shown=3 total=3",
+ 'diagnostic code=text_fallback_used message="No graph-backed CALLS/REFERENCES edges; showing text matches."',
+ "ref path=src/f00.ts line=1 snippet=foo(0);",
+ "ref path=src/f01.ts line=2 snippet=foo(1);",
+ "ref path=src/f02.ts line=3 snippet=foo(2);",
+ ]);
+ const json = JSON.parse((await run(["--format", "json"])).out.join("\n"));
+ expect(json.summary).toEqual({ candidatesFound: 3, candidatesReturned: 3 });
+ expect(json.diagnostics.map((d: { code: string }) => d.code)).toEqual(["text_fallback_used"]);
+ const text = await run([]);
+ expect(text.out).toHaveLength(3);
+ expect(text.err.join("")).not.toContain("total candidates");
+ });
+});
diff --git a/ix-cli/src/cli/commands/callers.ts b/ix-cli/src/cli/commands/callers.ts
index 67d93da7..330345c3 100644
--- a/ix-cli/src/cli/commands/callers.ts
+++ b/ix-cli/src/cli/commands/callers.ts
@@ -6,7 +6,7 @@ import type { Command } from "commander";
import chalk from "chalk";
import { createClient } from "../../client/factory.js";
import { resolveWorkspaceRoot } from "../config.js";
-import { expandCapped, formatEdgeResults, printJson, relativePath, sliceEdgeResults, type Diagnostic } from "../format.js";
+import { expandCapped, formatEdgeResults, printJson, relativePath, sliceEdgeResults, sliceRanked, truncationHint, type Diagnostic } from "../format.js";
import { checkGraphHealth, graphHealthProse, isUnhealthy, type GraphHealth } from "../graph-health.js";
import { parsePickOption } from "../options.js";
import { nextPageCommand, OFFSET_FLAG, parseOffset } from "../paging.js";
@@ -24,6 +24,9 @@ const execFileAsync = promisify(execFile);
* never a regex or a flag (a symbol named `--pre=x` would otherwise run an rg
* preprocessor). `--` ends the options before the root.
*/
+/** Rows per page of the text fallback. --limit does not apply to it. */
+export const TEXT_FALLBACK_PAGE = 10;
+
export function callersTextSearchArgs(name: string, root: string): string[] {
return ["--json", "--max-count", "10", "-F", "-e", name, "--", root];
}
@@ -76,7 +79,7 @@ export function registerCallersCommand(program: Command): void {
const remedy = health.fix ?? "ix ingest --force --recursive .";
if (result.nodes.length === 0) {
- // Fallback to text search. It shows a fixed 10 rows and ignores --offset.
+ // Fallback to text search: pages of TEXT_FALLBACK_PAGE rows, --offset honoured.
try {
const root = resolveWorkspaceRoot();
// The timeout bounds a search that rg could otherwise run for ever.
@@ -114,18 +117,32 @@ export function registerCallersCommand(program: Command): void {
target.name,
).map(({ snippet: _snippet, ...r }) => r);
const candidatesFound = ranked.length;
- const textResults = ranked.slice(0, 10);
+ // The ranking is a stable sort of a sorted list, so pages neither
+ // overlap nor skip a row.
+ const page = sliceRanked(ranked, TEXT_FALLBACK_PAGE, undefined, offset);
+ if (page.nextOffset !== undefined) page.next = nextPageCommand(cmd, [symbol], page.nextOffset);
+ const textResults = page.rows;
+ const pastEnd = candidatesFound > 0 && textResults.length === 0;
+ const pastEndMessage = `${candidatesFound} text candidates; --offset ${offset} is past the end.`;
+ const pageHint = page.truncated ? truncationHint(page, "text candidates") : undefined;
- if (textResults.length > 0) {
+ if (candidatesFound > 0) {
if (opts.format === "llm") {
console.log(llmLine("callers", [
["target", target.name], ["source", "text"],
+ ["offset", offset > 0 ? offset : undefined],
["shown", textResults.length], ["total", candidatesFound],
]));
console.log(llmLine("diagnostic", [
["code", "text_fallback_used"],
["message", "No graph-backed CALLS/REFERENCES edges; showing text matches."],
]));
+ if (pageHint) {
+ console.log(llmLine("diagnostic", [
+ ["code", "results_truncated"], ["next_offset", page.nextOffset], ["message", pageHint],
+ ]));
+ }
+ if (pastEnd) console.log(llmLine("diagnostic", [["code", "offset_past_end"], ["message", pastEndMessage]]));
for (const d of health.diagnostics ?? []) {
console.log(llmLine("diagnostic", [["code", d.code], ["message", d.message]]));
}
@@ -142,12 +159,20 @@ export function registerCallersCommand(program: Command): void {
summary: {
candidatesFound,
candidatesReturned: textResults.length,
+ ...(offset > 0 ? { offset } : {}),
+ ...(page.truncated ? { truncated: true } : {}),
+ ...(page.nextOffset !== undefined ? { nextOffset: page.nextOffset } : {}),
},
diagnostics: [{
code: "text_fallback_used",
message: `No graph-backed CALLS/REFERENCES edges found. If files were ingested before extraction was added, run: ${remedy}`,
- }, ...(health.diagnostics ?? [])],
+ },
+ ...(pageHint ? [{ code: "results_truncated", message: pageHint }] : []),
+ ...(pastEnd ? [{ code: "offset_past_end", message: pastEndMessage }] : []),
+ ...(health.diagnostics ?? [])],
});
+ } else if (pastEnd) {
+ console.log(pastEndMessage);
} else {
bannerOverRows(health, opts.format, textResults.length);
stderr(chalk.dim("No graph-backed CALLS/REFERENCES edges found. Showing text-based candidate usages."));
@@ -156,8 +181,10 @@ export function registerCallersCommand(program: Command): void {
const snippet = r.attrs?.snippet ?? "";
console.log(` ${chalk.dim(r.name)} ${snippet}`);
}
- if (candidatesFound > 10) {
- stderr(chalk.dim(`\n (${candidatesFound} total candidates; showing 10)`));
+ if (page.truncated || offset > 0) {
+ const range = offset > 0 ? `${offset + 1}-${offset + textResults.length}` : `${textResults.length}`;
+ const next = page.next ?? (page.nextOffset !== undefined ? `--offset ${page.nextOffset}` : undefined);
+ stderr(chalk.dim(`\n (${candidatesFound} total candidates; showing ${range})${next ? ` next: ${next}` : ""}`));
}
}
return;