Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat(cli): give every agent-facing row a place, and stop naming it three times

KageBinaryf2c41b925828
diff --git a/ix-cli/src/cli/__tests__/llm-tier5.test.ts b/ix-cli/src/cli/__tests__/llm-tier5.test.ts
index 659c6098..8fc7fd24 100644
--- a/ix-cli/src/cli/__tests__/llm-tier5.test.ts
+++ b/ix-cli/src/cli/__tests__/llm-tier5.test.ts
@@ -39,7 +39,7 @@ const role = { role: "service", confidence: "high", reasons: [] } as any;
const importance = { level: "high", category: "broad-shared-dependency", reasons: [] } as any;
const rendered = {
explanation: "PROSE_EXPLANATION", context: "PROSE_CONTEXT",
- usedBy: null, whyItMatters: "PROSE_WHY", notes: [],
+ usedBy: null, usedByIsNameList: true, whyItMatters: "PROSE_WHY", notes: [],
};
describe("explain --format llm", () => {
diff --git a/ix-cli/src/cli/__tests__/row-locations.test.ts b/ix-cli/src/cli/__tests__/row-locations.test.ts
new file mode 100644
index 00000000..d09bfdd2
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/row-locations.test.ts
@@ -0,0 +1,190 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ formatEdgeResults,
+ formatNodes,
+ lineSpan,
+ locationLabel,
+ renderEdgeResultsLlm,
+ rowLocation,
+ sliceEdgeResults,
+} from "../format.js";
+import { renderExplainLlm } from "../explain/llm.js";
+import { renderEntityLlm } from "../commands/entity.js";
+import type { EntityFacts } from "../explain/facts.js";
+
+function node(over: Record<string, unknown> = {}) {
+ return {
+ id: "aaaaaaaa-1111-0000-0000-000000000000",
+ name: "registerCallersCommand",
+ kind: "function",
+ attrs: { line_start: 17, line_end: 145 },
+ provenance: { source_uri: "ix-cli/src/cli/commands/callers.ts" },
+ ...over,
+ };
+}
+
+function captured(fn: () => void): string[] {
+ const spy = vi.spyOn(console, "log").mockImplementation(() => {});
+ try {
+ fn();
+ return spy.mock.calls.map((c) => String(c[0]));
+ } finally {
+ spy.mockRestore();
+ }
+}
+
+describe("rowLocation", () => {
+ it("reads the path and span off the node the row was built from", () => {
+ expect(rowLocation(node())).toEqual({
+ path: "ix-cli/src/cli/commands/callers.ts",
+ lineStart: 17,
+ lineEnd: 145,
+ });
+ });
+
+ it("gives a file no span, because its span is the file", () => {
+ expect(rowLocation(node({ kind: "file", name: "callers.ts" }))).toEqual({
+ path: "ix-cli/src/cli/commands/callers.ts",
+ });
+ });
+
+ it("ignores a line number that is not one", () => {
+ expect(rowLocation(node({ attrs: { line_start: 0, line_end: "12" } }))).toEqual({
+ path: "ix-cli/src/cli/commands/callers.ts",
+ lineStart: undefined,
+ lineEnd: undefined,
+ });
+ });
+
+ it("collapses a one-line entity to a single number", () => {
+ expect(lineSpan({ lineStart: 9, lineEnd: 9 })).toBe("9");
+ expect(lineSpan({ lineStart: 9, lineEnd: 12 })).toBe("9-12");
+ expect(lineSpan({})).toBeUndefined();
+ expect(locationLabel({ path: "a.ts", lineStart: 9, lineEnd: 12 })).toBe("a.ts:9-12");
+ expect(locationLabel({ path: "a.ts" })).toBe("a.ts");
+ expect(locationLabel({})).toBe("");
+ });
+});
+
+describe("edge results", () => {
+ it("put a span on every row that has one", () => {
+ const lines = renderEdgeResultsLlm(sliceEdgeResults([node()], 50), "callers", "relativePath", "graph");
+ expect(lines[1]).toBe(
+ "ref name=registerCallersCommand kind=function id=aaaaaaaa path=ix-cli/src/cli/commands/callers.ts lines=17-145",
+ );
+ });
+
+ it("carry the numbers into json, where a program can use them", () => {
+ const out = captured(() =>
+ formatEdgeResults(sliceEdgeResults([node()], 50), "callers", "relativePath", "json"),
+ );
+ const payload = JSON.parse(out[0]);
+ expect(payload.results[0]).toMatchObject({
+ name: "registerCallersCommand",
+ path: "ix-cli/src/cli/commands/callers.ts",
+ lineStart: 17,
+ lineEnd: 145,
+ });
+ });
+
+ it("show the place on the text row too", () => {
+ const out = captured(() =>
+ formatEdgeResults(sliceEdgeResults([node()], 50), "callers", "relativePath", "text"),
+ );
+ expect(out.join("\n")).toContain("ix-cli/src/cli/commands/callers.ts:17-145");
+ });
+});
+
+describe("search text rows", () => {
+ it("name a place, not just a word", () => {
+ // Four modules called `config.ts` answered `ix search config` with four
+ // rows that differed in nothing a caller could choose by.
+ const out = captured(() => formatNodes([node({ name: "config.ts", kind: "module" })], "text"));
+ expect(out[0]).toContain("ix-cli/src/cli/commands/callers.ts:17-145");
+ });
+});
+
+describe("ix entity", () => {
+ it("says where inside the file the entity is", () => {
+ const lines = renderEntityLlm({ node: node(), edges: [] });
+ expect(lines[0]).toContain("lines=17-145");
+ });
+});
+
+const role = { role: "shared-utility", confidence: "medium" } as never;
+const importance = { level: "medium", category: "normal" } as never;
+const prose = {
+ explanation: "e", context: "c", whyItMatters: "w", notes: [],
+ usedBy: "Used by registerCallersCommand, and 1 other.",
+ usedByIsNameList: true,
+};
+
+function facts(over: Partial<EntityFacts> = {}): EntityFacts {
+ return {
+ id: "e1", name: "relativePath", kind: "function", path: "ix-cli/src/cli/format.ts",
+ members: [], memberCount: 0,
+ callerCount: 0, calleeCount: 0, dependentCount: 0, importerCount: 0,
+ downstreamDependents: 0, downstreamDepth: 0,
+ topCallers: [], topDependents: [],
+ historyLength: 0, stale: false, diagnostics: [],
+ ...over,
+ } as EntityFacts;
+}
+
+describe("ix explain", () => {
+ const located = facts({
+ topCallers: ["registerCallersCommand"],
+ topCallerRefs: [{
+ id: "c1", name: "registerCallersCommand", kind: "function",
+ path: "ix-cli/src/cli/commands/callers.ts", lineStart: 17, lineEnd: 145,
+ }],
+ topDependents: ["registerCallersCommand"],
+ topDependentRefs: [{
+ id: "c1", name: "registerCallersCommand", kind: "function",
+ path: "ix-cli/src/cli/commands/callers.ts", lineStart: 17, lineEnd: 145,
+ }],
+ });
+
+ it("names a thing that is both a caller and a dependent once", () => {
+ const lines = renderExplainLlm(located, role, importance, prose);
+ const uses = lines.filter((l) => l.startsWith("uses "));
+ expect(uses).toEqual([
+ "uses name=registerCallersCommand rel=caller,dependent path=ix-cli/src/cli/commands/callers.ts lines=17-145",
+ ]);
+ expect(lines.filter((l) => l.startsWith("caller ") || l.startsWith("dependent "))).toEqual([]);
+ });
+
+ it("drops the generated used_by sentence, which is those names a third time", () => {
+ const lines = renderExplainLlm(located, role, importance, prose);
+ expect(lines.some((l) => l.startsWith("used_by "))).toBe(false);
+ });
+
+ it("keeps a used_by that says something the rows do not", () => {
+ const lines = renderExplainLlm(located, role, importance, {
+ ...prose,
+ usedBy: "Every ingest path reaches this through the parse pool.",
+ usedByIsNameList: false,
+ });
+ expect(lines).toContain('used_by text="Every ingest path reaches this through the parse pool."');
+ });
+
+ it("locates member rows", () => {
+ const lines = renderExplainLlm(
+ facts({
+ members: ["getEndpoint"],
+ memberRefs: [{ id: "m1", name: "getEndpoint", kind: "function", path: "ix-cli/src/cli/config.ts", lineStart: 198, lineEnd: 200 }],
+ memberCount: 1,
+ }),
+ role, importance, prose,
+ );
+ expect(lines).toContain("member name=getEndpoint path=ix-cli/src/cli/config.ts lines=198-200");
+ });
+
+ it("still emits a row when the facts carry no location for it", () => {
+ const lines = renderExplainLlm(facts({ topCallers: ["mystery"] }), role, importance, prose);
+ expect(lines).toContain("uses name=mystery rel=caller");
+ });
+});
diff --git a/ix-cli/src/cli/commands/entity.ts b/ix-cli/src/cli/commands/entity.ts
index 5b81a0df..4db308e0 100644
--- a/ix-cli/src/cli/commands/entity.ts
+++ b/ix-cli/src/cli/commands/entity.ts
@@ -4,19 +4,22 @@ import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
-import { relativePath, stripNulls } from "../format.js";
+import { lineSpan, relativePath, rowLocation, stripNulls } from "../format.js";
import { llmLine } from "../llm.js";
/** Render entity details as llm records: a header line then one `edge` row per edge. */
export function renderEntityLlm(result: any): string[] {
const node = result.node;
- const path = relativePath(node.provenance?.sourceUri ?? node.provenance?.source_uri);
+ const loc = rowLocation(node);
const edges = result.edges ?? [];
const lines = [llmLine("entity", [
["id", node.id],
["kind", node.kind],
["name", node.name || node.attrs?.name],
- ["path", path],
+ ["path", loc.path],
+ // `ix entity <id>` was the one command that answered with a file and left
+ // the caller to find the entity inside it.
+ ["lines", lineSpan(loc)],
["rev", node.createdRev],
["claims", (result.claims ?? []).length || undefined],
["edges", edges.length || undefined],
diff --git a/ix-cli/src/cli/commands/impact.ts b/ix-cli/src/cli/commands/impact.ts
index d26defea..4d6ddebf 100644
--- a/ix-cli/src/cli/commands/impact.ts
+++ b/ix-cli/src/cli/commands/impact.ts
@@ -8,7 +8,7 @@ import { getEndpoint } from "../config.js";
import { resolveFileOrReport, printResolved } from "../resolve.js";
import { bucketByHierarchy, getSystemPath, formatSystemPath, hasMapData, type SystemPath } from "../hierarchy.js";
import { inferRiskSemantics, humanizeLabel, type ImpactFacts, type RiskSemantics } from "../impact/risk-semantics.js";
-import { stripNulls } from "../format.js";
+import { lineSpan, rowLocation, stripNulls } from "../format.js";
import { llmLine } from "../llm.js";
import { parsePickOption } from "../options.js";
@@ -296,7 +296,10 @@ async function containerImpact(
// For each member (up to 20), get inbound callers
const membersToCheck = members.slice(0, 20);
- const memberCallerCounts: { name: string; kind: string; id: string; callerCount: number }[] = [];
+ const memberCallerCounts: Array<{
+ name: string; kind: string; id: string; callerCount: number;
+ path?: string; lineStart?: number; lineEnd?: number;
+ }> = [];
let totalMemberCallers = 0;
const callerPromises = membersToCheck.map(async (member: any) => {
@@ -310,6 +313,7 @@ async function containerImpact(
kind: member.kind || "unknown",
id: member.id,
callerCount: callersResult.nodes.length,
+ ...rowLocation(member),
};
} catch {
diagnostics.push(`Failed to expand callers for member ${member.id}`);
@@ -318,6 +322,7 @@ async function containerImpact(
kind: member.kind || "unknown",
id: member.id,
callerCount: 0,
+ ...rowLocation(member),
};
}
});
@@ -408,7 +413,12 @@ async function containerImpact(
["member_callers", totalMemberCallers],
]),
...impactPropagationLlm(propagationBuckets, risk.flowPropagation),
- ...topMembers.map((m) => llmLine("member", [["name", m.name], ["kind", m.kind], ["callers", m.callerCount]])),
+ // The rows `ix impact` exists to produce: the members a change reaches.
+ // They named a symbol and left the caller to find it.
+ ...topMembers.map((m) => llmLine("member", [
+ ["name", m.name], ["kind", m.kind], ["callers", m.callerCount],
+ ["path", m.path], ["lines", lineSpan(m)],
+ ])),
...impactTailLlm(risk, decisions, tasks, bugs),
];
for (const line of lines) console.log(line);
diff --git a/ix-cli/src/cli/explain/llm.ts b/ix-cli/src/cli/explain/llm.ts
index c5ef5bb8..7ec132e3 100644
--- a/ix-cli/src/cli/explain/llm.ts
+++ b/ix-cli/src/cli/explain/llm.ts
@@ -2,7 +2,7 @@
import { llmLine } from "../llm.js";
import { relativePath } from "../format.js";
-import type { EntityFacts } from "./facts.js";
+import type { EntityFacts, EntityLocation } from "./facts.js";
import type { RoleInference } from "./role-inference.js";
import type { ImportanceInference } from "./importance.js";
import type { ExplanationOutput } from "./render.js";
@@ -26,6 +26,14 @@ import type { ExplanationOutput } from "./render.js";
* is a real answer to "who calls this", and dropping the field would make it
* indistinguishable from a field the renderer forgot.
*/
+/** `17-145`, or `17`, from a located entity — nothing when it has no lines. */
+function lineSpanOf(ref: EntityLocation | undefined): string | undefined {
+ if (!ref || ref.lineStart === undefined) return undefined;
+ return ref.lineEnd !== undefined && ref.lineEnd !== ref.lineStart
+ ? `${ref.lineStart}-${ref.lineEnd}`
+ : `${ref.lineStart}`;
+}
+
export function renderExplainLlm(
facts: EntityFacts,
role: RoleInference,
@@ -82,19 +90,45 @@ export function renderExplainLlm(
if (facts.signature) lines.push(llmLine("signature", [["text", facts.signature]]));
- for (const caller of facts.topCallers) {
- lines.push(llmLine("caller", [["name", caller]]));
- }
- for (const dependent of facts.topDependents) {
- lines.push(llmLine("dependent", [["name", dependent]]));
- }
- for (const member of facts.members) {
- lines.push(llmLine("member", [["name", member]]));
+ // The same three names, three times over. A caller is nearly always also a
+ // dependent — `relativePath` on this repo emitted three `caller` rows, the
+ // same three as `dependent` rows, and then a `used_by` sentence naming them
+ // again: ten lines where three carry the information.
+ //
+ // So: callers first, dependents only where they are not already a caller,
+ // and each row says which relations it stands for.
+ const relations = new Map<string, { rel: string[]; ref?: EntityLocation }>();
+ const note = (name: string, rel: string, ref?: EntityLocation) => {
+ const entry = relations.get(name) ?? { rel: [], ref: undefined };
+ entry.rel.push(rel);
+ entry.ref = entry.ref ?? ref;
+ relations.set(name, entry);
+ };
+ facts.topCallers.forEach((name, i) => note(name, "caller", facts.topCallerRefs?.[i]));
+ facts.topDependents.forEach((name, i) => note(name, "dependent", facts.topDependentRefs?.[i]));
+ for (const [name, { rel, ref }] of relations) {
+ lines.push(llmLine("uses", [
+ ["name", name],
+ ["rel", rel.join(",")],
+ ["path", ref?.path],
+ ["lines", lineSpanOf(ref)],
+ ]));
}
- // Kept from the prose because it is the one part that is not derivable from
- // the records above: `usedBy` names call sites the counts only total up.
- if (rendered.usedBy) lines.push(llmLine("used_by", [["text", rendered.usedBy]]));
+ facts.members.forEach((name, i) => {
+ const ref = facts.memberRefs?.[i];
+ lines.push(llmLine("member", [
+ ["name", name],
+ ["path", ref?.path],
+ ["lines", lineSpanOf(ref)],
+ ]));
+ });
+
+ // The generated `used_by` sentence is those names a third time; only a
+ // hierarchy-derived narrative says something the rows above do not.
+ if (rendered.usedBy && !rendered.usedByIsNameList) {
+ lines.push(llmLine("used_by", [["text", rendered.usedBy]]));
+ }
for (const note of rendered.notes) {
lines.push(llmLine("note", [["text", note]]));
diff --git a/ix-cli/src/cli/explain/render.ts b/ix-cli/src/cli/explain/render.ts
index 25436dce..8dab6814 100644
--- a/ix-cli/src/cli/explain/render.ts
+++ b/ix-cli/src/cli/explain/render.ts
@@ -16,6 +16,13 @@ export interface ExplanationOutput {
explanation: string;
context: string;
usedBy: string | null;
+ /**
+ * True when `usedBy` is the generated list of caller names rather than a
+ * hierarchy-derived narrative. The record renderer emits those names as rows
+ * of their own now, with paths, so repeating them as a sentence is the third
+ * copy of the same three names.
+ */
+ usedByIsNameList: boolean;
whyItMatters: string;
notes: string[];
}
@@ -327,9 +334,9 @@ export function renderExplanation(
const context = contextLines.join("\n");
// ── Used by (named examples) ──────────────────────────────────────────
- const usedBy = (isFoundation && meaning!.usageSummary)
- ? meaning!.usageSummary
- : renderUsedBy(facts);
+ const usedByNarrative = isFoundation ? meaning!.usageSummary : null;
+ const usedBy = usedByNarrative ?? renderUsedBy(facts);
+ const usedByIsNameList = !usedByNarrative;
// ── Why it matters (role + importance + hierarchy fusion) ─────────────
const whyItMatters = (isFoundation && meaning!.importanceNarrative)
@@ -341,7 +348,7 @@ export function renderExplanation(
// ── Notes (clean diagnostics) ─────────────────────────────────────────
const notes = renderNotes(facts);
- return { explanation, context, usedBy, whyItMatters, notes };
+ return { explanation, context, usedBy, usedByIsNameList, whyItMatters, notes };
}
// ── Used by ─────────────────────────────────────────────────────────────────
diff --git a/ix-cli/src/cli/format.ts b/ix-cli/src/cli/format.ts
index d5bc9526..4367d0fb 100644
--- a/ix-cli/src/cli/format.ts
+++ b/ix-cli/src/cli/format.ts
@@ -124,6 +124,48 @@ export function truncationHint(slice: Slice<unknown>, relation: string): string
return `${slice.total} ${relation}; showing ${slice.shown}. Raise --limit to see the rest.`;
}
+// ── Row locations ──────────────────────────────────────────────────────────
+
+function lineNumber(value: unknown): number | undefined {
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;
+}
+
+/**
+ * Where a row's entity is, read off the graph node the row was built from.
+ *
+ * Every one of these rows already had the node in hand and printed a name from
+ * it. A bare name costs the reader a `locate` before it can do anything, which
+ * is a whole turn — around 30k tokens — against the ~30 bytes a path and a span
+ * cost here.
+ *
+ * A file gets no span: its range is the whole file, which says nothing its path
+ * does not. Same rule the context bundle's `toLocation` uses.
+ */
+export function rowLocation(node: any): { path?: string; lineStart?: number; lineEnd?: number } {
+ const path = relativePath(
+ node?.provenance?.source_uri ?? node?.provenance?.sourceUri ?? node?.attrs?.path ?? undefined,
+ );
+ if (String(node?.kind ?? "").toLowerCase() === "file") return { path };
+ const lineStart = lineNumber(node?.attrs?.line_start);
+ const lineEnd = lineNumber(node?.attrs?.line_end);
+ return { path, lineStart, lineEnd };
+}
+
+/** `17-145`, or `17` when the entity is one line, or nothing when unknown. */
+export function lineSpan(loc: { lineStart?: number; lineEnd?: number }): string | undefined {
+ if (loc.lineStart === undefined) return undefined;
+ return loc.lineEnd !== undefined && loc.lineEnd !== loc.lineStart
+ ? `${loc.lineStart}-${loc.lineEnd}`
+ : `${loc.lineStart}`;
+}
+
+/** `src/a.ts:17-145`, for a row a person reads. */
+export function locationLabel(loc: { path?: string; lineStart?: number; lineEnd?: number }): string {
+ if (!loc.path) return "";
+ const span = lineSpan(loc);
+ return span ? `${loc.path}:${span}` : loc.path;
+}
+
export function confidenceColor(score: number): (text: string) => string {
if (score >= 0.8) return chalk.green;
if (score >= 0.5) return chalk.yellow;
@@ -201,11 +243,16 @@ export function formatContext(result: any, format: string): void {
/** Render a flat node list as llm `node` records. */
export function renderNodesLlm(nodes: any[]): string[] {
- return nodes.map((n) => llmLine("node", [
- ["kind", n.kind],
- ["id", typeof n.id === "string" ? n.id.slice(0, 8) : undefined],
- ["name", n.name || n.attrs?.name || n.attrs?.title || "(unnamed)"],
- ]));
+ return nodes.map((n) => {
+ const loc = rowLocation(n);
+ return llmLine("node", [
+ ["kind", n.kind],
+ ["id", typeof n.id === "string" ? n.id.slice(0, 8) : undefined],
+ ["name", n.name || n.attrs?.name || n.attrs?.title || "(unnamed)"],
+ ["path", loc.path],
+ ["lines", lineSpan(loc)],
+ ]);
+ });
}
export function formatNodes(nodes: any[], format: string): void {
@@ -229,8 +276,13 @@ export function formatNodes(nodes: any[], format: string): void {
` ${chalk.blue("decision")} ${chalk.dim(shortId)} ${name}`
);
} else {
+ // The path is what makes a search row a place rather than a word: a
+ // graph with four `config.ts` modules in it answered `ix search config`
+ // with four identical-looking rows.
+ const where = locationLabel(rowLocation(n));
console.log(
` ${chalk.cyan(n.kind.padEnd(10))} ${chalk.dim(shortId)} ${chalk.bold(name)}`
+ + (where ? ` ${chalk.dim(where)}` : ""),
);
}
}
@@ -566,7 +618,7 @@ export function renderEdgeResultsLlm(
name,
kind: n.kind ?? undefined,
id: n.id ?? undefined,
- path: relativePath(n.provenance?.source_uri ?? n.provenance?.sourceUri ?? n.attrs?.path ?? undefined),
+ ...rowLocation(n),
};
});
const unresolved = refs.filter((r) => !r.resolved).length;
@@ -592,7 +644,10 @@ export function renderEdgeResultsLlm(
}
for (const ref of refs) {
lines.push(ref.resolved
- ? llmLine("ref", [["name", ref.name], ["kind", ref.kind], ["id", ref.id?.slice(0, 8)], ["path", ref.path]])
+ ? llmLine("ref", [
+ ["name", ref.name], ["kind", ref.kind], ["id", ref.id?.slice(0, 8)],
+ ["path", ref.path], ["lines", lineSpan(ref)],
+ ])
: llmLine("ref", [["kind", ref.kind], ["id", ref.id?.slice(0, 8)], ["resolved", false]]));
}
return lines;
@@ -621,7 +676,7 @@ export function formatEdgeResults(
name: resolved ? name : undefined,
kind: n.kind ?? undefined,
id: resolved ? n.id : undefined,
- path: relativePath(n.provenance?.source_uri ?? n.provenance?.sourceUri ?? n.attrs?.path ?? undefined),
+ ...rowLocation(n),
};
if (!resolved) {
ref.resolved = false;
@@ -689,7 +744,11 @@ export function formatEdgeResults(
if (!name || isRawIdName(name)) {
console.log(` ${chalk.cyan((n.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${chalk.dim("(unresolved)")}`);
} else {
- console.log(` ${chalk.cyan((n.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${chalk.bold(name)}`);
+ const where = locationLabel(rowLocation(n));
+ console.log(
+ ` ${chalk.cyan((n.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${chalk.bold(name)}`
+ + (where ? ` ${chalk.dim(where)}` : ""),
+ );
}
}
if (slice.truncated) console.log(chalk.dim(` ${truncationHint(slice, relation)}`));