Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat(context): rank files two steps from the target into the bundle

KageBinaryb4d01dad644a
diff --git a/ix-cli/src/cli/__tests__/related-files.test.ts b/ix-cli/src/cli/__tests__/related-files.test.ts
new file mode 100644
index 00000000..80de6108
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/related-files.test.ts
@@ -0,0 +1,272 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { describe, expect, it } from "vitest";
+
+import { buildBundle, clampBudgets, renderBundle } from "../commands/context.js";
+import type { ContextFacts, EntityLocation } from "../explain/facts.js";
+import { collectRelatedFiles, isTestPath, type RelatedRef } from "../explain/related-files.js";
+
+/**
+ * `collectRelatedFiles` against a small in-memory graph.
+ *
+ * Each case is one of the shapes the ix-bench bundles missed, or one of the
+ * ways a two-hop walk goes wrong: a hub everything reaches, a test that bridges
+ * to everything, a file the bundle already names.
+ */
+
+type Edge = { src: string; dst: string; predicate: string };
+type Node = { id: string; kind: string; name: string; provenance: { sourceUri: string } };
+
+class Graph {
+ nodes = new Map<string, Node>();
+ edges: Edge[] = [];
+
+ file(path: string): string {
+ const id = `file:${path}`;
+ this.nodes.set(id, { id, kind: "file", name: path.split("/").pop()!, provenance: { sourceUri: path } });
+ return id;
+ }
+
+ fn(path: string, name: string): string {
+ const id = `fn:${path}:${name}`;
+ this.nodes.set(id, { id, kind: "function", name, provenance: { sourceUri: path } });
+ this.edge(`file:${path}`, id, "CONTAINS");
+ return id;
+ }
+
+ edge(src: string, dst: string, predicate: string): void {
+ this.edges.push({ src, dst, predicate });
+ }
+
+ /** `/v1/expand`: breadth-first over the given predicates and direction. */
+ client() {
+ return {
+ expand: async (id: string, opts?: { direction?: string; predicates?: string[]; hops?: number }) => {
+ const direction = opts?.direction ?? "both";
+ const hops = opts?.hops ?? 1;
+ const allowed = (e: Edge) => !opts?.predicates || opts.predicates.includes(e.predicate);
+ const seen = new Set([id]);
+ const edges: Edge[] = [];
+ let frontier = [id];
+ for (let hop = 0; hop < hops; hop++) {
+ const next: string[] = [];
+ for (const at of frontier) {
+ for (const e of this.edges.filter(allowed)) {
+ const out = direction !== "in" && e.src === at ? e.dst : undefined;
+ const inn = direction !== "out" && e.dst === at ? e.src : undefined;
+ for (const other of [out, inn]) {
+ if (!other) continue;
+ if (!edges.includes(e)) edges.push(e);
+ if (!seen.has(other)) {
+ seen.add(other);
+ next.push(other);
+ }
+ }
+ }
+ }
+ frontier = next;
+ }
+ seen.delete(id);
+ return { nodes: [...seen].map((n) => this.nodes.get(n)!).filter(Boolean), edges };
+ },
+ };
+ }
+}
+
+const loc = (g: Graph, id: string): EntityLocation => {
+ const n = g.nodes.get(id)!;
+ return { id, name: n.name, kind: n.kind, path: n.provenance.sourceUri };
+};
+
+describe("collectRelatedFiles", () => {
+ it("finds a caller's import for a symbol target, and says which caller's file led there", async () => {
+ // parseBudgetOption is called from context.ts, which imports the schema
+ // the new flag has to be added to. options.ts itself never touches it.
+ const g = new Graph();
+ g.file("src/options.ts");
+ const target = g.fn("src/options.ts", "parseBudgetOption");
+ g.file("src/context.ts");
+ const caller = g.fn("src/context.ts", "registerContextCommand");
+ g.edge(caller, target, "CALLS");
+ g.file("src/schema.ts");
+ g.edge("file:src/context.ts", "file:src/schema.ts", "IMPORTS");
+
+ const related = await collectRelatedFiles(g.client(), { id: target, kind: "function" }, {
+ path: "src/options.ts",
+ topCallerRefs: [loc(g, caller)],
+ });
+
+ const schema = related.find((r) => r.path === "src/schema.ts");
+ expect(schema).toBeDefined();
+ expect(schema!.via).toContain("context.ts");
+ expect(related.map((r) => r.path)).not.toContain("src/options.ts");
+ });
+
+ it("ranks a sibling sharing a rare callee above one sharing only a common helper", async () => {
+ // inventory.ts and rank.ts both call listByKind (two callers); trace.ts
+ // shares only resolveWorkspaceId, which every command calls.
+ const g = new Graph();
+ g.file("src/api.ts");
+ const listByKind = g.fn("src/api.ts", "listByKind");
+ g.file("src/bootstrap.ts");
+ const common = g.fn("src/bootstrap.ts", "resolveWorkspaceId");
+ g.file("src/inventory.ts");
+ const inventory = g.fn("src/inventory.ts", "registerInventoryCommand");
+ g.edge(inventory, listByKind, "CALLS");
+ g.edge(inventory, common, "CALLS");
+ g.file("src/rank.ts");
+ const rank = g.fn("src/rank.ts", "registerRankCommand");
+ g.edge(rank, listByKind, "CALLS");
+ g.edge(rank, common, "CALLS");
+ for (const name of ["trace", "read", "overview", "impact", "callers", "depends"]) {
+ g.file(`src/${name}.ts`);
+ g.edge(g.fn(`src/${name}.ts`, `register_${name}`), common, "CALLS");
+ }
+
+ const related = await collectRelatedFiles(g.client(), { id: "file:src/inventory.ts", kind: "file" }, {
+ path: "src/inventory.ts",
+ memberRefs: [loc(g, inventory)],
+ // What the facts collector already names: the target's callees' files.
+ calleeRefs: [loc(g, listByKind), loc(g, common)],
+ });
+
+ expect(related[0]?.path).toBe("src/rank.ts");
+ expect(related[0]?.via).toContain("listByKind");
+ // Already one hop out, so not spent on a related slot.
+ expect(related.map((r) => r.path)).not.toContain("src/api.ts");
+ expect(related.map((r) => r.path)).not.toContain("src/bootstrap.ts");
+ });
+
+ it("does not let a test that touches everything outrank a real neighbour", async () => {
+ const g = new Graph();
+ g.file("src/watch.ts");
+ const watch = g.fn("src/watch.ts", "registerWatchCommand");
+ g.file("src/extensions.ts");
+ const exts = g.fn("src/extensions.ts", "SUPPORTED_EXTENSIONS");
+ g.edge(watch, exts, "REFERENCES");
+ g.file("src/walker.ts");
+ g.edge(g.fn("src/walker.ts", "walk"), exts, "REFERENCES");
+ g.file("src/__tests__/everything.test.ts");
+ const test = g.fn("src/__tests__/everything.test.ts", "suite");
+ g.edge(test, watch, "CALLS");
+ g.edge(test, exts, "CALLS");
+ for (let i = 0; i < 5; i++) {
+ g.file(`src/unrelated${i}.ts`);
+ g.edge(test, g.fn(`src/unrelated${i}.ts`, `u${i}`), "CALLS");
+ }
+
+ const related = await collectRelatedFiles(g.client(), { id: "file:src/watch.ts", kind: "file" }, {
+ path: "src/watch.ts",
+ memberRefs: [loc(g, watch)],
+ });
+
+ const order = related.map((r) => r.path);
+ expect(order.indexOf("src/walker.ts")).toBeGreaterThanOrEqual(0);
+ for (let i = 0; i < 5; i++) {
+ const u = order.indexOf(`src/unrelated${i}.ts`);
+ if (u >= 0) expect(u).toBeGreaterThan(order.indexOf("src/walker.ts"));
+ }
+ });
+
+ it("divides a file by its import degree, so a hub needs more than one path", async () => {
+ const g = new Graph();
+ g.file("src/target.ts");
+ const t = g.fn("src/target.ts", "doThing");
+ g.file("src/helper.ts");
+ const helper = g.fn("src/helper.ts", "shared");
+ g.edge(t, helper, "CALLS");
+ g.file("src/peer.ts");
+ g.edge(g.fn("src/peer.ts", "peer"), helper, "CALLS");
+ g.file("src/format.ts");
+ g.edge(g.fn("src/format.ts", "fmt"), helper, "CALLS");
+ for (let i = 0; i < 30; i++) g.edge(g.file(`src/cmd${i}.ts`), "file:src/format.ts", "IMPORTS");
+
+ const related = await collectRelatedFiles(g.client(), { id: "file:src/target.ts", kind: "file" }, {
+ path: "src/target.ts",
+ memberRefs: [loc(g, t)],
+ calleeRefs: [loc(g, helper)],
+ });
+ const order = related.map((r) => r.path);
+ expect(order.indexOf("src/peer.ts")).toBeLessThan(order.indexOf("src/format.ts"));
+ });
+
+ it("returns nothing, rather than failing, when the graph cannot be read", async () => {
+ const client = { expand: async () => { throw new Error("backend down"); } };
+ await expect(collectRelatedFiles(client, { id: "x", kind: "file" }, { path: "a.ts" })).resolves.toEqual([]);
+ });
+
+ it("treats fixtures as test data", () => {
+ expect(isTestPath("core-ingestion/test-fixtures/typescript/sample-command.ts")).toBe(true);
+ expect(isTestPath("src/__tests__/a.test.ts")).toBe(true);
+ expect(isTestPath("src/cli/commands/test.ts")).toBe(false);
+ });
+});
+
+describe("related files in a bundle", () => {
+ const MEMBERS: EntityLocation[] = Array.from({ length: 8 }, (_, i) => ({
+ id: `m-${i}`, name: `member${i}`, kind: "function", path: "src/inventory.ts", lineStart: i * 10 + 1, lineEnd: i * 10 + 5,
+ }));
+ const facts = (relatedRefs: RelatedRef[]): ContextFacts => ({
+ id: "f", name: "inventory.ts", kind: "file", path: "src/inventory.ts",
+ members: MEMBERS.map((m) => m.name),
+ memberRefs: MEMBERS,
+ memberCount: MEMBERS.length, callerCount: 0, calleeCount: 0, dependentCount: 0, importerCount: 0,
+ topCallers: [], topDependents: [], historyLength: 1, introducedRev: 1, stale: false, diagnostics: [],
+ relatedRefs,
+ });
+ const rank: RelatedRef = {
+ id: "file:src/rank.ts", name: "rank.ts", kind: "file", path: "src/rank.ts",
+ score: 1, reason: "two steps from the target, through listByKind", via: ["listByKind"],
+ };
+ const peer: RelatedRef = {
+ id: "file:src/peer.ts", name: "peer.ts", kind: "file", path: "src/peer.ts",
+ score: 0.5, reason: "linked to the target directly", via: [],
+ };
+
+ function build(refs: RelatedRef[]) {
+ return buildBundle({
+ resolved: { id: "f", name: "inventory.ts", kind: "file", resolutionMode: "exact" },
+ facts: facts(refs),
+ context: {
+ claims: [], conflicts: [], decisions: [], intents: [], nodes: [], edges: [],
+ metadata: { query: "", seedEntities: [], hopsExpanded: 1, asOfRev: 1 },
+ } as never,
+ provenance: {},
+ budgets: clampBudgets({}),
+ isStale: () => false,
+ });
+ }
+
+ it("names every related file in one evidence row, with what connects it", () => {
+ const bundle = build([rank, peer]);
+ const rows = bundle.evidence.filter((e) => e.source === "facts.related");
+ expect(rows).toHaveLength(1);
+ expect(rows[0].title).toBe("related files: src/rank.ts, src/peer.ts");
+ expect(rows[0].reason).toContain("rank.ts via listByKind");
+ expect(rows[0].reason).toContain("peer.ts directly");
+ expect(rows[0].refs).toEqual(["file:src/rank.ts", "file:src/peer.ts"]);
+ expect(bundle.entities.map((e) => e.path)).toContain("src/rank.ts");
+ });
+
+ it("puts the row after the leading members and ahead of the rest, and prints the paths", () => {
+ const bundle = build([rank]);
+ const titles = bundle.evidence.map((e) => e.title);
+ const at = titles.findIndex((t) => t.startsWith("related files:"));
+ expect(at).toBeGreaterThan(titles.indexOf("member member4"));
+ expect(at).toBeLessThan(titles.indexOf("member member5"));
+
+ const lines: string[] = [];
+ const orig = console.log;
+ console.log = (...a: unknown[]) => void lines.push(a.map(String).join(" "));
+ try {
+ renderBundle(bundle, "text");
+ } finally {
+ console.log = orig;
+ }
+ expect(lines.join("\n")).toContain("src/rank.ts");
+ });
+
+ it("adds no row when nothing was found", () => {
+ expect(build([]).evidence.some((e) => e.source === "facts.related")).toBe(false);
+ });
+});
diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.ts
index 4f7fef6c..8ce91b33 100644
--- a/ix-cli/src/cli/commands/context.ts
+++ b/ix-cli/src/cli/commands/context.ts
@@ -20,6 +20,7 @@ import type {
} from "../../client/types.js";
import { getEndpoint } from "../config.js";
import { collectFacts, type ContextFacts, type EntityLocation } from "../explain/facts.js";
+import { collectRelatedFiles, type RelatedRef } from "../explain/related-files.js";
import { llmLine, llmShortId, printLlmLines } from "../llm.js";
import { parseBudgetOption, parsePickOption, parseRevisionOption } from "../options.js";
import { resolveFileOrReport } from "../resolve.js";
@@ -402,7 +403,7 @@ export function registerContextCommand(program: Command): void {
// Also carries the provenance response: `collectFacts` needs it for the
// history length, and fetching it again here doubled one of the
// slowest calls the command makes (~1.3s on the Ix repo's graph).
- collectFacts(client, resolved.id, resolved.name, resolved.kind, "context"),
+ collectContextFacts(client, resolved),
// By id, not by name. Seeding by name makes the backend re-run the
// search the resolver just did, and it can land on a different node of
// the same name. Both call sites in this file must use it: converting
@@ -502,7 +503,7 @@ async function buildFreshBundle(
const asOfRev = opts.asOfRev;
const [facts, context] = await Promise.all([
- collectFacts(client, resolved.id, resolved.name, resolved.kind, "context"),
+ collectContextFacts(client, resolved),
client.contextForNode(resolved.id, { asOfRev, depth: opts.depth }),
]);
@@ -1444,6 +1445,21 @@ interface BuildInput {
graphCompleted?: boolean;
}
+/**
+ * The facts a bundle is built from: one hop from `collectFacts`, then the
+ * ranked files two hops out, which are seeded from those facts. The second
+ * step is best-effort -- a bundle without it is the bundle `ix context` built
+ * before it existed, and failing the command over it would be a regression.
+ */
+async function collectContextFacts(
+ client: IxClient,
+ resolved: { id: string; name: string; kind: string },
+): Promise<ContextFacts> {
+ const facts = await collectFacts(client, resolved.id, resolved.name, resolved.kind, "context");
+ const relatedRefs = await collectRelatedFiles(client, resolved, facts).catch(() => []);
+ return relatedRefs.length > 0 ? { ...facts, relatedRefs } : facts;
+}
+
export function buildBundle(input: BuildInput): ContextBundle {
const { resolved, facts, context, provenance, asOfRev, depth, budgets } = input;
@@ -1514,6 +1530,9 @@ export function buildBundle(input: BuildInput): ContextBundle {
...(facts.neighbourRefs ?? []),
...(facts.topCallerRefs ?? []),
...(facts.topDependentRefs ?? []),
+ // Two steps out, ranked. After everything one step out, and ahead of the
+ // backend's context nodes, which are ordered by kind and name only.
+ ...(facts.relatedRefs ?? []),
]);
// Compact and standard backend responses omit the full graph arrays and
// carry the same graph as summaries. Falling back here keeps the default
@@ -1742,10 +1761,36 @@ function rankEvidence(input: {
): 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.members, input.facts.memberRefs, LEADING_MEMBERS)) {
+ 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}`,
+ reason: ref ? memberReason(ref) : "defined in the target", refs: ref ? [ref.id] : [], ...locationField(ref),
+ });
+ }
+ };
+ // The most-used members first, the rest last. A file target's evidence at
+ // the default budget was the target and its first ten members and nothing
+ // else -- the part of a bundle an agent sees anyway the moment it opens the
+ // target. Measured on ix-bench, 0.55 of the expected files were in the
+ // bundle and 0.32 in the text an agent is shown.
+ pushMembers(leadingMembers.slice(0, MEMBERS_BEFORE_OUTWARD));
+ // Two steps out: a neighbour's import, or a file that depends on what the
+ // target depends on. Before the imports, which the target's own header
+ // lists; these are the files a one-hop bundle cannot name at all.
+ //
+ // One row for all of them. As a row each, five related files cost as much
+ // 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 ?? [];
+ if (relatedRefs.length > 0) {
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),
+ id: "related-files", source: "facts.related",
+ title: `related files: ${relatedRefs.map((ref) => ref.path ?? ref.name).join(", ")}`,
+ reason: `two steps from the target, ranked; ${relatedRefs.map(relatedClause).join("; ")}`,
+ refs: relatedRefs.map((ref) => ref.id),
});
}
// Then outward. The file an answer lives in is most often one the target
@@ -1786,6 +1831,7 @@ function rankEvidence(input: {
reason: "calls, imports or references the target", refs: ref ? [ref.id] : [], ...locationField(ref),
});
}
+ pushMembers(leadingMembers.slice(MEMBERS_BEFORE_OUTWARD));
structural.forEach((item, index) => {
items.push({ ...item, kind: "structural", score: 10 + index });
});
@@ -1965,6 +2011,7 @@ const CUT_LABELS: Record<string, string> = {
"facts.imports": "import",
"facts.callees": "call",
"facts.neighbours": "neighbouring definition",
+ "facts.related": "related file",
"facts.callers": "caller",
"facts.dependents": "dependent",
"context.claims": "claim",
@@ -2042,6 +2089,8 @@ const SHOWN_IMPORTS = 8;
/** Members of neighbouring files named in the evidence; the rest are entities. */
const SHOWN_NEIGHBOUR_MEMBERS = 6;
+/** Members shown before anything outside the target; the rest close the list. */
+const MEMBERS_BEFORE_OUTWARD = 5;
type Located = { path?: string; lineStart?: number; lineEnd?: number };
@@ -2106,6 +2155,12 @@ function formatLocation(location: EvidenceLocation): string {
return lines ? `${location.path}:${lines}` : location.path;
}
+/** `rank.ts via listByKind, resolveWorkspaceId`, or just `rank.ts`. */
+function relatedClause(ref: RelatedRef): string {
+ const name = (ref.path ?? ref.name).split("/").pop();
+ return ref.via.length > 0 ? `${name} via ${ref.via.join(", ")}` : `${name} directly`;
+}
+
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";
diff --git a/ix-cli/src/cli/explain/facts.ts b/ix-cli/src/cli/explain/facts.ts
index 7edb8aa2..feb31ef8 100644
--- a/ix-cli/src/cli/explain/facts.ts
+++ b/ix-cli/src/cli/explain/facts.ts
@@ -7,6 +7,7 @@ import { isRawId } from "../resolve.js";
import { isFileStale } from "../stale.js";
import { buildDependencyTree } from "../commands/depends.js";
import { getSystemPath } from "../hierarchy.js";
+import type { RelatedRef } from "./related-files.js";
/** A related entity and where it is defined. */
export interface EntityLocation {
@@ -69,6 +70,11 @@ export interface EntityFacts {
/** The entities behind `topCallers` / `topDependents`, same order. */
topCallerRefs?: EntityLocation[];
topDependentRefs?: 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.
+ */
+ relatedRefs?: RelatedRef[];
/**
* What the target itself reaches: the files it imports and the functions it
diff --git a/ix-cli/src/cli/explain/related-files.ts b/ix-cli/src/cli/explain/related-files.ts
new file mode 100644
index 00000000..56f07ac4
--- /dev/null
+++ b/ix-cli/src/cli/explain/related-files.ts
@@ -0,0 +1,286 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import type { IxClient } from "../../client/api.js";
+import { relativePath } from "../format.js";
+import type { EntityLocation } from "./facts.js";
+
+/**
+ * Files two steps from a context target, ranked.
+ *
+ * The facts collector reads one hop: what the target imports, calls, and is
+ * called or imported by. On the ix-bench task set, every expected file a bundle
+ * missed was one step further out, in one of two shapes:
+ *
+ * - **a neighbour's import.** `reset.ts` calls the target and imports
+ * `client/api.ts`, where the fix lives; `context.ts` calls
+ * `parseBudgetOption` and imports the schema the new flag has to join.
+ * - **a sibling.** A file that depends on what the target depends on:
+ * `main.ts` imports the same two registration modules as `mcp/runner.ts`,
+ * and `rank.ts` calls the same listing helpers as `inventory.ts`.
+ *
+ * Both are two-hop paths in the graph, so one bounded walk finds both. The
+ * work is in the ranking, because two hops from anything reaches most of a
+ * repository: `config.ts`, `format.ts` and the command registry are two steps
+ * from every command. Three things keep them from crowding out the answer:
+ *
+ * 1. a path is worth `1/degree` of the node it runs through, and less again
+ * for a busy node at its far end. Sharing `listByKind` with the target
+ * (five callers) is evidence; sharing `resolveWorkspaceId` (forty) is not,
+ * and a logarithmic discount left `rank.ts` twelfth behind every command
+ * that shares only the common helpers. With `1/degree` it is second;
+ * 2. a candidate file is divided by `log2(2 + its import degree)`, measured
+ * on the whole graph, so a module everything imports -- or one that
+ * imports everything -- has to be reached many ways to rank;
+ * 3. test files, and paths that run through them, count a fifth: a test
+ * imports the target and everything around it, which makes it a bridge
+ * to everywhere rather than evidence of anything. A test target is exempt.
+ *
+ * Files the bundle already names one step out -- imports, callers, callees,
+ * dependents, neighbours -- are skipped: the eight slots are for files a
+ * one-hop bundle cannot reach, and on the benchmark set most of the top-ranked
+ * candidates were the target's own imports.
+ */
+
+export interface RelatedRef extends EntityLocation {
+ /** Higher is closer. Comparable within one target only. */
+ score: number;
+ /** Why this file is here, for the evidence row. */
+ reason: string;
+ /** The names it was reached through, most weight first; empty when direct. */
+ via: string[];
+}
+
+/** How many related files a bundle carries. */
+export const MAX_RELATED = 8;
+
+const WALK_PREDICATES = ["IMPORTS", "CALLS", "REFERENCES"];
+/** A file target's members that seed the walk, most-used first. */
+const MAX_MEMBER_SEEDS = 40;
+/** A symbol target's direct neighbours whose files also seed the walk. */
+const MAX_NEIGHBOUR_SEEDS = 6;
+/** A second-hop path's weight relative to a direct link. */
+const SECOND_HOP_WEIGHT = 0.5;
+/** Weight of a test file, or of a path that runs through one. */
+const TEST_WEIGHT = 0.2;
+/** Leading candidates whose import degree is measured before the final rank. */
+const DEGREE_POOL = 40;
+const CONCURRENCY = 8;
+
+interface GraphNodeLike {
+ id: string;
+ kind?: string;
+ name?: string;
+ attrs?: Record<string, unknown>;
+ provenance?: { sourceUri?: string | null; source_uri?: string | null } | null;
+}
+
+interface GraphEdgeLike {
+ src: string;
+ dst: string;
+}
+
+/**
+ * A test, or test data: a `__tests__/` or fixtures directory, or a `*.test.*`
+ * / `*.spec.*` file. Fixtures are here because they are a bridge in the same
+ * way: calls to vitest's global `describe` resolve to a fixture method of that
+ * name, which linked `test-fixtures/typescript/sample-command.ts` to every test
+ * in the repository.
+ */
+export function isTestPath(path: string): boolean {
+ return /(^|\/)(__tests__|__fixtures__|(test-)?fixtures)\//.test(path) || /\.(test|spec)\.[^/]+$/.test(path);
+}
+
+export async function collectRelatedFiles(
+ client: Pick<IxClient, "expand">,
+ target: { id: string; kind: string },
+ facts: {
+ path?: string;
+ memberRefs?: EntityLocation[];
+ calleeRefs?: EntityLocation[];
+ topCallerRefs?: EntityLocation[];
+ topDependentRefs?: EntityLocation[];
+ importRefs?: EntityLocation[];
+ neighbourRefs?: EntityLocation[];
+ },
+ limit = MAX_RELATED,
+): Promise<RelatedRef[]> {
+ const targetPath = facts.path;
+ const targetIsTest = targetPath ? isTestPath(targetPath) : false;
+
+ // Seeds. A file's own edges are few -- its imports -- and its members carry
+ // the calls, so a file is walked from its members too. A symbol is walked
+ // from itself, its file, and the files of its direct neighbours: the
+ // neighbour-import shape runs symbol -> caller -> caller's FILE -> import,
+ // which is a CONTAINS step the walk's predicates do not take.
+ const nodes = new Map<string, GraphNodeLike>();
+ const seeds = [target.id];
+ if (target.kind === "file") {
+ for (const ref of (facts.memberRefs ?? []).slice(0, MAX_MEMBER_SEEDS)) seeds.push(ref.id);
+ }
+ // The target and its own members. A file one step from these is linked to
+ // the target; one step from a neighbour's file is reached through it.
+ const ownSeeds = new Set(seeds);
+ if (target.kind !== "file") {
+ const near = [
+ target.id,
+ ...[...(facts.topCallerRefs ?? []), ...(facts.topDependentRefs ?? []), ...(facts.calleeRefs ?? [])]
+ .slice(0, MAX_NEIGHBOUR_SEEDS)
+ .map((ref) => ref.id),
+ ];
+ const containers = await mapLimit(near, (id) =>
+ client.expand(id, { direction: "in", predicates: ["CONTAINS"], hops: 2 }).catch(() => EMPTY));
+ for (const result of containers) {
+ for (const node of result.nodes as GraphNodeLike[]) {
+ if (node.kind === "file" && !seeds.includes(node.id)) {
+ seeds.push(node.id);
+ nodes.set(node.id, node);
+ }
+ }
+ }
+ }
+
+ const adjacency = new Map<string, Set<string>>();
+ const link = (a: string, b: string) => {
+ if (!adjacency.has(a)) adjacency.set(a, new Set());
+ adjacency.get(a)!.add(b);
+ };
+ const walks = await mapLimit(seeds, (id) =>
+ client.expand(id, { direction: "both", predicates: WALK_PREDICATES, hops: 2 }).catch(() => EMPTY));
+ for (const walk of walks) {
+ for (const node of walk.nodes as GraphNodeLike[]) nodes.set(node.id, node);
+ for (const edge of walk.edges as GraphEdgeLike[]) {
+ link(edge.src, edge.dst);
+ link(edge.dst, edge.src);
+ }
+ }
+
+ const pathOf = (id: string): string | undefined => {
+ const node = nodes.get(id);
+ return relativePath(node?.provenance?.sourceUri ?? node?.provenance?.source_uri ?? undefined);
+ };
+ const degree = (id: string) => adjacency.get(id)?.size ?? 0;
+ const seedSet = new Set(seeds);
+
+ // Score per file, remembering the heaviest node reached in it (the entity to
+ // show when the file itself has no node in the walk) and the nodes it was
+ // reached through (the reason).
+ type Candidate = { score: number; direct: boolean; best?: { id: string; weight: number }; via: Map<string, number> };
+ const candidates = new Map<string, Candidate>();
+ const credit = (path: string, weight: number, reached: string, via: string | undefined, direct: boolean) => {
+ let c = candidates.get(path);
+ if (!c) candidates.set(path, (c = { score: 0, direct: false, via: new Map() }));
+ c.score += weight;
+ c.direct ||= direct;
+ if (!c.best || weight > c.best.weight) c.best = { id: reached, weight };
+ if (via) c.via.set(via, (c.via.get(via) ?? 0) + weight);
+ };
+
+ for (const seed of seeds) {
+ for (const mid of adjacency.get(seed) ?? []) {
+ if (seedSet.has(mid)) continue;
+ const midPath = pathOf(mid);
+ if (!midPath) continue;
+ if (midPath !== targetPath) {
+ const own = ownSeeds.has(seed);
+ credit(midPath, 1, mid, own ? undefined : seed, own);
+ }
+ const throughTest = !targetIsTest && isTestPath(midPath);
+ const midWeight = SECOND_HOP_WEIGHT / Math.max(1, degree(mid)) * (throughTest ? TEST_WEIGHT : 1);
+ for (const far of adjacency.get(mid) ?? []) {
+ if (far === seed || seedSet.has(far)) continue;
+ const farPath = pathOf(far);
+ if (!farPath || farPath === targetPath) continue;
+ credit(farPath, midWeight / Math.log2(2 + degree(far)), far, mid, false);
+ }
+ }
+ }
+ if (targetPath) candidates.delete(targetPath);
+ for (const ref of [
+ ...(facts.importRefs ?? []), ...(facts.calleeRefs ?? []), ...(facts.topCallerRefs ?? []),
+ ...(facts.topDependentRefs ?? []), ...(facts.neighbourRefs ?? []), ...(facts.memberRefs ?? []),
+ ]) {
+ if (ref.path) candidates.delete(ref.path);
+ }
+
+ for (const [path, c] of candidates) {
+ if (!targetIsTest && isTestPath(path)) c.score *= TEST_WEIGHT;
+ }
+
+ // File nodes seen in the walk, by path: the entity a related file is shown
+ // as, and the node its import degree is read from.
+ const fileNodes = new Map<string, GraphNodeLike>();
+ for (const node of nodes.values()) {
+ const path = node.kind === "file" ? pathOf(node.id) : undefined;
+ if (path) fileNodes.set(path, node);
+ }
+
+ const pool = [...candidates.entries()]
+ .sort((a, b) => b[1].score - a[1].score || cmp(a[0], b[0]))
+ .slice(0, DEGREE_POOL);
+ const degrees = await mapLimit(pool, async ([path, c]) => {
+ // A file reached only through a call has no node of its own in the walk,
+ // and an unmeasured file escaped the penalty entirely: `format.ts`,
+ // imported by thirty commands, ranked as if nothing imported it. Its node
+ // is one CONTAINS step above whatever was reached in it.
+ if (!fileNodes.has(path) && c.best) {
+ const up = await client.expand(c.best.id, { direction: "in", predicates: ["CONTAINS"], hops: 2 }).catch(() => EMPTY);
+ const file = (up.nodes as GraphNodeLike[]).find((n) => n.kind === "file");
+ if (file) fileNodes.set(path, file);
+ }
+ const file = fileNodes.get(path);
+ if (!file) return undefined;
+ const result = await client.expand(file.id, { direction: "both", predicates: ["IMPORTS"] }).catch(() => undefined);
+ return result?.nodes.length;
+ });
+
+ const ranked = pool.map(([path, c], index) => {
+ // A file with no node in the walk cannot be measured; the busiest node
+ // reached in it stands in, so an unmeasured file is not the only one
+ // spared the penalty.
+ const measured = degrees[index] ?? (c.best ? degree(c.best.id) : 0);
+ return { path, c, score: c.score / Math.log2(2 + measured) };
+ }).sort((a, b) => b.score - a.score || cmp(a.path, b.path));
+
+ return ranked.slice(0, limit).map(({ path, c, score }) => {
+ const file = fileNodes.get(path);
+ const shown = file ?? (c.best ? nodes.get(c.best.id) : undefined);
+ const via = [...c.via.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .map(([id]) => nodes.get(id)?.name)
+ .filter((name): name is string => !!name && name !== path.split("/").pop());
+ const through = [...new Set(via)].slice(0, 3);
+ const reason = c.direct
+ ? "linked to the target directly"
+ : through.length > 0
+ ? `two steps from the target, through ${through.join(", ")}`
+ : "two steps from the target";
+ return {
+ id: shown?.id ?? path,
+ name: file ? (file.name ?? path.split("/").pop()!) : (shown?.name ?? path.split("/").pop()!),
+ kind: file ? "file" : (shown?.kind ?? "file"),
+ path,
+ score: Math.round(score * 1000) / 1000,
+ reason,
+ via: c.direct ? [] : through,
+ };
+ });
+}
+
+const EMPTY = { nodes: [] as unknown[], edges: [] as unknown[] };
+
+async function mapLimit<T, R>(items: T[], fn: (item: T) => Promise<R>): Promise<R[]> {
+ const out = new Array<R>(items.length);
+ let next = 0;
+ const worker = async () => {
+ while (next < items.length) {
+ const index = next++;
+ out[index] = await fn(items[index]);
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, items.length) }, worker));
+ return out;
+}
+
+function cmp(a: string, b: string): number {
+ return a < b ? -1 : a > b ? 1 : 0;
+}