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
feat(context): end the bundle with the reads worth making
KageBinaryeec58bbdceaf
diff --git a/ix-cli/src/cli/__tests__/context-range-first.test.ts b/ix-cli/src/cli/__tests__/context-range-first.test.tsnew file mode 100644index 00000000..89f9b95b--- /dev/null+++ b/ix-cli/src/cli/__tests__/context-range-first.test.ts@@ -0,0 +1,67 @@+// Copyright 2026 Ix Infrastructure Inc.++import { describe, expect, it } from "vitest";++import { nextReads } from "../commands/context.js";++function bundleWith(evidence: Array<Record<string, unknown>>): never {+ return { evidence } as never;+}++function row(title: string, path?: string, lineStart?: number, lineEnd?: number) {+ return {+ id: title, kind: "structural", source: "facts.members", title, score: 10, reason: "", refs: [],+ ...(path ? { location: { path, lineStart, lineEnd } } : {}),+ };+}++describe("nextReads", () => {+ it("hands back ready-to-run commands, in evidence order", () => {+ expect(+ nextReads(bundleWith([+ row("target", "src/a.ts", 15, 27),+ row("caller", "src/b.ts", 17, 145),+ ])),+ ).toEqual([+ "ix read src/a.ts:15-27",+ "ix read src/b.ts:17-145",+ ]);+ });++ it("stops at three, so the closing instruction stays a closing instruction", () => {+ const reads = nextReads(bundleWith(+ [1, 2, 3, 4, 5].map((n) => row(`m${n}`, `src/${n}.ts`, n, n + 10)),+ ));+ expect(reads).toHaveLength(3);+ });++ it("does not repeat a range a caller and a dependent both name", () => {+ // The same function arrives twice in most bundles, once per relation.+ expect(+ nextReads(bundleWith([+ row("caller handleLogin", "src/b.ts", 17, 145),+ row("dependent handleLogin", "src/b.ts", 17, 145),+ row("member parse", "src/c.ts", 4, 9),+ ])),+ ).toEqual([+ "ix read src/b.ts:17-145",+ "ix read src/c.ts:4-9",+ ]);+ });++ it("skips a row that has no range, rather than emitting a whole-file read", () => {+ // A file entity carries a path and no span on purpose. Turning that into+ // `ix read src/huge.ts` is exactly the 34-61k-character read this is here+ // to avoid.+ expect(+ nextReads(bundleWith([+ row("container config.ts (file)", "src/huge.ts"),+ row("member parse", "src/c.ts", 4, 9),+ ])),+ ).toEqual(["ix read src/c.ts:4-9"]);+ });++ it("says nothing when nothing in the bundle is ranged", () => {+ expect(nextReads(bundleWith([row("a"), row("b", "src/x.ts")]))).toEqual([]);+ });+});diff --git a/ix-cli/src/cli/__tests__/explain-pipeline.test.ts b/ix-cli/src/cli/__tests__/explain-pipeline.test.tsindex 0b6fc26c..99fca4ac 100644--- a/ix-cli/src/cli/__tests__/explain-pipeline.test.ts+++ b/ix-cli/src/cli/__tests__/explain-pipeline.test.ts@@ -191,7 +191,7 @@ describe("inferRole", () => {kind: "method",name: "processPayment",path: "src/billing.ts",- container: { kind: "class", name: "PaymentService" },+ container: { id: "container-id", kind: "class", name: "PaymentService" },callerCount: 3,calleeCount: 2,});@@ -258,7 +258,7 @@ describe("inferRole", () => {callerCount: 0,calleeCount: 0,memberCount: 0,- container: { kind: "class", name: "Foo" },+ container: { id: "container-id", kind: "class", name: "Foo" },});const result = inferRole(facts);// Should NOT say "role could not be determined"@@ -416,7 +416,7 @@ describe("renderExplanation", () => {const facts = makeFacts({kind: "method",name: "resolve",- container: { kind: "class", name: "ConflictService" },+ container: { id: "container-id", kind: "class", name: "ConflictService" },callerCount: 3,calleeCount: 2,});@@ -428,7 +428,7 @@ describe("renderExplanation", () => {it("includes container context when present", () => {const facts = makeFacts({- container: { kind: "class", name: "OrderService" },+ container: { id: "container-id", kind: "class", name: "OrderService" },});const role = inferRole(facts);const importance = inferImportance(facts);@@ -957,7 +957,7 @@ describe("system-aware explanation sentence", () => {kind: "method",name: "resolve",path: "src/cli/conflict.ts",- container: { kind: "class", name: "ConflictService" },+ container: { id: "container-id", kind: "class", name: "ConflictService" },callerCount: 3,calleeCount: 2,dependentCount: 5,@@ -1526,7 +1526,7 @@ describe("inferFlowSemantics", () => {const facts = makeFacts({name: "resolveConflict",path: "src/cli/conflict.ts",- container: { kind: "class", name: "ConflictService" },+ container: { id: "container-id", kind: "class", name: "ConflictService" },});const flow = inferFlowSemantics(facts);expect(flow.flowName).toBe("conflict-resolution flow");@@ -1568,7 +1568,7 @@ describe("inferFlowSemantics", () => {it("container-based: execute in IngestionService → ingestion pipeline", () => {const facts = makeFacts({name: "execute",- container: { kind: "class", name: "IngestionService" },+ container: { id: "container-id", kind: "class", name: "IngestionService" },});const flow = inferFlowSemantics(facts);expect(flow.flowName).toBe("ingestion pipeline");@@ -1578,7 +1578,7 @@ describe("inferFlowSemantics", () => {const facts = makeFacts({name: "resolve",path: "src/conflict.ts",- container: { kind: "class", name: "ConflictService" },+ container: { id: "container-id", kind: "class", name: "ConflictService" },});const flow = inferFlowSemantics(facts);expect(flow.flowName).toBe("conflict-resolution flow");@@ -1660,7 +1660,7 @@ describe("flow-aware rendering for callables", () => {kind: "method",name: "resolveConflict",path: "src/cli/conflict.ts",- container: { kind: "class", name: "ConflictService" },+ container: { id: "container-id", kind: "class", name: "ConflictService" },callerCount: 3,calleeCount: 2,dependentCount: 5,diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.tsindex e5576f3a..01ee92a7 100644--- a/ix-cli/src/cli/commands/context.ts+++ b/ix-cli/src/cli/commands/context.ts@@ -1462,7 +1462,7 @@ export function buildBundle(input: BuildInput): ContextBundle {id: resolved.id,name: resolved.name,kind: resolved.kind,- path: facts.path,+ ...locationFields(targetLocation(facts) ?? {}),stale,},];@@ -1676,7 +1676,7 @@ function rankEvidence(input: {score: 0,reason: "resolved target — the bundle is centered on this entity",refs: [target.id],- ...locationField(input.facts.path ? { path: input.facts.path } : undefined),+ ...locationField(targetLocation(input.facts)),});type Structural = Omit<EvidenceItem, "kind" | "score">;@@ -1687,7 +1687,8 @@ function rankEvidence(input: {source: "facts.container",title: `container ${input.facts.container.name} (${input.facts.container.kind})`,reason: "contains the target",- refs: [],+ refs: [input.facts.container.id],+ ...locationField(input.facts.container),});}// Names alone when the facts carry no locations, so a caller that builds its@@ -1863,6 +1864,8 @@ export function renderBundle(bundle: ContextBundle, format: string): void {// surface, the ranked evidence is what it exists to deliver, and// `--format json` carries the rest for a caller that wants it....bundle.evidence.map(evidenceRecord(undefined)),+ // Last, so it reads as the closing instruction it is.+ ...nextReads(bundle).map((cmd) => llmLine("next", { cmd })),]);return;}@@ -1890,6 +1893,12 @@ export function renderBundle(bundle: ContextBundle, format: string): void {}}+ const reads = nextReads(bundle);+ if (reads.length > 0) {+ renderSection("Next");+ for (const cmd of reads) console.log(` ${cmd}`);+ }+const trunc = bundle.truncation;if (trunc.entitiesTruncated + trunc.relationshipsTruncated + trunc.evidenceTruncated > 0) {const advice = truncationAdvice(bundle);@@ -2004,6 +2013,41 @@ function locationFields(ref: Located): Located {}/** An evidence `location`, or nothing when the path is unknown. */+/** The target's own `path:start-end`, or just its path when it has no range. */+function targetLocation(facts: ContextFacts): Located | undefined {+ if (!facts.path) return undefined;+ return { path: facts.path, lineStart: facts.lineStart, lineEnd: facts.lineEnd };+}++/**+ * The reads worth making next, most valuable first.+ *+ * The evidence rows carry `path:start-end` and the caller still has to decide+ * which of them to open — so the bundle ends by saying so, as commands rather+ * than coordinates. The saving this exists for is the whole-file read: on the+ * benchmark set one avoided 34-61k-character read is worth more than every+ * byte the bundle spends, and an agent handed a path with no range opens the+ * file.+ *+ * 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[] {+ const seen = new Set<string>();+ const reads: string[] = [];+ 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}`);+ if (reads.length === limit) break;+ }+ return reads;+}+function locationField(ref: Located | undefined): { location?: EvidenceLocation } {if (!ref?.path) return {};return { location: { ...locationFields(ref), path: ref.path } };diff --git a/ix-cli/src/cli/explain/facts.ts b/ix-cli/src/cli/explain/facts.tsindex 8d5dfc66..7edb8aa2 100644--- a/ix-cli/src/cli/explain/facts.ts+++ b/ix-cli/src/cli/explain/facts.ts@@ -31,11 +31,23 @@ export interface EntityFacts {name: string;kind: string;path?: string;+ /**+ * The target's own line range — the one location in a bundle that was a bare+ * path. Read off the same `attrs` the members' ranges come from, so it costs+ * no request; absent for a file, whose span says nothing its path does not.+ */+ lineStart?: number;+ lineEnd?: number;signature?: string;docstring?: string;// Structural context- container?: { kind: string; name: string };+ /**+ * The container, located. It was a bare `{ kind, name }`, which is the one+ * evidence row in a bundle that named something with no way to open it — and+ * the node it is read from was already in hand, so the path cost nothing.+ */+ container?: EntityLocation;members: string[];/** The same members with their locations, in the same order as `members`. */memberRefs?: EntityLocation[];@@ -341,15 +353,11 @@ export async function collectFacts(const containsEdge = edges.find((e: any) => e.predicate === "CONTAINS" && e.dst === targetId,);- let container: { kind: string; name: string } | undefined;+ let container: EntityLocation | undefined;if (containsEdge) {try {const containerDetails = await client.entity(containsEdge.src);- const cNode = containerDetails.node as any;- container = {- kind: cNode.kind || "unknown",- name: cNode.name || cNode.attrs?.name || "(unknown)",- };+ container = toLocation(containerDetails.node);} catch {/* no container */}@@ -480,11 +488,17 @@ export async function collectFacts(const subsystemName = hierarchyPath.find((n: any) => n.kind === "subsystem")?.name;const moduleName = hierarchyPath.find((n: any) => n.kind === "module")?.name;+ const targetKindName = node.kind || targetKind;+ const targetLines = targetKindName === "file"+ ? {}+ : { lineStart: lineOf(node.attrs?.line_start), lineEnd: lineOf(node.attrs?.line_end) };+const facts: EntityFacts = {id: targetId,name: node.name || node.attrs?.name || targetName,- kind: node.kind || targetKind,+ kind: targetKindName,path,+ ...targetLines,signature,docstring,container,