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): evidence tiers, ranked callers, one used-by row (#852)
Ian Hockf6c0c906cce8
diff --git a/docs/llm-format.md b/docs/llm-format.mdindex ba95a5d2..8807c8b8 100644--- a/docs/llm-format.md+++ b/docs/llm-format.md@@ -474,12 +474,18 @@ item name=parseFile kind=method```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=0evidence 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-40-evidence score=20 kind=claim title="renders to DOM"-evidence score=30 kind=relationship title="Widget --calls--> render"-```--One header record, then the ranked evidence. The entity, relationship and claim+evidence score=2000 kind=structural title="member render" path=src/widget.ts lines=12-40+evidence score=3000 kind=claim title="renders to DOM"+evidence score=4000 kind=relationship title="Widget --calls--> mount"+```++One header record, then the ranked evidence. `score` is `tier * 1000` plus the+row's place in its tier, tiers in order target, issue, structural, claims,+relationships, provenance, so a tier never runs into the next. Each entity gets+one row: a relationship that restates a member, import or caller row is left+out. A target's callers and dependents share one row, titled with how many of+how many (`used by (3 of 214): ...`); `--format json` carries the two numbers+as `count: { shown, total }`. 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.@@ -500,7 +506,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="Widget --holds--> mount"+evidence change=added score=4000 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.tsindex 503bac22..083c9b67 100644--- a/ix-cli/src/cli/__tests__/context-evidence-locations.test.ts+++ b/ix-cli/src/cli/__tests__/context-evidence-locations.test.ts@@ -85,7 +85,9 @@ describe("ix context evidence says where things are", () => {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" });+ const usedBy = b.evidence.find((e) => e.id === "used-by");+ expect(usedBy?.title).toBe("used by (1 of 1): stats.ts");+ expect(usedBy?.location).toEqual({ path: "src/cli/commands/stats.ts" });});it("keeps the members in the order the facts ranked them, and says why", () => {@@ -156,7 +158,7 @@ describe("ix context evidence says where things are", () => {expect(b.entities).toHaveLength(50);});- it("says what the target imports and calls, ahead of what points back at it", () => {+ it("says what the target imports and calls, after what uses it", () => {// The answer to a question asked from an entry point is most often in a// file that entry point imports. Before this the bundle only pointed// inward -- members, callers, dependents -- and never named it.@@ -172,8 +174,10 @@ describe("ix context evidence says where things are", () => {const structural = b.evidence.filter((e) => e.kind === "structural").map((e) => e.title);expect(structural).toContain("imports resolve.ts");expect(structural).toContain("calls ensureReadScope");- expect(structural.indexOf("imports resolve.ts"))- .toBeLessThan(structural.indexOf("dependent stats.ts"));+ // What uses the target goes first: after the imports and neighbours it+ // missed the default budget on most file targets (CL-07).+ expect(structural.indexOf("used by (1 of 1): stats.ts"))+ .toBeLessThan(structural.indexOf("imports resolve.ts"));const imported = b.evidence.find((e) => e.title === "imports resolve.ts");expect(imported?.location).toEqual({ path: "src/cli/resolve.ts" });@@ -244,7 +248,8 @@ describe("ix context evidence says where things are", () => {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");+ // Restates the `member resolveWorkspaceRoot` row, so it is not repeated.+ expect(titles).not.toContain("config.ts --CONTAINS--> resolveWorkspaceRoot");expect(titles).toContain("config.ts --IMPORTS--> not-in-bundle");});@@ -263,7 +268,7 @@ describe("ix context evidence says where things are", () => {// structural facts: a file with many imports pushed all of its own members// out of the evidence budget when they came last.expect(llm).toContain(- 'evidence score=10 kind=structural title="member resolveWorkspaceRoot" path=src/cli/config.ts lines=322-342',+ 'evidence score=2000 kind=structural title="member resolveWorkspaceRoot" path=src/cli/config.ts lines=322-342',);});diff --git a/ix-cli/src/cli/__tests__/context-evidence-order.test.ts b/ix-cli/src/cli/__tests__/context-evidence-order.test.tsnew file mode 100644index 00000000..56d735b5--- /dev/null+++ b/ix-cli/src/cli/__tests__/context-evidence-order.test.ts@@ -0,0 +1,354 @@+// Copyright 2026 Ix Infrastructure Inc.++import { describe, expect, it } from "vitest";++import type { IxClient } from "../../client/api.js";+import { buildBundle, clampBudgets, diffInvestigations } from "../commands/context.js";+import { collectFacts, type ContextFacts, type EntityLocation } from "../explain/facts.js";+import { collectRelatedFiles } from "../explain/related-files.js";++/**+ * Evidence order for `ix context`: tiers that do not interleave, callers and+ * dependents ahead of the neighbour rows, one "used by" row with its total,+ * and no entity in two rows.+ */++function loc(id: string, name: string, path: string, lines?: [number, number], kind = "function"): EntityLocation {+ return { id, name, kind, path, ...(lines ? { lineStart: lines[0], lineEnd: lines[1] } : {}) };+}++function baseFacts(over: Partial<ContextFacts>): ContextFacts {+ return {+ id: "f-target", name: "config.ts", kind: "file", path: "src/cli/config.ts",+ members: [], memberCount: 0,+ callerCount: 0, calleeCount: 0, dependentCount: 0, importerCount: 0,+ topCallers: [], topDependents: [],+ historyLength: 1, introducedRev: 7, stale: false, diagnostics: [],+ ...over,+ };+}++function claims(n: number) {+ return Array.from({ length: n }, (_, i) => ({+ claim: { id: `cl-${i}`, entityId: "f-target", statement: `claim number ${i} about config`, status: "active" },+ relevance: 1, confidence: { score: 0.5 },+ }));+}++function bundleFor(facts: ContextFacts, extra: { claims?: number; edges?: Array<{ src: string; dst: string; predicate: string }> } = {}) {+ return buildBundle({+ resolved: { id: facts.id, name: facts.name, kind: facts.kind, resolutionMode: "exact" },+ facts,+ context: {+ claims: claims(extra.claims ?? 0), conflicts: [], decisions: [], intents: [],+ nodes: [], edges: extra.edges ?? [],+ metadata: { query: "", seedEntities: [], hopsExpanded: 1, asOfRev: 1 },+ } as never,+ provenance: {},+ budgets: clampBudgets({}, "llm"),+ format: "llm",+ isStale: () => false,+ });+}++/** A file target with more structural rows than the default budget holds. */+function bigFileFacts(): ContextFacts {+ const memberRefs = Array.from({ length: 10 }, (_, i) =>+ ({ ...loc(`m-${i}`, `member${i}`, "src/cli/config.ts", [i * 20 + 1, i * 20 + 15]), usedBy: 10 - i, usedFromFiles: 1 }));+ return baseFacts({+ memberRefs, members: memberRefs.map((m) => m.name), memberCount: 10,+ relatedRefs: [{ id: "r-1", name: "far.ts", kind: "file", path: "src/far.ts", score: 1, reason: "", via: ["x"] }] as never,+ importRefs: Array.from({ length: 8 }, (_, i) => loc(`i-${i}`, `dep${i}.ts`, `src/dep${i}.ts`, undefined, "file")),+ neighbourRefs: Array.from({ length: 6 }, (_, i) => loc(`n-${i}`, `helper${i}`, `src/dep${i}.ts`, [1, 9])),+ dependentCount: 214, topDependents: ["stats.ts", "rank.ts", "watch.ts"],+ topDependentRefs: [+ loc("d-1", "stats.ts", "src/cli/commands/stats.ts", undefined, "file"),+ loc("d-2", "rank.ts", "src/cli/commands/rank.ts", undefined, "file"),+ loc("d-3", "watch.ts", "src/cli/commands/watch.ts", undefined, "file"),+ ],+ callerCount: 2, topCallers: ["main"],+ topCallerRefs: [loc("c-1", "main", "src/cli/main.ts", [10, 40])],+ usedByCount: 214,+ });+}++describe("evidence tiers", () => {+ it("ranks callers and dependents of a file target inside the first 20 rows and within the default budget", () => {+ const bundle = bundleFor(bigFileFacts(), { claims: 6 });++ const usedBy = bundle.evidence.findIndex((e) => e.refs.includes("d-1"));+ expect(usedBy).toBeGreaterThanOrEqual(0);+ expect(usedBy).toBeLessThan(20);+ // Before the neighbour and import rows, after the leading members.+ const firstNeighbour = bundle.evidence.findIndex((e) => e.source === "facts.neighbours");+ const firstImport = bundle.evidence.findIndex((e) => e.source === "facts.imports");+ if (firstNeighbour >= 0) expect(usedBy).toBeLessThan(firstNeighbour);+ if (firstImport >= 0) expect(usedBy).toBeLessThan(firstImport);+ for (const id of ["c-1", "d-1", "d-2", "d-3"]) {+ expect(bundle.evidence.some((e) => e.refs.includes(id)), id).toBe(true);+ }+ });++ it("does not interleave tiers: every structural row ranks ahead of every claim", () => {+ const bundle = bundleFor(bigFileFacts(), { claims: 3 });+ const scores = bundle.evidence.map((e) => e.score);+ expect([...scores].sort((a, b) => a - b)).toEqual(scores);+ const kinds = bundle.evidence.map((e) => e.kind);+ const lastStructural = kinds.lastIndexOf("structural");+ const firstClaim = kinds.indexOf("claim");+ if (firstClaim >= 0) expect(lastStructural).toBeLessThan(firstClaim);+ });+});++describe("used-by row", () => {+ it("merges callers and dependents into one row titled with the total", () => {+ const facts = baseFacts({+ callerCount: 1, topCallers: ["main"], topCallerRefs: [loc("c-1", "main", "src/cli/main.ts", [10, 40])],+ dependentCount: 214, topDependents: ["main", "stats.ts"],+ topDependentRefs: [+ loc("c-1", "main", "src/cli/main.ts", [10, 40]),+ loc("d-1", "stats.ts", "src/cli/commands/stats.ts", undefined, "file"),+ ],+ usedByCount: 214,+ });+ const bundle = bundleFor(facts);+ const rows = bundle.evidence.filter((e) => e.refs.includes("c-1") || e.refs.includes("d-1"));+ expect(rows).toHaveLength(1);+ expect(rows[0]!.title).toMatch(/^used by \(2 of 214\): /);+ expect(rows[0]!.refs).toEqual(["c-1", "d-1"]);+ expect((rows[0] as { count?: unknown }).count).toEqual({ shown: 2, total: 214 });+ });+});++describe("evidence de-duplication", () => {+ it("never puts one entity in two rows", () => {+ const facts = bigFileFacts();+ // The same file as an import and a dependent, a member restated by a+ // CONTAINS edge, and an import restated by an IMPORTS edge.+ facts.topDependentRefs = [...facts.topDependentRefs!, loc("i-0", "dep0.ts", "src/dep0.ts", undefined, "file")];+ const bundle = buildBundle({+ resolved: { id: facts.id, name: facts.name, kind: facts.kind, resolutionMode: "exact" },+ facts,+ context: {+ claims: [], conflicts: [], decisions: [], intents: [], nodes: [],+ edges: [+ { src: "f-target", dst: "m-0", predicate: "CONTAINS" },+ { src: "f-target", dst: "i-1", predicate: "IMPORTS" },+ { src: "x-1", dst: "f-target", predicate: "REFERENCES" },+ ],+ metadata: { query: "", seedEntities: [], hopsExpanded: 1, asOfRev: 1 },+ } as never,+ provenance: {},+ budgets: clampBudgets({ maxEvidence: 200, maxTokens: 200_000 }, "json"),+ isStale: () => false,+ });++ const seen = new Map<string, string>();+ for (const row of bundle.evidence) {+ if (row.kind === "claim" || row.kind === "decision" || row.kind === "intent") continue;+ if (row.kind === "target" || row.id.startsWith("provenance:")) continue;+ for (const ref of row.refs) {+ if (ref === "f-target") continue;+ expect(seen.get(ref), `${ref} in ${row.id} and ${seen.get(ref)}`).toBeUndefined();+ seen.set(ref, row.id);+ }+ }+ // The relationship that names something new survives.+ expect(bundle.evidence.some((e) => e.refs.includes("x-1"))).toBe(true);+ });+});++describe("evidence ids", () => {+ it("keys member rows by entity id, so same-name members do not collide", () => {+ const facts = baseFacts({+ memberRefs: [+ loc("m-a", "render", "src/cli/config.ts", [1, 10]),+ loc("m-b", "render", "src/cli/config.ts", [20, 30]),+ ],+ members: ["render", "render"], memberCount: 2,+ });+ const bundle = bundleFor(facts);+ const ids = bundle.evidence.filter((e) => e.source === "facts.members").map((e) => e.id);+ expect(ids).toEqual(["member:m-a", "member:m-b"]);+ expect(new Set(bundle.evidence.map((e) => e.id)).size).toBe(bundle.evidence.length);+ });+});++describe("member use counts", () => {+ it("shows N+ when the use probe hit its cap", () => {+ const facts = baseFacts({+ memberRefs: [+ { ...loc("m-a", "hub", "src/cli/config.ts", [1, 10]), usedBy: 50, usedFromFiles: 12, usedByCapped: true },+ { ...loc("m-b", "leaf", "src/cli/config.ts", [20, 30]), usedBy: 3, usedFromFiles: 1 },+ ],+ members: ["hub", "leaf"], memberCount: 2,+ });+ const bundle = bundleFor(facts);+ const reason = (id: string) => bundle.evidence.find((e) => e.id === `member:${id}`)!.reason;+ expect(reason("m-a")).toContain("used by 50+ across");+ expect(reason("m-b")).toContain("used by 3 across");+ });+});++// ---------------------------------------------------------------- collectFacts++const TARGET = "t-0";++interface Raw { id: string; name: string; kind: string; path: string }++/** A target with the given callers; `order` permutes what the backend returns. */+function callerClient(callers: Raw[], edges: Array<{ src: string; dst: string; predicate: string }>, memberUses = 0): IxClient {+ const node = (r: Raw) => ({ id: r.id, name: r.name, kind: r.kind, attrs: {}, provenance: { sourceUri: r.path } });+ return {+ async entity(id: string) {+ return { node: { id, name: "rank", kind: "function", attrs: {}, provenance: { sourceUri: "src/cli/rank.ts" } }, edges: [] };+ },+ async expand(id: string, opts?: { direction?: string; predicates?: string[]; limit?: number }) {+ if (id === TARGET && opts?.direction === "in" && opts.predicates?.includes("CALLS")) {+ return { nodes: callers.map(node), edges };+ }+ if (id === TARGET && opts?.predicates?.[0] === "CONTAINS") {+ return { nodes: [{ id: "m-hub", name: "hub", kind: "function", attrs: {}, provenance: { sourceUri: "src/cli/rank.ts" } }], edges: [] };+ }+ if (id === "m-hub") {+ const nodes = Array.from({ length: memberUses }, (_, i) =>+ ({ id: `u-${i}`, name: `u${i}`, kind: "function", provenance: { sourceUri: `src/u${i}.ts` } }));+ return { nodes, edges: [] };+ }+ return { nodes: [], edges: [] };+ },+ async provenance(id: string) { return { entityId: id, chain: [] }; },+ } as unknown as IxClient;+}++const CALLERS: Raw[] = [+ { id: "c-test", name: "itRanks", kind: "function", path: "src/cli/__tests__/rank.test.ts" },+ { id: "c-far1", name: "farOne", kind: "function", path: "src/other/far.ts" },+ { id: "c-far2", name: "farTwo", kind: "function", path: "src/other/far.ts" },+ { id: "c-near", name: "nearby", kind: "function", path: "src/cli/near.ts" },+ { id: "c-heavy", name: "heavy", kind: "function", path: "src/zz/heavy.ts" },+ { id: "c-light", name: "light", kind: "function", path: "src/aa/light.ts" },+];+const EDGES = [+ ...CALLERS.map((c) => ({ src: c.id, dst: TARGET, predicate: "CALLS" })),+ { src: "c-heavy", dst: TARGET, predicate: "CALLS" },+ { src: "c-heavy", dst: TARGET, predicate: "CALLS" },+];++function permutations<T>(xs: T[]): T[][] {+ // Rotations and reversals: enough to change every position.+ const out: T[][] = [];+ for (let i = 0; i < xs.length; i++) {+ const rot = [...xs.slice(i), ...xs.slice(0, i)];+ out.push(rot, [...rot].reverse());+ }+ return out;+}++describe("collectFacts caller ranking", () => {+ it("is independent of the backend's return order", async () => {+ const lists = await Promise.all(permutations(CALLERS).map(async (order) => {+ const facts = await collectFacts(callerClient(order, [...EDGES].reverse()), TARGET, "rank", "function", "context");+ return { callers: facts.topCallerRefs!.map((r) => r.id), dependents: facts.topDependentRefs!.map((r) => r.id) };+ }));+ for (const l of lists) expect(l).toEqual(lists[0]);+ });++ it("ranks non-test, distinct-file, same-directory, then most-linked callers first", async () => {+ const facts = await collectFacts(callerClient(CALLERS, EDGES), TARGET, "rank", "function", "context");+ // Same directory first, then the caller with the most edges to the target,+ // then path order; the second caller from far.ts and the test come last.+ expect(facts.topCallerRefs!.map((r) => r.id)).toEqual(["c-near", "c-heavy", "c-light"]);+ expect(facts.callerCount).toBe(6);+ });++ it("marks a member use count that hit the probe cap", async () => {+ const facts = await collectFacts(callerClient(CALLERS, EDGES, 50), TARGET, "rank", "function", "context");+ expect(facts.memberRefs?.[0]).toMatchObject({ usedBy: 50, usedByCapped: true });+ const under = await collectFacts(callerClient(CALLERS, EDGES, 7), TARGET, "rank", "function", "context");+ expect(under.memberRefs?.[0]?.usedByCapped).toBeUndefined();+ });+});++// ------------------------------------------------------------- walk fan-out++describe("walk seeds", () => {+ // The backend's first three dependents are all in one test directory; the+ // ranked list spreads over distinct non-test files. The walks must keep+ // starting from the backend's three, so ranking adds no fetches (CL-07 perf).+ const deps: Raw[] = [+ { id: "d-1", name: "a.test.ts", kind: "file", path: "src/__tests__/a.test.ts" },+ { id: "d-2", name: "b.test.ts", kind: "file", path: "src/__tests__/b.test.ts" },+ { id: "d-3", name: "c.test.ts", kind: "file", path: "src/__tests__/c.test.ts" },+ { id: "d-4", name: "x.ts", kind: "file", path: "src/x.ts" },+ { id: "d-5", name: "y.ts", kind: "file", path: "src/y.ts" },+ { id: "d-6", name: "z.ts", kind: "file", path: "src/z.ts" },+ ];++ function client(expanded: string[]): IxClient {+ const node = (r: Raw) => ({ id: r.id, name: r.name, kind: r.kind, attrs: {}, provenance: { sourceUri: r.path } });+ return {+ async entity(id: string) {+ return { node: { id, name: "rank", kind: "function", attrs: {}, provenance: { sourceUri: "src/rank.ts" } }, edges: [] };+ },+ async expand(id: string, opts?: { direction?: string; predicates?: string[] }) {+ if (id === TARGET && opts?.direction === "in" && opts.predicates?.includes("REFERENCES")) {+ return { nodes: deps.map(node), edges: [] };+ }+ if (id !== TARGET) expanded.push(id);+ return { nodes: [], edges: [] };+ },+ async provenance(id: string) { return { entityId: id, chain: [] }; },+ } as unknown as IxClient;+ }++ it("fans out from the backend's sample, not the ranked display list", async () => {+ const expanded: string[] = [];+ const facts = await collectFacts(client(expanded), TARGET, "rank", "function", "context");++ expect(facts.topDependentRefs!.map((r) => r.id)).toEqual(["d-4", "d-5", "d-6"]);+ expect(facts.walkSeeds?.dependents.map((r) => r.id)).toEqual(["d-1", "d-2", "d-3"]);+ expect([...new Set(expanded)].sort()).toEqual(["d-1", "d-2", "d-3"]);++ const walked: string[] = [];+ await collectRelatedFiles(client(walked), { id: TARGET, kind: "function" }, facts);+ for (const id of ["d-4", "d-5", "d-6"]) expect(walked).not.toContain(id);+ for (const id of ["d-1", "d-2", "d-3"]) expect(walked).toContain(id);+ });+});++describe("explain scope", () => {+ it("keeps the backend's caller order for ix explain, and no used-by total", async () => {+ const facts = await collectFacts(callerClient(CALLERS, EDGES), TARGET, "rank", "function");+ expect(facts.topCallerRefs!.map((r) => r.id)).toEqual(["c-test", "c-far1", "c-far2"]);+ expect(facts).not.toHaveProperty("usedByCount");+ });+});++describe("--diff across a callers change", () => {+ it("reports the used-by row as changed when its callers or total change", () => {+ const before = bundleFor(baseFacts({+ callerCount: 3, topCallers: ["main"], topCallerRefs: [loc("c-1", "main", "src/cli/main.ts", [10, 40])],+ usedByCount: 3,+ }));+ const after = bundleFor(baseFacts({+ callerCount: 40, topCallers: ["main", "run"],+ topCallerRefs: [loc("c-1", "main", "src/cli/main.ts", [10, 40]), loc("c-2", "run", "src/cli/run.ts", [1, 9])],+ usedByCount: 40,+ }));+ const diff = diffInvestigations({ id: "x", savedAt: "2026-01-01T00:00:00Z", bundle: before } as never, after);+ expect(diff.removed.evidence.map((e) => e.title)).toEqual(["used by (1 of 3): main (main.ts)"]);+ expect(diff.added.evidence.map((e) => e.title)).toEqual(["used by (2 of 40): main (main.ts), run (run.ts)"]);++ const same = diffInvestigations({ id: "x", savedAt: "2026-01-01T00:00:00Z", bundle: before } as never, before);+ expect(same.added.evidence).toEqual([]);+ expect(same.removed.evidence).toEqual([]);+ });++ it("keeps the used-by reason to locations, not a second copy of the names", () => {+ const b = bundleFor(bigFileFacts());+ const row = b.evidence.find((e) => e.id === "used-by")!;+ expect(row.reason).not.toContain("main ");+ expect(row.reason).toContain("src/cli/main.ts:10-40");+ });+});diff --git a/ix-cli/src/cli/__tests__/context-from-issue-bundle.test.ts b/ix-cli/src/cli/__tests__/context-from-issue-bundle.test.tsindex edea2406..a2cbdceb 100644--- a/ix-cli/src/cli/__tests__/context-from-issue-bundle.test.ts+++ b/ix-cli/src/cli/__tests__/context-from-issue-bundle.test.ts@@ -128,8 +128,8 @@ describe("ix context --from-issue bundle", () => {it("renders both rows in llm and text output", () => {const b = build(issue());const llm = captureLog(() => renderBundle(b, "llm")).join("\n");- expect(llm).toMatch(/^evidence score=1 kind=target title="starting points: listByKind/m);- expect(llm).toMatch(/^evidence score=2 kind=structural title="ranked files: src\/client\/api.ts, /m);+ expect(llm).toMatch(/^evidence score=1000 kind=target title="starting points: listByKind/m);+ expect(llm).toMatch(/^evidence score=1001 kind=structural title="ranked files: src\/client\/api.ts, /m);expect(llm).not.toContain("issue_fallback");const text = captureLog(() => renderBundle(b, "text")).join("\n");diff --git a/ix-cli/src/cli/__tests__/context-investigation.test.ts b/ix-cli/src/cli/__tests__/context-investigation.test.tsindex 51473f07..d580eb6f 100644--- a/ix-cli/src/cli/__tests__/context-investigation.test.ts+++ b/ix-cli/src/cli/__tests__/context-investigation.test.ts@@ -765,10 +765,10 @@ describe("ix context investigation state", () => {// 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="Widget --holds--> mount"',+ 'evidence change=added score=4000 kind=relationship title="Widget --holds--> mount"',);expect(lines).toContain(- 'evidence change=removed score=30 kind=relationship title="Widget --calls--> render"',+ 'evidence change=removed score=4000 kind=relationship title="Widget --calls--> render"',);// One record per line — the wire format invariant.@@ -817,7 +817,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="Widget --calls--> render"',+ 'evidence score=4000 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__/context-symbol-unchanged.test.ts b/ix-cli/src/cli/__tests__/context-symbol-unchanged.test.tsindex 14774283..f77db279 100644--- a/ix-cli/src/cli/__tests__/context-symbol-unchanged.test.ts+++ b/ix-cli/src/cli/__tests__/context-symbol-unchanged.test.ts@@ -83,18 +83,19 @@ describe("ix context <symbol> is unchanged by --from-issue", () => {});});+// CL-07: tier scores (tier * 1000 + place), the caller and dependent rows+// merged into one "used by" row, and the `runRank --CALLS-->` relationship+// dropped because the used-by row already names runRank.const RECORDED_LLM: string[] = [- "context target=listByKind target_kind=method target_path=src/client/api.ts stale=false classification=current entities=5 relationships=1 claims=0 decisions=0 conflicts=0 intents=0 evidence=9 truncated_entities=0 truncated_relationships=0 truncated_evidence=0 truncated_chars=0",+ "context target=listByKind target_kind=method target_path=src/client/api.ts stale=false classification=current entities=5 relationships=1 claims=0 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=\"listByKind (method)\" path=src/client/api.ts lines=141-152",- "evidence score=10 kind=structural title=\"container IxClient (class)\" path=src/client/api.ts lines=20-400",- "evidence score=11 kind=structural title=\"related files: src/cli/commands/smells.ts\"",- "evidence score=12 kind=provenance title=\"recent commits to api.ts: abc1234 fix: scope listByKind\"",- "evidence score=13 kind=structural title=\"calls post\" path=src/client/api.ts lines=500-520",- "evidence score=14 kind=structural title=\"caller runRank\" path=src/cli/commands/rank.ts lines=30-90",- "evidence score=15 kind=structural title=\"dependent inventory.ts\" path=src/cli/commands/inventory.ts",- "evidence score=30 kind=relationship title=\"runRank --CALLS--> listByKind\"",- "evidence score=40 kind=provenance title=\"history length 3, introduced rev 7\"",+ "evidence score=2000 kind=structural title=\"container IxClient (class)\" path=src/client/api.ts lines=20-400",+ "evidence score=2001 kind=structural title=\"related files: src/cli/commands/smells.ts\"",+ "evidence score=2002 kind=structural title=\"used by (2 of 2): runRank (rank.ts), inventory.ts\" path=src/cli/commands/rank.ts lines=30-90",+ "evidence score=2003 kind=provenance title=\"recent commits to api.ts: abc1234 fix: scope listByKind\"",+ "evidence score=2004 kind=structural title=\"calls post\" path=src/client/api.ts lines=500-520",+ "evidence score=5000 kind=provenance title=\"history length 3, introduced rev 7\"","next cmd=\"ix read src/client/api.ts:141-152\"","next cmd=\"ix read src/client/api.ts:20-400\"",- "next cmd=\"ix read src/client/api.ts:500-520\"",+ "next cmd=\"ix read src/cli/commands/rank.ts:30-90\"",];diff --git a/ix-cli/src/cli/__tests__/context.test.ts b/ix-cli/src/cli/__tests__/context.test.tsindex d602ef34..bb3b5109 100644--- a/ix-cli/src/cli/__tests__/context.test.ts+++ b/ix-cli/src/cli/__tests__/context.test.ts@@ -566,13 +566,19 @@ describe("ix context budget is charged against the emitted text", () => {expect(bundle.evidence.length).toBe(full.evidence.length);});- it("bounds json evidence by its serialization, within 10% when cut", () => {+ it("bounds json evidence by its serialization, and cuts only where the next row would not fit", () => {const budgets = clampBudgets({ maxTokens: 600 }, "json");const bundle = buildBundle({ ...manyMembers(), budgets, format: "json" });expect(bundle.truncation.evidenceTruncated).toBeGreaterThan(0);const kept = bundle.evidence.reduce((n, e) => n + JSON.stringify(e).length, 0);expect(kept).toBeLessThanOrEqual(budgets.maxChars);- expect(kept).toBeGreaterThanOrEqual(0.9 * budgets.maxChars);+ // The cut is a prefix, so how full it is depends on the size of the row at+ // the boundary (here the one "used by" row, larger than a member row). What+ // must hold is that the first dropped row did not fit.+ const all = buildBundle({ ...manyMembers(), budgets: clampBudgets({ maxEvidence: 200, maxTokens: 200_000 }, "json"), format: "json" });+ const next = all.evidence[bundle.evidence.length]!;+ expect(kept + JSON.stringify(next).length).toBeGreaterThan(budgets.maxChars);+ expect(kept).toBeGreaterThanOrEqual(0.8 * budgets.maxChars);});it("bounds text evidence by the lines it prints, leaving room for the header", () => {diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.tsindex eed12c1e..938c77ac 100644--- a/ix-cli/src/cli/commands/context.ts+++ b/ix-cli/src/cli/commands/context.ts@@ -264,6 +264,12 @@ interface EvidenceItem {* `config.ts`, first work out which of several `config.ts` files it was.*/location?: EvidenceLocation;+ /**+ * How many of how many, for a row that samples a larger set (the "used by"+ * row). Structured so the number can be rendered as a floor where the backend+ * capped it, without parsing the title.+ */+ count?: { shown: number; total: number };}interface ContextBundle {@@ -1272,8 +1278,13 @@ export function diffInvestigations(const removedRelationships = prev.relationships.filter((p) => !fresh.relationships.some((r) => r.src === p.src && r.dst === p.dst && r.predicate === p.predicate),);- const addedEvidence = fresh.evidence.filter((e) => !prev.evidence.some((p) => p.id === e.id));- const removedEvidence = prev.evidence.filter((p) => !fresh.evidence.some((e) => e.id === p.id));+ // Same id and same title. A row that summarises a set -- `used-by`,+ // `recent-commits`, `related-files` -- keeps its id while what it says+ // changes, and matched on id alone a new top caller or a total going from 3+ // to 40 was no change at all. A changed row is reported as removed and added.+ const sameEvidence = (a: EvidenceItem, b: EvidenceItem) => a.id === b.id && a.title === b.title;+ const addedEvidence = fresh.evidence.filter((e) => !prev.evidence.some((p) => sameEvidence(p, e)));+ const removedEvidence = prev.evidence.filter((p) => !fresh.evidence.some((e) => sameEvidence(p, e)));const addedClaims = fresh.claims.filter((c) => !prev.claims.some((p) => p.id === c.id));const removedClaims = prev.claims.filter((p) => !fresh.claims.some((c) => c.id === p.id));@@ -2294,6 +2305,15 @@ export function buildBundle(input: BuildInput): ContextBundle {return bundle;}+/**+ * Evidence tiers. A row's score is `tier * TIER_WIDTH + its place in the tier`,+ * so no tier can run into the next: structural rows were `10 + index`, and from+ * the eleventh on they interleaved with claims (20) and relationships (30+).+ */+const TIER = { target: 0, issue: 1, structural: 2, claims: 3, relationships: 4, provenance: 5 } as const;+const TIER_WIDTH = 1000;+const tierScore = (tier: number, index = 0): number => tier * TIER_WIDTH + Math.min(index, TIER_WIDTH - 1);+/** Deterministic evidence ranking: tier, then a stable id tiebreaker. */function rankEvidence(input: {resolved: { id: string; name: string; kind: string };@@ -2322,17 +2342,35 @@ function rankEvidence(input: {// these two rows are what `--from-issue` exists to deliver.if (input.issue) items.push(...issueEvidence(input.issue));+ // Each entity gets one row. The rows below are pushed in rank order, and a+ // row about something already shown is dropped (or, for a row that lists+ // several, loses that entry): the same file as an import and a dependent, or+ // a member restated by its CONTAINS edge, cost the budget twice for one fact.+ // The target is exempt -- every edge in the bundle touches it.+ const shown = new Set<string>([target.id]);+ for (const s of input.issue?.startingPoints ?? []) if (s.id) shown.add(s.id);+ const fresh = (id: string | undefined): boolean => id === undefined || !shown.has(id);+ const show = (ids: string[]) => { for (const id of ids) shown.add(id); };+type Structural = Omit<EvidenceItem, "kind" | "score">;const structural: Structural[] = [];+ const pushOne = (item: Structural, ref: EntityLocation | undefined) => {+ if (!fresh(ref?.id)) return;+ if (ref) show([ref.id]);+ structural.push(item);+ };+ // Keyed by entity id, not name: two members called `render` were one id.+ const rowId = (prefix: string, name: string, ref: EntityLocation | undefined) => `${prefix}:${ref?.id ?? name}`;if (input.facts.container) {- structural.push({- id: `container:${input.facts.container.name}`,+ const container = input.facts.container;+ pushOne({+ id: rowId("container", container.name, container),source: "facts.container",- title: `container ${input.facts.container.name} (${input.facts.container.kind})`,+ title: `container ${container.name} (${container.kind})`,reason: "contains the target",- refs: [input.facts.container.id],- ...locationField(input.facts.container),- });+ refs: [container.id],+ ...locationField(container),+ }, container);}// 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.@@ -2346,10 +2384,10 @@ function rankEvidence(input: {const leadingMembers = related(input.facts.members, input.facts.memberRefs, LEADING_MEMBERS);const pushMembers = (members: typeof leadingMembers) => {for (const { name, ref } of members) {- structural.push({- id: `member:${name}`, source: "facts.members", title: `member ${name}`,+ pushOne({+ id: rowId("member", name, ref), source: "facts.members", title: `member ${name}`,reason: ref ? memberReason(ref) : "defined in the target", refs: ref ? [ref.id] : [], ...locationField(ref),- });+ }, ref);}};// The most-used members first, the rest last. A file target's evidence at@@ -2366,8 +2404,9 @@ function rankEvidence(input: {// of the evidence budget as five imports, and at the default budget the// imports then fell off the end instead: the files moved, the count the// agent could see did not.- const relatedRefs = input.facts.relatedRefs ?? [];+ const relatedRefs = (input.facts.relatedRefs ?? []).filter((ref) => fresh(ref.id));if (relatedRefs.length > 0) {+ show(relatedRefs.map((ref) => ref.id));structural.push({id: "related-files", source: "facts.related",title: `related files: ${relatedRefs.map((ref) => ref.path ?? ref.name).join(", ")}`,@@ -2375,6 +2414,15 @@ function rankEvidence(input: {refs: relatedRefs.map((ref) => ref.id),});}+ // What uses the target: callers, then the dependents not already among them,+ // as one row whose title carries the total. Ahead of the imports and the+ // neighbours: as a row each, after them, they missed the default budget on+ // nearly every file target -- and they are what an edit has to keep working.+ const usedBy = usedByRow(input.facts, fresh);+ if (usedBy) {+ show(usedBy.refs);+ structural.push(usedBy);+ }// What happened to the target's file lately. The subjects carry what a// one-hop bundle cannot: that the sibling commands were already fixed for// the same condition, or that the same bug was fixed next door.@@ -2395,51 +2443,45 @@ function rankEvidence(input: {// items, and a file with many imports (resolve.ts) pushed all 27 of its own// members out of the bundle entirely.for (const ref of (input.facts.importRefs ?? []).slice(0, SHOWN_IMPORTS)) {- structural.push({- id: `imports:${ref.name}`, source: "facts.imports", title: `imports ${ref.name}`,+ pushOne({+ id: rowId("imports", ref.name, ref), source: "facts.imports", title: `imports ${ref.name}`,reason: "the target imports this", refs: [ref.id], ...locationField(ref),- });+ }, ref);}for (const ref of input.facts.calleeRefs ?? []) {- structural.push({- id: `calls:${ref.name}`, source: "facts.callees", title: `calls ${ref.name}`,+ pushOne({+ id: rowId("calls", ref.name, ref), source: "facts.callees", title: `calls ${ref.name}`,reason: "the target calls this", refs: [ref.id], ...locationField(ref),- });+ }, ref);}for (const ref of (input.facts.neighbourRefs ?? []).slice(0, SHOWN_NEIGHBOUR_MEMBERS)) {const where = ref.path ? ref.path.split("/").pop() : undefined;- structural.push({- id: `defines:${ref.path ?? ""}:${ref.name}`, source: "facts.neighbours",+ pushOne({+ id: rowId("defines", ref.name, ref), source: "facts.neighbours",title: `${where ?? "a neighbouring file"} defines ${ref.name}`,reason: "defined in a file next to the target", refs: [ref.id], ...locationField(ref),- });- }- 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, ref } of related(input.facts.topDependents, input.facts.topDependentRefs, 3)) {- structural.push({- id: `dependent:${name}`, source: "facts.dependents", title: `dependent ${name}`,- reason: "calls, imports or references the target", refs: ref ? [ref.id] : [], ...locationField(ref),- });+ }, ref);}pushMembers(leadingMembers.slice(MEMBERS_BEFORE_OUTWARD));structural.forEach((item, index) => {// Recent commits are provenance -- where the file's current shape came// from -- and keep to the stable kinds consumers already route on.- items.push({ ...item, kind: item.source === "git.history" ? "provenance" : "structural", score: 10 + index });+ items.push({+ ...item,+ kind: item.source === "git.history" ? "provenance" : "structural",+ score: tierScore(TIER.structural, index),+ });});+ // Claims, decisions and intents share a tier, in that order; within each,+ // the id tiebreaker below orders them.for (const scored of input.context.claims) {items.push({id: `claim:${scored.claim.id}`,kind: "claim",source: "context.claims",title: scored.claim.statement,- score: 20,+ score: tierScore(TIER.claims, 0),reason: `context claim (relevance ${scored.relevance}, confidence ${scored.confidence?.score ?? "n/a"})`,refs: [scored.claim.entityId],});@@ -2450,48 +2492,56 @@ function rankEvidence(input: {kind: "decision",source: "context.decisions",title: decision.title,- score: 21,+ score: tierScore(TIER.claims, 1),reason: decision.rationale,refs: decision.entityId ? [decision.entityId] : [],});}// Conflicts are deliberately NOT evidence. A report names its two claims by- // uuid, which is nothing an agent can act on, and at score 22 they outranked- // every relationship: on recorded bundles they were taking 12 to 17 of the 25- // slots and truncating away the members and imports that answer the question.- // The count is carried in the bundle header and the reports themselves stay- // in `conflicts[]` for a caller that wants them; `ix conflicts` renders them.+ // uuid, which is nothing an agent can act on, and ranked between decisions+ // and intents they outranked every relationship: on recorded bundles they+ // were taking 12 to 17 of the 25 slots and truncating away the members and+ // imports that answer the question. The count is carried in the bundle+ // header and the reports themselves stay in `conflicts[]` for a caller that+ // wants them; `ix conflicts` renders them.for (const intent of input.context.intents) {items.push({id: `intent:${intent.id}`,kind: "intent",source: "context.intents",title: intent.statement,- score: 23,+ score: tierScore(TIER.claims, 2),reason: `intent status ${intent.status}`,refs: [],});}+ // A relationship row is kept only when it names something no earlier row+ // does: `config.ts --CONTAINS--> getEndpoint` under a `member getEndpoint`+ // row restates it, and so does an edge to an entity an earlier edge named.const label = entityLabeller(input.entities);- input.relationships.slice(0, 50).forEach((edge, index) => {+ let relationshipIndex = 0;+ for (const edge of input.relationships.slice(0, 50)) {+ const ends = [...new Set([edge.src, edge.dst])].filter((id) => id !== target.id);+ if (ends.length === 0 || !ends.every((id) => fresh(id))) continue;+ show(ends);items.push({id: `relationship:${edge.src}:${edge.dst}:${edge.predicate}`,kind: "relationship",source: "context.edges",title: `${label(edge.src)} --${edge.predicate}--> ${label(edge.dst)}`,- score: 30 + Math.min(index, 10),+ score: tierScore(TIER.relationships, relationshipIndex++),reason: "graph relationship from the context service",refs: [edge.src, edge.dst],});- });+ }items.push({id: `provenance:${target.id}`,kind: "provenance",source: "provenance + facts.history",title: `history length ${input.facts.historyLength}, introduced rev ${input.facts.introducedRev ?? "unknown"}`,- score: 40,+ score: tierScore(TIER.provenance),reason: `provenance ${input.prov.sourceType ?? "unknown"}, extractor ${input.prov.extractor ?? "unknown"}`,refs: [target.id],});@@ -2500,6 +2550,59 @@ function rankEvidence(input: {return items.sort((a, b) => a.score - b.score || cmp(a.id, b.id));}+/** Named callers and dependents shown in the "used by" row, at most. */+const SHOWN_USED_BY = 6;++/**+ * The one "used by" row: the target's callers, then its dependents that are not+ * already among them, each list ranked by the facts collector. The title says+ * how many of how many; `count` carries the same two numbers for a caller that+ * wants them without parsing.+ */+function usedByRow(+ facts: ContextFacts, fresh: (id: string | undefined) => boolean,+): Omit<EvidenceItem, "kind" | "score"> | undefined {+ const named = (names: string[], refs: EntityLocation[] | undefined) =>+ refs ?? names.map((name) => ({ id: "", name, kind: "unknown" }) as EntityLocation);+ const callers = named(facts.topCallers, facts.topCallerRefs);+ const dependents = named(facts.topDependents, facts.topDependentRefs);+ const picked: EntityLocation[] = [];+ const ids = new Set<string>();+ const names = new Set<string>();+ for (const ref of [...callers, ...dependents]) {+ if (picked.length >= SHOWN_USED_BY) break;+ // A name-only entry (no ref) is matched by name; a located one by id.+ if (ref.id ? ids.has(ref.id) || !fresh(ref.id) : names.has(ref.name)) continue;+ if (ref.id) ids.add(ref.id);+ names.add(ref.name);+ picked.push(ref);+ }+ if (picked.length === 0) return undefined;+ const total = Math.max(+ facts.usedByCount ?? Math.max(facts.callerCount, facts.dependentCount),+ picked.length,+ );+ const short = (ref: EntityLocation) => {+ const file = ref.path?.split("/").pop();+ return file && file !== ref.name ? `${ref.name} (${file})` : ref.name;+ };+ // Locations only: the title already names each entry and its file, and the+ // row is sized against the evidence budget like any other.+ const where = picked.filter((ref) => ref.path).map((ref) => formatLocation(locationFields(ref) as EvidenceLocation));+ const anyCaller = picked.some((ref) => callers.includes(ref));+ return {+ id: "used-by",+ // `facts.callers` when the row holds a caller, so a budget that cuts it+ // names `ix callers` as the way back; `ix impact` for dependents alone.+ source: anyCaller ? "facts.callers" : "facts.dependents",+ title: `used by (${picked.length} of ${total}): ${picked.map(short).join(", ")}`,+ reason: `calls, imports or references the target, most relevant first${where.length > 0 ? `; ${where.join(", ")}` : ""}`,+ refs: picked.flatMap((ref) => (ref.id ? [ref.id] : [])),+ count: { shown: picked.length, total },+ ...locationField(picked.find((ref) => ref.path)),+ };+}+/** Ranked files named in the evidence row; the JSON bundle carries the rest. */const SHOWN_RANKED_FILES = 10;@@ -2520,7 +2623,7 @@ function issueEvidence(issue: IssueBundleInput): EvidenceItem[] {kind: "target",source: "issue.starts",title: `starting points: ${starts.map((s) => `${s.name} (${formatLocation(locationFields(s) as EvidenceLocation)})`).join(", ")}`,- score: 1,+ score: tierScore(TIER.issue, 0),reason: (issue.fallback? "no code name in the issue resolved to a definition; starting from the file BM25 ranks first against the issue text; ": "") + why + unresolved,@@ -2535,7 +2638,7 @@ function issueEvidence(issue: IssueBundleInput): EvidenceItem[] {kind: "structural",source: "issue.ranking",title: `ranked files: ${shown.map((f) => f.path).join(", ")}`,- score: 2,+ score: tierScore(TIER.issue, 1),reason: `starting points first, then bm25 against the issue text, graph neighbours of a starting point boosted up to ${Math.round(CLOSENESS_BOOST * 100)}%; `+ shown.map((f) => `${f.path.split("/").pop()} (${f.reason})`).join("; "),refs: [],@@ -2988,7 +3091,7 @@ function memberReason(ref: EntityLocation): string {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}`;+ return `defined in the target; used by ${ref.usedBy}${ref.usedByCapped ? "+" : ""}${where}`;}/**diff --git a/ix-cli/src/cli/context-bundle-schema.ts b/ix-cli/src/cli/context-bundle-schema.tsindex e3da9963..3d14e4d5 100644--- a/ix-cli/src/cli/context-bundle-schema.ts+++ b/ix-cli/src/cli/context-bundle-schema.ts@@ -149,6 +149,14 @@ function buildSchemas(z: typeof Zod.z) {lineEnd: z.number().int().positive().optional(),}).optional(),+ // The "used by" row's sample size and total. Optional and additive,+ // listed for the same reason as `location`.+ count: z+ .object({+ shown: z.number().int().nonnegative(),+ total: z.number().int().nonnegative(),+ })+ .optional(),}),),budgets: z.object({diff --git a/ix-cli/src/cli/explain/facts.ts b/ix-cli/src/cli/explain/facts.tsindex 7d490594..360ee661 100644--- a/ix-cli/src/cli/explain/facts.ts+++ b/ix-cli/src/cli/explain/facts.ts@@ -8,7 +8,7 @@ import { isFileStale } from "../stale.js";import { buildDependencyTree } from "../commands/depends.js";import { getSystemPath } from "../hierarchy.js";import type { CommitRef } from "./history.js";-import type { RelatedRef } from "./related-files.js";+import { isTestPath, type RelatedRef } from "./related-files.js";import { forMcp, toolCall } from "../next-step.js";/** A related entity and where it is defined. */@@ -26,6 +26,8 @@ export interface EntityLocation {usedBy?: number;/** How many of those live in a different file. */usedFromFiles?: number;+ /** True when the probe hit `MEMBER_USE_CAP`: `usedBy` is a floor, not a count. */+ usedByCapped?: boolean;}export interface EntityFacts {@@ -72,6 +74,22 @@ export interface EntityFacts {/** The entities behind `topCallers` / `topDependents`, same order. */topCallerRefs?: EntityLocation[];topDependentRefs?: EntityLocation[];+ /**+ * Distinct entities among the callers and dependents together: the total the+ * `topCallers` / `topDependents` samples are drawn from, as the backend+ * returned them. The expands ask for no limit; should the backend cap one by+ * default, this is a floor rather than a total (rendering it as one is+ * CL-08). `ix context` only.+ */+ usedByCount?: number;+ /**+ * The callers, dependents and callees the neighbour and related-file walks+ * start from: the backend's first few, as before the display lists were+ * ranked. Ranking picks one per file, and each distinct file is another+ * walk, so seeding from the ranked lists made `ix context` fetch noticeably+ * more for rows the agent never sees. `ix context` only.+ */+ walkSeeds?: { callers: EntityLocation[]; dependents: EntityLocation[]; callees: EntityLocation[] };/*** Files two steps out, ranked (`collectRelatedFiles`). Filled by `ix context`* only: the walk costs a second round of requests that `explain` does not need.@@ -325,7 +343,9 @@ async function rankMembersByUse(client: IxClient, members: EntityLocation[]): Prif (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 };+ // At the cap the count is where the probe stopped, not how many there are.+ const capped = (result.nodes ?? []).length >= MEMBER_USE_CAP || (result.edges ?? []).length >= MEMBER_USE_CAP;+ measured[index] = { ...member, usedBy: users.size, usedFromFiles: files.size, ...(capped ? { usedByCapped: true } : {}) };} catch {// Unmeasured, not zero: it keeps its structural place below.measured[index] = member;@@ -344,6 +364,64 @@ async function rankMembersByUse(client: IxClient, members: EntityLocation[]): Prreturn [...ranked, ...structural.slice(MEMBER_USE_POOL)];}+function uniqueById(nodes: any[] | undefined): any[] {+ const seen = new Set<string>();+ return (nodes ?? []).filter((n: any) => {+ if (!n?.id || seen.has(n.id)) return false;+ seen.add(n.id);+ return true;+ });+}++function dirOf(path: string | undefined): string | undefined {+ if (!path) return undefined;+ const at = path.lastIndexOf("/");+ return at < 0 ? "" : path.slice(0, at);+}++/**+ * Callers, dependents or callees, most useful first, whatever order the+ * backend returned them in. Keys, in order: not a test; the first from its+ * file before a second from any file; in the target's directory; most edges in+ * this response (how many ways it is tied to the target); then path, name and+ * id, so the order is total.+ */+function rankUsers(nodes: any[], edges: any[] | undefined, targetPath: string | undefined): any[] {+ const degree = new Map<string, number>();+ for (const e of edges ?? []) {+ for (const end of new Set([e?.src, e?.dst])) {+ if (typeof end === "string") degree.set(end, (degree.get(end) ?? 0) + 1);+ }+ }+ const targetDir = dirOf(targetPath);+ const keyed = nodes.map((n: any) => {+ const path = relativePath(n.provenance?.sourceUri ?? n.provenance?.source_uri) ?? "";+ return {+ n, path,+ name: String(n.name || n.attrs?.name || ""),+ test: path ? isTestPath(path) : false,+ sameDir: targetDir !== undefined && path !== "" && dirOf(path) === targetDir,+ degree: degree.get(n.id) ?? 0,+ fileRank: 0,+ };+ });+ type Keyed = (typeof keyed)[number];+ const str = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);+ const within = (a: Keyed, b: Keyed) =>+ Number(b.sameDir) - Number(a.sameDir) || b.degree - a.degree ||+ str(a.path, b.path) || str(a.name, b.name) || str(String(a.n.id), String(b.n.id));+ // Which of its file's entries each one is, best first.+ const perFile = new Map<string, number>();+ for (const k of [...keyed].sort(within)) {+ const rank = perFile.get(k.path) ?? 0;+ k.fileRank = k.path ? rank : 0;+ perFile.set(k.path, rank + 1);+ }+ return keyed+ .sort((a, b) => Number(a.test) - Number(b.test) || a.fileRank - b.fileRank || within(a, b))+ .map((k) => k.n);+}+/** The entity that contains the target, or undefined when it cannot be read. */async function lookUpContainer(client: IxClient, containerId: string): Promise<EntityLocation | undefined> {try {@@ -452,12 +530,9 @@ export async function collectFacts();// Deduplicate dependents by node ID- const seenIds = new Set<string>();- const uniqueDependents = dependentsResult.nodes.filter((n: any) => {- if (seenIds.has(n.id)) return false;- seenIds.add(n.id);- return true;- });+ const uniqueDependents = uniqueById(dependentsResult.nodes);+ const uniqueCallers = uniqueById(callersResult.nodes);+ const usedByCount = new Set([...uniqueCallers, ...uniqueDependents].map((n: any) => n.id)).size;// Named usage examples (up to 3 resolved names from callers/dependents)const extractRefs = (nodes: any[], limit: number): EntityLocation[] => {@@ -469,8 +544,14 @@ export async function collectFacts(}return refs;};- const topCallerRefs = extractRefs(callersResult.nodes, 3);- const topDependentRefs = extractRefs(uniqueDependents, 3);+ // Ranked before the cut: the backend returns them in id order, which chose+ // the three an agent sees by uuid.+ // `ix context` only: `ix explain` keeps the backend's order, so its prose+ // ("called from X") and JSON are what they were.+ const ranked = (nodes: any[], rankEdges: any[] | undefined) =>+ forExplain ? nodes : rankUsers(nodes, rankEdges, path);+ const topCallerRefs = extractRefs(forExplain ? callersResult.nodes : ranked(uniqueCallers, callersResult.edges), 3);+ const topDependentRefs = extractRefs(ranked(uniqueDependents, dependentsResult.edges), 3);// Where the target leads. Self-edges are dropped: a file that imports its own// directory index resolves back to itself and says nothing.const outward = (nodes: any[], limit: number): EntityLocation[] =>@@ -485,7 +566,14 @@ export async function collectFacts([...importsResult.nodes].sort((a: any, b: any) =>Number(a?.kind !== "file") - Number(b?.kind !== "file")),MAX_IMPORT_REFS);- const calleeRefs = outward(calleesResult.nodes, MAX_CALLEE_REFS);+ const calleeRefs = outward(+ forExplain ? calleesResult.nodes : ranked(uniqueById(calleesResult.nodes), calleesResult.edges), MAX_CALLEE_REFS);+ // What the walks below fan out from: unranked, so they fetch what they did.+ const walkSeeds = {+ callers: extractRefs(callersResult.nodes, 3),+ dependents: extractRefs(uniqueDependents, 3),+ callees: outward(calleesResult.nodes, MAX_CALLEE_REFS),+ };// Build callList from outgoing CALLS edges (reuse logic from explain.ts)const calleeEdges = edges.filter(@@ -506,7 +594,7 @@ export async function collectFacts(// it, so it is not paid for there.forExplain? Promise.resolve(undefined)- : collectNeighbourMembers(client, [...importRefs, ...topDependentRefs], targetId),+ : collectNeighbourMembers(client, [...importRefs, ...walkSeeds.dependents], targetId),forExplain && calleeEdges.length > 0 && calleeEdges.length <= 20? resolveCallList(client, calleeEdges): Promise.resolve(undefined),@@ -607,5 +695,5 @@ export async function collectFacts(moduleName: _moduleName,...contextFacts} = facts;- return { ...contextFacts, provenance };+ return { ...contextFacts, usedByCount, walkSeeds, provenance };}diff --git a/ix-cli/src/cli/explain/related-files.ts b/ix-cli/src/cli/explain/related-files.tsindex 46ab00c9..6a80f7da 100644--- a/ix-cli/src/cli/explain/related-files.ts+++ b/ix-cli/src/cli/explain/related-files.ts@@ -103,6 +103,7 @@ export async function collectRelatedFiles(topDependentRefs?: EntityLocation[];importRefs?: EntityLocation[];neighbourRefs?: EntityLocation[];+ walkSeeds?: { callers: EntityLocation[]; dependents: EntityLocation[]; callees: EntityLocation[] };},limit = MAX_RELATED,): Promise<RelatedRef[]> {@@ -125,7 +126,11 @@ export async function collectRelatedFiles(if (target.kind !== "file") {const near = [target.id,- ...[...(facts.topCallerRefs ?? []), ...(facts.topDependentRefs ?? []), ...(facts.calleeRefs ?? [])]+ // Seeded from the unranked samples when the collector kept them: see+ // `walkSeeds`. The ranked lists are for display.+ ...(facts.walkSeeds+ ? [...facts.walkSeeds.callers, ...facts.walkSeeds.dependents, ...facts.walkSeeds.callees]+ : [...(facts.topCallerRefs ?? []), ...(facts.topDependentRefs ?? []), ...(facts.calleeRefs ?? [])]).slice(0, MAX_NEIGHBOUR_SEEDS).map((ref) => ref.id),];