Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
feat(context): build a bundle from an issue with --from-issue
KageBinary4c41041c878d
diff --git a/ix-cli/src/cli/__tests__/context-from-issue-bundle.test.ts b/ix-cli/src/cli/__tests__/context-from-issue-bundle.test.tsnew file mode 100644index 00000000..735c6da3--- /dev/null+++ b/ix-cli/src/cli/__tests__/context-from-issue-bundle.test.ts@@ -0,0 +1,158 @@+// Copyright 2026 Ix Infrastructure Inc.++import { describe, expect, it } from "vitest";++import { buildBundle, clampBudgets, renderBundle } from "../commands/context.js";+import { contextBundleSchema } from "../context-bundle-schema.js";+import type { ContextFacts, EntityLocation } from "../explain/facts.js";+import type { RankedFile, StartingPoint } from "../explain/issue.js";++/**+ * The bundle `ix context --from-issue` builds: the usual bundle around the+ * first starting point, plus two rows that lead the evidence -- where the+ * issue starts, and the files ranked against its text. They have to lead:+ * the default budget is a few thousand characters, and a file target with+ * many members fills it before anything ranked at 10 or later is reached.+ */++function member(i: number): EntityLocation {+ return { id: `m-${i}`, name: `helper${i}`, kind: "function", path: "src/client/api.ts", lineStart: i * 10 + 1, lineEnd: i * 10 + 9 };+}++function facts(): ContextFacts {+ const memberRefs = Array.from({ length: 60 }, (_, i) => member(i));+ return {+ id: "s-list", name: "listByKind", kind: "method", path: "src/client/api.ts", lineStart: 141, lineEnd: 152,+ members: memberRefs.map((m) => m.name), memberRefs, memberCount: memberRefs.length,+ callerCount: 0, calleeCount: 0, dependentCount: 0, importerCount: 0,+ topCallers: [], topDependents: [],+ historyLength: 1, introducedRev: 7, stale: false, diagnostics: [],+ } as ContextFacts;+}++const STARTS: StartingPoint[] = [+ { token: "listByKind", id: "s-list", name: "listByKind", kind: "method", path: "src/client/api.ts", lineStart: 141, lineEnd: 152, via: "identifier in issue" },+ { token: "rank.ts", id: "f-rank", name: "rank.ts", kind: "file", path: "src/cli/commands/rank.ts", via: "path in issue" },+];++function ranked(n: number): RankedFile[] {+ return [+ { path: "src/client/api.ts", score: 7.5, reason: "starting point (identifier in issue)" },+ { path: "src/cli/commands/rank.ts", score: 6.1, reason: "starting point (path in issue)" },+ ...Array.from({ length: n - 2 }, (_, i) => ({+ path: `src/cli/commands/c${i}.ts`, score: 5 - i * 0.1, reason: `bm25 ${(5 - i * 0.1).toFixed(2)}`,+ })),+ ];+}++function build(issue: Parameters<typeof buildBundle>[0]["issue"]) {+ return buildBundle({+ resolved: { id: "s-list", name: "listByKind", kind: "method", resolutionMode: "issue" },+ facts: facts(),+ context: {+ // Enough claims that the default budget has to cut something.+ claims: Array.from({ length: 30 }, (_, i) => ({+ claim: { id: `c-${i}`, entityId: "s-list", statement: `listByKind returns nodes of kind ${i} in revision order`, status: "active" },+ relevance: 1, confidence: { score: 0.9 },+ })),+ conflicts: [], decisions: [], intents: [], nodes: [], edges: [],+ metadata: { query: "", seedEntities: [], hopsExpanded: 1, asOfRev: 1 },+ } as never,+ provenance: {},+ budgets: clampBudgets({}),+ isStale: () => false,+ graphCompleted: true,+ issue,+ });+}++function captureLog(fn: () => void): string[] {+ const lines: string[] = [];+ const orig = console.log;+ console.log = (...a: unknown[]) => void lines.push(a.map(String).join(" "));+ try {+ fn();+ } finally {+ console.log = orig;+ }+ return lines;+}++const issue = (over: Partial<NonNullable<Parameters<typeof buildBundle>[0]["issue"]>> = {}) => ({+ startingPoints: STARTS,+ unresolved: ["flexLayout"],+ fallback: false,+ rankedFiles: ranked(12),+ extraEntities: [{ id: "r-smells", name: "smells.ts", kind: "file", path: "src/cli/commands/smells.ts" }],+ ...over,+});++describe("ix context --from-issue bundle", () => {+ it("leads the evidence with the starting points and the ranked files, inside the default budget", () => {+ const b = build(issue());+ expect(b.evidence.map((e) => e.id).slice(0, 3)).toEqual(["target:s-list", "issue-starts", "issue-ranked-files"]);+ expect(b.truncation.evidenceTruncated).toBeGreaterThan(0); // the budget did cut, just not these++ const starts = b.evidence[1];+ expect(starts.title).toBe("starting points: listByKind (src/client/api.ts:141-152), rank.ts (src/cli/commands/rank.ts)");+ expect(starts.reason).toContain("listByKind: identifier in issue");+ expect(starts.reason).toContain("rank.ts: path in issue");+ expect(starts.reason).toContain("unresolved: flexLayout");+ expect(starts.location).toEqual({ path: "src/client/api.ts", lineStart: 141, lineEnd: 152 });++ const files = b.evidence[2];+ const shown = files.title.replace(/^ranked files: /, "").split(", ");+ expect(shown).toHaveLength(10);+ expect(shown[0]).toBe("src/client/api.ts");+ expect(files.reason).toContain("bm25");+ });++ it("carries the full ranked list and the starting points in JSON, and the schema keeps them", () => {+ const b = build(issue());+ expect(b.rankedFiles).toHaveLength(12);+ expect(b.issue?.startingPoints.map((s) => s.path)).toEqual(["src/client/api.ts", "src/cli/commands/rank.ts"]);+ expect(b.issue?.unresolved).toEqual(["flexLayout"]);++ const parsed = contextBundleSchema.safeParse(JSON.parse(JSON.stringify(b)));+ expect(parsed.success).toBe(true);+ expect(parsed.data?.rankedFiles).toEqual(b.rankedFiles);+ expect(parsed.data?.issue).toEqual(b.issue);+ });++ it("puts the other starting points right after the target, and their neighbours in the bundle", () => {+ const b = build(issue());+ expect(b.entities[1]).toMatchObject({ id: "f-rank", path: "src/cli/commands/rank.ts" });+ expect(b.entities.map((e) => e.id)).toContain("r-smells");+ });++ it("renders both rows in llm and text output", () => {+ const b = build(issue());+ const llm = captureLog(() => renderBundle(b, "llm")).join("\n");+ expect(llm).toMatch(/^evidence score=1 kind=target title="starting points: listByKind/m);+ expect(llm).toMatch(/^evidence score=2 kind=structural title="ranked files: src\/client\/api.ts, /m);+ expect(llm).not.toContain("issue_fallback");++ const text = captureLog(() => renderBundle(b, "text")).join("\n");+ expect(text).toContain("starting points: listByKind (src/client/api.ts:141-152)");+ expect(text).toContain("ranked files: src/client/api.ts");+ });++ it("says so when the start came from BM25 because nothing in the issue resolved", () => {+ const b = build(issue({+ startingPoints: [{ token: "src/client/api.ts", id: "f-api", name: "api.ts", kind: "file", path: "src/client/api.ts", via: "bm25 fallback" }],+ unresolved: ["flexLayout", "gridArea"],+ fallback: true,+ }));+ expect(b.issue?.fallback).toBe(true);+ expect(b.evidence[1].reason).toContain("no code name in the issue resolved to a definition");+ const llm = captureLog(() => renderBundle(b, "llm")).join("\n");+ expect(llm).toMatch(/^diagnostic code=issue_fallback /m);+ });++ it("still validates a saved bundle that has neither field", () => {+ const b = build(undefined);+ expect(b.rankedFiles).toBeUndefined();+ expect(b.issue).toBeUndefined();+ expect(contextBundleSchema.safeParse(JSON.parse(JSON.stringify(b))).success).toBe(true);+ });+});diff --git a/ix-cli/src/cli/__tests__/context-from-issue.test.ts b/ix-cli/src/cli/__tests__/context-from-issue.test.tsnew file mode 100644index 00000000..a61672af--- /dev/null+++ b/ix-cli/src/cli/__tests__/context-from-issue.test.ts@@ -0,0 +1,316 @@+// Copyright 2026 Ix Infrastructure Inc.++import { execFileSync } from "node:child_process";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { Readable } from "node:stream";++import { afterEach, describe, expect, it } from "vitest";++import {+ bm25Rank,+ bm25Tokens,+ extractCandidates,+ isSourcePath,+ pickStartingPoints,+ planIssue,+ rankIssueFiles,+ readIssueText,+ type SymbolHit,+} from "../explain/issue.js";+import { gitRepoAccess, type RepoAccess } from "../explain/text-references.js";++/**+ * `ix context --from-issue`: from an issue's text to where the fix starts.+ *+ * The cases are the ones the SWE-PolyBench pilot got wrong before its picker+ * was fixed: a CSS output file, a changelog and test fixtures chosen as+ * starting points, an import chosen over the definition it imports, and a+ * prose word resolved as if it were a code name.+ */++function memoryRepo(files: Record<string, string>): RepoAccess {+ return {+ files: () => Object.keys(files),+ read: (path) => files[path],+ grep: () => [],+ };+}++/** A search that answers from a fixed table, and records what it was asked. */+function fakeSearch(table: Record<string, SymbolHit[]>) {+ const asked: string[] = [];+ const search = async (name: string) => {+ asked.push(name);+ return table[name] ?? [];+ };+ return { search, asked };+}++const hit = (name: string, kind: string, path: string, lines?: [number, number]): SymbolHit => ({+ id: `${kind}:${path}:${name}`, name, kind, path,+ ...(lines ? { lineStart: lines[0], lineEnd: lines[1] } : {}),+});++describe("extractCandidates", () => {+ it("takes paths first, then multi-part names, then backticked words, and never prose", () => {+ const text = [+ "Calling `save` on a model fails in keras/src/saving/saving_api.py.",+ "The `saveModel` helper and GsonBuilder both call new_json_writer,",+ "but `flex` and `code` are fine. The Widget renders the page.",+ ].join("\n");+ const { paths, identifiers } = extractCandidates(text);+ expect(paths).toEqual(["keras/src/saving/saving_api.py"]);+ expect(identifiers.slice(0, 3)).toEqual(["saveModel", "GsonBuilder", "new_json_writer"]);+ // Single words only from backticks, four letters or more, after every+ // multi-part name.+ expect(identifiers.slice(-3)).toEqual(["save", "flex", "code"]);+ for (const prose of ["Calling", "model", "fails", "Widget", "renders", "page", "The"]) {+ expect(identifiers).not.toContain(prose);+ }+ });++ it("drops short backticked words and keeps a name once", () => {+ const { identifiers } = extractCandidates("`id` and `run` then `listByKind` and listByKind again");+ expect(identifiers).toEqual(["listByKind"]);+ });+});++describe("isSourcePath", () => {+ it("accepts code and refuses tests, fixtures, docs, build output, vendored and non-code files", () => {+ expect(isSourcePath("src/cli/commands/rank.ts")).toBe(true);+ expect(isSourcePath("keras/src/saving/saving_api.py")).toBe(true);+ for (const noise of [+ "src/css/preflight.css", "CHANGELOG.md", "docs/api.ts", "package.json",+ "src/__tests__/rank.test.ts", "tests/test_saving.py", "src/saving_test.py",+ "test-fixtures/typescript/sample.ts", "__fixtures__/a.js", "examples/demo.js",+ "vendor/lib.js", "dist/index.js", "build/out.js", "lib/jquery.min.js",+ ]) {+ expect(isSourcePath(noise), noise).toBe(false);+ }+ });+});++describe("pickStartingPoints", () => {+ it("does not start from a CSS output file for `flex`", async () => {+ const { search } = fakeSearch({ flex: [hit("flex", "rule", "src/css/output.css")] });+ const out = await pickStartingPoints("Setting `flex` breaks the layout", { files: [], search });+ expect(out.starts).toEqual([]);+ expect(out.unresolved).toEqual(["flex"]);+ });++ it("chooses the definition, not the module entity of the file that imports it", async () => {+ const { search } = fakeSearch({+ borderStylesReset: [+ hit("borderStylesReset", "module", "src/util/generateUtilities.js"),+ hit("borderStylesReset", "function", "src/util/borderStylesReset.js", [3, 20]),+ ],+ });+ const out = await pickStartingPoints("borderStylesReset is applied twice", { files: [], search });+ expect(out.starts).toHaveLength(1);+ expect(out.starts[0]).toMatchObject({+ token: "borderStylesReset", path: "src/util/borderStylesReset.js", kind: "function",+ lineStart: 3, lineEnd: 20, via: "identifier in issue",+ });+ });++ it("leaves a name unresolved when its only hit is an import", async () => {+ const { search } = fakeSearch({ borderStylesReset: [hit("borderStylesReset", "module", "src/a.js")] });+ const out = await pickStartingPoints("`borderStylesReset`", { files: [], search });+ expect(out.starts).toEqual([]);+ expect(out.unresolved).toEqual(["borderStylesReset"]);+ });++ it("ignores changelog, markdown and test hits, and inexact names", async () => {+ const { search } = fakeSearch({+ newJsonWriter: [+ hit("newJsonWriter", "section", "CHANGELOG.md"),+ hit("newJsonWriter", "heading", "docs/guide.md"),+ hit("newJsonWriter", "method", "gson/src/test/java/com/google/gson/GsonTest.java"),+ hit("newJsonWriterAsync", "method", "gson/src/main/java/com/google/gson/Other.java"),+ ],+ });+ const out = await pickStartingPoints("newJsonWriter drops the lenient flag", { files: [], search });+ expect(out.starts).toEqual([]);+ expect(out.unresolved).toEqual(["newJsonWriter"]);+ });++ it("puts a multi-part name ahead of a single backticked word", async () => {+ const { search } = fakeSearch({+ save: [hit("save", "function", "keras/src/models/model.py", [10, 40])],+ saveModel: [hit("saveModel", "function", "keras/src/saving/saving_api.py", [5, 60])],+ });+ const out = await pickStartingPoints("`save` fails, and so does `saveModel`", { files: [], search });+ expect(out.starts.map((s) => s.token)).toEqual(["saveModel", "save"]);+ expect(out.starts[0].path).toBe("keras/src/saving/saving_api.py");+ });++ it("keeps at most three starting points, one per file", async () => {+ const { search } = fakeSearch({+ alphaOne: [hit("alphaOne", "function", "src/a.ts")],+ alphaTwo: [hit("alphaTwo", "function", "src/a.ts")],+ betaOne: [hit("betaOne", "function", "src/b.ts")],+ gammaOne: [hit("gammaOne", "function", "src/c.ts")],+ deltaOne: [hit("deltaOne", "function", "src/d.ts")],+ });+ const out = await pickStartingPoints("alphaOne alphaTwo betaOne gammaOne deltaOne", { files: [], search });+ expect(out.starts.map((s) => s.path)).toEqual(["src/a.ts", "src/b.ts", "src/c.ts"]);+ expect(out.unresolved).toEqual([]);+ });++ it("breaks a tie between two definitions of one name by the issue's text", async () => {+ const { search } = fakeSearch({+ renderRow: [hit("renderRow", "function", "src/table.ts"), hit("renderRow", "function", "src/grid.ts")],+ });+ const out = await pickStartingPoints("renderRow in the grid", {+ files: [], search, fileScore: (p) => (p === "src/grid.ts" ? 2 : 1),+ });+ expect(out.starts[0].path).toBe("src/grid.ts");+ });+});++describe("path candidates resolve against the tracked files", () => {+ let dir: string | undefined;+ afterEach(() => {+ if (dir) rmSync(dir, { recursive: true, force: true });+ dir = undefined;+ });++ it("resolves a unique basename and a unique suffix via git ls-files, and refuses an ambiguous one", async () => {+ dir = mkdtempSync(join(tmpdir(), "ix-from-issue-"));+ const write = (path: string, text: string) => {+ mkdirSync(dirname(join(dir!, path)), { recursive: true });+ writeFileSync(join(dir!, path), text);+ };+ execFileSync("git", ["init", "-q"], { cwd: dir });+ write("keras/src/saving/saving_api.py", "def save_model():\n pass\n");+ write("src/a/index.ts", "export {};\n");+ write("src/b/index.ts", "export {};\n");+ write("src/untracked.ts", "export {};\n");+ execFileSync("git", ["add", "keras", "src/a", "src/b"], { cwd: dir });+ const repo = gitRepoAccess(dir)!;++ const { search, asked } = fakeSearch({});+ const out = await pickStartingPoints(+ "See saving_api.py, then a/index.ts; index.ts and untracked.ts are unrelated.",+ { files: repo.files(), search },+ );+ expect(out.starts.map((s) => [s.path, s.via])).toEqual([+ ["keras/src/saving/saving_api.py", "path in issue"],+ ["src/a/index.ts", "path in issue"],+ ]);+ expect(out.unresolved).toEqual(expect.arrayContaining(["index.ts", "untracked.ts"]));+ // A path is resolved against the file list, not the symbol index.+ expect(asked).not.toContain("saving_api.py");+ });+});++describe("readIssueText", () => {+ it("reads stdin for `-`", async () => {+ const text = await readIssueText("-", Readable.from(["The `listByKind` ", "call is slow\n"]));+ expect(text).toBe("The `listByKind` call is slow\n");+ });++ it("reads a file path", async () => {+ const dir = mkdtempSync(join(tmpdir(), "ix-issue-text-"));+ try {+ writeFileSync(join(dir, "issue.md"), "rank is wrong\n");+ expect(await readIssueText(join(dir, "issue.md"))).toBe("rank is wrong\n");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});++describe("BM25", () => {+ it("splits camelCase and snake_case and drops short parts", () => {+ expect(bm25Tokens("listByKind save_model_v2 a IO HTTPServer"))+ .toEqual(["list", "kind", "save", "model", "http", "server"]);+ });++ it("ranks the file that shares the issue's rare words first, and skips files over 200KB", () => {+ const repo = memoryRepo({+ "src/auth/login.ts": "export function checkPassword(password: string) { return password.length > 0; }",+ "src/util/strings.ts": "export function trim(s: string) { return s.trim(); }",+ "src/big.ts": "password ".repeat(30_000),+ });+ const ranked = bm25Rank(repo, repo.files(), "Login crashes when the password is empty");+ expect(ranked[0].path).toBe("src/auth/login.ts");+ expect(ranked.map((r) => r.path)).not.toContain("src/big.ts");+ });+});++describe("planIssue", () => {+ it("falls back to BM25 when nothing in the issue resolves, and says so", async () => {+ const repo = memoryRepo({+ "src/auth/login.ts": "export function checkPassword(password: string) { return password.length > 0; }",+ "src/util/strings.ts": "export function trim(s: string) { return s.trim(); }",+ "src/auth/login.test.ts": "password password password login login",+ "CHANGELOG.md": "login password login password",+ });+ const { search } = fakeSearch({});+ const plan = await planIssue("The login page crashes when the password is empty. `flex`", { repo, search });+ expect(plan.fallback).toBe(true);+ expect(plan.starts).toHaveLength(1);+ expect(plan.starts[0]).toMatchObject({ path: "src/auth/login.ts", via: "bm25 fallback" });+ expect(plan.unresolved).toEqual(["flex"]);+ // BM25 ranks source files only.+ expect(plan.bm25.map((r) => r.path)).not.toContain("src/auth/login.test.ts");+ expect(plan.bm25.map((r) => r.path)).not.toContain("CHANGELOG.md");+ });++ it("does not fall back when a name resolves", async () => {+ const repo = memoryRepo({ "src/client/api.ts": "listByKind", "src/other.ts": "other" });+ const { search } = fakeSearch({ listByKind: [hit("listByKind", "method", "src/client/api.ts", [141, 152])] });+ const plan = await planIssue("`listByKind` returns nothing", { repo, search });+ expect(plan.fallback).toBe(false);+ expect(plan.starts.map((s) => s.path)).toEqual(["src/client/api.ts"]);+ });+});++describe("rankIssueFiles", () => {+ const starts = [+ { token: "listByKind", name: "listByKind", kind: "method", path: "src/client/api.ts", via: "identifier in issue" as const },+ ];++ it("puts starting points first, then BM25 order", () => {+ const ranked = rankIssueFiles({+ starts,+ bm25: [+ { path: "src/cli/commands/inventory.ts", score: 9 },+ { path: "src/client/api.ts", score: 5 },+ { path: "src/cli/commands/rank.ts", score: 4 },+ ],+ near: new Map(),+ });+ expect(ranked.map((r) => r.path)).toEqual([+ "src/client/api.ts", "src/cli/commands/inventory.ts", "src/cli/commands/rank.ts",+ ]);+ expect(ranked[0].reason).toContain("starting point");+ expect(ranked[1].reason).toContain("bm25");+ });++ it("uses graph closeness to break ties and nudge, never to overturn a clear lexical lead", () => {+ const ranked = rankIssueFiles({+ starts,+ bm25: [+ { path: "src/far-strong.ts", score: 10 },+ { path: "src/far-tie.ts", score: 4 },+ { path: "src/near-tie.ts", score: 4 },+ { path: "src/near-weak.ts", score: 1 },+ ],+ near: new Map([+ ["src/near-tie.ts", { weight: 1, reason: "one hop from listByKind" }],+ ["src/near-weak.ts", { weight: 1, reason: "one hop from listByKind" }],+ ["src/near-only.ts", { weight: 0.5, reason: "related to listByKind" }],+ ["src/near-test.test.ts", { weight: 1, reason: "one hop from listByKind" }],+ ]),+ });+ expect(ranked.map((r) => r.path)).toEqual([+ "src/client/api.ts", "src/far-strong.ts", "src/near-tie.ts", "src/far-tie.ts",+ "src/near-weak.ts", "src/near-only.ts",+ ]);+ expect(ranked.find((r) => r.path === "src/near-tie.ts")?.reason).toContain("one hop from listByKind");+ });+});diff --git a/ix-cli/src/cli/__tests__/context-mode-conflict.test.ts b/ix-cli/src/cli/__tests__/context-mode-conflict.test.tsindex 3b26540d..5fd5d919 100644--- a/ix-cli/src/cli/__tests__/context-mode-conflict.test.ts+++ b/ix-cli/src/cli/__tests__/context-mode-conflict.test.ts@@ -246,6 +246,11 @@ describe("mode-flag coverage does not drift from the command", () => {];/** Meaningful to every mode, so in neither group. */const CONTEXT_UNIVERSAL_FLAGS = ["format"];+ /**+ * Where the target comes from, in place of the positional. Builds a bundle,+ * so `--out` and `--save` take it, and every budget applies to it.+ */+ const CONTEXT_TARGET_FLAGS = ["fromIssue"];function registeredAttributes(register: (p: Command) => void, name: string): string[] {const program = new Command();@@ -257,7 +262,7 @@ describe("mode-flag coverage does not drift from the command", () => {it("classifies every option ix context registers", () => {expect(registeredAttributes(registerContextCommand, "context")).toEqual(- [...CONTEXT_MODE_FLAGS, ...CONTEXT_BUILD_FLAGS, ...CONTEXT_UNIVERSAL_FLAGS].sort(),+ [...CONTEXT_MODE_FLAGS, ...CONTEXT_BUILD_FLAGS, ...CONTEXT_UNIVERSAL_FLAGS, ...CONTEXT_TARGET_FLAGS].sort(),);});@@ -298,6 +303,25 @@ describe("mode-flag coverage does not drift from the command", () => {}});+ it("refuses --from-issue with a second target or a mode that does not build from it", () => {+ expect(detectContextModeConflict({ fromIssue: "issue.md" }, "Widget")).toMatch(/--from-issue/);+ for (const mode of ["list", "resume", "diff"] as const) {+ const opts = { fromIssue: "issue.md", [mode]: mode === "list" ? true : "x" } as Record<string, unknown>;+ expect(detectContextModeConflict(opts), `--from-issue + --${mode}`).toMatch(/--from-issue/);+ }+ // --kind, --path and --pick choose among the candidates for a named+ // target; an issue has none, so they would change nothing.+ for (const flag of ["kind", "path", "pick"]) {+ expect(detectContextModeConflict({ fromIssue: "-", [flag]: 1 }), `--from-issue + --${flag}`).toBeTruthy();+ }+ });++ it("lets --from-issue build, write and save like a named target", () => {+ for (const extra of [{}, { out: "b.json" }, { save: "x" }, { format: "llm" }, { depth: "full" }, { maxTokens: 800 }]) {+ expect(detectContextModeConflict({ fromIssue: "-", ...extra })).toBeUndefined();+ }+ });+it("leaves every single mode flag alone", () => {// The mirror of the above: a rule that fires on one flag would refuse the// command's ordinary use, and a pair-only assertion cannot see that.diff --git a/ix-cli/src/cli/__tests__/context-seeds-by-id.test.ts b/ix-cli/src/cli/__tests__/context-seeds-by-id.test.tsindex c57f2eb7..daee7652 100644--- a/ix-cli/src/cli/__tests__/context-seeds-by-id.test.ts+++ b/ix-cli/src/cli/__tests__/context-seeds-by-id.test.ts@@ -70,10 +70,11 @@ describe("context.ts call sites", () => {join(dirname(fileURLToPath(import.meta.url)), "..", "commands", "context.ts"),"utf8",);- // Two call sites, and both must convert. Leaving one behind makes `--diff`+ // Three call sites, and all must be by id. Leaving one behind makes `--diff`// compare a by-id bundle against a by-name one and report the entire graph- // as changed on the first run after upgrade.+ // as changed on the first run after upgrade. The third is `--from-issue`,+ // which seeds from the node its starting point resolved to.expect(src).not.toContain("client.query(resolved.name");- expect(src.match(/client\.contextForNode\(resolved\.id/g) ?? []).toHaveLength(2);+ expect(src.match(/client\.contextForNode\(resolved\.id/g) ?? []).toHaveLength(3);});});diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.tsindex 06b87289..29d95853 100644--- a/ix-cli/src/cli/commands/context.ts+++ b/ix-cli/src/cli/commands/context.ts@@ -15,17 +15,28 @@ import { IxClient } from "../../client/api.js";import type {ConflictReport,DecisionReport,+ GraphNode,IntentReport,StructuredContext,} from "../../client/types.js";import { getEndpoint, resolveWorkspaceRoot } from "../config.js";import { collectFacts, type ContextFacts, type EntityLocation } from "../explain/facts.js";+import {+ CLOSENESS_BOOST,+ planIssue,+ rankIssueFiles,+ readIssueText,+ type Closeness,+ type RankedFile,+ type StartingPoint,+ type SymbolHit,+} from "../explain/issue.js";import { collectRelatedFiles, MAX_RELATED, type RelatedRef } from "../explain/related-files.js";import { collectTextReferences, gitRepoAccess, type TextSource } from "../explain/text-references.js";import { coChangedFiles, gitRunner, recentCommits, type CommitRef } from "../explain/history.js";import { llmLine, llmShortId, printLlmLines } from "../llm.js";import { parseBudgetOption, parsePickOption, parseRevisionOption } from "../options.js";-import { activeReadScope, resolveFileOrReport } from "../resolve.js";+import { activeReadScope, ensureReadScope, resolveFileOrReport } from "../resolve.js";import { createStaleProbe, hasCompletedSourceGraphBaseline } from "../stale.js";import { renderNote, renderSection, renderWarning, renderWarningErr, reportFailure } from "../ui.js";import { printJson, relativePath } from "../format.js";@@ -153,6 +164,8 @@ export function clampBudgets(opts: Partial<BudgetSnapshot>): BudgetSnapshot {}interface ContextOptions extends Partial<BudgetSnapshot> {+ /** An issue or bug report to start from, in place of a target: a file, or `-` for stdin. */+ fromIssue?: string;kind?: string;path?: string;pick?: number;@@ -237,6 +250,13 @@ interface ContextBundle {/** The one explicitly declared time-dependent field. */generatedAt: string;target: { id: string; name: string; kind: string; resolutionMode: string; path?: string };+ /**+ * Where an issue's bundle starts, and what in the issue did not resolve.+ * Only on a bundle built with `--from-issue`; absent, not empty, otherwise.+ */+ issue?: IssueSummary;+ /** The files to read for the issue, best first. Only with `--from-issue`. */+ rankedFiles?: RankedFile[];entities: Array<{id: string;name: string;@@ -302,6 +322,10 @@ export function registerContextCommand(program: Command): void {.description("Build a bounded, deterministic context bundle for a symbol, file, or entity (or resume/diff a saved investigation without a target)",)+ .option(+ "--from-issue <file>",+ "Start from an issue or bug report instead of a target: a file, or - for stdin",+ ).option("--kind <kind>", "Filter target entity by kind").option("--path <path>", "Restrict to symbols from files matching this path substring").option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)@@ -338,7 +362,7 @@ export function registerContextCommand(program: Command): void {.option("--list", "List saved investigations (no target, no backend)").addHelpText("after",- "\nExamples:\n ix context IngestionService\n ix context src/main.ts --format json\n ix context Widget --max-entities 20 --max-evidence 10\n ix context Widget --save widget-investigation\n ix context --resume widget-investigation\n ix context --diff widget-investigation\n ix context --list",+ "\nExamples:\n ix context IngestionService\n ix context src/main.ts --format json\n ix context --from-issue issue.md --format llm\n gh issue view 123 --json body -q .body | ix context --from-issue -\n ix context Widget --max-entities 20 --max-evidence 10\n ix context Widget --save widget-investigation\n ix context --resume widget-investigation\n ix context --diff widget-investigation\n ix context --list",).action(async (target: string | undefined, opts: ContextOptions) => {const conflict = detectContextModeConflict(opts, target);@@ -377,13 +401,18 @@ export function registerContextCommand(program: Command): void {renderInvestigationDiff(saved, fresh, opts.format, requestedBudgets);return;}+ if (opts.fromIssue) {+ const bundle = await buildIssueBundle(opts.fromIssue, opts, clampBudgets(opts));+ if (bundle) await emitBundle(bundle, opts);+ return;+ }if (!target) {// An error with a non-zero status, not a stdout warning with a zero one:// a script asked for a bundle and got none, and a `--format llm` caller// got a prose line in the middle of a record stream saying so.reportFailure("missing_target",- "ix context requires a target unless --resume <id>, --diff <id> or --list is given.",+ "ix context requires a target unless --from-issue <file>, --resume <id>, --diff <id> or --list is given.",opts.format,);return;@@ -429,65 +458,70 @@ export function registerContextCommand(program: Command): void {graphCompleted: hasCompletedSourceGraphBaseline(),});- if (opts.save) {- saveInvestigation(opts.save, bundle);- renderNote(`Saved investigation "${opts.save}" (${bundle.entities.length} entities, ${bundle.relationships.length} relationships, ${bundle.evidence.length} evidence items). Resume with: ix context --resume ${opts.save}`);- return;- }+ await emitBundle(bundle, opts);+ });- if (opts.out && opts.format !== "json") {- // stderr: --out still writes the file and still prints a note, so this- // advisory would otherwise sit in the stdout an `llm` caller is reading.- renderWarningErr("--out writes JSON; ignoring --format and forcing json.");- }- const out = opts.out;- if (out) {- const fs = await import("node:fs");- // Validate the network-derived bundle against the versioned contract- // before persisting it: only a bundle matching ix-context-bundle/1 is- // written, so a malformed or unexpected backend payload can never land- // in a caller-owned file (CodeQL js/network-data-written-to-file).- const parsed = contextBundleSchema.safeParse(bundle);- if (!parsed.success) {- reportFailure(- "out_refused",- `--out "${out}" refused: the bundle does not match the ${BUNDLE_SCHEMA} schema (${parsed.error.issues.length} issue(s)).`,- opts.format,- );- return;- }- // Atomic write: serialize to a private temp file in the SAME directory,- // then rename over the target, so the write is never a check-then-write- // race and a partial file is never visible (CodeQL js/file-system-race;- // same pattern as the config writer in src/cli/config.ts). Renaming- // onto an existing directory fails, which surfaces as the refusal below.- const targetPath = resolve(out);- const tmpPath = join(dirname(targetPath), `.${process.pid}.${Date.now().toString(36)}.tmp`);+/** `--save`, `--out`, or render: what every freshly built bundle goes through. */+async function emitBundle(bundle: ContextBundle, opts: ContextOptions): Promise<void> {+ if (opts.save) {+ saveInvestigation(opts.save, bundle);+ renderNote(`Saved investigation "${opts.save}" (${bundle.entities.length} entities, ${bundle.relationships.length} relationships, ${bundle.evidence.length} evidence items). Resume with: ix context --resume ${opts.save}`);+ return;+ }++ if (opts.out && opts.format !== "json") {+ // stderr: --out still writes the file and still prints a note, so this+ // advisory would otherwise sit in the stdout an `llm` caller is reading.+ renderWarningErr("--out writes JSON; ignoring --format and forcing json.");+ }+ const out = opts.out;+ if (out) {+ const fs = await import("node:fs");+ // Validate the network-derived bundle against the versioned contract+ // before persisting it: only a bundle matching ix-context-bundle/1 is+ // written, so a malformed or unexpected backend payload can never land+ // in a caller-owned file (CodeQL js/network-data-written-to-file).+ const parsed = contextBundleSchema.safeParse(bundle);+ if (!parsed.success) {+ reportFailure(+ "out_refused",+ `--out "${out}" refused: the bundle does not match the ${BUNDLE_SCHEMA} schema (${parsed.error.issues.length} issue(s)).`,+ opts.format,+ );+ return;+ }+ // Atomic write: serialize to a private temp file in the SAME directory,+ // then rename over the target, so the write is never a check-then-write+ // race and a partial file is never visible (CodeQL js/file-system-race;+ // same pattern as the config writer in src/cli/config.ts). Renaming+ // onto an existing directory fails, which surfaces as the refusal below.+ const targetPath = resolve(out);+ const tmpPath = join(dirname(targetPath), `.${process.pid}.${Date.now().toString(36)}.tmp`);+ try {+ fs.writeFileSync(tmpPath, JSON.stringify(parsed.data, null, 2) + "\n", "utf8");+ fs.renameSync(tmpPath, targetPath);+ } catch (error) {+ try { fs.rmSync(tmpPath, { force: true }); } catch { /* best effort */ }+ const err = error as NodeJS.ErrnoException;+ if (err.code === "EISDIR" || err.code === "EPERM") {try {- fs.writeFileSync(tmpPath, JSON.stringify(parsed.data, null, 2) + "\n", "utf8");- fs.renameSync(tmpPath, targetPath);- } catch (error) {- try { fs.rmSync(tmpPath, { force: true }); } catch { /* best effort */ }- const err = error as NodeJS.ErrnoException;- if (err.code === "EISDIR" || err.code === "EPERM") {- try {- if (fs.statSync(targetPath).isDirectory()) {- reportFailure(- "out_refused",- `--out "${out}" is a directory; refusing to write the bundle there.`,- opts.format,- );- return;- }- } catch { /* target may not exist; fall through to rethrow */ }+ if (fs.statSync(targetPath).isDirectory()) {+ reportFailure(+ "out_refused",+ `--out "${out}" is a directory; refusing to write the bundle there.`,+ opts.format,+ );+ return;}- throw error;- }- renderNote(`Wrote ${parsed.data.entities.length} entities, ${parsed.data.relationships.length} relationships, ${parsed.data.evidence.length} evidence items to ${out}`);- return;+ } catch { /* target may not exist; fall through to rethrow */ }}- renderBundle(bundle, opts.format);- });+ throw error;+ }+ renderNote(`Wrote ${parsed.data.entities.length} entities, ${parsed.data.relationships.length} relationships, ${parsed.data.evidence.length} evidence items to ${out}`);+ return;+ }+ renderBundle(bundle, opts.format);+}async function buildFreshBundle(target: string,@@ -546,6 +580,7 @@ export type ContextModeOptions = Partial<ContextOptions>;* typed, and Commander's camelCase attribute is not that.*/const BUILD_FLAGS: ReadonlyArray<[keyof ContextOptions, string]> = [+ ["fromIssue", "--from-issue"],["kind", "--kind"],["path", "--path"],["pick", "--pick"],@@ -587,6 +622,24 @@ export function detectContextModeConflict(if (opts.resume && target) {return `--resume takes no target; it renders the investigation you name, whatever that was built for. Drop "${target}", or use --diff <id> to compare a saved investigation against a fresh build of it.`;}+ if (opts.fromIssue !== undefined) {+ // The issue is the target: it names its own starting points, so a second+ // target, or a flag that narrows the candidates for one, has nothing to+ // act on. `--diff` rebuilds a saved investigation by its target's name,+ // which a bundle built from an issue does not have.+ if (target) {+ return `--from-issue takes no target; the issue's text picks the starting points. Drop "${target}", or drop --from-issue to build a bundle for it.`;+ }+ if (opts.diff) {+ return "--from-issue cannot be combined with --diff; --diff rebuilds a saved investigation from its target's name. Save the issue's bundle with --save and --resume it instead.";+ }+ const narrowing = ([["kind", "--kind"], ["path", "--path"], ["pick", "--pick"]] as const)+ .filter(([field]) => opts[field] !== undefined)+ .map(([, flag]) => flag);+ if (narrowing.length > 0 && !opts.list && !opts.resume) {+ return `${narrowing.join(", ")} cannot be combined with --from-issue; ${narrowing.length > 1 ? "they narrow" : "it narrows"} the candidates for a named target, and the issue's starting points are chosen from its text.`;+ }+ }// Flags that shape a bundle, given to a mode that builds none. Reported as// one message naming every offender, because dropping one at a time and// re-running to find the next is the experience this detector exists to@@ -1445,6 +1498,22 @@ interface BuildInput {* silently reclassified.*/graphCompleted?: boolean;+ /** Set by `--from-issue`: the starting points and the ranked files. */+ issue?: IssueBundleInput;+}++/** What `--from-issue` records in the bundle. */+interface IssueSummary {+ startingPoints: StartingPoint[];+ unresolved: string[];+ /** Nothing in the issue resolved; the start is BM25's best file. */+ fallback: boolean;+}++export interface IssueBundleInput extends IssueSummary {+ rankedFiles: RankedFile[];+ /** The other starting points' related files, entered as entities. */+ extraEntities?: EntityLocation[];}/**@@ -1506,10 +1575,154 @@ async function collectHistory(* back to a synthetic id rather than dropping a file the graph has not seen.*/async function fileNodeId(client: IxClient, path: string): Promise<string> {+ return (await findFileNode(client, path)) ?? `file:${path}`;+}++/** A file's graph node id, or undefined when the graph has no node for it. */+async function findFileNode(client: IxClient, path: string): Promise<string | undefined> {const name = path.split("/").pop()!;const nodes = await client.search(name, { kind: "file", nameOnly: true, limit: 10, ...activeReadScope() }).catch(() => []);- return nodes.find((n) => relativePath(n.provenance?.sourceUri) === path)?.id ?? `file:${path}`;+ return nodes.find((n) => relativePath(n.provenance?.sourceUri) === path)?.id;+}++/** Search candidates fetched per name the issue mentions; only exact names are kept. */+const ISSUE_SEARCH_LIMIT = 20;++/**+ * `ix context --from-issue`: a bundle built from an issue's text rather than a+ * named target. See `explain/issue.ts` for how starting points are chosen and+ * files ranked.+ *+ * The bundle is centred on the first starting point the graph has a node for,+ * built exactly as `ix context <that target>` would be. The other starting+ * points enter it as entities, with their own related files, and every+ * starting point's neighbourhood feeds the closeness that nudges the ranking.+ * Their facts are collected without text references or git history: those+ * are the expensive, centre-only parts of `collectContextFacts`.+ */+async function buildIssueBundle(+ arg: string,+ opts: ContextOptions,+ budgets: BudgetSnapshot,+): Promise<ContextBundle | undefined> {+ let text: string;+ try {+ text = await readIssueText(arg);+ } catch (error) {+ reportFailure(+ "issue_unreadable",+ `Cannot read the issue from ${arg === "-" ? "stdin" : `"${arg}"`}: ${(error as Error).message}`,+ opts.format,+ );+ return undefined;+ }+ if (!text.trim()) {+ reportFailure("empty_issue", `The issue ${arg === "-" ? "on stdin" : `in "${arg}"`} is empty.`, opts.format);+ return undefined;+ }++ const client = new IxClient(getEndpoint());+ await ensureReadScope(client);+ const scope = activeReadScope();+ const plan = await planIssue(text, {+ repo: gitRepoAccess(resolveWorkspaceRoot()),+ search: async (name) =>+ (await client.search(name, { limit: ISSUE_SEARCH_LIMIT, nameOnly: true, ...scope })).map(symbolHit),+ });+ // A path start has no node yet; the graph may not have one either.+ const starts: StartingPoint[] = await Promise.all(plan.starts.map(async (s) => {+ const id = s.id ?? (await findFileNode(client, s.path));+ return id ? { ...s, id } : s;+ }));++ const centre = starts.find((s) => s.id);+ if (!centre) {+ reportFailure(+ "issue_unresolved",+ starts.length === 0+ ? `Nothing the issue names resolved to a definition${plan.unresolved.length > 0 ? ` (tried ${plan.unresolved.slice(0, 5).join(", ")})` : ""}, and no tracked source file matched its text. Name a symbol or file and run ix context <target>.`+ : `The issue's starting points (${starts.map((s) => s.path).join(", ")}) have no node in the graph. Run ix map if this workspace has not been mapped.`,+ opts.format,+ );+ return undefined;+ }+ const resolved = { id: centre.id!, name: centre.name, kind: centre.kind, resolutionMode: "issue" };+ const [facts, context, around] = await Promise.all([+ collectContextFacts(client, resolved),+ client.contextForNode(resolved.id, { asOfRev: opts.asOfRev, depth: opts.depth }),+ Promise.all(starts.filter((s) => s.id && s !== centre).map((s) => startNeighbourhood(client, s))),+ ]);++ const near = new Map<string, Closeness>();+ const mark = (path: string | undefined, weight: number, reason: string) => {+ if (!path) return;+ const prior = near.get(path);+ if (!prior || weight > prior.weight) near.set(path, { weight, reason });+ };+ for (const n of [{ start: centre, facts, related: facts.relatedRefs ?? [] }, ...around]) {+ for (const ref of oneHopRefs(n.facts)) {+ if (ref.path !== n.start.path) mark(ref.path, 1, `one hop from ${n.start.name}`);+ }+ for (const ref of n.related) mark(ref.path, 0.5, `near ${n.start.name}`);+ }++ return buildBundle({+ resolved,+ facts,+ context,+ provenance: facts.provenance,+ asOfRev: opts.asOfRev,+ depth: opts.depth,+ budgets,+ graphCompleted: hasCompletedSourceGraphBaseline(),+ issue: {+ startingPoints: starts,+ unresolved: plan.unresolved,+ fallback: plan.fallback,+ rankedFiles: rankIssueFiles({ starts, bm25: plan.bm25, near }),+ extraEntities: around.flatMap((n) => n.related),+ },+ });+}++/** A secondary starting point's one-hop facts and related files. Best-effort. */+async function startNeighbourhood(+ client: IxClient,+ start: StartingPoint,+): Promise<{ start: StartingPoint; facts?: ContextFacts; related: RelatedRef[] }> {+ try {+ const facts = await collectFacts(client, start.id!, start.name, start.kind, "context");+ const related = await collectRelatedFiles(client, { id: start.id!, kind: start.kind }, facts).catch(() => []);+ return { start, facts, related };+ } catch {+ return { start, related: [] };+ }+}++/** What a target reaches, and what reaches it, one step out. */+function oneHopRefs(facts: ContextFacts | undefined): EntityLocation[] {+ if (!facts) return [];+ return [+ ...(facts.importRefs ?? []), ...(facts.calleeRefs ?? []), ...(facts.topCallerRefs ?? []),+ ...(facts.topDependentRefs ?? []), ...(facts.neighbourRefs ?? []),+ ];+}++/** A search result as the starting-point picker reads it. */+function symbolHit(node: GraphNode): SymbolHit {+ const attrs = (node.attrs ?? {}) as Record<string, unknown>;+ const line = (v: unknown) => (typeof v === "number" && Number.isInteger(v) && v > 0 ? v : undefined);+ const lineStart = line(attrs.line_start);+ const lineEnd = line(attrs.line_end);+ return {+ id: node.id,+ name: node.name || (typeof attrs.name === "string" ? attrs.name : ""),+ kind: node.kind || "unknown",+ path: relativePath(node.provenance?.sourceUri),+ ...(lineStart !== undefined ? { lineStart } : {}),+ ...(lineEnd !== undefined ? { lineEnd } : {}),+ };}/** Imported files whose text is read for names, after the target's own. */@@ -1609,7 +1822,13 @@ export function buildBundle(input: BuildInput): ContextBundle {});}};+ const issue = input.issue;pushLocated([+ // The issue's other starting points, right after the one the bundle is+ // centred on: they are as much the target as it is.+ ...(issue?.startingPoints ?? [])+ .filter((s) => s.id && s.id !== resolved.id)+ .map((s) => ({ id: s.id!, name: s.name, kind: s.kind, ...locationFields(s) })),...memberRefs.slice(0, LEADING_MEMBERS),// What the target reaches, before what reaches it: an agent starting from// an entry point is looking for where to go next.@@ -1623,6 +1842,7 @@ export function buildBundle(input: BuildInput): ContextBundle {// 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 ?? []),+ ...(issue?.extraEntities ?? []),]);// Compact and standard backend responses omit the full graph arrays and// carry the same graph as summaries. Falling back here keeps the default@@ -1679,7 +1899,7 @@ export function buildBundle(input: BuildInput): ContextBundle {.sort((a, b) => cmp(a.src, b.src) || cmp(a.dst, b.dst) || cmp(a.predicate, b.predicate)).map((edge) => ({ src: edge.src, dst: edge.dst, predicate: edge.predicate }));- const evidence = rankEvidence({ resolved, facts, context, relationships, prov, entities });+ const evidence = rankEvidence({ resolved, facts, context, relationships, prov, entities, issue });const bundle: ContextBundle = {schema: BUNDLE_SCHEMA,@@ -1691,6 +1911,12 @@ export function buildBundle(input: BuildInput): ContextBundle {resolutionMode: resolved.resolutionMode,...(facts.path ? { path: facts.path } : {}),},+ ...(issue+ ? {+ issue: { startingPoints: issue.startingPoints, unresolved: issue.unresolved, fallback: issue.fallback },+ rankedFiles: issue.rankedFiles,+ }+ : {}),entities: [],relationships: [],claims: [...context.claims]@@ -1815,6 +2041,7 @@ function rankEvidence(input: {relationships: Array<{ src: string; dst: string; predicate: string }>;prov: Record<string, unknown>;entities: ContextBundle["entities"];+ issue?: IssueBundleInput;}): EvidenceItem[] {const items: EvidenceItem[] = [];@@ -1829,6 +2056,10 @@ function rankEvidence(input: {refs: [target.id],...locationField(targetLocation(input.facts)),});+ // Straight after the target, ahead of everything structural: a file target+ // with many members fills the default budget before score 10 runs out, and+ // these two rows are what `--from-issue` exists to deliver.+ if (input.issue) items.push(...issueEvidence(input.issue));type Structural = Omit<EvidenceItem, "kind" | "score">;const structural: Structural[] = [];@@ -2008,6 +2239,50 @@ function rankEvidence(input: {return items.sort((a, b) => a.score - b.score || cmp(a.id, b.id));}+/** Ranked files named in the evidence row; the JSON bundle carries the rest. */+const SHOWN_RANKED_FILES = 10;++/**+ * The `--from-issue` rows: where the bundle starts and why, then the files to+ * read, ranked against the issue's text.+ */+function issueEvidence(issue: IssueBundleInput): EvidenceItem[] {+ const items: EvidenceItem[] = [];+ const starts = issue.startingPoints;+ if (starts.length > 0) {+ const unresolved = issue.unresolved.length > 0+ ? `; unresolved: ${issue.unresolved.slice(0, 8).join(", ")}${issue.unresolved.length > 8 ? ", ..." : ""}`+ : "";+ const why = starts.map((s) => `${s.token}: ${s.via}`).join("; ");+ items.push({+ id: "issue-starts",+ kind: "target",+ source: "issue.starts",+ title: `starting points: ${starts.map((s) => `${s.name} (${formatLocation(locationFields(s) as EvidenceLocation)})`).join(", ")}`,+ score: 1,+ reason: (issue.fallback+ ? "no code name in the issue resolved to a definition; starting from the file BM25 ranks first against the issue text; "+ : "") + why + unresolved,+ refs: starts.flatMap((s) => (s.id ? [s.id] : [])),+ ...locationField(starts[0]),+ });+ }+ const shown = issue.rankedFiles.slice(0, SHOWN_RANKED_FILES);+ if (shown.length > 0) {+ items.push({+ id: "issue-ranked-files",+ kind: "structural",+ source: "issue.ranking",+ title: `ranked files: ${shown.map((f) => f.path).join(", ")}`,+ score: 2,+ reason: `starting points first, then bm25 against the issue text, graph neighbours of a starting point boosted up to ${Math.round(CLOSENESS_BOOST * 100)}%; `+ + shown.map((f) => `${f.path.split("/").pop()} (${f.reason})`).join("; "),+ refs: [],+ });+ }+ return items;+}+export function renderBundle(bundle: ContextBundle, format: string): void {if (format === "json") {printJson(bundle);@@ -2047,6 +2322,9 @@ export function renderBundle(bundle: ContextBundle, format: string): void {truncationAdvice(bundle)? llmLine("diagnostic", { code: "bundle_truncated", message: truncationAdvice(bundle) }): null,+ bundle.issue?.fallback+ ? llmLine("diagnostic", { code: "issue_fallback", message: ISSUE_FALLBACK_NOTE })+ : null,// Evidence only, as before. The entity, relationship and claim lists are// deliberately still counts here: `--format llm` is the token-minimal// surface, the ranked evidence is what it exists to deliver, and@@ -2073,6 +2351,12 @@ export function renderBundle(bundle: ContextBundle, format: string): void {` conflicts: ${conflictCount}${conflictCount > 0 ? " (run ix conflicts to inspect)" : ""}`,);console.log(` intents: ${bundle.intents.length}`);+ if (bundle.issue) {+ console.log(+ ` from issue: ${bundle.issue.startingPoints.length} starting point(s), ${bundle.rankedFiles?.length ?? 0} ranked files`,+ );+ if (bundle.issue.fallback) renderNote(ISSUE_FALLBACK_NOTE);+ }if (bundle.freshness.stale) {renderWarning("Source has changed since last ingest. Run ix map to update.");}@@ -2110,7 +2394,13 @@ export function renderBundle(bundle: ContextBundle, format: string): void {* imports, calls, callers and dependents alike, and "cut: 48 structural" is the* uninformative sentence this exists to replace.*/+/** Said wherever a bundle's start came from BM25 rather than from the issue's names. */+const ISSUE_FALLBACK_NOTE =+ "Nothing the issue names resolved to a definition; the bundle starts from the file whose text matches the issue best (BM25).";+const CUT_LABELS: Record<string, string> = {+ "issue.starts": "starting points row",+ "issue.ranking": "ranked files row","facts.container": "container","facts.members": "member","facts.imports": "import",diff --git a/ix-cli/src/cli/context-bundle-schema.ts b/ix-cli/src/cli/context-bundle-schema.tsindex c0c44dde..f20a66a2 100644--- a/ix-cli/src/cli/context-bundle-schema.ts+++ b/ix-cli/src/cli/context-bundle-schema.ts@@ -44,6 +44,31 @@ export const contextBundleSchema = z.object({resolutionMode: z.string(),path: z.string().optional(),}),+ // Both optional, and only on a bundle built with `--from-issue`: every+ // bundle saved before them, and every bundle built from a named target,+ // still validates. Declared rather than left out, because zod strips an+ // undeclared key on the way to disk and on the way back.+ issue: z+ .object({+ startingPoints: z.array(+ z.object({+ token: z.string(),+ id: z.string().optional(),+ name: z.string(),+ kind: z.string(),+ path: z.string(),+ lineStart: z.number().int().positive().optional(),+ lineEnd: z.number().int().positive().optional(),+ via: z.enum(["path in issue", "identifier in issue", "bm25 fallback"]),+ }),+ ),+ unresolved: z.array(z.string()),+ fallback: z.boolean(),+ })+ .optional(),+ rankedFiles: z+ .array(z.object({ path: z.string(), score: z.number(), reason: z.string() }))+ .optional(),entities: z.array(z.object({id: z.string(),diff --git a/ix-cli/src/cli/explain/issue.ts b/ix-cli/src/cli/explain/issue.tsnew file mode 100644index 00000000..e7811aa6--- /dev/null+++ b/ix-cli/src/cli/explain/issue.ts@@ -0,0 +1,402 @@+// Copyright 2026 Ix Infrastructure Inc.++import { readFileSync } from "node:fs";+import { posix } from "node:path";++import { isTestPath } from "./related-files.js";+import { resolveToken, type RepoAccess } from "./text-references.js";++/**+ * From an issue's text to the files its fix starts in, for+ * `ix context --from-issue`.+ *+ * Measured on SWE-PolyBench (28 fresh instances, not used while building+ * this): resolving the code names an issue mentions to their definitions put+ * a changed file in the top five 0.600 of the time, against 0.485 for BM25+ * over the repository. But a graph-expanded bundle, ranked by graph distance,+ * lost to BM25 at equal size (0.57 against 0.67). So the ranking here is+ * lexical first: the resolved starting files lead, BM25 against the issue+ * orders the rest, and graph closeness to a starting point only breaks ties+ * and nudges.+ *+ * Starting points, most specific first:+ *+ * 1. file paths the issue names, resolved against the tracked files;+ * 2. multi-part identifiers -- `newJsonWriter`, `save_model`, `GsonBuilder`+ * -- from backticks or running text. A multi-part name is almost always a+ * code name;+ * 3. single backticked words of four letters or more. `save` was the right+ * start for a keras fix; `flex`, `code` and `version` were not, which is+ * why a single word counts only in backticks, and only after the rest.+ *+ * A name resolves only to an exact-name definition in source code. The first+ * pilot run started from a CSS output file, a changelog, test fixtures, and an+ * import: `borderStylesReset` resolved to the file that imported it, because+ * the graph's `module` entity for an import is located in the importing file.+ */++/** Starting points a bundle is built from. */+export const MAX_STARTS = 3;+/** Candidate names looked up, in order. */+export const MAX_CANDIDATES = 25;+/** Files larger than this are not scored: generated, bundled or data. */+export const MAX_BM25_BYTES = 200 * 1024;+/** Ranked files carried in the JSON bundle. */+export const MAX_RANKED_FILES = 20;+/**+ * How much being next to a starting point is worth, as a fraction of a file's+ * BM25 score. Small on purpose: on the benchmark, graph order lost to BM25 at+ * equal size, so closeness may reorder files the text scores alike and may+ * not overturn a clear lexical lead.+ */+export const CLOSENESS_BOOST = 0.1;++/** Extensions of files a fix edits. */+const CODE_EXTENSIONS = [+ "ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs", "py", "java", "svelte", "vue", "go", "rs",+ "kt", "kts", "scala", "rb", "php", "cs", "c", "h", "cc", "cpp", "hpp", "swift",+];+const CODE_FILE = new RegExp(`\\.(?:${CODE_EXTENSIONS.join("|")})$`);++/**+ * Not code a fix edits: tests, test data, samples, docs, vendored or built+ * output. The pilot's list, plus what `isTestPath` already knows.+ */+const NOISE = new RegExp(+ "(^|/)(__tests__|tests?|spec|specs|fixtures?|__fixtures__|test-fixtures|samples|examples?|vendor|"+ + "third_party|node_modules|dist|build|coverage|docs?|changelog_unreleased)/"+ + "|\\.(test|spec)\\.[^/]+$|\\.min\\.js$|(^|/)test_[^/]+\\.py$|_test\\.(py|go)$",+);++/** Source code a fix would edit: a code file that is not a test, fixture, doc or build output. */+export function isSourcePath(path: string): boolean {+ return CODE_FILE.test(path) && !NOISE.test(path) && !isTestPath(path);+}++// A path-like token with a code extension: `saving_api.py`, `src/a/index.ts`.+const PATH = new RegExp(+ `(?<![\\w/])((?:[\\w.-]+/)*[\\w.-]+\\.(?:${CODE_EXTENSIONS.join("|")}))\\b`, "g");+const BACKTICK = /`([^`\n]{2,80})`/g;+const WORD = /[A-Za-z_][A-Za-z0-9_]{2,}/g;+// camelCase, PascalCase with two or more parts, snake_case, SCREAMING_SNAKE.+const IDENT_SOURCE =+ "(?:[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*)+|[a-z]+(?:[A-Z][a-z0-9]*)+|[a-z0-9]+(?:_[a-z0-9]+)+|[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+)";+const IDENT = new RegExp(`\\b${IDENT_SOURCE}\\b`, "g");+const IDENT_FULL = new RegExp(`^${IDENT_SOURCE}$`);++export interface IssueCandidates {+ /** Path-like tokens, in the order the issue names them. */+ paths: string[];+ /** Code names: multi-part first, then single backticked words. */+ identifiers: string[];+}++/** The paths and code names an issue mentions, most specific first. */+export function extractCandidates(text: string): IssueCandidates {+ const paths = unique([...text.matchAll(PATH)].map((m) => m[1]));+ // A path's own parts are not names in the issue: `saving_api` in+ // `saving/saving_api.py` is the path again, not a function.+ const prose = text.replace(PATH, " ");+ const inTicks = [...prose.matchAll(BACKTICK)].flatMap((m) => [...m[1].matchAll(WORD)].map((w) => w[0]));+ const multi = [...inTicks, ...[...prose.matchAll(IDENT)].map((m) => m[0])].filter((t) => IDENT_FULL.test(t));+ const single = inTicks.filter((t) => !IDENT_FULL.test(t) && t.length >= 4);+ const seen = new Set(paths);+ const identifiers: string[] = [];+ for (const token of [...multi, ...single]) {+ if (seen.has(token)) continue;+ seen.add(token);+ identifiers.push(token);+ }+ return { paths, identifiers: identifiers.slice(0, MAX_CANDIDATES) };+}++/** One search hit, as the starting-point picker needs it. */+export interface SymbolHit {+ id: string;+ name: string;+ kind: string;+ path?: string;+ lineStart?: number;+ lineEnd?: number;+}++export type StartVia = "path in issue" | "identifier in issue" | "bm25 fallback";++export interface StartingPoint {+ /** What the issue said: the path or name as written. */+ token: string;+ /** The graph node, when known. A path start may have none. */+ id?: string;+ name: string;+ kind: string;+ path: string;+ lineStart?: number;+ lineEnd?: number;+ via: StartVia;+}++/** Kinds a definition has, most navigable first. Anything else ranks after. */+const DEFINITION_KINDS = [+ "class", "interface", "trait", "struct", "enum", "type", "object", "function", "method",+ "constant", "variable", "property", "field",+];+/** Never a definition: an import (located in the importer), a chunk, a file. */+const NOT_DEFINITIONS = new Set(["module", "chunk", "file"]);++function kindRank(kind: string): number {+ const i = DEFINITION_KINDS.indexOf(kind.toLowerCase());+ return i === -1 ? DEFINITION_KINDS.length : i;+}++export interface PickDeps {+ /** Tracked files, repository-relative. Empty outside a git checkout. */+ files: string[];+ /** The symbol index: the search `ix search` runs. */+ search: (name: string) => Promise<SymbolHit[]>;+ /**+ * How well a file matches the issue's text. Breaks a tie between two+ * definitions of one name -- `renderRow` in `table.ts` and in `grid.ts` --+ * in favour of the one the issue reads like.+ */+ fileScore?: (path: string) => number;+}++/**+ * Up to `max` starting points, first found wins, one per file; and the+ * candidates that resolved to nothing. Candidates after the last start are+ * not looked up, and not reported as unresolved.+ */+export async function pickStartingPoints(+ text: string,+ deps: PickDeps,+ max = MAX_STARTS,+): Promise<{ starts: StartingPoint[]; unresolved: string[] }> {+ const { paths, identifiers } = extractCandidates(text);+ const starts: StartingPoint[] = [];+ const unresolved: string[] = [];+ const taken = (path: string) => starts.some((s) => s.path === path);++ const tracked = new Set(deps.files);+ const byBasename = new Map<string, string[]>();+ for (const file of deps.files) {+ const base = posix.basename(file);+ byBasename.set(base, [...(byBasename.get(base) ?? []), file]);+ }+ for (const token of paths) {+ if (starts.length >= max) return { starts, unresolved };+ const path = resolveToken(token, "", tracked, byBasename);+ if (!path || !isSourcePath(path)) {+ unresolved.push(token);+ continue;+ }+ if (!taken(path)) starts.push({ token, name: posix.basename(path), kind: "file", path, via: "path in issue" });+ }++ const score = deps.fileScore ?? (() => 0);+ for (const token of identifiers) {+ if (starts.length >= max) break;+ // Not caught: a backend that cannot answer is an error to report, not an+ // issue that names nothing.+ const hits = (await deps.search(token))+ .filter((h): h is SymbolHit & { path: string } =>+ h.name === token && !!h.path && !NOT_DEFINITIONS.has(h.kind.toLowerCase()) && isSourcePath(h.path))+ .sort((a, b) =>+ kindRank(a.kind) - kindRank(b.kind) || score(b.path) - score(a.path) || cmp(a.path, b.path));+ if (hits.length === 0) {+ unresolved.push(token);+ continue;+ }+ const best = hits[0];+ if (taken(best.path)) continue;+ starts.push({+ token, id: best.id, name: best.name, kind: best.kind, path: best.path,+ ...(best.lineStart !== undefined ? { lineStart: best.lineStart } : {}),+ ...(best.lineEnd !== undefined ? { lineEnd: best.lineEnd } : {}),+ via: "identifier in issue",+ });+ }+ return { starts, unresolved };+}++/**+ * Words for BM25: identifiers split at camelCase and underscores, lowercased,+ * parts of two letters or fewer dropped. `listByKind` is `list kind`, so an+ * issue that says "list by kind" matches the code that spells it as one word.+ */+export function bm25Tokens(text: string): string[] {+ const out: string[] = [];+ for (const word of text.match(/[A-Za-z][A-Za-z0-9]*/g) ?? []) {+ const parts = word.match(/[A-Z]?[a-z0-9]+|[A-Z]+(?![a-z])/g) ?? [word];+ for (const part of parts) if (part.length > 2) out.push(part.toLowerCase());+ }+ return out;+}++export interface Bm25Hit {+ path: string;+ score: number;+}++/**+ * Okapi BM25 (k1 1.2, b 0.75) of each file against `query`, best first, files+ * that share no word with it left out. A file's path is part of its text, so+ * `auth/login.ts` matches an issue about logging in before it is opened.+ */+export function bm25Rank(+ repo: Pick<RepoAccess, "read">,+ files: string[],+ query: string,+ k1 = 1.2,+ b = 0.75,+): Bm25Hit[] {+ const docs = new Map<string, { tf: Map<string, number>; length: number }>();+ for (const path of files) {+ const text = repo.read(path);+ if (text === undefined || Buffer.byteLength(text, "utf8") > MAX_BM25_BYTES) continue;+ const tf = new Map<string, number>();+ const tokens = bm25Tokens(`${path.replace(/\//g, " ")} ${text}`);+ for (const t of tokens) tf.set(t, (tf.get(t) ?? 0) + 1);+ docs.set(path, { tf, length: tokens.length });+ }+ if (docs.size === 0) return [];+ const n = docs.size;+ let total = 0;+ const df = new Map<string, number>();+ for (const doc of docs.values()) {+ total += doc.length;+ for (const t of doc.tf.keys()) df.set(t, (df.get(t) ?? 0) + 1);+ }+ const avg = total / n || 1;+ const terms = [...new Set(bm25Tokens(query))];+ const out: Bm25Hit[] = [];+ for (const [path, doc] of docs) {+ let score = 0;+ for (const t of terms) {+ const f = doc.tf.get(t);+ if (!f) continue;+ const d = df.get(t)!;+ const idf = Math.log(1 + (n - d + 0.5) / (d + 0.5));+ score += idf * (f * (k1 + 1)) / (f + k1 * (1 - b + b * doc.length / avg));+ }+ if (score > 0) out.push({ path, score });+ }+ return out.sort((a, c) => c.score - a.score || cmp(a.path, c.path));+}++export interface IssuePlan {+ starts: StartingPoint[];+ unresolved: string[];+ /** True when nothing in the issue resolved and the start is BM25's best file. */+ fallback: boolean;+ /** BM25 over the tracked source files, best first. */+ bm25: Bm25Hit[];+}++/**+ * Starting points and the lexical ranking for one issue. Without a git+ * checkout there is no file list: paths do not resolve, BM25 is empty, and+ * only names can start the bundle.+ */+export async function planIssue(+ text: string,+ deps: { repo?: RepoAccess; search: PickDeps["search"] },+): Promise<IssuePlan> {+ const files = deps.repo?.files() ?? [];+ const bm25 = deps.repo ? bm25Rank(deps.repo, files.filter(isSourcePath), text) : [];+ const scores = new Map(bm25.map((h) => [h.path, h.score]));+ const { starts, unresolved } = await pickStartingPoints(text, {+ files, search: deps.search, fileScore: (p) => scores.get(p) ?? 0,+ });+ if (starts.length > 0 || bm25.length === 0) return { starts, unresolved, fallback: false, bm25 };+ const top = bm25[0].path;+ return {+ starts: [{ token: top, name: posix.basename(top), kind: "file", path: top, via: "bm25 fallback" }],+ unresolved,+ fallback: true,+ bm25,+ };+}++export interface RankedFile {+ path: string;+ /** BM25 against the issue, boosted by closeness to a starting point. */+ score: number;+ reason: string;+}++/** Why a file is near a starting point, and how near: 1 one hop, 0.5 two. */+export interface Closeness {+ weight: number;+ reason: string;+}++/**+ * The files to read, best first: the starting files in the order they were+ * found, then every other source file by+ *+ * bm25(file, issue) * (1 + CLOSENESS_BOOST * closeness(file))+ *+ * where closeness is 1 for a file one hop from a starting point, 0.5 for one+ * of its ranked related files, 0 otherwise. Ties go to the closer file, then+ * the path. A graph neighbour the issue's text does not match at all still+ * ranks, after every file it does match.+ */+export function rankIssueFiles(+ input: { starts: StartingPoint[]; bm25: Bm25Hit[]; near: ReadonlyMap<string, Closeness> },+ limit = MAX_RANKED_FILES,+): RankedFile[] {+ const lexical = new Map(input.bm25.map((h) => [h.path, h.score]));+ const out: RankedFile[] = [];+ const startPaths = new Set<string>();+ for (const s of input.starts) {+ if (startPaths.has(s.path)) continue;+ startPaths.add(s.path);+ out.push({+ path: s.path,+ score: round(lexical.get(s.path) ?? 0),+ reason: `starting point (${s.via}: ${s.token})`,+ });+ }+ const pool = new Set([...lexical.keys(), ...input.near.keys()]);+ const rest = [...pool]+ .filter((path) => !startPaths.has(path) && isSourcePath(path))+ .map((path) => {+ const bm25 = lexical.get(path) ?? 0;+ const near = input.near.get(path);+ const closeness = near?.weight ?? 0;+ const reason = [bm25 > 0 ? `bm25 ${bm25.toFixed(2)}` : "no bm25 match", near?.reason]+ .filter(Boolean).join("; ");+ return { path, score: bm25 * (1 + CLOSENESS_BOOST * closeness), closeness, reason };+ })+ .sort((a, b) => b.score - a.score || b.closeness - a.closeness || cmp(a.path, b.path));+ for (const r of rest) out.push({ path: r.path, score: round(r.score), reason: r.reason });+ return out.slice(0, limit);+}++/**+ * The issue's text: a file, or stdin for `-`. `stdin` is a parameter so the+ * stream can be replaced under test.+ */+export async function readIssueText(+ arg: string,+ stdin: AsyncIterable<unknown> = process.stdin,+): Promise<string> {+ if (arg !== "-") return readFileSync(arg, "utf8");+ const chunks: Buffer[] = [];+ for await (const chunk of stdin) {+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk, "utf8") : Buffer.from(chunk as Uint8Array));+ }+ return Buffer.concat(chunks).toString("utf8");+}++function unique(items: string[]): string[] {+ return [...new Set(items)];+}++function round(n: number): number {+ return Math.round(n * 1000) / 1000;+}++function cmp(a: string, b: string): number {+ return a < b ? -1 : a > b ? 1 : 0;+}diff --git a/skills/ix/SKILL.md b/skills/ix/SKILL.mdindex 21112044..757f31ff 100644--- a/skills/ix/SKILL.md+++ b/skills/ix/SKILL.md@@ -31,6 +31,7 @@ the backend, and maps the repo. Re-run it per repo.| Step | Command | Example ||---|---|---|| Bounded context to start from | `ix context` | `ix context IngestionService` |+| Start from an issue or bug report | `ix context --from-issue` | `ix context --from-issue issue.md` (or `-` for stdin) || Understand a component | `ix explain` | `ix explain IngestionService` || Trace a flow | `ix trace` | `ix trace user_login_flow` || Blast radius of a change | `ix impact` | `ix impact verify_token` |diff --git a/skills/ix/references/commands.md b/skills/ix/references/commands.mdindex 4cc50c51..e42035eb 100644--- a/skills/ix/references/commands.md+++ b/skills/ix/references/commands.md@@ -23,6 +23,7 @@ These aggregate multiple graph operations into single bounded responses.| Hotspot discovery | `ix rank` | `ix rank --by dependents --kind class --top 10` || One-shot summary | `ix overview` | `ix overview IngestionService` || Deterministic context bundle | `ix context` | `ix context IngestionService` |+| Files to read for an issue, ranked | `ix context --from-issue` | `ix context --from-issue issue.md --format llm` || Scoped entity listing | `ix inventory` | `ix inventory --kind function --path auth.py` |## Finding & Understanding Codediff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.mdindex 6e1cb951..11d43348 100644--- a/skills/ix/references/flags.md+++ b/skills/ix/references/flags.md@@ -189,6 +189,7 @@ Build a bounded, deterministic context bundle for a symbol, file, or entity (or| Flag | Value | Default | Effect ||---|---|---|---|+| `--from-issue` | `<file>` | — | Start from an issue or bug report instead of a target: a file, or `-` for stdin. Resolves the paths and code names it mentions to up to 3 definitions (tests, docs, build output and imports excluded), builds the bundle around the first, and adds a `rankedFiles` list: starting files first, then BM25 against the issue text, nudged by graph closeness. Falls back to the best BM25 file when nothing resolves. Not combinable with a target, `--kind`, `--path`, `--pick` or `--diff` || `--kind` | `<kind>` | — | Filter target entity by kind || `--path` | `<path>` | — | Restrict to symbols from files matching this path substring || `--pick` | `<n>` | — | Pick Nth candidate from ambiguous results (1-based) |