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): ix around -- who depends on the code at a file location
KageBinary267e226bb1fb
diff --git a/docs/llm-format.md b/docs/llm-format.mdindex 9c7db687..63aa92d8 100644--- a/docs/llm-format.md+++ b/docs/llm-format.md@@ -189,6 +189,31 @@ use, skipping comments and the name's own declaration. A row whose file ismissing, outside the workspace, or has no findable use simply has no `site=`.`--format json` carries the same object as `site: {path, line, snippet, also}`.+`ix around <path>[:<line>]` — the dependents of the code at a location, sized+for an agent's context (`--budget`, default 300 tokens):++```+around path=ix-cli/src/cli/options.ts lines=90 symbols=1+symbol name=parsePickOption kind=function path=ix-cli/src/cli/options.ts lines=90-92 callers=0 users=14 tests=1+user site=ix-cli/src/cli/commands/subsystems.ts:70 snippet=".option(\"--pick <n>\", \"Resolve an ambiguous region target by numbered candidate\", parsePickOption)"+user site=ix-cli/src/cli/commands/diff.ts:473 snippet=".option(\"--pick <n>\", \"Pick Nth candidate from ambiguous results (1-based)\", parsePickOption)"+test site=ix-cli/src/cli/__tests__/pick-option-validation.test.ts:52 snippet="expect(() => parsePickOption(value)).toThrow(\"must be a positive integer\");"+importers shown=0 total=17 tests=2+```++(Three `user` rows are left out above.) A `symbol` record carries the totals+(`callers`, `users`, `tests`); the `caller` / `user` / `test` / `same_name`+rows after it are the ones shown, so fewer rows than a total means the list+was cut to the budget. With more than one symbol each row names its own with+`of=`. `caller` is a CALLS/REFERENCES edge at its call site; `user` is a file+that imports this one, names the symbol in that import, and uses it -- found+on disk, so it also catches a function handed over by name, which no edge+records; `test` is a test file that calls it, calls a caller of it (`via=`+that caller), or imports and uses it. `importers` counts every file importing+this one; its `importer` rows are the first cut when the answer is over+budget. Empty lists print no rows. On a degraded graph a `graph` record+follows the header and the totals are floors.+`ix text <pattern>` — `match path=... line=... symbol=... snippet=...`. No`lang=`: the extension on `path` says it; `--format json` keeps `language`.diff --git a/ix-cli/src/cli/__tests__/around.test.ts b/ix-cli/src/cli/__tests__/around.test.tsnew file mode 100644index 00000000..873f7bfa--- /dev/null+++ b/ix-cli/src/cli/__tests__/around.test.ts@@ -0,0 +1,322 @@+// 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, beforeAll, describe, expect, it, vi } from "vitest";++vi.mock("../resolve.js", () => ({+ ensureReadScope: vi.fn(async () => undefined),+ activeReadScope: () => ({ workspaceId: "ws-test" }),+}));++import {+ DEFAULT_CAPS, estimateTokens, findUseInImporter, fitToBudget, gatherAround, importStatementText, isTestFile,+ outermostDefs, parseAroundTarget, placeDefs, selectEdited, type AroundResult, type FileDef,+} from "../around.js";+import { aroundJson, renderAroundLlm, renderAroundText } from "../around-render.js";+import { SourceFiles } from "../edge-sites.js";++describe("parseAroundTarget", () => {+ it("reads a path, a line, and a range", () => {+ expect(parseAroundTarget("src/a.ts")).toEqual({ file: "src/a.ts" });+ expect(parseAroundTarget("src/a.ts:12")).toEqual({ file: "src/a.ts", range: { start: 12, end: 12 } });+ expect(parseAroundTarget("src/a.ts:12-20")).toEqual({ file: "src/a.ts", range: { start: 12, end: 20 } });+ });++ it("keeps a Windows drive letter in the path and refuses a backwards range", () => {+ expect(parseAroundTarget("C:\\a.ts")).toEqual({ file: "C:\\a.ts" });+ expect(parseAroundTarget("a.ts:20-12")).toBeUndefined();+ expect(parseAroundTarget("a.ts:0")).toBeUndefined();+ });+});++describe("isTestFile", () => {+ it("knows the test layouts of the benchmark languages", () => {+ for (const p of [+ "src/__tests__/a.test.ts", "tests/test_api.py", "pkg/api_test.go", "src/test/java/a/FooTest.java",+ "ix-cli/test/client.test.ts", "lib/foo.spec.js",+ ]) expect(isTestFile(p), p).toBe(true);+ });++ it("does not count source or fixtures", () => {+ for (const p of ["src/cli/commands/test.ts", "src/testing.py", "core/test-fixtures/ts/sample.ts"]) {+ expect(isTestFile(p), p).toBe(false);+ }+ });+});++const def = (id: string, name: string, lineStart: number, lineEnd: number, extra: Partial<FileDef> = {}): FileDef =>+ ({ id, name, kind: "function", lineStart, lineEnd, topLevel: true, ...extra });++describe("placeDefs: re-anchoring after the file moved", () => {+ // As the graph recorded the file.+ const defs = [def("a", "alpha", 1, 3), def("b", "beta", 5, 7)];++ it("shifts spans to where the declarations are now", () => {+ const now = ["// new header", "// another", "function alpha() {", " return 1;", "}", "", "function beta() {", " return 2;", "}"];+ const placed = placeDefs(defs, now);+ expect(placed.find((d) => d.id === "a")).toMatchObject({ start: 3, end: 5 });+ expect(placed.find((d) => d.id === "b")).toMatchObject({ start: 7, end: 9 });+ });++ it("stretches the end of a definition that grew, keeping its gap to the next one", () => {+ const now = ["function alpha() {", " const x = 1;", " const y = 2;", " return x + y;", "}", "", "function beta() {", " return 2;", "}"];+ const placed = placeDefs(defs, now);+ expect(placed.find((d) => d.id === "a")).toMatchObject({ start: 1, end: 5 });+ });+});++describe("selectEdited", () => {+ const placed = placeDefs([+ def("cls", "Box", 1, 20, { kind: "class" }),+ def("m1", "open", 2, 5, { kind: "method", topLevel: false, container: "Box" }),+ def("m2", "close", 7, 10, { kind: "method", topLevel: false, container: "Box" }),+ def("f", "free", 22, 25),+ ], []);++ it("puts the innermost definition first and leaves out the class around it", () => {+ expect(selectEdited(placed, [{ start: 3, end: 3 }], 3).map((d) => d.id)).toEqual(["m1"]);+ });++ it("keeps the class when the edit also touched it outside its methods", () => {+ expect(selectEdited(placed, [{ start: 4, end: 6 }], 3).map((d) => d.id)).toEqual(["m1", "cls"]);+ });++ it("reports every definition a range spans, up to the cap", () => {+ expect(selectEdited(placed, [{ start: 3, end: 23 }], 2).map((d) => d.id)).toEqual(["m1", "m2"]);+ });++ it("counts an insertion only for a definition holding both neighbours", () => {+ expect(selectEdited(placed, [{ start: 5, end: 6, insertion: true }], 3).map((d) => d.id)).toEqual(["cls"]);+ expect(selectEdited(placed, [{ start: 20, end: 21, insertion: true }], 3)).toEqual([]);+ });++ it("finds the outermost definitions for a whole-file question", () => {+ expect(outermostDefs(placed).map((d) => d.id)).toEqual(["cls", "f"]);+ });+});++describe("importers that use the symbol", () => {+ const importer = [+ "import {", // 1+ " parseBudgetOption,", // 2+ " parsePickOption,", // 3+ "} from \"../options.js\";", // 4+ "", // 5+ "program.option(\"--pick <n>\", \"n\", parsePickOption);", // 6+ ];++ it("reads a multi-line import as one statement", () => {+ expect(importStatementText(importer, 4)).toMatchObject({ start: 1, end: 4 });+ });++ it("finds the use of a name the import brings in, outside the import", () => {+ expect(findUseInImporter(importer, [4], { name: "parsePickOption" })).toBe(6);+ });++ it("is nothing for a name imported but unused, or never imported", () => {+ expect(findUseInImporter(importer, [4], { name: "parseBudgetOption" })).toBeUndefined();+ expect(findUseInImporter(importer, [4], { name: "parseRevisionOption" })).toBeUndefined();+ });++ it("through the class, counts only a call to the member", () => {+ const viaClass = ["import { IxClient } from \"./api.js\";", "const o = { expand: true };", "await client.expand(id);"];+ expect(findUseInImporter(viaClass, [1], { name: "expand", container: "IxClient" })).toBe(3);+ expect(findUseInImporter(viaClass.slice(0, 2), [1], { name: "expand", container: "IxClient" })).toBeUndefined();+ });+});++// ── gatherAround over a mocked backend ───────────────────────────────────────++const node = (id: string, kind: string, name: string, path: string, lines?: [number, number]) => ({+ id, kind, name, provenance: { sourceUri: path },+ attrs: lines ? { line_start: lines[0], line_end: lines[1] } : {},+});++const FILES: Record<string, string[]> = {+ "src/lib.ts": [+ "export function target(x: number) {", // 1+ " return x + 1;", // 2+ "}", // 3+ "", // 4+ "export function other() {", // 5+ " return 0;", // 6+ "}", // 7+ ],+ "src/app.ts": [+ "import { target } from \"./lib.js\";", // 1+ "export function run() {", // 2+ " return target(2);", // 3+ "}", // 4+ ],+ "src/cli.ts": [+ "import { target } from \"./lib.js\";", // 1+ "program.option(\"--x <n>\", \"x\", target);", // 2+ ],+ "src/__tests__/app.test.ts": [+ "import { run } from \"../app.js\";", // 1+ "it(\"runs\", () => expect(run()).toBe(3));", // 2+ ],+};++let root: string;+const env = { ...process.env };++beforeAll(() => {+ root = mkdtempSync(join(tmpdir(), "ix-around-"));+ for (const [rel, lines] of Object.entries(FILES)) {+ mkdirSync(join(root, rel, ".."), { recursive: true });+ writeFileSync(join(root, rel), lines.join("\n"));+ }+ process.env.IX_HOME = join(root, ".ix-home");+ process.env.IX_GRAPH_HEALTH = "0";+});++afterAll(() => {+ rmSync(root, { recursive: true, force: true });+ process.env = env;+});++function mockClient(extraCallers: number = 0) {+ const file = node("f-lib", "file", "lib.ts", "src/lib.ts");+ const target = node("d-target", "function", "target", "src/lib.ts", [1, 3]);+ const other = node("d-other", "function", "other", "src/lib.ts", [5, 7]);+ const run = node("d-run", "function", "run", "src/app.ts", [2, 4]);+ const testFile = node("f-test", "file", "app.test.ts", "src/__tests__/app.test.ts");+ const fillers = Array.from({ length: extraCallers }, (_, i) =>+ node(`d-fill${i}`, "function", `fill${i}`, `src/fill${i}.ts`, [1, 3]));+ return {+ endpoint: "http://mock",+ search: vi.fn(async () => [file]),+ workspaceSystem: vi.fn(async () => ({ systemId: null })),+ currentRevision: vi.fn(async () => ({ rev: 1 })),+ stats: vi.fn(async () => ({})),+ expand: vi.fn(async (id: string, opts: any) => {+ const preds = (opts?.predicates ?? []).join(",");+ if (id === "f-lib" && preds === "CONTAINS") {+ return { nodes: [target, other], edges: [+ { src: "f-lib", dst: "d-target", predicate: "CONTAINS" },+ { src: "f-lib", dst: "d-other", predicate: "CONTAINS" },+ ] };+ }+ if (id === "f-lib" && preds === "IMPORTS") {+ return { nodes: [node("f-app", "file", "app.ts", "src/app.ts"), node("f-cli", "file", "cli.ts", "src/cli.ts")], edges: [] };+ }+ if (id === "d-target" && preds === "CALLS,REFERENCES") {+ if ((opts.hops ?? 1) === 2) {+ return { nodes: [run, testFile, ...fillers], edges: [+ { src: "d-run", dst: "d-target", predicate: "CALLS" },+ { src: "f-test", dst: "d-run", predicate: "CALLS" },+ ] };+ }+ return { nodes: [run, ...fillers], edges: [] };+ }+ return { nodes: [], edges: [] };+ }),+ };+}++describe("gatherAround", () => {+ it("reports callers at their sites, importers that use the symbol, and tests two hops back", async () => {+ const result = await gatherAround(mockClient() as any, {+ relPath: "src/lib.ts",+ ranges: [{ start: 2, end: 2 }],+ anchorLines: FILES["src/lib.ts"],+ files: new SourceFiles(root),+ });+ expect(result.symbols).toHaveLength(1);+ const s = result.symbols[0];+ expect(s).toMatchObject({ name: "target", lineStart: 1, lineEnd: 3 });+ expect(s.callers).toEqual({ total: 1, rows: [{ path: "src/app.ts", line: 3, snippet: "return target(2);", name: "run" }] });+ // app.ts is already a caller; cli.ts hands `target` over by name, which the graph has no edge for.+ expect(s.users.rows).toEqual([{ path: "src/cli.ts", line: 2, snippet: "program.option(\"--x <n>\", \"x\", target);" }]);+ expect(s.tests.rows).toEqual([{ path: "src/__tests__/app.test.ts", line: 2, snippet: "it(\"runs\", () => expect(run()).toBe(3));", name: undefined, via: "run" }]);+ expect(result.importers.total).toBe(2);+ });++ it("caps callers and keeps the total", async () => {+ const result = await gatherAround(mockClient(20) as any, {+ relPath: "src/lib.ts",+ ranges: [{ start: 1, end: 1 }],+ anchorLines: FILES["src/lib.ts"],+ files: new SourceFiles(root),+ caps: { callers: 4 },+ });+ expect(result.symbols[0].callers.total).toBe(21);+ expect(result.symbols[0].callers.rows).toHaveLength(4);+ expect(renderAroundText(result)).toContain("callers (4 of 21):");+ });++ it("answers a whole-file question with the most-called top-level definitions", async () => {+ const result = await gatherAround(mockClient() as any, {+ relPath: "src/lib.ts", anchorLines: FILES["src/lib.ts"], files: new SourceFiles(root),+ });+ expect(result.symbols.map((s) => s.name)).toEqual(["target", "other"]);+ });++ it("refuses a file the graph does not hold", async () => {+ const client = mockClient();+ client.search.mockResolvedValueOnce([]);+ await expect(gatherAround(client as any, {+ relPath: "src/missing.ts", anchorLines: [], files: new SourceFiles(root),+ })).rejects.toMatchObject({ code: "file_not_in_graph" });+ });+});++// ── Rendering and size ──────────────────────────────────────────────────────++function bigResult(): AroundResult {+ const refs = (n: number, prefix: string) => Array.from({ length: n }, (_, i) => ({+ path: `src/very/long/path/to/${prefix}${i}.ts`, line: 100 + i,+ snippet: `const value${i} = await someLongFunctionName(argumentNumberOne, argumentNumberTwo, ${i});`,+ }));+ const sym = (name: string) => ({+ id: name, name, kind: "function", path: "src/lib.ts", lineStart: 10, lineEnd: 40,+ callers: { total: 40, rows: refs(8, `${name}-caller`) },+ users: { total: 9, rows: refs(5, `${name}-user`) },+ tests: { total: 12, rows: refs(5, `${name}-test`) },+ sameName: [],+ });+ return {+ path: "src/lib.ts",+ symbols: [sym("alpha"), sym("beta"), sym("gamma")],+ importers: { total: 30, tests: 4, rows: refs(5, "importer") },+ };+}++describe("fitToBudget", () => {+ it("brings text and llm output under the token budget and keeps the totals", () => {+ for (const render of [(r: AroundResult) => renderAroundText(r, { importerRows: true }), (r: AroundResult) => renderAroundLlm(r).join("\n")]) {+ const fitted = fitToBudget(bigResult(), render, 300, DEFAULT_CAPS);+ expect(estimateTokens(render(fitted))).toBeLessThanOrEqual(300);+ expect(fitted.symbols[0].callers.total).toBe(40);+ }+ });++ it("leaves an answer that already fits alone", () => {+ const small = bigResult();+ small.symbols = small.symbols.slice(0, 1).map((s) => ({ ...s, callers: { total: 1, rows: s.callers.rows.slice(0, 1) }, users: { total: 0, rows: [] }, tests: { total: 0, rows: [] } }));+ const render = (r: AroundResult) => renderAroundText(r);+ expect(render(fitToBudget(small, render, 300))).toBe(render(small));+ });+});++describe("renderers", () => {+ it("drop empty sections instead of printing none", () => {+ const r = bigResult();+ r.symbols = [{ ...r.symbols[0], users: { total: 0, rows: [] }, tests: { total: 0, rows: [] } }];+ const text = renderAroundText(r);+ expect(text).not.toMatch(/used by importers|^tests|none/m);+ const llm = renderAroundLlm(r);+ expect(llm.some((l) => l.startsWith("user ") || l.startsWith("test "))).toBe(false);+ expect(llm[0]).toBe("around path=src/lib.ts symbols=1");+ });++ it("say the graph is degraded rather than implying there are no dependents", () => {+ const r: AroundResult = { ...bigResult(), graph: { status: "degraded", reason: "hollow", message: "m", fix: "f" } };+ expect(renderAroundText(r)).toContain("Graph is degraded");+ expect(renderAroundLlm(r)[1]).toMatch(/^graph status=degraded reason=hollow/);+ expect(aroundJson(r).graph).toMatchObject({ status: "degraded" });+ });+});diff --git a/ix-cli/src/cli/around-render.ts b/ix-cli/src/cli/around-render.tsnew file mode 100644index 00000000..647e429b--- /dev/null+++ b/ix-cli/src/cli/around-render.ts@@ -0,0 +1,131 @@+// Copyright 2026 Ix Infrastructure Inc.++import * as path from "node:path";+import { llmLine } from "./llm.js";+import { graphHealthJson, graphHealthLlmFields } from "./graph-health.js";+import type { AroundRef, AroundResult, AroundSection, AroundSymbol } from "./around.js";++/**+ * Renderers for `ix around`. All three show the same facts; text is also what+ * the post-edit hook hands an agent, so every line of it is paid for in+ * context on every edit -- no section is printed empty, no row twice.+ */++function span(s: { lineStart: number; lineEnd: number }): string {+ return s.lineEnd > s.lineStart ? `${s.lineStart}-${s.lineEnd}` : `${s.lineStart}`;+}++function refText(r: AroundRef): string {+ const where = r.line !== undefined ? `${r.path}:${r.line}` : r.path;+ const via = r.via ? ` (via ${r.via})` : "";+ return r.snippet ? `${where}${via} ${r.snippet}` : `${where}${via}`;+}++function sectionLines(label: string, section: AroundSection, indent: string): string[] {+ if (section.total === 0 || section.rows.length === 0) return [];+ const count = section.rows.length < section.total ? `${section.rows.length} of ${section.total}` : `${section.total}`;+ return [`${label} (${count}):`, ...section.rows.map((r) => `${indent}${refText(r)}`)];+}++export interface AroundTextOptions {+ /** What the first line says before the symbols: "Ix: you changed". */+ lead?: string;+ /** One short closing line, printed only when there is something above it. */+ footer?: string;+ /** Print the file-level importer rows, not just their count. */+ importerRows?: boolean;+}++/** The symbols as the first line names them: `` `name` (path:lines) ``. */+function symbolList(result: AroundResult): string {+ return result.symbols.map((s) => `\`${s.name}\` (${s.path}:${span(s)})`).join(", ");+}++export function renderAroundText(result: AroundResult, opts: AroundTextOptions = {}): string {+ const lines: string[] = [];+ const lead = opts.lead ?? "Around";+ if (result.symbols.length > 0) {+ lines.push(`${lead} ${symbolList(result)}.`);+ } else {+ lines.push(`${lead} ${result.path}: no definition in the graph covers ${result.lines ? `lines ${span({ lineStart: result.lines.start, lineEnd: result.lines.end })}` : "it"}.`);+ }+ if (result.graph) {+ lines.push(`Graph is ${result.graph.status}: dependents below may be incomplete, not absent.`);+ }+ const many = result.symbols.length > 1;+ for (const s of result.symbols) {+ const p = many ? `\`${s.name}\` ` : "";+ lines.push(...sectionLines(`${p}callers`, s.callers, " "));+ lines.push(...sectionLines(`${p}used by importers`, s.users, " "));+ lines.push(...sectionLines(`${p}tests`, s.tests, " "));+ if (s.sameName.length > 0) {+ lines.push(`${p}same name in file: ${s.sameName.map((o) => `${span(o)} (${o.kind})`).join(", ")}`);+ }+ }+ const imp = result.importers;+ if (imp.total > 0) {+ const tests = imp.tests > 0 ? ` (${imp.tests} test${imp.tests === 1 ? "" : "s"})` : "";+ lines.push(`${path.posix.basename(result.path)} is imported by ${imp.total} file${imp.total === 1 ? "" : "s"}${tests}${opts.importerRows && imp.rows.length > 0 ? ":" : "."}`);+ if (opts.importerRows) {+ for (const r of imp.rows) lines.push(` ${refText(r)}`);+ const rest = imp.total - imp.tests - imp.rows.length;+ if (rest > 0 && imp.rows.length > 0) lines.push(` +${rest} more`);+ }+ }+ if (opts.footer && lines.length > 1) lines.push(opts.footer);+ return lines.join("\n");+}++function refFields(r: AroundRef): Array<[string, string | number | undefined]> {+ return [+ ["site", r.line !== undefined ? `${r.path}:${r.line}` : r.path],+ ["name", r.name],+ ["via", r.via],+ ["snippet", r.snippet],+ ];+}++function symbolLlm(s: AroundSymbol, many: boolean): string[] {+ const of: Array<[string, string | undefined]> = [["of", many ? s.name : undefined]];+ return [+ llmLine("symbol", [+ ["name", s.name], ["kind", s.kind], ["path", s.path], ["lines", span(s)],+ ["moved_from", s.movedFrom],+ ["callers", s.callers.total], ["users", s.users.total], ["tests", s.tests.total],+ ]),+ ...s.callers.rows.map((r) => llmLine("caller", [...of, ...refFields(r)])),+ ...s.users.rows.map((r) => llmLine("user", [...of, ...refFields(r)])),+ ...s.tests.rows.map((r) => llmLine("test", [...of, ...refFields(r)])),+ ...s.sameName.map((o) => llmLine("same_name", [...of, ["kind", o.kind], ["lines", span(o)]])),+ ];+}++/**+ * `around path=... symbols=<n>`, then per symbol a `symbol` record carrying+ * the totals and the `caller` / `user` / `test` rows shown, then the file's+ * `importers` header and rows. Fewer rows than a total means the list was cut.+ */+export function renderAroundLlm(result: AroundResult): string[] {+ const many = result.symbols.length > 1;+ const out = [+ llmLine("around", [+ ["path", result.path],+ ["lines", result.lines ? span({ lineStart: result.lines.start, lineEnd: result.lines.end }) : undefined],+ ["symbols", result.symbols.length],+ ]),+ ];+ if (result.graph) out.push(llmLine("graph", graphHealthLlmFields(result.graph)));+ for (const s of result.symbols) out.push(...symbolLlm(s, many));+ if (result.importers.total > 0) {+ out.push(llmLine("importers", [+ ["shown", result.importers.rows.length], ["total", result.importers.total], ["tests", result.importers.tests],+ ]));+ for (const r of result.importers.rows) out.push(llmLine("importer", refFields(r)));+ }+ return out;+}++export function aroundJson(result: AroundResult): Record<string, unknown> {+ const { graph, ...rest } = result;+ return graph ? { ...rest, graph: graphHealthJson(graph) } : rest;+}diff --git a/ix-cli/src/cli/around.ts b/ix-cli/src/cli/around.tsnew file mode 100644index 00000000..762e79dc--- /dev/null+++ b/ix-cli/src/cli/around.ts@@ -0,0 +1,630 @@+// Copyright 2026 Ix Infrastructure Inc.++import * as path from "node:path";+import type { IxClient } from "../client/api.js";+import { activeReadScope, ensureReadScope } from "./resolve.js";+import {+ SourceFiles, anchorSpan, bareName, findEdgeSite, findImports, findUses, importKeys, type EdgeSite,+} from "./edge-sites.js";+import { rowLocation } from "./format.js";+import { checkGraphHealth, isUnhealthy, type GraphHealth } from "./graph-health.js";+import { isTestPath } from "./explain/related-files.js";++/**+ * `ix around`: who depends on the code at a place in a file.+ *+ * Built for the moment right after an agent edits code. The edit is local; the+ * places a multi-file fix also has to touch are not, and they are exactly what+ * grep cannot list cheaply: the callers of the function just changed, the+ * files that import it, and the tests that reach it. The graph has those, so+ * this answers with them, located (`path:line` and the line itself), and small+ * enough to land in an agent's context after every edit.+ *+ * The file may be newer than the graph -- it was just edited -- so the graph's+ * spans are re-anchored to the declarations in the text the edit's lines index+ * into (see {@link placeDefs}) before any span is compared with a line.+ */++/** 1-based inclusive line range. */+export interface LineRange {+ start: number;+ end: number;+ /**+ * A pure insertion between `start` and `end` (two adjacent lines). Only a+ * definition that holds both neighbours was edited; one that merely ends on+ * `start` had a new sibling added after it.+ */+ insertion?: boolean;+}++/** A definition the graph has in the file, with its span as recorded. */+export interface FileDef {+ id: string;+ name: string;+ kind: string;+ lineStart: number;+ lineEnd: number;+ /** Contained by the file itself rather than by a class in it. */+ topLevel: boolean;+ /** The class (or other container) holding it, when it is not top-level. */+ container?: string;+}++/** A definition placed on a text: where it is in those lines now. */+export interface PlacedDef extends FileDef {+ start: number;+ end: number;+}++export interface AroundRef {+ /** Workspace-relative path of the file the dependent site is in. */+ path: string;+ line?: number;+ snippet?: string;+ /** The entity at that site (the caller), when there is one. */+ name?: string;+ /** For a test reached in two hops: the caller it calls. */+ via?: string;+}++export interface AroundSection {+ /** How many there are. `rows` is the shown prefix of them. */+ total: number;+ rows: AroundRef[];+}++export interface AroundSymbol {+ id: string;+ name: string;+ kind: string;+ path: string;+ lineStart: number;+ lineEnd: number;+ /** Where the graph last recorded it, when the file has moved under it. */+ movedFrom?: number;+ /** Non-test callers, cross-file first, each at its call site. */+ callers: AroundSection;+ /** Files that import this file, name the symbol, and use it -- at the use. */+ users: AroundSection;+ /** Test files that call it, call a caller of it, or import and use it. */+ tests: AroundSection;+ /** Other definitions in the same file with the same name. */+ sameName: Array<{ kind: string; lineStart: number; lineEnd: number }>;+}++export interface AroundResult {+ path: string;+ /** The lines asked about, in the file's current coordinates; absent for the whole file. */+ lines?: { start: number; end: number };+ graph?: GraphHealth;+ symbols: AroundSymbol[];+ /** Every importer of the file, at its import line. */+ importers: AroundSection & { tests: number };+}++export interface AroundCaps {+ symbols: number;+ callers: number;+ users: number;+ tests: number;+ importers: number;+}++export const DEFAULT_CAPS: AroundCaps = { symbols: 3, callers: 8, users: 5, tests: 5, importers: 5 };++/** The default token budget for rendered output: it lands in an agent's context after every edit. */+export const DEFAULT_TOKEN_BUDGET = 300;++/** Whole-file questions rank at most this many top-level definitions by caller count. */+const WHOLE_FILE_CANDIDATES = 12;+/** How far up and down an import statement is followed across lines. */+const IMPORT_STATEMENT_LINES = 40;++export class AroundError extends Error {+ constructor(readonly code: "file_not_in_graph" | "file_not_found" | "no_definitions", message: string) {+ super(message);+ this.name = "AroundError";+ }+}++// ── Targets ─────────────────────────────────────────────────────────────────++/**+ * `path`, `path:12` or `path:12-20`. A Windows drive letter is part of the+ * path, not a line.+ */+export function parseAroundTarget(target: string): { file: string; range?: LineRange } | undefined {+ const m = /^(.*?):(\d+)(?:-(\d+))?$/.exec(target);+ if (!m || /^[A-Za-z]$/.test(m[1])) return target ? { file: target } : undefined;+ const start = Number(m[2]);+ const end = m[3] !== undefined ? Number(m[3]) : start;+ if (!m[1] || start < 1 || end < start) return undefined;+ return { file: m[1], range: { start, end } };+}++/**+ * A test file, across the languages the benchmark repositories use.+ *+ * `isTestPath` knows `__tests__/` and `*.test.*`; a Python suite lives in+ * `tests/test_*.py`, a Java one in `src/test/` as `FooTest.java`. Fixtures are+ * test *data*, not tests that exercise the code, so they are left out here.+ */+export function isTestFile(file: string): boolean {+ const p = file.replace(/\\/g, "/");+ if (/(^|\/)(__fixtures__|(test-)?fixtures)\//.test(p)) return false;+ return isTestPath(p)+ || /(^|\/)(tests?|__tests__|spec|specs|src\/test)\//.test(p)+ || /(^|\/)test_[^/]+\.py$/.test(p)+ || /_test\.(py|go|rb)$/.test(p)+ || /(Test|Tests|IT|Spec)\.(java|kt|kts|scala|cs|groovy)$/.test(p);+}++// ── Placing definitions on the text ──────────────────────────────────────────++/**+ * Where each definition is in `lines` now.+ *+ * The start is re-anchored to the nearest declaration of the name+ * ({@link anchorSpan}, the step `ix read` and the edge sites use). The end+ * cannot be found that way, and shifting it by the start's delta is wrong for+ * the one definition that matters most -- the one just edited, which grew or+ * shrank. So the end keeps its distance to the next definition that started+ * after it in the graph: if `parseFoo` ended two lines before `parseBar`+ * began, it still does. The last definition in the file, with nothing after+ * it, is shifted.+ */+export function placeDefs(defs: FileDef[], lines: string[]): PlacedDef[] {+ const anchored = new Map<string, { start: number; end: number; anchored: boolean }>();+ for (const d of defs) anchored.set(d.id, anchorSpan(lines, bareName(d.name), d.lineStart, d.lineEnd));+ const byStart = [...defs].sort((a, b) => a.lineStart - b.lineStart);+ return defs.map((d) => {+ const a = anchored.get(d.id)!;+ let end = a.end;+ const next = byStart.find((o) => o.lineStart > d.lineEnd);+ const nextAnchor = next ? anchored.get(next.id) : undefined;+ if (next && nextAnchor?.anchored && a.anchored) {+ const gap = next.lineStart - d.lineEnd;+ const estimated = nextAnchor.start - gap;+ if (estimated >= a.start) end = estimated;+ }+ return { ...d, start: a.start, end: Math.max(a.start, Math.min(end, lines.length || end)) };+ });+}++function spanOverlaps(d: PlacedDef, r: LineRange): boolean {+ if (r.insertion) return d.start <= r.start && d.end >= r.end;+ return d.start <= r.end && d.end >= r.start;+}++/**+ * The definitions an edit touched, innermost first: a method before its+ * class, a nested helper before the function around it. Ties go to the one+ * that starts first.+ *+ * A definition around one already chosen is left out unless the edit also+ * touched it outside that one: changing a method's body is not a change to+ * every user of its class, and `IxClient` has 65 of them.+ */+export function selectEdited(placed: PlacedDef[], ranges: LineRange[], cap: number): PlacedDef[] {+ const candidates = placed+ .filter((d) => ranges.some((r) => spanOverlaps(d, r)))+ .sort((a, b) => (a.end - a.start) - (b.end - b.start) || a.start - b.start);+ const chosen: PlacedDef[] = [];+ for (const d of candidates) {+ if (chosen.length >= cap) break;+ const inner = chosen.filter((c) => c.start >= d.start && c.end <= d.end);+ if (inner.length > 0 && !touchedOutside(d, ranges, inner)) continue;+ chosen.push(d);+ }+ return chosen;+}++/** Whether an edited line inside `d` falls outside every one of `inner`. */+function touchedOutside(d: PlacedDef, ranges: LineRange[], inner: PlacedDef[]): boolean {+ for (const r of ranges) {+ if (r.insertion) {+ if (spanOverlaps(d, r) && !inner.some((c) => c.start <= r.start && c.end >= r.end)) return true;+ continue;+ }+ for (let l = Math.max(r.start, d.start); l <= Math.min(r.end, d.end); l++) {+ if (!inner.some((c) => l >= c.start && l <= c.end)) return true;+ }+ }+ return false;+}++/** Top-level definitions not nested inside another one, in file order. */+export function outermostDefs(placed: PlacedDef[]): PlacedDef[] {+ return placed+ .filter((d) => d.topLevel)+ .filter((d) => !placed.some((o) => o.id !== d.id && o.start <= d.start && o.end >= d.end+ && (o.end - o.start) > (d.end - d.start)))+ .sort((a, b) => a.start - b.start);+}++// ── Import statements ───────────────────────────────────────────────────────++const STATEMENT_START = /^\s*(?:import\b|from\s|export\b|use\s|using\s|#\s*include|require\b|package\b)/;++/**+ * The whole import statement around one of its lines: `import {\n a,\n b\n}+ * from "./x.js"` matches its key on the last line and names what it imports+ * on the lines above it; Python's `from x import (\n a,\n)` the other way.+ */+export function importStatementText(lines: string[], line: number): { text: string; start: number; end: number } {+ let start = line;+ while (start > 1 && line - start < IMPORT_STATEMENT_LINES && !STATEMENT_START.test(lines[start - 1] ?? "")) start--;+ if (!STATEMENT_START.test(lines[start - 1] ?? "")) start = line;+ let end = line;+ let depth = 0;+ for (let l = start; l <= end; l++) depth += delimiterDepth(lines[l - 1] ?? "");+ while (depth > 0 && end < lines.length && end - line < IMPORT_STATEMENT_LINES) {+ end++;+ depth += delimiterDepth(lines[end - 1] ?? "");+ }+ return { text: lines.slice(start - 1, end).join(" "), start, end };+}++function delimiterDepth(text: string): number {+ let depth = 0;+ for (const ch of text) {+ if (ch === "(" || ch === "{") depth++;+ else if (ch === ")" || ch === "}") depth--;+ }+ return depth;+}++function wordIn(text: string, name: string): boolean {+ const n = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ return new RegExp(`(?<![\\w$])${n}(?![\\w$])`).test(text);+}++/**+ * Where an importing file uses the symbol, or undefined when it does not.+ *+ * An importer of the file is a user of the symbol only when its import names+ * the symbol (or, for a member, the class holding it) *and* the rest of the+ * file uses the name. Both, because each alone is noise: `options.ts` is+ * imported by seventeen files, of which one uses `parseBudgetOption`, and a+ * common method name appears in files that never import its class. This is+ * also how a use the graph has no edge for is found -- a function handed to+ * a framework by name (`.option("--pick <n>", "...", parsePickOption)`).+ */+export function findUseInImporter(+ lines: string[], importLines: number[], symbol: { name: string; container?: string },+): number | undefined {+ const bare = bareName(symbol.name);+ const statements = importLines.map((l) => importStatementText(lines, l));+ const namesSymbol = statements.some((s) => wordIn(s.text, bare));+ const namesContainer = !!symbol.container && statements.some((s) => wordIn(s.text, bareName(symbol.container!)));+ if (!namesSymbol && !namesContainer) return undefined;+ const inImport = (l: number) => statements.some((s) => l >= s.start && l <= s.end);+ // Through its class only a call counts: `expand: true` in an object, or the+ // word in a help string, is not a use of `IxClient.expand`.+ const call = callPattern(bare);+ return findUses(lines, bare, 1, lines.length)+ .find((l) => !inImport(l) && (namesSymbol || call.test(lines[l - 1])));+}++function callPattern(name: string): RegExp {+ const n = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ return new RegExp(`(?<![\\w$])${n}\\s*(?:<[^()]*>)?\\s*\\(`);+}++// ── Gathering ───────────────────────────────────────────────────────────────++export interface AroundRequest {+ /** Workspace-relative path of the file, as the graph spells its source_uri. */+ relPath: string;+ /** The lines asked about, in the coordinates of `anchorLines`. None: the whole file. */+ ranges?: LineRange[];+ /**+ * The text `ranges` index into. For a pre-edit range (the old side of a+ * patch) this is the file before the edit; otherwise the file as it is now.+ */+ anchorLines: string[];+ /** The file as it is now, for the locations reported. Defaults to `anchorLines`. */+ currentLines?: string[];+ /** Reads the dependents' files for their sites. */+ files: SourceFiles;+ caps?: Partial<AroundCaps>;+}++type AroundClient = Pick<IxClient, "search" | "expand" | "workspaceSystem" | "currentRevision" | "stats"> & { endpoint?: string };++function nodeUri(n: any): string {+ return String(n?.provenance?.sourceUri ?? n?.provenance?.source_uri ?? "").replace(/\\/g, "/");+}++/** The graph's file node for a workspace-relative path: exact, else a unique suffix match. */+export async function findFileNode(client: Pick<IxClient, "search">, relPath: string): Promise<any | undefined> {+ const want = relPath.replace(/\\/g, "/").replace(/^\.\//, "");+ const { workspaceId, systemId } = activeReadScope();+ const nodes = await client.search(path.posix.basename(want), {+ kind: "file", nameOnly: true, limit: 50, workspaceId, systemId, scope: want,+ });+ const files = (nodes as any[]).filter((n) => String(n.kind).toLowerCase() === "file");+ const exact = files.find((n) => nodeUri(n) === want);+ if (exact) return exact;+ const suffix = files.filter((n) => {+ const uri = nodeUri(n);+ return uri.endsWith(`/${want}`) || want.endsWith(`/${uri}`);+ });+ return suffix.length === 1 ? suffix[0] : undefined;+}++function toDef(n: any, topLevel: boolean, container?: string): FileDef | undefined {+ const loc = rowLocation(n);+ if (loc.lineStart === undefined) return undefined;+ return {+ id: n.id, name: String(n.name ?? ""), kind: String(n.kind ?? ""),+ lineStart: loc.lineStart, lineEnd: loc.lineEnd ?? loc.lineStart, topLevel, container,+ };+}++/** The file's definitions, two levels deep (file -> class -> method). */+export function defsFromContains(fileId: string, expansion: { nodes: any[]; edges: any[] }): FileDef[] {+ const byId = new Map(expansion.nodes.map((n) => [n.id, n]));+ const parent = new Map<string, string>();+ for (const e of expansion.edges ?? []) {+ if (e?.predicate === "CONTAINS" && !parent.has(e.dst)) parent.set(e.dst, e.src);+ }+ const defs: FileDef[] = [];+ for (const n of expansion.nodes) {+ if (String(n.kind).toLowerCase() === "file" || n.id === fileId) continue;+ const p = parent.get(n.id);+ const topLevel = p === undefined || p === fileId;+ const def = toDef(n, topLevel, topLevel ? undefined : byId.get(p!)?.name);+ if (def && def.name) defs.push(def);+ }+ return defs;+}++interface CallerSets {+ hop1: any[];+ hop2: { nodes: any[]; edges: any[] };+}++/** Callers one hop back (unless already fetched), and two hops back for the tests. */+async function callerSets(client: AroundClient, id: string, hop1Known?: any[]): Promise<CallerSets> {+ const predicates = ["CALLS", "REFERENCES"];+ const [hop1, hop2] = await Promise.all([+ hop1Known ?? client.expand(id, { direction: "in", predicates }).then((r) => r.nodes),+ client.expand(id, { direction: "in", predicates, hops: 2 }),+ ]);+ return { hop1: hop1.filter((n: any) => n.id !== id), hop2 };+}++function siteRef(row: any, site: EdgeSite | undefined, extra: Partial<AroundRef> = {}): AroundRef {+ const loc = rowLocation(row);+ return {+ path: site?.path ?? loc.path ?? "",+ line: site?.line ?? loc.lineStart,+ snippet: site?.snippet,+ name: String(row?.kind ?? "").toLowerCase() === "file" ? undefined : row?.name,+ ...extra,+ };+}++/**+ * Everything `ix around` reports. Throws `WorkspaceNotMappedError` outside a+ * mapped workspace and {@link AroundError} for a file the graph does not hold.+ */+export async function gatherAround(client: AroundClient, req: AroundRequest): Promise<AroundResult> {+ const caps: AroundCaps = { ...DEFAULT_CAPS, ...req.caps };+ await ensureReadScope(client);+ const healthP = checkGraphHealth(client, activeReadScope());+ // Never let the health probe reject past a caller that stopped waiting.+ healthP.catch(() => undefined);++ const file = await findFileNode(client, req.relPath);+ if (!file) throw new AroundError("file_not_in_graph", `${req.relPath} is not in the graph.`);+ const relPath = nodeUri(file) || req.relPath;++ const [contains, imported] = await Promise.all([+ client.expand(file.id, { direction: "out", predicates: ["CONTAINS"], hops: 2 }),+ client.expand(file.id, { direction: "in", predicates: ["IMPORTS"] }),+ ]);+ const defs = defsFromContains(file.id, contains);+ const anchorPlaced = placeDefs(defs, req.anchorLines);+ const current = req.currentLines && req.currentLines !== req.anchorLines+ ? new Map(placeDefs(defs, req.currentLines).map((d) => [d.id, d]))+ : new Map(anchorPlaced.map((d) => [d.id, d]));++ // Which definitions to report on.+ let chosen: PlacedDef[];+ const preloaded = new Map<string, any[]>();+ if (req.ranges && req.ranges.length > 0) {+ chosen = selectEdited(anchorPlaced, req.ranges, caps.symbols);+ } else {+ // The whole file: its outermost definitions, the most-called first, so a+ // capped answer keeps the ones with dependents.+ const candidates = outermostDefs(anchorPlaced).slice(0, WHOLE_FILE_CANDIDATES);+ const counts = await Promise.all(candidates.map(async (d) => {+ const r = await client.expand(d.id, { direction: "in", predicates: ["CALLS", "REFERENCES"] });+ preloaded.set(d.id, r.nodes.filter((n: any) => n.id !== d.id));+ return r.nodes.length;+ }));+ chosen = candidates+ .map((d, i) => ({ d, i, c: counts[i] }))+ .sort((a, b) => b.c - a.c || a.i - b.i)+ .slice(0, caps.symbols)+ .map(({ d }) => d);+ }++ // Importers of the file, each at its import line(s).+ const fileKeys = importKeys(path.posix.basename(relPath), "file", relPath);+ const importerRows = imported.nodes.filter((n: any) => n.id !== file.id);+ const importerLines = new Map<string, { row: any; path: string; lines: number[] }>();+ for (const row of importerRows) {+ const p = rowLocation(row).path;+ if (!p) continue;+ const lines = req.files.lines(p);+ importerLines.set(row.id, { row, path: p, lines: lines ? findImports(lines, fileKeys) : [] });+ }++ const symbols = await Promise.all(chosen.map(async (d): Promise<AroundSymbol> => {+ const sets = await callerSets(client, d.id, preloaded.get(d.id));+ const hop1 = sets.hop1;+ const target = { name: d.name, kind: d.kind, path: relPath };++ const nonTest = hop1.filter((r) => !isTestFile(rowLocation(r).path ?? ""));+ const crossFirst = [...nonTest].sort((a, b) =>+ Number(rowLocation(a).path === relPath) - Number(rowLocation(b).path === relPath));+ const callers = crossFirst.slice(0, caps.callers)+ .map((row) => siteRef(row, safeSite("callers", row, target, req.files)));+ const callerPaths = new Set(hop1.map((r) => rowLocation(r).path));++ // Tests: callers that are tests, then tests calling a caller, then test+ // files that import the file and use the symbol. One row per test file.+ const tests = new Map<string, AroundRef>();+ for (const row of hop1) {+ const p = rowLocation(row).path ?? "";+ if (isTestFile(p) && !tests.has(p)) tests.set(p, siteRef(row, safeSite("callers", row, target, req.files)));+ }+ const hop1Ids = new Map(hop1.map((r) => [r.id, r]));+ const hop2ById = new Map(sets.hop2.nodes.map((n: any) => [n.id, n]));+ for (const e of sets.hop2.edges ?? []) {+ const via = hop1Ids.get(e?.dst);+ const row = hop2ById.get(e?.src);+ if (!via || !row || row.id === d.id) continue;+ const p = rowLocation(row).path ?? "";+ if (!isTestFile(p) || tests.has(p)) continue;+ const viaTarget = { name: via.name, kind: via.kind, path: rowLocation(via).path };+ tests.set(p, siteRef(row, safeSite("callers", row, viaTarget, req.files), { via: via.name }));+ }++ const users: AroundRef[] = [];+ for (const { path: p, lines } of importerLines.values()) {+ if (callerPaths.has(p) && !isTestFile(p)) continue;+ const text = req.files.lines(p);+ if (!text || lines.length === 0) continue;+ const use = findUseInImporter(text, lines, d);+ if (use === undefined) continue;+ const ref: AroundRef = { path: p, line: use, snippet: text[use - 1].trim() };+ if (isTestFile(p)) { if (!tests.has(p)) tests.set(p, ref); } else users.push(ref);+ }++ const here = current.get(d.id) ?? d;+ const sameName = defs+ .filter((o) => o.id !== d.id && bareName(o.name) === bareName(d.name))+ .map((o) => {+ const c = current.get(o.id);+ return { kind: o.kind, lineStart: c?.start ?? o.lineStart, lineEnd: c?.end ?? o.lineEnd };+ });+ const testRows = [...tests.values()];+ return {+ id: d.id,+ name: d.name,+ kind: d.kind,+ path: relPath,+ lineStart: here.start,+ lineEnd: here.end,+ movedFrom: here.start !== d.lineStart ? d.lineStart : undefined,+ callers: { total: nonTest.length, rows: callers },+ users: { total: users.length, rows: users.slice(0, caps.users) },+ tests: { total: testRows.length, rows: testRows.slice(0, caps.tests) },+ sameName,+ };+ }));++ const importerList = [...importerLines.values()];+ const importers = {+ total: importerList.length,+ tests: importerList.filter((i) => isTestFile(i.path)).length,+ rows: importerList+ .filter((i) => !isTestFile(i.path))+ .slice(0, caps.importers)+ .map((i) => {+ const text = req.files.lines(i.path);+ const line = i.lines[0];+ return { path: i.path, line, snippet: line && text ? text[line - 1].trim() : undefined };+ }),+ };++ const health = await healthP.catch(() => undefined);+ return {+ path: relPath,+ graph: isUnhealthy(health) ? health : undefined,+ symbols,+ importers,+ };+}++function safeSite(relation: "callers", row: any, target: { name: string; kind?: string; path?: string }, files: SourceFiles): EdgeSite | undefined {+ try { return findEdgeSite(relation, row, target, files); } catch { return undefined; }+}++// ── Sizing ──────────────────────────────────────────────────────────────────++/** The estimate the budget is held to: four characters a token. */+export function estimateTokens(text: string): number {+ return Math.ceil(text.length / 4);+}++/** Any dependents at all: nothing to say otherwise. */+export function hasDependents(result: AroundResult): boolean {+ return result.symbols.some((s) => s.callers.total + s.users.total + s.tests.total > 0);+}++function withCaps(result: AroundResult, caps: AroundCaps, snippetChars: number): AroundResult {+ const trimRef = (r: AroundRef): AroundRef => ({+ ...r,+ snippet: r.snippet && r.snippet.length > snippetChars ? `${r.snippet.slice(0, snippetChars - 1)}…` : r.snippet,+ });+ return {+ ...result,+ symbols: result.symbols.slice(0, caps.symbols).map((s) => ({+ ...s,+ callers: { total: s.callers.total, rows: s.callers.rows.slice(0, caps.callers).map(trimRef) },+ users: { total: s.users.total, rows: s.users.rows.slice(0, caps.users).map(trimRef) },+ tests: { total: s.tests.total, rows: s.tests.rows.slice(0, caps.tests).map(trimRef) },+ })),+ importers: { ...result.importers, rows: result.importers.rows.slice(0, caps.importers).map(trimRef) },+ };+}++/**+ * Cut the answer until its rendering fits `budget` tokens, least useful first:+ * the file-level importer rows (the count stays), then long snippets, then+ * rows from each list down to a floor, then symbols, then everything down to+ * one row. Totals are kept, so what was cut reads as "N of M", never as+ * absence.+ */+export function fitToBudget(+ result: AroundResult,+ render: (r: AroundResult) => string,+ budget: number,+ start: Partial<AroundCaps> = {},+): AroundResult {+ const caps: AroundCaps = { ...DEFAULT_CAPS, ...start };+ let snippet = 100;+ const fits = () => {+ const fitted = withCaps(result, caps, snippet);+ return estimateTokens(render(fitted)) <= budget ? fitted : undefined;+ };+ const shrink = (keys: Array<keyof AroundCaps>, floor: number): AroundResult | undefined => {+ for (;;) {+ const key = keys.filter((k) => caps[k] > floor).sort((a, b) => caps[b] - caps[a])[0];+ if (!key) return undefined;+ caps[key]--;+ const fitted = fits();+ if (fitted) return fitted;+ }+ };+ const steps: Array<() => AroundResult | undefined> = [+ fits,+ () => shrink(["importers"], 0),+ () => { snippet = 70; return fits(); },+ () => shrink(["callers", "users", "tests"], 3),+ () => shrink(["callers", "users", "tests"], 2),+ () => { while (caps.symbols > 1) { caps.symbols--; const f = fits(); if (f) return f; } return undefined; },+ () => shrink(["callers", "users", "tests"], 1),+ () => { snippet = 40; return fits(); },+ ];+ for (const step of steps) {+ const fitted = step();+ if (fitted) return fitted;+ }+ return withCaps(result, caps, snippet);+}diff --git a/ix-cli/src/cli/commands/around.ts b/ix-cli/src/cli/commands/around.tsnew file mode 100644index 00000000..ff1b886d--- /dev/null+++ b/ix-cli/src/cli/commands/around.ts@@ -0,0 +1,128 @@+// Copyright 2026 Ix Infrastructure Inc.++import * as fs from "node:fs";+import * as path from "node:path";+import type { Command } from "commander";+import chalk from "chalk";+import { IxClient } from "../../client/api.js";+import { getEndpoint, resolveWorkspaceRoot } from "../config.js";+import { printJson } from "../format.js";+import { llmError, printLlmLines } from "../llm.js";+import { parseBudgetOption } from "../options.js";+import { isQuiet } from "../output-shape.js";+import { stderr } from "../stderr.js";+import { SourceFiles } from "../edge-sites.js";+import {+ AroundError, DEFAULT_CAPS, DEFAULT_TOKEN_BUDGET, fitToBudget, gatherAround, parseAroundTarget,+ type AroundCaps, type AroundResult,+} from "../around.js";+import { aroundJson, renderAroundLlm, renderAroundText } from "../around-render.js";++function reportError(code: string, message: string, format: string, extra: Array<[string, string]> = []): void {+ if (format === "json") printJson({ error: code, message, ...Object.fromEntries(extra) });+ else if (format === "llm") console.log(llmError(code, message, extra));+ else stderr(chalk.red(message));+ process.exitCode = 1;+}++/** The file's lines, or none when it is not on disk (the graph's spans then stand as recorded). */+export function readLines(abs: string): string[] {+ try {+ const stat = fs.statSync(abs);+ if (!stat.isFile() || stat.size > 2 * 1024 * 1024) return [];+ return fs.readFileSync(abs, "utf-8").split("\n");+ } catch {+ return [];+ }+}++/** A path relative to the workspace root first, then to the cwd; absolute as given. */+export function resolveAroundFile(file: string, root: string, cwd = process.cwd()): string {+ if (path.isAbsolute(file)) return path.resolve(file);+ const fromRoot = path.resolve(root, file);+ if (fs.existsSync(fromRoot)) return fromRoot;+ const fromCwd = path.resolve(cwd, file);+ return fs.existsSync(fromCwd) ? fromCwd : fromRoot;+}++export function capsFor(limit: number): AroundCaps {+ return {+ ...DEFAULT_CAPS,+ callers: limit,+ users: Math.min(limit, DEFAULT_CAPS.users),+ tests: Math.min(limit, DEFAULT_CAPS.tests),+ importers: Math.min(limit, DEFAULT_CAPS.importers),+ };+}++export function registerAroundCommand(program: Command): void {+ program+ .command("around <target>")+ .description("Show who depends on the code at a file location: callers, importers, tests")+ .option("--limit <n>", "Max rows per list (callers; users, tests and importers cap at 5)", String(DEFAULT_CAPS.callers))+ .option("--budget <tokens>", `Token budget for text/llm output (~4 chars a token)`, (v: string) => parseBudgetOption(v, String(DEFAULT_TOKEN_BUDGET)), DEFAULT_TOKEN_BUDGET)+ .option("--format <fmt>", "Output format (text|json|llm)", "text")+ .addHelpText("after", `+<target> is path[:line[-end]], relative to the workspace root or absolute.+With a line, reports the definitions whose span covers it (innermost first);+without one, the file's most-called top-level definitions. At most 3 symbols.++Examples:+ ix around src/cli/options.ts:109+ ix around src/cli/options.ts:100-140 --format llm+ ix around src/cli/config.ts --limit 3`)+ .action(async (target: string, opts: { limit: string; budget: number; format: string }) => {+ const parsed = parseAroundTarget(target);+ if (!parsed) {+ reportError("invalid_line_range", `Invalid target "${target}". Use path, path:line or path:start-end (1-based).`, opts.format);+ return;+ }+ const root = resolveWorkspaceRoot();+ const abs = resolveAroundFile(parsed.file, root);+ const relPath = path.relative(root, abs).split(path.sep).join("/");+ if (relPath.startsWith("..") || path.isAbsolute(relPath)) {+ reportError("path_outside_workspace", `${abs} is outside the workspace root ${root}.`, opts.format);+ return;+ }+ const lines = readLines(abs);+ const limit = Math.max(1, parseInt(opts.limit, 10) || DEFAULT_CAPS.callers);+ const caps = capsFor(limit);+ const client = new IxClient(getEndpoint());++ let result: AroundResult;+ try {+ result = await gatherAround(client, {+ relPath,+ ranges: parsed.range ? [parsed.range] : undefined,+ anchorLines: lines,+ files: new SourceFiles(root),+ caps,+ });+ } catch (err) {+ if (err instanceof AroundError) {+ const onDisk = lines.length > 0;+ const reason = onDisk ? "file_not_in_graph" : "file_not_found";+ const message = onDisk+ ? `"${relPath}" exists on disk but is not in the graph: it has not been mapped yet (run \`ix map\`), or Ix does not parse it.`+ : `No file "${relPath}" in the graph, and none at that path on disk.`;+ reportError("unresolved_target", message, opts.format, [["reason", reason]]);+ return;+ }+ throw err;+ }+ if (parsed.range) result.lines = { start: parsed.range.start, end: parsed.range.end };++ if (opts.format === "json") {+ printJson(aroundJson(result));+ return;+ }+ if (opts.format === "llm") {+ const fitted = fitToBudget(result, (r) => renderAroundLlm(r).join("\n"), opts.budget, caps);+ printLlmLines(renderAroundLlm(fitted));+ return;+ }+ const textOpts = { importerRows: !isQuiet() };+ const fitted = fitToBudget(result, (r) => renderAroundText(r, textOpts), opts.budget, caps);+ console.log(renderAroundText(fitted, textOpts));+ });+}diff --git a/ix-cli/src/cli/help-text.ts b/ix-cli/src/cli/help-text.tsindex f3ed0a48..5ee9a6e1 100644--- a/ix-cli/src/cli/help-text.ts+++ b/ix-cli/src/cli/help-text.ts@@ -17,6 +17,7 @@ const OSS_HELP = [` impact <target> Analyze impact`,` overview <target> Summarize structure`,` read <target> Read source`,+ ` around <path:line> Who depends on it`,` smells Detect issues`,``,chalk.bold(`Explore:`),diff --git a/ix-cli/src/cli/register/oss.ts b/ix-cli/src/cli/register/oss.tsindex 4eb27eee..2461ee88 100644--- a/ix-cli/src/cli/register/oss.ts+++ b/ix-cli/src/cli/register/oss.ts@@ -39,6 +39,7 @@ import { registerSavingsCommand } from "../commands/savings.js";import { registerPatchesCommand } from "../commands/patches.js";import { registerMcpCommand } from "../commands/mcp.js";import { registerContextCommand } from "../commands/context.js";+import { registerAroundCommand } from "../commands/around.js";import { validateCliOptions } from "../options.js";import { setPrettyJson } from "../format.js";import { setOutputShape } from "../output-shape.js";@@ -216,6 +217,7 @@ export function registerOssCommands(program: Command): void {registerPatchesCommand(program);registerMcpCommand(program);registerContextCommand(program);+ registerAroundCommand(program);configureOssOptions(program);diff --git a/skills/ix/references/commands.md b/skills/ix/references/commands.mdindex a4d29b24..fa35d8ca 100644--- a/skills/ix/references/commands.md+++ b/skills/ix/references/commands.md@@ -47,6 +47,16 @@ These aggregate multiple graph operations into single bounded responses.| What an entity imports | `ix imports` | `ix imports auth_provider.py` || What imports an entity | `ix imported-by` | `ix imported-by AuthProvider` || Dependency impact | `ix depends` | `ix depends verify_token --depth 2` |+| Who depends on the code at a line you are editing | `ix around` | `ix around src/auth.py:120` |++`ix around <path>[:<line>[-<end>]]` names the definitions whose span covers the+line (innermost first, at most 3; the file's most-called top-level definitions+when no line is given) and, for each, its callers at their call sites, the+importing files that use it (including uses the graph has no edge for, such as+a function passed by name), and the tests that reach it within two caller hops.+The graph's spans are re-anchored to the file on disk first, so a file edited+since the last map is still read correctly. Output is held to `--budget` tokens+(default 300); lists are cut, never their totals.## History, Diffs & Contradictionsdiff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.mdindex 33cae524..72a64604 100644--- a/skills/ix/references/flags.md+++ b/skills/ix/references/flags.md@@ -114,6 +114,19 @@ before a command name — `ix --version`, not `ix map --version`.| --- | --- | --- | --- || `--version` | — | off | Print the CLI version and exit (`-V`) |+### `ix around <target>`++Show who depends on the code at a file location: callers, importers, tests. `<target>` is `path[:line[-end]]`, relative to the workspace root or absolute.++| Flag | Value | Default | Effect |+|---|---|---|---|+| `--limit` | `<n>` | `8` | Max rows per list (callers; users, tests and importers cap at 5) |+| `--budget` | `<tokens>` | `300` | Token budget for text/llm output (~4 chars a token); rows are cut to fit, totals are kept. json is not cut |+| `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |+| `--quiet` | — | off | Drop headers, section titles and advisory hints (text: the importer rows) |+| `--fields` | `<list>` | — | Keep only these fields on each row, in this order (e.g. `name,path,lines`) |+### `ix callees <symbol>`Show methods/functions called by the given symbol (cross-file).