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
fix(trace): validate --depth/--cap and label --to steps with their predicate (CL-20G) (#836)
Ian Hock699bead13375
diff --git a/ix-cli/src/cli/__tests__/llm-tier2.test.ts b/ix-cli/src/cli/__tests__/llm-tier2.test.tsindex 2cc53537..2eb07be9 100644--- a/ix-cli/src/cli/__tests__/llm-tier2.test.ts+++ b/ix-cli/src/cli/__tests__/llm-tier2.test.ts@@ -84,6 +84,19 @@ describe("trace llm renderers", () => {]);});+ it("renderTracePathLlm labels steps with the predicate that reached them", () => {+ const lines = renderTracePathLlm({ name: "A", kind: "function" }, { name: "C", kind: "function" }, "mixed", [+ { id: "a", name: "A", kind: "function" },+ { id: "b", name: "B", kind: "function", via: "CALLS" },+ { id: "c", name: "C", kind: "function", via: "IMPORTS", reversed: true },+ ]);+ expect(lines.slice(1)).toEqual([+ "step name=A kind=function",+ "step name=B kind=function via=CALLS",+ "step name=C kind=function via=IMPORTS reversed=true",+ ]);+ });+it("renderTracePathLlm emits a no_path diagnostic when empty", () => {const lines = renderTracePathLlm({ name: "A", kind: "function" }, { name: "B", kind: "function" }, "mixed", []);expect(lines[1]).toBe('diagnostic code=no_path message="No route found from A to B."');diff --git a/ix-cli/src/cli/__tests__/trace-completeness.test.ts b/ix-cli/src/cli/__tests__/trace-completeness.test.tsindex 73103301..efc85088 100644--- a/ix-cli/src/cli/__tests__/trace-completeness.test.ts+++ b/ix-cli/src/cli/__tests__/trace-completeness.test.ts@@ -161,3 +161,63 @@ describe('searchPath cut semantics', () => {expect(cycle).toEqual({ path: null, cut: false });});});++// ---------------------------------------------------------------------------+// searchPath — the predicate each step was reached by+// ---------------------------------------------------------------------------++describe('searchPath step predicates', () => {+ function edgeClient(responses: Record<string, Record<string, { nodes: any[]; edges: any[] }>>) {+ return {+ async expand(id: string, opts?: { direction?: string }) {+ return responses[id]?.[opts?.direction ?? 'out'] ?? { nodes: [], edges: [] };+ },+ };+ }++ it('picks the first predicate in request order when several join the same pair', async () => {+ const client = edgeClient({+ A: { out: { nodes: [n('b')], edges: [+ { src: 'A', dst: 'b', predicate: 'IMPORTS' },+ { src: 'A', dst: 'b', predicate: 'CALLS' },+ ] } },+ });+ const found = await searchPath(client as any, 'A', 'b', ['CALLS', 'IMPORTS'], 10, 10);+ expect(found.path?.[1]).toEqual({ id: 'b', name: 'B', kind: 'file', via: 'CALLS' });+ });++ it('marks a step reached against its edge direction as reversed', async () => {+ const client = edgeClient({+ A: { in: { nodes: [n('b')], edges: [{ src: 'b', dst: 'A', predicate: 'IMPORTS' }] } },+ });+ const found = await searchPath(client as any, 'A', 'b', ['CALLS', 'IMPORTS'], 10, 10);+ expect(found.path?.[1]).toEqual({ id: 'b', name: 'B', kind: 'file', via: 'IMPORTS', reversed: true });+ });++ it('ignores a stray edge that does not touch the expanded node', async () => {+ const client = edgeClient({+ A: { out: { nodes: [n('x'), n('b')], edges: [+ { src: 'x', dst: 'b', predicate: 'CALLS' },+ { src: 'A', dst: 'x', predicate: 'CALLS' },+ ] } },+ });+ const found = await searchPath(client as any, 'A', 'b', ['CALLS'], 10, 10);+ expect(found.path?.map((p) => p.id)).toEqual(['A', 'b']);+ expect(found.path?.[1]).toEqual({ id: 'b', name: 'B', kind: 'file' });+ expect(found.path?.[0].via).toBeUndefined();+ });++ it('keeps the old result shape, with no via key, when the expansion carries no edges', async () => {+ const client = makeClient({ A: { out: [n('b')] }, b: { in: [n('c')] } });+ const found = await searchPath(client as any, 'A', 'c', ['CALLS'], 10, 10);+ expect(found).toEqual({+ path: [+ { id: 'A', name: '', kind: '' },+ { id: 'b', name: 'B', kind: 'file' },+ { id: 'c', name: 'C', kind: 'file' },+ ],+ cut: false,+ });+ expect(found.path?.some((p) => 'via' in p || 'reversed' in p)).toBe(false);+ });+});diff --git a/ix-cli/src/cli/__tests__/trace-path-budgets.test.ts b/ix-cli/src/cli/__tests__/trace-path-budgets.test.tsindex 53e33202..ea0d5b91 100644--- a/ix-cli/src/cli/__tests__/trace-path-budgets.test.ts+++ b/ix-cli/src/cli/__tests__/trace-path-budgets.test.ts@@ -153,3 +153,130 @@ describe("trace completeness in command output", () => {expect(codes(out)).toEqual(["truncated"]);});});++describe("trace --depth/--cap validation", () => {+ beforeEach(() => {+ expand.mockReset().mockResolvedValue({ nodes: [], edges: [] });+ });+ afterEach(() => vi.restoreAllMocks());++ // These harnesses register the command without the root preAction hook, so+ // the action's own parse is what stands between a typo and a NaN bound.+ it.each([+ ["--depth", "abc"],+ ["--cap", "1e3"],+ ["--depth", "-1"],+ ["--cap", "10abc"],+ ])("rejects %s %s in --to mode before any expansion", async (flag, value) => {+ await expect(run([flag, value])).rejects.toThrow(/must be a non-negative integer/);+ expect(expand).not.toHaveBeenCalled();+ });++ it("rejects a bad --depth in directional mode before any expansion", async () => {+ await expect(runTrace(["--depth", "abc"])).rejects.toThrow(/must be a non-negative integer/);+ expect(expand).not.toHaveBeenCalled();+ });+});++describe("trace --to predicate labels", () => {+ async function runPath(args: string[], format = "json") {+ const program = new Command().name("ix").exitOverride();+ registerTraceCommand(program);+ const output: string[] = [];+ vi.spyOn(console, "log").mockImplementation((...parts) => { output.push(parts.join(" ")); });+ await program.parseAsync(["trace", "A", "--to", "C", ...args, "--format", format], { from: "user" });+ return output.join("\n");+ }++ // A --CALLS--> B, and C --IMPORTS--> B (so C is reached walking "in" from B).+ // B's in-expansion also carries a stray CONTAINS edge between two of its+ // neighbours, which must not label either step.+ beforeEach(() => {+ expand.mockReset().mockImplementation(async (id: string, opts: { direction: string }) => {+ const fn = (name: string) => ({ id: name, name, kind: "function" });+ if (id === "A" && opts.direction === "out") {+ return { nodes: [fn("B")], edges: [{ src: "A", dst: "B", predicate: "CALLS" }] };+ }+ if (id === "B" && opts.direction === "in") {+ return {+ nodes: [fn("A"), fn("C")],+ edges: [+ { src: "A", dst: "C", predicate: "CONTAINS" },+ { src: "A", dst: "B", predicate: "CALLS" },+ { src: "C", dst: "B", predicate: "IMPORTS" },+ ],+ };+ }+ return { nodes: [], edges: [] };+ });+ });+ afterEach(() => vi.restoreAllMocks());++ it("labels each text step with the predicate and its direction", async () => {+ const out = await runPath([], "text");+ expect(out).toContain("--CALLS-->");+ expect(out).toContain("<--IMPORTS--");+ expect(out).not.toContain("CONTAINS");+ });++ it("adds via and reversed to llm step rows", async () => {+ const out = await runPath([], "llm");+ expect(out).toContain("step name=A kind=function\n");+ expect(out).toContain("step name=B kind=function via=CALLS");+ expect(out).toContain("step name=C kind=function via=IMPORTS reversed=true");+ });++ it("adds via and reversed to json path items", async () => {+ const out = JSON.parse(await runPath([]));+ expect(out.path[0]).toEqual({ name: "A", kind: "function" });+ expect(out.path[1].via).toBe("CALLS");+ expect(out.path[1].reversed).toBeUndefined();+ expect(out.path[2].via).toBe("IMPORTS");+ expect(out.path[2].reversed).toBe(true);+ expect(out.kind).toBe("mixed");+ });++ // The default --to search follows all six predicates, as before: a route+ // that exists only over one of the non-call relationships is still found.+ it.each(["REFERENCES", "EXTENDS", "CONTAINS"])(+ "without --kind, finds a route that exists only over %s",+ async (predicate) => {+ expand.mockImplementation(async (id: string, opts: { direction: string; predicates: string[] }) => {+ if (id === "A" && opts.direction === "out" && opts.predicates.includes(predicate)) {+ return { nodes: [{ id: "C", name: "C", kind: "function" }], edges: [{ src: "A", dst: "C", predicate }] };+ }+ return { nodes: [], edges: [] };+ });++ const json = JSON.parse(await runPath([]));+ expect(json.path.map((n: { name: string; via?: string }) => [n.name, n.via])).toEqual([["A", undefined], ["C", predicate]]);+ expect(json.kind).toBe("mixed");+ expect(expand.mock.calls[0][1].predicates).toEqual(+ ["CALLS", "IMPORTS", "REFERENCES", "EXTENDS", "IMPLEMENTS", "CONTAINS"],+ );+ },+ );++ it("keeps all six predicates for a directional walk without --kind", async () => {+ const program = new Command().name("ix").exitOverride();+ registerTraceCommand(program);+ vi.spyOn(console, "log").mockImplementation(() => {});+ await program.parseAsync(["trace", "A", "--downstream", "--depth", "1", "--format", "json"], { from: "user" });+ expect(expand.mock.calls.map(([, o]) => o.predicates).flat()).toEqual(+ ["CALLS", "IMPORTS", "REFERENCES", "EXTENDS", "IMPLEMENTS", "CONTAINS"],+ );+ });++ it("falls back to a bare arrow when the expansion carries no edges", async () => {+ expand.mockImplementation(async (id: string, opts: { direction: string }) => {+ const adjacent: Record<string, string[]> = opts.direction === "out"+ ? { A: ["B"], B: ["C"] } : { B: ["A"], C: ["B"] };+ return { nodes: (adjacent[id] ?? []).map(name => ({ id: name, name, kind: "function" })), edges: [] };+ });+ const out = await runPath([], "text");+ expect(out).toContain("→");+ expect(out).not.toContain("-->");+ const json = JSON.parse(await runPath([]));+ expect(json.path.every((n: { via?: string }) => n.via === undefined)).toBe(true);+ });+});diff --git a/ix-cli/src/cli/commands/trace.ts b/ix-cli/src/cli/commands/trace.tsindex d2d395ed..eabc1eab 100644--- a/ix-cli/src/cli/commands/trace.ts+++ b/ix-cli/src/cli/commands/trace.ts@@ -18,7 +18,7 @@ import {import { compactTreeNode, relativePath, printJson } from "../format.js";import { llmLine, llmShortId, type LlmValue } from "../llm.js";import { traversalHint } from "./depends.js";-import { parsePickOption } from "../options.js";+import { parseCountOption, parsePickOption } from "../options.js";import { createLimiter, EXPAND_CONCURRENCY, walkTree, type Limiter, type TreeWalkResult } from "../tree-walk.js";// ── Types ────────────────────────────────────────────────────────────@@ -37,6 +37,10 @@ interface PathNode {id: string;name: string;kind: string;+ /** Predicate of the edge that reached this step from the previous one; set only when the edge was found. */+ via?: string;+ /** True when that edge runs from this step back to the previous one (found walking "in"). */+ reversed?: boolean;}// ── Constants ────────────────────────────────────────────────────────@@ -45,8 +49,8 @@ interface PathNode {* What an unasked-for traversal is allowed to cost — the same bounds* `ix depends` uses, for the same reason: both were `Infinity`, and on a hub* that is thousands of nodes the caller pays for before seeing any of them.- * `--depth` and `--cap` still take anything, and the output says when a bound- * was reached.+ * `--depth` and `--cap` must be non-negative integers, and the output says+ * when a bound was reached.*/const DEFAULT_MAX_DEPTH = 3;const MAX_NODES = 100;@@ -231,6 +235,22 @@ export async function searchPath(if (maxNodes < 1) return { path: null, cut: true, cutReason: "node-cap" };if (fromId === toId) return { path: [{ id: fromId, name: "", kind: "" }], cut: false };const nodeMap = new Map<string, { name: string; kind: string }>();+ // How each visited node was first reached from its BFS parent.+ const linkMap = new Map<string, { via: string; reversed: boolean }>();+ const predicateRank = (p: string) => {+ const i = predicates.indexOf(p);+ return i < 0 ? predicates.length : i;+ };+ // The predicate joining parent and child in the given orientation, first in+ // request order when several do. Edges between two neighbours are ignored.+ const linkPredicate = (edges: any[] | undefined, src: string, dst: string): string | undefined => {+ let best: string | undefined;+ for (const e of edges ?? []) {+ if (e?.src !== src || e?.dst !== dst || typeof e.predicate !== "string") continue;+ if (best === undefined || predicateRank(e.predicate) < predicateRank(best)) best = e.predicate;+ }+ return best;+ };// Breadth-first as before, and still read one entry at a time in queue// order, so the route returned — the shortest, first-queued on a tie — does@@ -259,7 +279,7 @@ export async function searchPath(try {for (let head = 0; head < queue.length; head++) {- const { path, next } = queue[head];+ const { id, path, next } = queue[head];if (!next) {depthCut = true;continue;@@ -267,7 +287,10 @@ export async function searchPath(const [outResult, inResult] = await next;- for (const n of [...outResult.nodes, ...inResult.nodes]) {+ const outCount = outResult.nodes.length;+ const found = [...outResult.nodes, ...inResult.nodes];+ for (let k = 0; k < found.length; k++) {+ const n = found[k];if (visited.has(n.id)) continue;if (visited.size >= maxNodes) return { path: null, cut: true, cutReason: "node-cap" };visited.add(n.id);@@ -275,6 +298,13 @@ export async function searchPath(if (!nodeMap.has(n.id)) {nodeMap.set(n.id, { name, kind: n.kind ?? "unknown" });}+ if (!linkMap.has(n.id)) {+ const reversed = k >= outCount;+ const via = reversed+ ? linkPredicate(inResult.edges, n.id, id)+ : linkPredicate(outResult.edges, id, n.id);+ if (via) linkMap.set(n.id, { via, reversed });+ }if (n.id === toId) {const fullPath = [...path, n.id];@@ -282,7 +312,13 @@ export async function searchPath(path: fullPath.map((nodeId) => {if (nodeId === fromId) return { id: nodeId, name: "", kind: "" }; // filled belowconst meta = nodeMap.get(nodeId) ?? { name: nodeId.slice(0, 8), kind: "unknown" };- return { id: nodeId, ...meta };+ const link = linkMap.get(nodeId);+ return {+ id: nodeId,+ ...meta,+ ...(link ? { via: link.via } : {}),+ ...(link?.reversed ? { reversed: true } : {}),+ };}),cut: false,};@@ -410,7 +446,13 @@ export function renderTracePathLlm(if (cutHint) lines.push(llmLine("diagnostic", [["code", cutHint.code], ["message", cutHint.message]]));return lines;}- for (const n of pathNodes) lines.push(llmLine("step", [["name", n.name], ["kind", n.kind]]));+ for (const n of pathNodes) {+ lines.push(llmLine("step", [+ ["name", n.name], ["kind", n.kind],+ ["via", n.via],+ ["reversed", n.reversed ? true : undefined],+ ]));+ }return lines;}@@ -518,8 +560,8 @@ export function registerTraceCommand(program: Command): void {testsOnly: opts.testsOnly,};- const maxDepth = opts.depth ? parseInt(opts.depth, 10) : DEFAULT_MAX_DEPTH;- const maxNodes = opts.cap ? parseInt(opts.cap, 10) : MAX_NODES;+ const maxDepth = opts.depth !== undefined ? parseCountOption(opts.depth, "3") : DEFAULT_MAX_DEPTH;+ const maxNodes = opts.cap !== undefined ? parseCountOption(opts.cap, "100") : MAX_NODES;// ── Path mode (--to) ────────────────────────────────────────if (opts.to) {@@ -578,7 +620,12 @@ export function registerTraceCommand(program: Command): void {kind: relKind,};if (pathNodes.length > 0) {- const mapped = pathNodes.map((n) => ({ name: n.name, kind: n.kind }));+ const mapped = pathNodes.map((n) => ({+ name: n.name,+ kind: n.kind,+ ...(n.via ? { via: n.via } : {}),+ ...(n.reversed ? { reversed: true } : {}),+ }));output.path = mapped;output.summary = { path_length: pathNodes.length };} else {@@ -622,6 +669,9 @@ export function registerTraceCommand(program: Command): void {const kindStr = colorizeKind(n.kind ?? "");if (i === 0) {console.log(` ${kindStr} ${n.name}`);+ } else if (n.via) {+ const arrow = n.reversed ? `<--${n.via}--` : `--${n.via}-->`;+ console.log(` ${chalk.dim(arrow)} ${kindStr} ${n.name}`);} else {console.log(` ${chalk.dim("→")} ${kindStr} ${n.name}`);}diff --git a/ix-cli/src/cli/options.ts b/ix-cli/src/cli/options.tsindex 53cb1b6f..5e5b8378 100644--- a/ix-cli/src/cli/options.ts+++ b/ix-cli/src/cli/options.ts@@ -89,6 +89,21 @@ export function validateCliOptions(command: Command): void {}}+/**+ * Parse a count flag read inside a command's action, such as `ix trace+ * --depth`/`--cap`: a non-negative integer.+ *+ * The root `validateCliOptions` hook already refuses a malformed `<n>` value+ * before the action runs; this is the same rule at the point of use, so a+ * command registered without that hook (the test harnesses) still cannot turn+ * `abc` into NaN the way `parseInt` did. It is not a commander option parser+ * on purpose: that path prints commander's plain error, not the formatted+ * `cli_error` record.+ */+export function parseCountOption(value: string, example: string): number {+ return parseNonNegativeInt(value, example);+}+export function parsePickOption(value: string): number {return parsePositiveInt(value, "1 or 2");}diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.mdindex 9a9cb8d4..b62c8e36 100644--- a/skills/ix/references/flags.md+++ b/skills/ix/references/flags.md@@ -87,10 +87,11 @@ surfaces (#575).the walk stopped descending and there may or may not be more. JSON carriesthem per direction in each `summary`. When `ix trace --to` finds no route, asearch a bound cut short adds the same code after `no_path`; a bare `no_path`- means the whole reachable graph was searched. `--depth` and `--cap` take- anything. When the cap cuts a `depends` or directional `trace` walk, the- nodes kept are the shallowest: every node at depth d before any at depth- d+1, so the first level is complete before the second begins. (The walk+ means the whole reachable graph was searched. `ix trace` rejects a+ `--depth` or `--cap` that is not a non-negative integer as a usage error.+ When the cap cuts a `depends` or directional `trace` walk, the nodes kept+ are the shallowest: every node at depth d before any at depth d+1, so the+ first level is complete before the second begins. (The walkused to be depth-first, and could spend the whole cap down its firstbranch.) A walk the cap does not cut is the same tree it always was.- **`ix ingest <path>` writes to the workspace the path belongs to** -- the