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(cli): edge rows say where the call or import is, not just who
KageBinary62f263d9b35a
diff --git a/ix-cli/src/cli/__tests__/edge-sites.test.ts b/ix-cli/src/cli/__tests__/edge-sites.test.tsnew file mode 100644index 00000000..9b41de32--- /dev/null+++ b/ix-cli/src/cli/__tests__/edge-sites.test.ts@@ -0,0 +1,254 @@+// Copyright 2026 Ix Infrastructure Inc.++import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";++import {+ SourceFiles,+ anchorSpan,+ bareName,+ edgeTargetFor,+ findImports,+ findUses,+ importKeys,+ rankTextUses,+ withEdgeSites,+} from "../edge-sites.js";+import { formatEdgeResults, renderEdgeResultsLlm, sliceEdgeResults } from "../format.js";+import { setOutputShape } from "../output-shape.js";++const CALLER = [+ "import { target } from \"./lib.js\";", // 1+ "", // 2+ "// target() is called below", // 3+ "export function caller(x: number) {", // 4+ " const a = x + 1;", // 5+ " const y = target(a);", // 6+ " log(target);", // 7+ " return target(", // 8+ " y,", // 9+ " );", // 10+ "}", // 11+];++describe("findUses", () => {+ it("prefers call syntax, skips comments, and lists every call in the range", () => {+ expect(findUses(CALLER, "target", 4, 11)).toEqual([6, 8]);+ });++ it("falls back to a bare use when nothing in the range calls the name", () => {+ // REFERENCES edges are listed as callers too: a callback passed by name.+ expect(findUses(CALLER, "target", 7, 7)).toEqual([7]);+ });++ it("respects word boundaries", () => {+ expect(findUses(["targets(1);", "retarget(2);", "$target(3);"], "target", 1, 3)).toEqual([]);+ });++ it("never counts the name's own declaration as a use", () => {+ const recursive = ["function walk(n) {", " return n && walk(n - 1);", "}"];+ expect(findUses(recursive, "walk", 1, 3)).toEqual([2]);+ });++ it("counts a constructor call", () => {+ expect(findUses(["const c = new IxClient(url);"], "IxClient", 1, 1)).toEqual([1]);+ });+});++describe("anchorSpan", () => {+ it("keeps a span whose declaration is where the graph says", () => {+ expect(anchorSpan(CALLER, "caller", 4, 11)).toEqual({ start: 4, end: 11, anchored: true });+ });++ it("shifts a span the file has moved out from under", () => {+ // The graph recorded lines 4-11; two lines were inserted above since.+ const moved = ["// new", "// new", ...CALLER];+ expect(anchorSpan(moved, "caller", 4, 11)).toEqual({ start: 6, end: 13, anchored: true });+ });++ it("says when it could not re-anchor, so the caller can widen instead", () => {+ expect(anchorSpan(["a", "b", "c", "d"], "missing", 2, 3).anchored).toBe(false);+ });+});++describe("importKeys / findImports", () => {+ it("imports a file by its stem, trying the directory first", () => {+ expect(importKeys("config.ts", "file", "ix-cli/src/cli/config.ts")).toEqual(["cli/config", "config"]);+ expect(importKeys("commander", "module", undefined)).toEqual(["commander"]);+ });++ it("finds the import line, not a use of the same word", () => {+ const lines = [+ "import { a } from \"../cli/config.js\";",+ "const config = load();",+ "from pkg.config import b",+ ];+ expect(findImports(lines, ["cli/config", "config"])).toEqual([1]);+ expect(findImports(lines, ["config"])).toEqual([1, 3]);+ });++ it("finds the module specifier line of a multi-line import", () => {+ const lines = ["import {", " a,", " b,", "} from \"./lib.js\";"];+ expect(findImports(lines, ["lib"])).toEqual([4]);+ });+});++describe("bareName", () => {+ it("is the last segment of a qualified name", () => {+ expect(bareName("Foo::bar")).toBe("bar");+ expect(bareName("Foo.bar")).toBe("bar");+ expect(bareName("plain")).toBe("plain");+ });+});++describe("rankTextUses", () => {+ it("puts calls first, comments last, and drops the declaration", () => {+ const ranked = rankTextUses([+ { snippet: "import { go } from \"./go.js\";" },+ { snippet: "// go() is documented here" },+ { snippet: "export function go() {" },+ { snippet: "const r = go();" },+ ], "go");+ expect(ranked.map((r) => r.snippet)).toEqual([+ "const r = go();",+ "import { go } from \"./go.js\";",+ "// go() is documented here",+ ]);+ });+});++describe("withEdgeSites against files on disk", () => {+ let root: string;++ beforeAll(() => {+ root = mkdtempSync(join(tmpdir(), "ix-edge-sites-"));+ mkdirSync(join(root, "src"));+ writeFileSync(join(root, "src/caller.ts"), CALLER.join("\n"));+ writeFileSync(join(root, "src/lib.ts"), "export function target(n: number) {\n return helper(n);\n}\n");+ });+ afterAll(() => rmSync(root, { recursive: true, force: true }));+ afterEach(() => setOutputShape({}));++ const callerRow = {+ id: "11111111-2222-3333-4444-555555555555", name: "caller", kind: "function",+ attrs: { line_start: 4, line_end: 11 }, provenance: { sourceUri: "src/caller.ts" },+ };++ it("callers: the call inside the caller's span, with the others in also", () => {+ const [row] = withEdgeSites([callerRow], "callers", { name: "target" }, { root });+ expect(row.site).toEqual({+ path: "src/caller.ts",+ line: 6,+ snippet: "const y = target(a);",+ also: [8],+ });+ });++ it("callees: the call inside the target's span, in the target's file", () => {+ const helper = { name: "helper", kind: "function", provenance: { sourceUri: "src/other.ts" } };+ const [row] = withEdgeSites([helper], "callees", {+ name: "target", kind: "function", path: "src/lib.ts", lineStart: 1, lineEnd: 3,+ }, { root });+ expect(row.site).toMatchObject({ path: "src/lib.ts", line: 2, snippet: "return helper(n);" });+ });++ it("imported-by: the import line in the importing file", () => {+ const importer = { name: "caller.ts", kind: "file", provenance: { sourceUri: "src/caller.ts" } };+ const [row] = withEdgeSites([importer], "imported-by", {+ name: "lib.ts", kind: "file", path: "src/lib.ts",+ }, { root });+ expect(row.site).toMatchObject({ path: "src/caller.ts", line: 1 });+ });++ it("re-anchors a span recorded before the file moved", () => {+ const [row] = withEdgeSites(+ [{ ...callerRow, attrs: { line_start: 8, line_end: 15 } }],+ "callers", { name: "target" }, { root },+ );+ // `caller` is declared on line 4 now, not 8: the span shifts to 4-11 and+ // the first call is 6 again, rather than 8 from the stale span.+ expect(row.site.line).toBe(6);+ });++ it("joins the continuation lines of a call left open", () => {+ writeFileSync(join(root, "src/multi.ts"), ["function m() {", " return target(", " y,", " );", "}"].join("\n"));+ const [row] = withEdgeSites(+ [{ name: "m", kind: "function", attrs: { line_start: 1, line_end: 5 }, provenance: { sourceUri: "src/multi.ts" } }],+ "callers", { name: "target" }, { root },+ );+ expect(row.site).toMatchObject({ line: 2, snippet: "return target( y, );" });+ });++ it("leaves a row alone when its file is missing, or the relation has no site", () => {+ const gone = { ...callerRow, provenance: { sourceUri: "src/deleted.ts" } };+ expect(withEdgeSites([gone], "callers", { name: "target" }, { root })[0].site).toBeUndefined();+ expect(withEdgeSites([callerRow], "contains", { name: "target" }, { root })[0]).toBe(callerRow);+ });++ it("refuses a file outside every readable root", () => {+ const outside = { ...callerRow, provenance: { sourceUri: "/etc/hostname" } };+ expect(withEdgeSites([outside], "callers", { name: "target" }, { root })[0].site).toBeUndefined();+ });++ it("reads each file once", () => {+ const files = new SourceFiles(root);+ const spy = vi.spyOn(files, "lines");+ withEdgeSites([callerRow, callerRow], "callers", { name: "target" }, { root, files });+ expect(spy).toHaveBeenCalledTimes(2);+ expect(files.lines("src/caller.ts")).toBe(files.lines("src/caller.ts"));+ });++ it("renders as site=path:line, also= and a snippet, after the row's own location", () => {+ const rows = withEdgeSites([callerRow], "callers", { name: "target" }, { root });+ const lines = renderEdgeResultsLlm(sliceEdgeResults(rows, 50), "callers", "target", "graph");+ expect(lines[1]).toBe(+ 'ref name=caller kind=function path=src/caller.ts lines=4-11 site=src/caller.ts:6 also=8 snippet="const y = target(a);"',+ );+ });++ it("carries the site into json and onto a second text line", () => {+ const rows = withEdgeSites([callerRow], "callers", { name: "target" }, { root });+ const out: string[] = [];+ const spy = vi.spyOn(console, "log").mockImplementation((...a: unknown[]) => { out.push(a.map(String).join(" ")); });+ try {+ formatEdgeResults(sliceEdgeResults(rows, 50), "callers", "target", "json");+ formatEdgeResults(sliceEdgeResults(rows, 50), "callers", "target", "text");+ } finally {+ spy.mockRestore();+ }+ expect(JSON.parse(out[0]).results[0].site).toEqual({+ path: "src/caller.ts", line: 6, snippet: "const y = target(a);", also: [8],+ });+ // eslint-disable-next-line no-control-regex+ const plain = out.slice(1).map((l) => l.replace(/\x1b\[[0-9;]*m/g, ""));+ expect(plain).toContain(" at src/caller.ts:6 const y = target(a);");+ });+});++describe("edgeTargetFor", () => {+ const entity = vi.fn(async () => ({+ node: { attrs: { line_start: 10, line_end: 20 }, provenance: { sourceUri: "src/lib.ts" } },+ }));+ afterEach(() => entity.mockClear());++ it("asks the backend for the span only where the relation needs one", async () => {+ const target = { id: "x", name: "target", kind: "function", path: "src/lib.ts" };+ expect(await edgeTargetFor({ entity }, target, "callers")).toEqual({ name: "target", kind: "function", path: "src/lib.ts" });+ expect(entity).not.toHaveBeenCalled();+ expect(await edgeTargetFor({ entity }, target, "callees")).toMatchObject({ lineStart: 10, lineEnd: 20 });+ expect(entity).toHaveBeenCalledTimes(1);+ });++ it("fills in the path of a target resolved by id", async () => {+ const byId = { id: "x", name: "lib.ts", kind: "file" };+ expect(await edgeTargetFor({ entity }, byId, "imports")).toEqual({ name: "lib.ts", kind: "file", path: "src/lib.ts" });+ });++ it("degrades to what it has when the backend fails", async () => {+ const failing = { entity: async () => { throw new Error("down"); } };+ const target = { id: "x", name: "target", kind: "function", path: "src/lib.ts" };+ expect(await edgeTargetFor(failing, target, "callees")).toEqual({ name: "target", kind: "function", path: "src/lib.ts" });+ });+});diff --git a/ix-cli/src/cli/__tests__/llm-tier2.test.ts b/ix-cli/src/cli/__tests__/llm-tier2.test.tsindex 3fca8ef5..2cc53537 100644--- a/ix-cli/src/cli/__tests__/llm-tier2.test.ts+++ b/ix-cli/src/cli/__tests__/llm-tier2.test.ts@@ -15,7 +15,9 @@ describe("renderEdgeResultsLlm", () => {];const lines = renderEdgeResultsLlm(sliceEdgeResults(nodes, 50), "callers", "verify_token", "graph");expect(lines[0]).toBe("callers target=verify_token shown=2 total=2 resolved=1 unresolved=1");- expect(lines[1]).toBe("ref name=handleLogin kind=method id=abcdef12 path=src/a.ts");+ // A resolved row is identified by name + path; the id stays only on the+ // unresolved one, where it is the only identity there is.+ expect(lines[1]).toBe("ref name=handleLogin kind=method path=src/a.ts");expect(lines[2]).toBe("ref kind=method id=deadbeef resolved=false");});diff --git a/ix-cli/src/cli/__tests__/row-locations.test.ts b/ix-cli/src/cli/__tests__/row-locations.test.tsindex d09bfdd2..de569f95 100644--- a/ix-cli/src/cli/__tests__/row-locations.test.ts+++ b/ix-cli/src/cli/__tests__/row-locations.test.ts@@ -73,7 +73,8 @@ describe("edge results", () => {it("put a span on every row that has one", () => {const lines = renderEdgeResultsLlm(sliceEdgeResults([node()], 50), "callers", "relativePath", "graph");expect(lines[1]).toBe(- "ref name=registerCallersCommand kind=function id=aaaaaaaa path=ix-cli/src/cli/commands/callers.ts lines=17-145",+ // No id: name + path already identify the row (see disambiguatingIds).+ "ref name=registerCallersCommand kind=function path=ix-cli/src/cli/commands/callers.ts lines=17-145",);});diff --git a/ix-cli/src/cli/__tests__/row-noise.test.ts b/ix-cli/src/cli/__tests__/row-noise.test.tsindex 0b1e88a7..75d1299d 100644--- a/ix-cli/src/cli/__tests__/row-noise.test.ts+++ b/ix-cli/src/cli/__tests__/row-noise.test.ts@@ -3,6 +3,7 @@import { afterEach, describe, expect, it } from "vitest";import { dropNonNameMatches, emptySearchHint, renderSearchLlm } from "../commands/search.js";+import { renderEdgeResultsLlm, sliceEdgeResults } from "../format.js";import { setOutputShape } from "../output-shape.js";afterEach(() => setOutputShape({}));@@ -85,3 +86,16 @@ describe("an empty search", () => {expect(lines.some((l) => l.startsWith("hint"))).toBe(false);});});++describe("edge rows", () => {+ it("keep ids on rows that collide on name, kind and path", () => {+ const node = (id: string, start: number) => ({+ id, name: "dup", kind: "function", attrs: { line_start: start, line_end: start + 1 }, provenance: { sourceUri: "a.ts" },+ });+ const lines = renderEdgeResultsLlm(+ sliceEdgeResults([node("aaaaaaaa11112222", 1), node("bbbbbbbb11112222", 5)], 10), "callers", "t", "graph",+ );+ expect(lines[1]).toContain("id=aaaaaaaa");+ expect(lines[2]).toContain("id=bbbbbbbb");+ });+});diff --git a/ix-cli/src/cli/commands/callers.ts b/ix-cli/src/cli/commands/callers.tsindex 96d90e00..229b1211 100644--- a/ix-cli/src/cli/commands/callers.ts+++ b/ix-cli/src/cli/commands/callers.ts@@ -11,6 +11,7 @@ import { parsePickOption } from "../options.js";import { resolveFileOrReport, printResolved } from "../resolve.js";import { stderr } from "../stderr.js";import { llmLine } from "../llm.js";+import { edgeTargetFor, rankTextUses, withEdgeSites } from "../edge-sites.js";const execFileAsync = promisify(execFile);@@ -65,8 +66,14 @@ export function registerCallersCommand(program: Command): void {} catch { /* skip malformed lines */ }}- const candidatesFound = allTextResults.length;- const textResults = allTextResults.slice(0, 10);+ // Calls first and the definition out: an unranked fallback led with+ // import lines and the target's own signature.+ const ranked = rankTextUses(+ allTextResults.map((r) => ({ ...r, snippet: r.attrs.snippet as string })),+ target.name,+ ).map(({ snippet: _snippet, ...r }) => r);+ const candidatesFound = ranked.length;+ const textResults = ranked.slice(0, 10);if (textResults.length > 0) {if (opts.format === "llm") {@@ -115,7 +122,9 @@ export function registerCallersCommand(program: Command): void {// Both graph and text emptyformatEdgeResults(sliceEdgeResults([], limit), "callers", target.name, opts.format, target, "graph");} else {- formatEdgeResults(sliceEdgeResults(result.nodes, limit), "callers", target.name, opts.format, target, "graph");+ const slice = sliceEdgeResults(result.nodes, limit);+ const site = await edgeTargetFor(client, target, "callers");+ formatEdgeResults({ ...slice, rows: withEdgeSites(slice.rows, "callers", site) }, "callers", target.name, opts.format, target, "graph");}});@@ -140,6 +149,8 @@ export function registerCallersCommand(program: Command): void {direction: "out",predicates: ["CALLS", "REFERENCES"],});- formatEdgeResults(sliceEdgeResults(result.nodes, calleeLimit), "callees", target.name, opts.format, target, "graph");+ const slice = sliceEdgeResults(result.nodes, calleeLimit);+ const site = await edgeTargetFor(client, target, "callees");+ formatEdgeResults({ ...slice, rows: withEdgeSites(slice.rows, "callees", site) }, "callees", target.name, opts.format, target, "graph");});}diff --git a/ix-cli/src/cli/commands/imports.ts b/ix-cli/src/cli/commands/imports.tsindex a68bf18b..8523be75 100644--- a/ix-cli/src/cli/commands/imports.ts+++ b/ix-cli/src/cli/commands/imports.ts@@ -6,6 +6,7 @@ import { getEndpoint } from "../config.js";import { formatEdgeResults, sliceEdgeResults } from "../format.js";import { resolveFileOrReport, printResolved } from "../resolve.js";import { parsePickOption } from "../options.js";+import { edgeTargetFor, withEdgeSites } from "../edge-sites.js";export function registerImportsCommand(program: Command): void {program@@ -25,7 +26,9 @@ export function registerImportsCommand(program: Command): void {if (!target) return;if (opts.format === "text") printResolved(target);const result = await client.expand(target.id, { direction: "out", predicates: ["IMPORTS"] });- formatEdgeResults(sliceEdgeResults(result.nodes, limit), "imports", target.name, opts.format, target, "graph");+ const slice = sliceEdgeResults(result.nodes, limit);+ const site = await edgeTargetFor(client, target, "imports");+ formatEdgeResults({ ...slice, rows: withEdgeSites(slice.rows, "imports", site) }, "imports", target.name, opts.format, target, "graph");});program@@ -45,6 +48,8 @@ export function registerImportsCommand(program: Command): void {if (!target) return;if (opts.format === "text") printResolved(target);const result = await client.expand(target.id, { direction: "in", predicates: ["IMPORTS"] });- formatEdgeResults(sliceEdgeResults(result.nodes, limit), "imported-by", target.name, opts.format, target, "graph");+ const slice = sliceEdgeResults(result.nodes, limit);+ const site = await edgeTargetFor(client, target, "imported-by");+ formatEdgeResults({ ...slice, rows: withEdgeSites(slice.rows, "imported-by", site) }, "imported-by", target.name, opts.format, target, "graph");});}diff --git a/ix-cli/src/cli/edge-sites.ts b/ix-cli/src/cli/edge-sites.tsnew file mode 100644index 00000000..9e7fe916--- /dev/null+++ b/ix-cli/src/cli/edge-sites.ts@@ -0,0 +1,384 @@+// Copyright 2026 Ix Infrastructure Inc.++import * as fs from "node:fs";+import { absoluteFromSourceUri, isReadablePath } from "./config.js";+import { rowLocation } from "./format.js";++/**+ * Where an edge happens: the call, or the import, rather than the entity at+ * the other end of it.+ *+ * `ix callers` used to answer with the caller's whole span — `ingestFiles+ * lines=1368-3683` is 2,315 lines to find one call in — and every agent that+ * got that answer spent its next turn grepping for the line. The graph cannot+ * say where the call is: core-ingestion folds every call from one scope to one+ * callee into a single CALLS relationship and emits it with empty attrs+ * (`patch-builder.ts`), and the backend's `/v1/expand` hands those attrs back+ * as they are. So the site is recovered here, off the file on disk, which the+ * CLI already reads for `ix read`: one read per distinct file, bounded to the+ * rows being printed.+ */+export interface EdgeSite {+ /** Workspace-relative path of the file the call or import is in. */+ path: string;+ /** 1-based line of the first site. */+ line: number;+ /** That line, trimmed, with up to two continuation lines of an open call. */+ snippet: string;+ /** Further sites in the same scope, capped at {@link MAX_ALSO}. */+ also?: number[];+}++/** The entity an edge query was asked about. */+export interface EdgeTarget {+ name: string;+ kind?: string;+ path?: string;+ lineStart?: number;+ lineEnd?: number;+}++/** Relations whose rows can carry a site. `contains` has nothing to point at. */+export type SiteRelation = "callers" | "callees" | "imports" | "imported-by";++const MAX_FILE_BYTES = 2 * 1024 * 1024;+const SNIPPET_CHARS = 160;+const MAX_ALSO = 4;+/** How far past a span a site is still looked for when the span cannot be re-anchored. */+const SPAN_SLACK = 30;++export function isSiteRelation(relation: string): relation is SiteRelation {+ return relation === "callers" || relation === "callees" || relation === "imports" || relation === "imported-by";+}++/**+ * The identifier a call site spells: `Foo::bar` and `Foo.bar` are called as+ * `bar`, so that is what is searched for.+ */+export function bareName(name: string): string {+ const parts = name.split(/::|[.#/\\]/).filter((p) => p !== "");+ return parts[parts.length - 1] ?? name;+}++function escapeRegExp(value: string): string {+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++/** `name` as a whole identifier. `$` counts as an identifier character, as it does in JS. */+function wordRe(name: string): RegExp {+ return new RegExp(`(?<![\\w$])${escapeRegExp(name)}(?![\\w$])`);+}++/** `name(`, `name<T>(`, `new Name`, and the member form `.name(` (which the first covers). */+function callRe(name: string): RegExp {+ const n = escapeRegExp(name);+ return new RegExp(`\\bnew\\s+${n}(?![\\w$])|(?<![\\w$])${n}\\s*(?:<[^()]*>)?\\s*\\(`);+}++const DEF_KEYWORDS = [+ "function", "def", "fn", "func", "class", "interface", "struct", "trait", "object",+ "enum", "type", "const", "let", "var", "val", "module", "record", "sub", "macro",+].join("|");++/**+ * A line that declares `name` with a keyword (`function name`, `def name`,+ * `const name`, Go's `func (r *T) name(`). Never a use of it.+ */+function keywordDeclRe(name: string): RegExp {+ const n = escapeRegExp(name);+ return new RegExp(+ `\\b(?:${DEF_KEYWORDS})\\s*\\*?\\s+${n}(?![\\w$])`+ + `|\\bfunc\\s*\\([^)]*\\)\\s*${n}\\s*\\(`,+ );+}++/**+ * Any line that looks like it declares `name`, including the keyword-less+ * method shorthand of a class body (`async name(x) {`). That form is only+ * trusted when the line opens a body or a parameter list, because without the+ * keyword it is otherwise indistinguishable from a bare call statement.+ */+function declRe(name: string): RegExp {+ const n = escapeRegExp(name);+ const keyword = keywordDeclRe(name).source;+ return new RegExp(+ `${keyword}`+ + `|^\\s*(?:(?:export|default|public|private|protected|internal|static|async|override|abstract|final|readonly|get|set|pub(?:\\([^)]*\\))?)\\s+)*${n}\\s*(?:<[^>]*>)?\\s*\\(.*[{(,]\\s*$`,+ );+}++const COMMENT_ONLY = /^\s*(?:\/\/|\/\*|\*|#(?!include|import)|--|;)/;++/** The site's text: its line, plus the lines of a call left open across them. */+function snippetAt(lines: string[], index: number): string {+ let text = lines[index].trim();+ let depth = parenDepth(text);+ for (let next = index + 1; depth > 0 && next < lines.length && next <= index + 2; next++) {+ const more = lines[next].trim();+ text = `${text} ${more}`;+ depth += parenDepth(more);+ }+ return text.length > SNIPPET_CHARS ? `${text.slice(0, SNIPPET_CHARS - 1)}…` : text;+}++function parenDepth(text: string): number {+ let depth = 0;+ for (const ch of text) {+ if (ch === "(") depth++;+ else if (ch === ")") depth--;+ }+ return depth;+}++/**+ * The span as it is on disk now.+ *+ * Graph spans are from the last ingest, and a file edited since has moved+ * under them: on a live workspace `readableRoots` sat at `250-253` in the graph+ * and at 283 on disk. Scanning the stale span finds the wrong call or none.+ * The nearest line that declares the entity's name is taken as its start now,+ * and the span is shifted with it; a decorator or doc line recorded as the+ * start moves it by a line or two, which costs nothing. With no declaration in+ * sight the recorded span stands, and is trusted only if the name is still on+ * one of its first lines.+ */+export function anchorSpan(+ lines: string[], name: string, lineStart: number, lineEnd: number | undefined,+): { start: number; end: number; anchored: boolean } {+ const end = lineEnd ?? lineStart;+ const def = declRe(name);+ let best = -1;+ for (let i = 0; i < lines.length; i++) {+ if (!def.test(lines[i])) continue;+ if (best < 0 || Math.abs(i + 1 - lineStart) < Math.abs(best + 1 - lineStart)) best = i;+ }+ if (best >= 0) {+ const delta = best + 1 - lineStart;+ return { start: lineStart + delta, end: end + delta, anchored: true };+ }+ const word = wordRe(name);+ for (let l = lineStart; l <= Math.min(lineStart + 2, lines.length); l++) {+ if (word.test(lines[l - 1] ?? "")) return { start: lineStart, end, anchored: true };+ }+ return { start: lineStart, end, anchored: false };+}++/**+ * Lines inside [from, to] (1-based, inclusive) that use `name`, calls first.+ *+ * Comment lines never count, and neither does a line that declares `name`: a+ * recursive function's own signature is not a call to it. When no line in the+ * range calls `name`, a bare use stands in — a callback passed by name, a type+ * reference — because REFERENCES edges are listed as callers too.+ */+export function findUses(lines: string[], name: string, from: number, to: number): number[] {+ const call = callRe(name);+ const word = wordRe(name);+ const def = keywordDeclRe(name);+ const calls: number[] = [];+ const refs: number[] = [];+ const first = Math.max(1, from);+ const last = Math.min(lines.length, to);+ for (let l = first; l <= last; l++) {+ const text = lines[l - 1];+ if (!word.test(text) || COMMENT_ONLY.test(text) || def.test(text)) continue;+ (call.test(text) ? calls : refs).push(l);+ }+ return calls.length > 0 ? calls : refs;+}++/** Statement shapes that bring a name in from elsewhere, across the languages Ix parses. */+const IMPORT_LINE = /^\s*(?:import\b|export\b.*\bfrom\b|from\s+\S+\s+import\b|use\s|using\s|#\s*(?:include|import)\b|require\b|include\b|extern\s+crate\b|@import\b)|\bfrom\s+['"]|\brequire\s*\(|\bimport\s*\(/;++/**+ * The keys an import of this entity spells, most specific first.+ *+ * A file is imported by its path, so `src/cli/config.ts` shows up as+ * `./config.js` or `cli.config`; `index.ts` is too common a stem to trust on+ * its own and is tried with its directory first. Anything else is imported by+ * its name.+ */+export function importKeys(name: string, kind: string | undefined, path: string | undefined): string[] {+ const isFile = (kind ?? "").toLowerCase() === "file";+ const source = isFile ? (path ?? name) : name;+ const segments = source.replace(/\\/g, "/").split("/").filter((s) => s !== "");+ const base = segments[segments.length - 1] ?? source;+ if (!isFile) return [base];+ const stem = base.replace(/\.[^.]+$/, "");+ const parent = segments[segments.length - 2];+ return parent ? [`${parent}/${stem}`, stem] : [stem];+}++/** Import lines in the file that name any of `keys`, trying the most specific key first. */+export function findImports(lines: string[], keys: string[]): number[] {+ for (const key of keys) {+ const re = new RegExp(`(?<![\\w$-])${escapeRegExp(key)}(?![\\w$-])`);+ const hits: number[] = [];+ for (let i = 0; i < lines.length; i++) {+ if (IMPORT_LINE.test(lines[i]) && re.test(lines[i])) hits.push(i + 1);+ }+ if (hits.length > 0) return hits;+ }+ return [];+}++/** Reads each file at most once per command, and only inside a readable workspace. */+export class SourceFiles {+ private readonly cache = new Map<string, string[] | null>();++ constructor(private readonly root?: string) {}++ lines(relPath: string | undefined): string[] | null {+ if (!relPath) return null;+ if (this.cache.has(relPath)) return this.cache.get(relPath)!;+ let lines: string[] | null = null;+ try {+ const abs = absoluteFromSourceUri(relPath, this.root);+ if (isReadablePath(abs, this.root)) {+ const stat = fs.statSync(abs);+ if (stat.isFile() && stat.size <= MAX_FILE_BYTES) {+ lines = fs.readFileSync(abs, "utf-8").split("\n");+ }+ }+ } catch {+ lines = null;+ }+ this.cache.set(relPath, lines);+ return lines;+ }+}++function toSite(path: string, lines: string[], hits: number[]): EdgeSite | undefined {+ if (hits.length === 0) return undefined;+ const [line, ...rest] = hits;+ return {+ path,+ line,+ snippet: snippetAt(lines, line - 1),+ also: rest.length > 0 ? rest.slice(0, MAX_ALSO) : undefined,+ };+}++/** Uses of `name` inside the scope of an entity, the scope re-anchored to the file on disk. */+function usesInScope(+ lines: string[], name: string,+ scope: { name: string; kind?: string; lineStart?: number; lineEnd?: number },+): number[] {+ if ((scope.kind ?? "").toLowerCase() === "file" || scope.lineStart === undefined) {+ return findUses(lines, name, 1, lines.length);+ }+ const span = anchorSpan(lines, bareName(scope.name), scope.lineStart, scope.lineEnd);+ const inside = findUses(lines, name, span.start, span.end);+ if (inside.length > 0 || span.anchored) return inside;+ return findUses(lines, name, span.start - SPAN_SLACK, span.end + SPAN_SLACK);+}++/**+ * The site of one edge row, or undefined when it cannot be found honestly.+ *+ * - callers: the call to the target, inside the caller's span, in the caller's file+ * - callees: the call to the row, inside the target's span, in the target's file+ * - imported-by: the import of the target, in the importing row's file+ * - imports: the import of the row, in the target's file+ */+export function findEdgeSite(+ relation: SiteRelation, row: any, target: EdgeTarget, files: SourceFiles,+): EdgeSite | undefined {+ const rowName: string = row?.name || row?.attrs?.name || "";+ if (!rowName) return undefined;+ const loc = rowLocation(row);+ const rowScope = { name: rowName, kind: row?.kind, lineStart: loc.lineStart, lineEnd: loc.lineEnd };++ switch (relation) {+ case "callers": {+ const lines = files.lines(loc.path);+ return lines && loc.path ? toSite(loc.path, lines, usesInScope(lines, bareName(target.name), rowScope)) : undefined;+ }+ case "callees": {+ const lines = files.lines(target.path);+ return lines && target.path ? toSite(target.path, lines, usesInScope(lines, bareName(rowName), target)) : undefined;+ }+ case "imported-by": {+ const lines = files.lines(loc.path);+ return lines && loc.path ? toSite(loc.path, lines, findImports(lines, importKeys(target.name, target.kind, target.path))) : undefined;+ }+ case "imports": {+ const lines = files.lines(target.path);+ return lines && target.path ? toSite(target.path, lines, findImports(lines, importKeys(rowName, row?.kind, loc.path))) : undefined;+ }+ }+}++/**+ * Attach a `site` to each row whose edge can be located on disk.+ *+ * Returns new row objects; the input is left alone. Rows with no findable+ * site come back unchanged, so a file that is missing, outside the workspace,+ * or edited past recognition costs a field, never a row.+ */+export function withEdgeSites(+ rows: any[], relation: string, target: EdgeTarget, opts: { root?: string; files?: SourceFiles } = {},+): any[] {+ if (!isSiteRelation(relation)) return rows;+ const files = opts.files ?? new SourceFiles(opts.root);+ return rows.map((row) => {+ let site: EdgeSite | undefined;+ try {+ site = findEdgeSite(relation, row, target, files);+ } catch {+ site = undefined;+ }+ return site ? { ...row, site } : row;+ });+}++/**+ * The target as the site finder needs it.+ *+ * `callers` and `imported-by` look in the rows' files and need only the+ * target's name. `callees` and `imports` look in the target's own file —+ * `callees` inside its span, which the resolver does not carry — so those cost+ * a `/v1/entity` read (~20 ms) whenever the resolver left out what they need:+ * the span of a non-file target, or the path of a target resolved by id.+ */+export async function edgeTargetFor(+ client: { entity(id: string): Promise<{ node: any }> },+ target: { id: string; name: string; kind: string; path?: string },+ relation: string,+): Promise<EdgeTarget> {+ const base: EdgeTarget = { name: target.name, kind: target.kind, path: target.path };+ const isFile = (target.kind ?? "").toLowerCase() === "file";+ const needsSpan = relation === "callees" && !isFile;+ const needsPath = (relation === "callees" || relation === "imports") && !base.path;+ if (!needsSpan && !needsPath) return base;+ try {+ const { node } = await client.entity(target.id);+ const loc = rowLocation(node);+ return {+ ...base,+ path: base.path ?? loc.path,+ lineStart: needsSpan ? loc.lineStart : undefined,+ lineEnd: needsSpan ? loc.lineEnd : undefined,+ };+ } catch {+ return base;+ }+}++/**+ * Order raw text matches of `name` the way a callers answer should read: calls+ * first, then other uses, then comments, with the name's own declaration+ * dropped — it is where the name is defined, not a caller of it. Stable within+ * each group, so ripgrep's file order survives.+ */+export function rankTextUses<T extends { snippet: string }>(matches: T[], name: string): T[] {+ const bare = bareName(name);+ const call = callRe(bare);+ const decl = keywordDeclRe(bare);+ const group = (text: string): number => (COMMENT_ONLY.test(text) ? 2 : call.test(text) ? 0 : 1);+ return matches+ .filter((m) => !decl.test(m.snippet))+ .map((m, i) => ({ m, i, g: group(m.snippet) }))+ .sort((a, b) => a.g - b.g || a.i - b.i)+ .map(({ m }) => m);+}diff --git a/ix-cli/src/cli/format.ts b/ix-cli/src/cli/format.tsindex dde594dd..b517ea05 100644--- a/ix-cli/src/cli/format.ts+++ b/ix-cli/src/cli/format.ts@@ -3,6 +3,7 @@import chalk from "chalk";import { llmLine, llmShortId } from "./llm.js";import { projectRow, requestedFields } from "./output-shape.js";+import type { EdgeSite } from "./edge-sites.js";export type ResultSource = "graph" | "text" | "graph+text" | "heuristic";@@ -226,6 +227,11 @@ export function disambiguatingIds<T>(return rows.map((row) => (wanted || (counts.get(key(row)) ?? 0) > 1 ? llmShortId(id(row)) : undefined));}+/** `path:line`, the form an editor and every agent tool cites. */+export function siteLabel(site: EdgeSite): string {+ return `${site.path}:${site.line}`;+}+export function confidenceColor(score: number): (text: string) => string {if (score >= 0.8) return chalk.green;if (score >= 0.5) return chalk.yellow;@@ -678,9 +684,15 @@ export function renderEdgeResultsLlm(name,kind: n.kind ?? undefined,id: n.id ?? undefined,+ site: n.site as EdgeSite | undefined,...rowLocation(n),};});+ const ids = disambiguatingIds(+ refs,+ (r) => `${r.name}\u0000${r.kind ?? ""}\u0000${r.path ?? ""}`,+ (r) => r.id,+ );const unresolved = refs.filter((r) => !r.resolved).length;const lines = [llmLine(relation, [["target", symbol],@@ -702,14 +714,18 @@ export function renderEdgeResultsLlm(for (const d of diagnostics ?? []) {lines.push(llmLine("diagnostic", [["code", d.code], ["message", d.message]]));}- for (const ref of refs) {+ refs.forEach((ref, i) => {+ // An unresolved row has no name to go by, so its id is all there is.lines.push(ref.resolved? llmLine("ref", projectRow([- ["name", ref.name], ["kind", ref.kind], ["id", llmShortId(ref.id)],+ ["name", ref.name], ["kind", ref.kind], ["id", ids[i]],["path", ref.path], ["lines", lineSpan(ref)],+ ["site", ref.site ? siteLabel(ref.site) : undefined],+ ["also", ref.site?.also?.join(",")],+ ["snippet", ref.site?.snippet],])): llmLine("ref", projectRow([["kind", ref.kind], ["id", llmShortId(ref.id)], ["resolved", false]])));- }+ });return lines;}@@ -737,6 +753,7 @@ export function formatEdgeResults(kind: n.kind ?? undefined,id: resolved ? n.id : undefined,...rowLocation(n),+ ...(n.site ? { site: n.site } : {}),};if (!resolved) {ref.resolved = false;@@ -809,6 +826,8 @@ export function formatEdgeResults(` ${chalk.cyan((n.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${chalk.bold(name)}`+ (where ? ` ${chalk.dim(where)}` : ""),);+ const site = n.site as EdgeSite | undefined;+ if (site) console.log(` ${chalk.dim(`at ${siteLabel(site)}`)} ${site.snippet}`);}}if (slice.truncated) console.log(chalk.dim(` ${truncationHint(slice, relation)}`));