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): say where evidence is, and rank members by use
KageBinaryd41fed88fb13
diff --git a/docs/llm-format.md b/docs/llm-format.mdindex 37c2453b..5d8ea29e 100644--- a/docs/llm-format.md+++ b/docs/llm-format.md@@ -94,16 +94,24 @@ item name=parseFile kind=method`ix context <target>`:```-context target=Widget target_kind=class stale=false classification=current entities=2 relationships=1 claims=1 decisions=0 conflicts=0 intents=0 evidence=7 truncated_entities=0 truncated_relationships=0 truncated_evidence=0 truncated_chars=0-evidence score=0 kind=target title="Widget (class)"+context target=Widget target_kind=class target_path=src/widget.ts stale=false classification=current entities=2 relationships=1 claims=1 decisions=0 conflicts=0 intents=0 evidence=7 truncated_entities=0 truncated_relationships=0 truncated_evidence=0 truncated_chars=0+evidence score=0 kind=target title="Widget (class)" path=src/widget.ts+evidence score=10 kind=structural title="member render" path=src/widget.ts lines=12-40evidence score=20 kind=claim title="renders to DOM"-evidence score=30 kind=relationship title="entity-1 --calls--> entity-2"+evidence score=30 kind=relationship title="Widget --calls--> render"```One header record, then the ranked evidence. The entity, relationship and claimlists stay counts here — `llm` is the token-minimal surface and the rankedevidence is what it exists to deliver; `--format json` carries the rest.+`path=` and `lines=` say where an item is defined, when the graph knows, so a+reader can open it instead of searching for it. For a file target, members are+ranked by use — those used from other files first — so the ones that survive+the evidence budget are the ones worth reading. Relationship titles name their+endpoints; a name shared by two entities in the bundle is qualified with its+path, and the ids stay in the `relationship` records.+`ix context --diff <id>`:```@@ -114,7 +122,7 @@ budgets scope=effective entities=50 relationships=100 evidence=25 chars=12000count added_entities=1 removed_entities=0 added_relationships=1 removed_relationships=1 added_evidence=2 removed_evidence=1 added_claims=1 removed_claims=0entity change=added id=entity-3 kind=method name=mount path=src/widget.tsrelationship change=removed src=entity-1 pred=calls dst=entity-2-evidence change=added score=30 kind=relationship title="entity-1 --holds--> entity-3"+evidence change=added score=30 kind=relationship title="Widget --holds--> mount"claim change=added id=c-8f31a2 entity=entity-1 status=active statement="mounts to DOM"```diff --git a/ix-cli/src/cli/__tests__/context-evidence-locations.test.ts b/ix-cli/src/cli/__tests__/context-evidence-locations.test.tsnew file mode 100644index 00000000..bea5cdb2--- /dev/null+++ b/ix-cli/src/cli/__tests__/context-evidence-locations.test.ts@@ -0,0 +1,188 @@+// Copyright 2026 Ix Infrastructure Inc.++import { describe, expect, it } from "vitest";++import type { GraphEdge, GraphNode } from "../../client/types.js";+import { buildBundle, renderBundle } from "../commands/context.js";+import { contextBundleSchema } from "../context-bundle-schema.js";+import type { ContextFacts, EntityLocation } from "../explain/facts.js";++const FILE = "file-1";++function member(id: string, name: string, lines: [number, number], use?: [number, number]): EntityLocation {+ return {+ id, name, kind: "function", path: "src/cli/config.ts", lineStart: lines[0], lineEnd: lines[1],+ ...(use ? { usedBy: use[0], usedFromFiles: use[1] } : {}),+ };+}++function facts(overrides: Partial<ContextFacts> = {}): ContextFacts {+ const memberRefs = overrides.memberRefs ?? [+ member("m-resolve", "resolveWorkspaceRoot", [322, 342], [13, 5]),+ member("m-real", "real", [40, 41], [2, 0]),+ ];+ return {+ id: FILE, name: "config.ts", kind: "file", path: "src/cli/config.ts",+ members: memberRefs.map((m) => m.name), memberRefs, memberCount: memberRefs.length,+ callerCount: 0, calleeCount: 0, dependentCount: 1, importerCount: 1,+ topCallers: [], topCallerRefs: [],+ topDependents: ["stats.ts"],+ topDependentRefs: [{ id: "d-stats", name: "stats.ts", kind: "file", path: "src/cli/commands/stats.ts" }],+ historyLength: 1, introducedRev: 7, stale: false, diagnostics: [],+ ...overrides,+ };+}++function node(id: string, name: string, kind = "function", sourceUri?: string): GraphNode {+ return {+ id, name, kind, attrs: {},+ provenance: sourceUri ? { sourceUri } : undefined,+ createdRev: 1, createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z",+ } as unknown as GraphNode;+}++function bundle(opts: {+ facts?: ContextFacts;+ nodes?: GraphNode[];+ edges?: GraphEdge[];+ provenance?: unknown;+ maxEntities?: number;+} = {}) {+ return buildBundle({+ resolved: { id: FILE, name: "config.ts", kind: "file", resolutionMode: "exact" },+ facts: opts.facts ?? facts(),+ context: {+ claims: [], conflicts: [], decisions: [], intents: [],+ nodes: opts.nodes ?? [], edges: opts.edges ?? [],+ metadata: { query: "", seedEntities: [], hopsExpanded: 1, asOfRev: 1 },+ } as never,+ provenance: opts.provenance ?? {},+ budgets: { maxEntities: opts.maxEntities ?? 50, maxRelationships: 100, maxEvidence: 25, maxChars: 12000 },+ isStale: () => false,+ });+}++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;+}++describe("ix context evidence says where things are", () => {+ it("locates the target, its members and its dependents", () => {+ const b = bundle();++ expect(b.target.path).toBe("src/cli/config.ts");+ const byTitle = new Map(b.evidence.map((e) => [e.title, e]));+ expect(byTitle.get("config.ts (file)")?.location).toEqual({ path: "src/cli/config.ts" });+ expect(byTitle.get("member resolveWorkspaceRoot")?.location).toEqual({+ path: "src/cli/config.ts", lineStart: 322, lineEnd: 342,+ });+ expect(byTitle.get("member resolveWorkspaceRoot")?.refs).toEqual(["m-resolve"]);+ expect(byTitle.get("dependent stats.ts")?.location).toEqual({ path: "src/cli/commands/stats.ts" });+ });++ it("keeps the members in the order the facts ranked them, and says why", () => {+ const b = bundle();+ const members = b.evidence.filter((e) => e.id.startsWith("member:"));++ expect(members.map((e) => e.title)).toEqual(["member resolveWorkspaceRoot", "member real"]);+ expect(members[0]?.reason).toBe("defined in the target; used by 13 across 5 other files");+ expect(members[1]?.reason).toBe("defined in the target; used by 2 within this file");+ });++ it("still gives name-only evidence when the facts carry no locations", () => {+ const b = bundle({+ facts: facts({ memberRefs: undefined, topDependentRefs: undefined, members: ["render"] }),+ });+ const render = b.evidence.find((e) => e.title === "member render");++ expect(render).toBeDefined();+ expect(render?.location).toBeUndefined();+ expect(render?.reason).toBe("defined in the target");+ });++ it("puts located entities ahead of the backend's alphabetical nodes, so the budget keeps them", () => {+ const nodes = ["aaa", "bbb", "ccc"].map((n) => node(`n-${n}`, n));+ const b = bundle({ nodes, maxEntities: 3 });++ expect(b.entities.map((e) => e.name)).toEqual(["config.ts", "resolveWorkspaceRoot", "real"]);+ expect(b.entities[1]).toMatchObject({ path: "src/cli/config.ts", lineStart: 322, lineEnd: 342 });+ expect(b.truncation.entitiesTruncated).toBe(4);+ });++ it("reads provenance from the chain /v1/provenance actually returns", () => {+ const b = bundle({+ provenance: {+ entityId: FILE,+ chain: [+ { rev: 3, source: { uri: "src/old.ts", extractor: "tree-sitter/1.0", sourceType: "code" } },+ { rev: 9, source: { uri: "src/cli/config.ts", sourceHash: "abc", extractor: "tree-sitter/1.25", sourceType: "code" } },+ ],+ },+ });++ expect(b.provenance).toMatchObject({+ sourceUri: "src/cli/config.ts", sourceHash: "abc", extractor: "tree-sitter/1.25", sourceType: "code",+ });+ expect(b.evidence.find((e) => e.kind === "provenance")?.reason).toBe(+ "provenance code, extractor tree-sitter/1.25",+ );+ });++ it("names relationship endpoints, qualifying a name two entities share", () => {+ const nodes = [+ node("n-a", "README.md", "file", "docs/README.md"),+ node("n-b", "README.md", "file", "README.md"),+ ];+ const edges = [+ { id: "e1", src: "n-a", dst: "n-b", predicate: "REFERENCES", attrs: {}, createdRev: 1 },+ { id: "e2", src: FILE, dst: "m-resolve", predicate: "CONTAINS", attrs: {}, createdRev: 1 },+ { id: "e3", src: FILE, dst: "not-in-bundle", predicate: "IMPORTS", attrs: {}, createdRev: 1 },+ ] as GraphEdge[];+ const titles = bundle({ nodes, edges }).evidence.filter((e) => e.kind === "relationship").map((e) => e.title);++ expect(titles).toContain("README.md (docs/README.md) --REFERENCES--> README.md (README.md)");+ expect(titles).toContain("config.ts --CONTAINS--> resolveWorkspaceRoot");+ expect(titles).toContain("config.ts --IMPORTS--> not-in-bundle");+ });++ it("renders locations in text and llm output", () => {+ const b = bundle();++ const text = captureLog(() => renderBundle(b, "text"));+ expect(text.some((l) => l.includes("path:") && l.includes("src/cli/config.ts"))).toBe(true);+ expect(text).toContain(+ " src/cli/config.ts:322-342 — defined in the target; used by 13 across 5 other files",+ );++ const llm = captureLog(() => renderBundle(b, "llm"));+ expect(llm[0]).toContain("target_path=src/cli/config.ts");+ expect(llm).toContain(+ 'evidence score=11 kind=structural title="member resolveWorkspaceRoot" path=src/cli/config.ts lines=322-342',+ );+ });++ it("survives the schema round trip, and older bundles without locations still parse", () => {+ const b = bundle();+ const parsed = contextBundleSchema.parse(JSON.parse(JSON.stringify(b)));++ expect(parsed.target.path).toBe("src/cli/config.ts");+ expect(parsed.entities[1]).toMatchObject({ lineStart: 322, lineEnd: 342 });+ expect(parsed.evidence.find((e) => e.title === "member real")?.location).toEqual({+ path: "src/cli/config.ts", lineStart: 40, lineEnd: 41,+ });++ const legacy = JSON.parse(JSON.stringify(b));+ delete legacy.target.path;+ for (const e of legacy.evidence) delete e.location;+ for (const e of legacy.entities) { delete e.lineStart; delete e.lineEnd; }+ expect(contextBundleSchema.safeParse(legacy).success).toBe(true);+ });+});diff --git a/ix-cli/src/cli/__tests__/context-investigation.test.ts b/ix-cli/src/cli/__tests__/context-investigation.test.tsindex 8a9e05ad..7a3f60e4 100644--- a/ix-cli/src/cli/__tests__/context-investigation.test.ts+++ b/ix-cli/src/cli/__tests__/context-investigation.test.ts@@ -725,12 +725,13 @@ describe("ix context investigation state", () => {);// An evidence title is a sentence. Same rule, and the reason the value- // must never be built with a template literal.+ // must never be built with a template literal. Its endpoints are names:+ // the ids stay in the evidence id and in the `relationship` records.expect(lines).toContain(- 'evidence change=added score=30 kind=relationship title="entity-1 --holds--> entity-3"',+ 'evidence change=added score=30 kind=relationship title="Widget --holds--> mount"',);expect(lines).toContain(- 'evidence change=removed score=30 kind=relationship title="entity-1 --calls--> entity-2"',+ 'evidence change=removed score=30 kind=relationship title="Widget --calls--> render"',);// One record per line — the wire format invariant.@@ -779,7 +780,7 @@ describe("ix context investigation state", () => {}// The exact record `--diff` would emit for the same item, minus `change=`.expect(lines).toContain(- 'evidence score=30 kind=relationship title="entity-1 --calls--> entity-2"',+ 'evidence score=30 kind=relationship title="Widget --calls--> render"',);// And the header is a record too, not fifteen bare `key=value` lines// built by interpolation — `target=${name}` breaks on any name with adiff --git a/ix-cli/src/cli/__tests__/facts-scope.test.ts b/ix-cli/src/cli/__tests__/facts-scope.test.tsindex 06ac7187..3fc6afbe 100644--- a/ix-cli/src/cli/__tests__/facts-scope.test.ts+++ b/ix-cli/src/cli/__tests__/facts-scope.test.ts@@ -86,3 +86,110 @@ describe("collectFacts scope", () => {expect(facts.callList?.map((c) => c.name)).toEqual(["callee"]);});});++/**+ * A file whose members the backend returns in an unhelpful order, with usage+ * recorded per member: `uses[id]` lists the files that use it.+ */+function fileWithMembers(+ calls: Call[],+ members: Array<{ id: string; name: string; kind?: string; lines?: [number, number] }>,+ uses: Record<string, string[]>,+ failing = new Set<string>(),+): IxClient {+ const memberNode = (m: (typeof members)[number]) => ({+ id: m.id, name: m.name, kind: m.kind ?? "function",+ attrs: m.lines ? { line_start: m.lines[0], line_end: m.lines[1] } : {},+ provenance: { sourceUri: "src/config.ts" },+ });+ return {+ async entity(id: string) {+ calls.push({ method: "entity", id });+ return { node: { id, name: "config.ts", kind: "file", attrs: {}, provenance: { sourceUri: "src/config.ts" } }, edges: [] };+ },+ async expand(id: string, opts?: { direction?: string; predicates?: string[]; limit?: number }) {+ calls.push({ method: "expand", id, predicates: opts?.predicates, hops: opts?.limit });+ if (id === TARGET && opts?.predicates?.[0] === "CONTAINS") {+ return { nodes: members.map(memberNode), edges: [] };+ }+ if (id !== TARGET) {+ if (failing.has(id)) throw new Error("backend unavailable");+ const nodes = (uses[id] ?? []).map((file, i) => ({+ id: `${id}-user-${i}`, name: `user${i}`, kind: "function", provenance: { sourceUri: file },+ }));+ return { nodes, edges: [] };+ }+ return { nodes: [], edges: [] };+ },+ async provenance(id: string) {+ calls.push({ method: "provenance", id });+ return { entityId: id, chain: [] };+ },+ } as unknown as IxClient;+}++describe("collectFacts member ranking", () => {+ const members = [+ { id: "m-real", name: "real", lines: [40, 41] as [number, number] },+ { id: "m-const", name: "DEFAULTS", kind: "variable", lines: [1, 30] as [number, number] },+ { id: "m-resolve", name: "resolveWorkspaceRoot", lines: [322, 342] as [number, number] },+ { id: "m-local", name: "localHelper", lines: [50, 60] as [number, number] },+ ];+ const uses = {+ "m-real": ["src/config.ts", "src/config.ts", "src/config.ts"],+ "m-resolve": ["src/a.ts", "src/b.ts", "src/b.ts", "src/config.ts"],+ "m-local": ["src/config.ts"],+ };++ it("ranks members used from other files first, for ix context", async () => {+ const calls: Call[] = [];+ const facts = await collectFacts(fileWithMembers(calls, members, uses), TARGET, "config.ts", "file", "context");++ expect(facts.members).toEqual(["resolveWorkspaceRoot", "real", "localHelper", "DEFAULTS"]);+ expect(facts.memberRefs?.[0]).toMatchObject({+ id: "m-resolve", path: "src/config.ts", lineStart: 322, lineEnd: 342, usedBy: 4, usedFromFiles: 2,+ });+ expect(facts.memberRefs?.[1]).toMatchObject({ usedBy: 3, usedFromFiles: 0 });+ // Bounded reads: the usage probe asks the backend for at most 50 users.+ const probes = calls.filter((c) => c.method === "expand" && c.id !== TARGET);+ expect(probes).toHaveLength(4);+ expect(probes.every((c) => c.hops === 50)).toBe(true);+ });++ it("leaves ix explain's member order, and its request count, alone", async () => {+ const calls: Call[] = [];+ const facts = await collectFacts(fileWithMembers(calls, members, uses), TARGET, "config.ts", "file");++ expect(facts.members).toEqual(["real", "DEFAULTS", "resolveWorkspaceRoot", "localHelper"]);+ expect(facts.memberRefs?.every((m) => m.usedBy === undefined)).toBe(true);+ expect(calls.some((c) => c.method === "expand" && c.id.startsWith("m-"))).toBe(false);+ });++ it("probes at most 40 members, chosen by kind and size", async () => {+ const many = Array.from({ length: 45 }, (_, i) => ({+ id: `m-${i}`, name: `fn${String(i).padStart(2, "0")}`, lines: [i + 1, i + 1 + i] as [number, number],+ }));+ const calls: Call[] = [];+ const facts = await collectFacts(fileWithMembers(calls, many, {}), TARGET, "config.ts", "file", "context");++ const probed = calls.filter((c) => c.method === "expand" && c.id !== TARGET).map((c) => c.id);+ expect(probed).toHaveLength(40);+ // The five smallest are the ones left unprobed, and they come last.+ expect(probed).not.toContain("m-0");+ expect(facts.memberRefs?.slice(-5).map((m) => m.id)).toEqual(["m-4", "m-3", "m-2", "m-1", "m-0"]);+ expect(facts.members).toHaveLength(45);+ });++ it("keeps a member it could not measure, below the measured ones", async () => {+ const calls: Call[] = [];+ const facts = await collectFacts(+ fileWithMembers(calls, members, uses, new Set(["m-resolve"])),+ TARGET, "config.ts", "file", "context",+ );++ expect(facts.members).toContain("resolveWorkspaceRoot");+ expect(facts.memberRefs?.find((m) => m.id === "m-resolve")?.usedBy).toBeUndefined();+ expect(facts.members[0]).toBe("real");+ expect(facts.members.at(-1)).toBe("resolveWorkspaceRoot");+ });+});diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.tsindex 94552a26..1c06f884 100644--- a/ix-cli/src/cli/commands/context.ts+++ b/ix-cli/src/cli/commands/context.ts@@ -19,7 +19,7 @@ import type {StructuredContext,} from "../../client/types.js";import { getEndpoint } from "../config.js";-import { collectFacts, type ContextFacts } from "../explain/facts.js";+import { collectFacts, type ContextFacts, type EntityLocation } from "../explain/facts.js";import { llmLine, printLlmLines } from "../llm.js";import { parseBudgetOption, parsePickOption, parseRevisionOption } from "../options.js";import { resolveFileOrReport } from "../resolve.js";@@ -163,6 +163,13 @@ type EvidenceKind =| "relationship"| "provenance";+/** Where an evidence item is defined, when the graph knows. */+interface EvidenceLocation {+ path: string;+ lineStart?: number;+ lineEnd?: number;+}+interface EvidenceItem {id: string;kind: EvidenceKind;@@ -172,14 +179,28 @@ interface EvidenceItem {score: number;reason: string;refs: string[];+ /**+ * Without it an agent handed `member resolveWorkspaceRoot` has to search the+ * repository for the thing Ix just found -- and for a file target named+ * `config.ts`, first work out which of several `config.ts` files it was.+ */+ location?: EvidenceLocation;}interface ContextBundle {schema: typeof BUNDLE_SCHEMA;/** The one explicitly declared time-dependent field. */generatedAt: string;- target: { id: string; name: string; kind: string; resolutionMode: string };- entities: Array<{ id: string; name: string; kind: string; path?: string; stale: boolean }>;+ target: { id: string; name: string; kind: string; resolutionMode: string; path?: string };+ entities: Array<{+ id: string;+ name: string;+ kind: string;+ path?: string;+ lineStart?: number;+ lineEnd?: number;+ stale: boolean;+ }>;relationships: Array<{ src: string; dst: string; predicate: string }>;claims: Array<{ id: string; entityId: string; statement: string; status: string }>;decisions: DecisionReport[];@@ -1179,7 +1200,14 @@ function entityRecord(change: RecordChange) {function evidenceRecord(change: RecordChange) {return (e: EvidenceItem): string =>- llmLine("evidence", { change, score: e.score, kind: e.kind, title: e.title });+ llmLine("evidence", {+ change,+ score: e.score,+ kind: e.kind,+ title: e.title,+ path: e.location?.path,+ lines: e.location ? lineRange(e.location) : undefined,+ });}function claimRecord(change: RecordChange) {@@ -1357,7 +1385,7 @@ export function buildBundle(input: BuildInput): ContextBundle {// written; this is the first thing to produce it.const graphCompleted = input.graphCompleted ?? true;const classification = !graphCompleted ? "unverified" : stale ? "stale" : "current";- const prov = asRecord(provenance);+ const prov = provenanceSource(provenance);// Entities: the target itself plus every referenced node, deduped by id and// ordered deterministically (kind, name, id) before budgeting.@@ -1378,6 +1406,27 @@ export function buildBundle(input: BuildInput): ContextBundle {stale,},];+ // The entities the facts collector located, most relevant first: members in+ // usage order, then the named callers and dependents. They go ahead of the+ // backend's context nodes, which are ordered by kind and name, so the entity+ // budget cuts what matters least. They also carry the paths and lines that+ // the backend's node summaries do not.+ const located = [+ ...(facts.memberRefs ?? []),+ ...(facts.topCallerRefs ?? []),+ ...(facts.topDependentRefs ?? []),+ ];+ for (const ref of located) {+ if (seen.has(ref.id)) continue;+ seen.add(ref.id);+ entities.push({+ id: ref.id,+ name: ref.name,+ kind: ref.kind,+ ...locationFields(ref),+ stale: false, // replaced below, for the entities that survive the budget+ });+ }// Compact and standard backend responses omit the full graph arrays and// carry the same graph as summaries. Falling back here keeps the default// context mode from collapsing to a target-only bundle.@@ -1412,7 +1461,7 @@ export function buildBundle(input: BuildInput): ContextBundle {.sort((a, b) => cmp(a.src, b.src) || cmp(a.dst, b.dst) || cmp(a.predicate, b.predicate)).map((edge) => ({ src: edge.src, dst: edge.dst, predicate: edge.predicate }));- const evidence = rankEvidence({ resolved, facts, context, relationships, prov });+ const evidence = rankEvidence({ resolved, facts, context, relationships, prov, entities });const bundle: ContextBundle = {schema: BUNDLE_SCHEMA,@@ -1422,6 +1471,7 @@ export function buildBundle(input: BuildInput): ContextBundle {name: resolved.name,kind: resolved.kind,resolutionMode: resolved.resolutionMode,+ ...(facts.path ? { path: facts.path } : {}),},entities: [],relationships: [],@@ -1534,6 +1584,7 @@ function rankEvidence(input: {context: StructuredContext;relationships: Array<{ src: string; dst: string; predicate: string }>;prov: Record<string, unknown>;+ entities: ContextBundle["entities"];}): EvidenceItem[] {const items: EvidenceItem[] = [];@@ -1546,33 +1597,49 @@ 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),});- const structural: Array<{ id: string; source: string; title: string; refs: string[] }> = [];+ type Structural = Omit<EvidenceItem, "kind" | "score">;+ const structural: Structural[] = [];if (input.facts.container) {structural.push({id: `container:${input.facts.container.name}`,source: "facts.container",title: `container ${input.facts.container.name} (${input.facts.container.kind})`,+ reason: "contains the target",refs: [],});}- for (const name of input.facts.topCallers) {- structural.push({ id: `caller:${name}`, source: "facts.callers", title: `caller ${name}`, refs: [] });+ // Names alone when the facts carry no locations, so a caller that builds its+ // own facts (or an older collector) still gets the structural evidence.+ const related = (+ names: string[],+ refs: EntityLocation[] | undefined,+ limit: number,+ ): Array<{ name: string; ref?: EntityLocation }> =>+ (refs ? refs.map((ref) => ({ name: ref.name, ref })) : names.map((name) => ({ name }))).slice(0, limit);++ for (const { name, ref } of related(input.facts.topCallers, input.facts.topCallerRefs, 3)) {+ structural.push({+ id: `caller:${name}`, source: "facts.callers", title: `caller ${name}`,+ reason: "calls the target", refs: ref ? [ref.id] : [], ...locationField(ref),+ });}- for (const name of input.facts.topDependents) {+ for (const { name, ref } of related(input.facts.topDependents, input.facts.topDependentRefs, 3)) {structural.push({- id: `dependent:${name}`,- source: "facts.dependents",- title: `dependent ${name}`,- refs: [],+ id: `dependent:${name}`, source: "facts.dependents", title: `dependent ${name}`,+ reason: "calls, imports or references the target", refs: ref ? [ref.id] : [], ...locationField(ref),});}- for (const name of input.facts.members.slice(0, 10)) {- structural.push({ id: `member:${name}`, source: "facts.members", title: `member ${name}`, refs: [] });+ for (const { name, ref } of related(input.facts.members, input.facts.memberRefs, 10)) {+ structural.push({+ id: `member:${name}`, source: "facts.members", title: `member ${name}`,+ reason: ref ? memberReason(ref) : "defined in the target", refs: ref ? [ref.id] : [], ...locationField(ref),+ });}structural.forEach((item, index) => {- items.push({ ...item, kind: "structural", score: 10 + index, reason: "direct structural relationship" });+ items.push({ ...item, kind: "structural", score: 10 + index });});for (const scored of input.context.claims) {@@ -1620,12 +1687,13 @@ function rankEvidence(input: {});}+ const label = entityLabeller(input.entities);input.relationships.slice(0, 50).forEach((edge, index) => {items.push({id: `relationship:${edge.src}:${edge.dst}:${edge.predicate}`,kind: "relationship",source: "context.edges",- title: `${edge.src} --${edge.predicate}--> ${edge.dst}`,+ title: `${label(edge.src)} --${edge.predicate}--> ${label(edge.dst)}`,score: 30 + Math.min(index, 10),reason: "graph relationship from the context service",refs: [edge.src, edge.dst],@@ -1663,6 +1731,7 @@ export function renderBundle(bundle: ContextBundle, format: string): void {llmLine("context", {target: bundle.target.name,target_kind: bundle.target.kind,+ target_path: bundle.target.path,stale: bundle.freshness.stale,classification: bundle.freshness.classification,entities: bundle.entities.length,@@ -1688,6 +1757,7 @@ export function renderBundle(bundle: ContextBundle, format: string): void {renderSection(`Context: ${bundle.target.name}`);console.log(` kind: ${bundle.target.kind}`);+ if (bundle.target.path) console.log(` path: ${bundle.target.path}`);console.log(` classification:${bundle.freshness.classification}`);console.log(` entities: ${bundle.entities.length}`);console.log(` relationships: ${bundle.relationships.length}`);@@ -1703,7 +1773,8 @@ export function renderBundle(bundle: ContextBundle, format: string): void {renderSection("Evidence (highest relevance first)");for (const item of bundle.evidence) {console.log(` [${item.score}] ${item.kind} — ${item.title}`);- console.log(` ${item.reason}`);+ const where = item.location ? `${formatLocation(item.location)} — ` : "";+ console.log(` ${where}${item.reason}`);}}@@ -1716,6 +1787,86 @@ export function renderBundle(bundle: ContextBundle, format: string): void {console.log();}+type Located = { path?: string; lineStart?: number; lineEnd?: number };++/** `path`, `lineStart` and `lineEnd`, omitting the unknown ones rather than writing `undefined`. */+function locationFields(ref: Located): Located {+ return {+ ...(ref.path ? { path: ref.path } : {}),+ ...(ref.lineStart !== undefined ? { lineStart: ref.lineStart } : {}),+ ...(ref.lineEnd !== undefined ? { lineEnd: ref.lineEnd } : {}),+ };+}++/** An evidence `location`, or nothing when the path is unknown. */+function locationField(ref: Located | undefined): { location?: EvidenceLocation } {+ if (!ref?.path) return {};+ return { location: { ...locationFields(ref), path: ref.path } };+}++function lineRange(location: EvidenceLocation): string | undefined {+ const { lineStart, lineEnd } = location;+ if (lineStart === undefined) return undefined;+ return lineEnd !== undefined && lineEnd !== lineStart ? `${lineStart}-${lineEnd}` : `${lineStart}`;+}++function formatLocation(location: EvidenceLocation): string {+ const lines = lineRange(location);+ return lines ? `${location.path}:${lines}` : location.path;+}++function memberReason(ref: EntityLocation): string {+ if (ref.usedBy === undefined) return "defined in the target";+ if (ref.usedBy === 0) return "defined in the target; no recorded uses";+ const files = ref.usedFromFiles ?? 0;+ const where = files > 0 ? ` across ${files} other file${files === 1 ? "" : "s"}` : " within this file";+ return `defined in the target; used by ${ref.usedBy}${where}`;+}++/**+ * Names for relationship endpoints. Relationship evidence used to print raw+ * ids -- `264cc04d-... --CONTAINS--> d1898d46-...` -- which an agent cannot use.+ * A name shared by two entities is qualified with its path, since several+ * files are routinely named `config.ts` or `README.md`; an id the bundle knows+ * nothing about stays an id.+ */+function entityLabeller(entities: ContextBundle["entities"]): (id: string) => string {+ const byId = new Map(entities.map((e) => [e.id, e]));+ const nameCounts = new Map<string, number>();+ for (const e of entities) nameCounts.set(e.name, (nameCounts.get(e.name) ?? 0) + 1);+ return (id) => {+ const e = byId.get(id);+ if (!e) return id;+ return (nameCounts.get(e.name) ?? 0) > 1 && e.path ? `${e.name} (${e.path})` : e.name;+ };+}++/**+ * The source record of a `/v1/provenance` response.+ *+ * The endpoint answers `{ entityId, chain: [{ rev, source: { uri, extractor,+ * ... } }] }`, and this used to read `sourceUri` and `extractor` off the top+ * level, where they never are -- so every bundle reported "provenance unknown,+ * extractor unknown". The newest chain entry is the one that describes the+ * current node. A flat record is still accepted as-is.+ */+function provenanceSource(provenance: unknown): Record<string, unknown> {+ const record = asRecord(provenance);+ const chain = Array.isArray(record.chain) ? record.chain.map(asRecord) : undefined;+ if (!chain) return record;+ if (chain.length === 0) return {};+ const latest = chain.reduce((a, b) =>+ (typeof b.rev === "number" ? b.rev : -Infinity) > (typeof a.rev === "number" ? a.rev : -Infinity) ? b : a);+ const source = asRecord(latest.source);+ return {+ sourceUri: source.uri ?? source.sourceUri,+ sourceHash: source.sourceHash,+ extractor: source.extractor,+ sourceType: source.sourceType,+ observedAt: latest.observedAt ?? source.observedAt,+ };+}+function orderedNodes<T extends { id: string; kind: string; name: string }>(nodes: T[]): T[] {return [...nodes].sort((a, b) => cmp(a.kind, b.kind) || cmp(a.name, b.name) || cmp(a.id, b.id));}diff --git a/ix-cli/src/cli/context-bundle-schema.ts b/ix-cli/src/cli/context-bundle-schema.tsindex f5240d82..6d4ad35d 100644--- a/ix-cli/src/cli/context-bundle-schema.ts+++ b/ix-cli/src/cli/context-bundle-schema.ts@@ -42,9 +42,18 @@ export const contextBundleSchema = z.object({name: z.string(),kind: z.string(),resolutionMode: z.string(),+ path: z.string().optional(),}),entities: z.array(- z.object({ id: z.string(), name: z.string(), kind: z.string(), path: z.string().optional(), stale: z.boolean() }),+ z.object({+ id: z.string(),+ name: z.string(),+ kind: z.string(),+ path: z.string().optional(),+ lineStart: z.number().int().positive().optional(),+ lineEnd: z.number().int().positive().optional(),+ stale: z.boolean(),+ }),),relationships: z.array(z.object({ src: z.string(), dst: z.string(), predicate: z.string() })),claims: z.array(@@ -81,6 +90,16 @@ export const contextBundleSchema = z.object({score: z.number(),reason: z.string(),refs: z.array(z.string()),+ // Optional and additive: bundles saved before it existed still parse.+ // Listed rather than left to `catchall`, because an unlisted key is+ // stripped on the way to disk and on the way back.+ location: z+ .object({+ path: z.string(),+ lineStart: z.number().int().positive().optional(),+ lineEnd: z.number().int().positive().optional(),+ })+ .optional(),}),),budgets: z.object({diff --git a/ix-cli/src/cli/explain/facts.ts b/ix-cli/src/cli/explain/facts.tsindex b7f17ecf..9bb99b06 100644--- a/ix-cli/src/cli/explain/facts.ts+++ b/ix-cli/src/cli/explain/facts.ts@@ -8,6 +8,23 @@ import { isFileStale } from "../stale.js";import { buildDependencyTree } from "../commands/depends.js";import { getSystemPath } from "../hierarchy.js";+/** A related entity and where it is defined. */+export interface EntityLocation {+ id: string;+ name: string;+ kind: string;+ path?: string;+ lineStart?: number;+ lineEnd?: number;+ /**+ * Distinct entities with an inbound CALLS, REFERENCES or IMPORTS edge, capped+ * at `MEMBER_USE_CAP`. Only measured for members, and only by `ix context`.+ */+ usedBy?: number;+ /** How many of those live in a different file. */+ usedFromFiles?: number;+}+export interface EntityFacts {// Identityid: string;@@ -20,6 +37,8 @@ export interface EntityFacts {// Structural contextcontainer?: { kind: string; name: string };members: string[];+ /** The same members with their locations, in the same order as `members`. */+ memberRefs?: EntityLocation[];memberCount: number;// Relationship counts@@ -35,6 +54,9 @@ export interface EntityFacts {// Named usage examples (up to 3 each)topCallers: string[];topDependents: string[];+ /** The entities behind `topCallers` / `topDependents`, same order. */+ topCallerRefs?: EntityLocation[];+ topDependentRefs?: EntityLocation[];// HistoryintroducedRev?: number;@@ -74,6 +96,95 @@ export type ContextFacts = Omit<EntityFacts, ExplainOnlyFact> & { provenance?: uconst NO_DOWNSTREAM = { tree: [], truncated: false, nodesVisited: 0, maxDepthReached: 0 };+/** Members probed for usage; the rest keep their structural order after them. */+const MEMBER_USE_POOL = 40;+/** Inbound edges read per member. Enough to rank by; a hub is a hub at 50. */+const MEMBER_USE_CAP = 50;+const MEMBER_USE_CONCURRENCY = 6;+const USE_PREDICATES = ["CALLS", "REFERENCES", "IMPORTS"];++/** Kinds a reader navigates by. Everything else ranks after them. */+const PRIMARY_MEMBER_KINDS = new Set([+ "class", "interface", "function", "method", "type", "enum", "trait", "struct", "object", "module",+]);++function lineOf(value: unknown): number | undefined {+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;+}++function toLocation(n: any): EntityLocation {+ const kind = n.kind || "unknown";+ // A file's line span is the whole file, which says nothing a path does not.+ const lines = kind === "file" ? {} : { lineStart: lineOf(n.attrs?.line_start), lineEnd: lineOf(n.attrs?.line_end) };+ return {+ id: n.id,+ name: n.name || n.attrs?.name || "(unnamed)",+ kind,+ path: relativePath(n.provenance?.sourceUri ?? n.provenance?.source_uri),+ ...lines,+ };+}++/**+ * Order members so the ones a reader needs survive the cut.+ *+ * `ix context` shows the first ten members, and the backend returns them in no+ * particular order. On `config.ts` in the Ix repo that dropped+ * `resolveWorkspaceRoot` -- 13 callers, the function the file exists for --+ * while showing `real`, a two-line helper.+ *+ * Usage is measured, not guessed: one bounded inbound expand per member, for at+ * most `MEMBER_USE_POOL` of them, chosen by kind and then by size. Members used+ * from other files rank first, then by total uses; ties keep the structural+ * order, which is itself deterministic.+ */+async function rankMembersByUse(client: IxClient, members: EntityLocation[]): Promise<EntityLocation[]> {+ const span = (m: EntityLocation) =>+ m.lineStart !== undefined && m.lineEnd !== undefined ? m.lineEnd - m.lineStart : 0;+ const structural = members+ .map((m, index) => ({ m, index }))+ .sort((a, b) =>+ Number(!PRIMARY_MEMBER_KINDS.has(a.m.kind)) - Number(!PRIMARY_MEMBER_KINDS.has(b.m.kind)) ||+ span(b.m) - span(a.m) ||+ (a.m.name < b.m.name ? -1 : a.m.name > b.m.name ? 1 : 0) ||+ a.index - b.index)+ .map(({ m }) => m);++ const pool = structural.slice(0, MEMBER_USE_POOL);+ const measured: EntityLocation[] = new Array(pool.length);+ let next = 0;+ const worker = async () => {+ while (next < pool.length) {+ const index = next++;+ const member = pool[index];+ try {+ const result = await client.expand(member.id, {+ direction: "in", predicates: USE_PREDICATES, limit: MEMBER_USE_CAP,+ });+ const users = new Map<string, string | undefined>();+ for (const n of result.nodes ?? []) {+ if (n?.id && n.id !== member.id) users.set(n.id, relativePath(n.provenance?.sourceUri ?? n.provenance?.source_uri));+ }+ const files = new Set([...users.values()].filter((p) => p && p !== member.path));+ measured[index] = { ...member, usedBy: users.size, usedFromFiles: files.size };+ } catch {+ // Unmeasured, not zero: it keeps its structural place below.+ measured[index] = member;+ }+ }+ };+ await Promise.all(Array.from({ length: Math.min(MEMBER_USE_CONCURRENCY, pool.length) }, worker));++ const ranked = measured+ .map((m, index) => ({ m, index }))+ .sort((a, b) =>+ (b.m.usedFromFiles ?? -1) - (a.m.usedFromFiles ?? -1) ||+ (b.m.usedBy ?? -1) - (a.m.usedBy ?? -1) ||+ a.index - b.index)+ .map(({ m }) => m);+ return [...ranked, ...structural.slice(MEMBER_USE_POOL)];+}+/*** Collect the structural facts about one entity.*@@ -155,23 +266,26 @@ export async function collectFacts(return true;});- // Members- const memberNames = membersResult.nodes.map(- (n: any) => n.name || n.attrs?.name || "(unnamed)",- );+ // Members. `ix context` ranks them by use; `ix explain` keeps graph order.+ const memberRefs = forExplain+ ? membersResult.nodes.map(toLocation)+ : await rankMembersByUse(client, membersResult.nodes.map(toLocation));+ const memberNames = memberRefs.map((m) => m.name);// Named usage examples (up to 3 resolved names from callers/dependents)- const extractNames = (nodes: any[], limit: number): string[] => {- const names: string[] = [];+ const extractRefs = (nodes: any[], limit: number): EntityLocation[] => {+ const refs: EntityLocation[] = [];for (const n of nodes) {- if (names.length >= limit) break;+ if (refs.length >= limit) break;const name = n.name || n.attrs?.name || "";- if (name && !isRawId(name)) names.push(name);+ if (name && !isRawId(name)) refs.push(toLocation(n));}- return names;+ return refs;};- const topCallers = extractNames(callersResult.nodes, 3);- const topDependents = extractNames(uniqueDependents, 3);+ const topCallerRefs = extractRefs(callersResult.nodes, 3);+ const topDependentRefs = extractRefs(uniqueDependents, 3);+ const topCallers = topCallerRefs.map((r) => r.name);+ const topDependents = topDependentRefs.map((r) => r.name);// Build callList from outgoing CALLS edges (reuse logic from explain.ts)const calleeEdges = edges.filter(@@ -257,6 +371,7 @@ export async function collectFacts(docstring,container,members: memberNames,+ memberRefs,memberCount: membersResult.nodes.length,callerCount: callersResult.nodes.length,calleeCount: calleesResult.nodes.length,@@ -266,6 +381,8 @@ export async function collectFacts(downstreamDepth: downstream.maxDepthReached,topCallers,topDependents,+ topCallerRefs,+ topDependentRefs,introducedRev: node.createdRev ?? node.created_rev,historyLength: history?.chain?.length ?? 0,callList,diff --git a/ix-cli/src/client/api.ts b/ix-cli/src/client/api.tsindex c99d8d0e..2d09d80c 100644--- a/ix-cli/src/client/api.ts+++ b/ix-cli/src/client/api.ts@@ -189,13 +189,15 @@ export class IxClient {async expand(id: string,- opts?: { direction?: string; predicates?: string[]; hops?: number }+ opts?: { direction?: string; predicates?: string[]; hops?: number; limit?: number }): Promise<{ nodes: any[]; edges: any[] }> {return this.post("/v1/expand", {nodeId: id,direction: opts?.direction ?? "both",predicates: opts?.predicates,hops: opts?.hops ?? 1,+ // Only when asked for, so every existing caller sends the body it did.+ ...(opts?.limit !== undefined ? { limit: opts.limit } : {}),});}