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): deterministic bounded context bundles via ix context (#423)
Alot1z85152eb9895e
diff --git a/ix-cli/src/cli/__tests__/context-investigation.test.ts b/ix-cli/src/cli/__tests__/context-investigation.test.tsnew file mode 100644index 00000000..b10e6737--- /dev/null+++ b/ix-cli/src/cli/__tests__/context-investigation.test.ts@@ -0,0 +1,268 @@+import { existsSync, mkdtempSync, mkdirSync, readdirSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import type {+ ConflictReport,+ DecisionReport,+ GraphEdge,+ GraphNode,+ IntentReport,+ ScoredClaim,+} from "../../client/types.js";+import type { EntityFacts } from "../explain/facts.js";+import {+ buildBundle,+ diffInvestigations,+ loadInvestigation,+ mergeDiffOptions,+ saveInvestigation,+} from "../commands/context.js";++let home: string;++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), "ix-investigation-test-"));+ process.env.IX_HOME = home;+ // IX_HOME is the Ix home directory; investigations live in a subdirectory of+ // it, which saveInvestigation creates. Nothing is pre-created here — the tests+ // below assert on where the code actually writes, not on a directory the test+ // made itself.+});++/** Where saved investigations are expected to live, given IX_HOME. */+const investigationsDir = () => join(home, "investigations");++afterEach(() => {+ delete process.env.IX_HOME;+ rmSync(home, { recursive: true, force: true });+});++function makeFacts(overrides: Partial<EntityFacts> = {}): EntityFacts {+ return {+ id: "entity-1",+ name: "Widget",+ kind: "class",+ members: ["render"],+ memberCount: 1,+ callerCount: 1,+ calleeCount: 1,+ dependentCount: 1,+ importerCount: 0,+ downstreamDependents: 2,+ downstreamDepth: 1,+ topCallers: ["App"],+ topDependents: ["App"],+ historyLength: 2,+ introducedRev: 1,+ stale: false,+ diagnostics: [],+ ...overrides,+ };+}++function makeClaim(statement: string, relevance: number): ScoredClaim {+ return {+ claim: { id: `claim-${statement}`, entityId: "entity-1", statement, status: "active" },+ relevance,+ finalScore: relevance,+ confidence: {+ baseAuthority: { value: 0.5, reason: "base" },+ verification: { value: 0.5, reason: "verify" },+ recency: { value: 0.5, reason: "recent" },+ corroboration: { value: 0.5, reason: "corroborate" },+ conflictPenalty: { value: 0.5, reason: "penalty" },+ intentAlignment: { value: 0.5, reason: "intent" },+ score: 0.5,+ },+ };+}++function makeContext(overrides: Partial<{ nodes: GraphNode[]; edges: GraphEdge[]; claims: ScoredClaim[] }> = {}) {+ return {+ claims: overrides.claims ?? [makeClaim("renders to DOM", 0.9)],+ conflicts: [] as ConflictReport[],+ decisions: [] as DecisionReport[],+ intents: [] as IntentReport[],+ nodes:+ overrides.nodes ??+ ([+ {+ id: "entity-2",+ kind: "method",+ name: "render",+ attrs: {},+ provenance: { sourceUri: "src/widget.ts", extractor: "tree-sitter", sourceType: "source", observedAt: "2026-01-01T00:00:00Z" },+ createdRev: 1,+ createdAt: "2026-01-01T00:00:00Z",+ updatedAt: "2026-01-01T00:00:00Z",+ },+ ] as GraphNode[]),+ edges:+ overrides.edges ??+ ([+ { id: "edge-1", src: "entity-1", dst: "entity-2", predicate: "calls", attrs: {}, createdRev: 1 },+ ] as GraphEdge[]),+ metadata: { query: "Widget", seedEntities: ["entity-1"], hopsExpanded: 1, asOfRev: 1 },+ };+}++function bundleWith(claims: ScoredClaim[], stale = false) {+ return buildBundle({+ resolved: { id: "entity-1", name: "Widget", kind: "class", resolutionMode: "exact" },+ facts: makeFacts({ stale }),+ context: makeContext({ claims }),+ provenance: { sourceType: "source", extractor: "tree-sitter", observedAt: "2026-01-01T00:00:00Z" },+ asOfRev: undefined,+ depth: undefined,+ budgets: { maxEntities: 50, maxRelationships: 100, maxEvidence: 25, maxChars: 12000 },+ });+}++describe("ix context investigation state", () => {+ it("persists and resumes an investigation under ~/.ix/investigations", () => {+ const bundle = bundleWith([makeClaim("renders to DOM", 0.9)]);+ saveInvestigation("widget-check", bundle);++ const loaded = loadInvestigation("widget-check");+ expect(loaded).toBeDefined();+ expect(loaded?.schema).toBe("ix-investigation/1");+ expect(loaded?.bundle.target.name).toBe("Widget");+ expect(loaded?.bundle.evidence).toEqual(bundle.evidence);+ });++ it("writes into an investigations subdirectory of IX_HOME, not its root", () => {+ // IX_HOME is the Ix home itself — it holds config.yaml, bin/, cli/ and+ // dotfiles like .version-check.json. Saved state belongs in a subdirectory+ // of it, not loose among them.+ writeFileSync(join(home, "config.yaml"), "endpoint: http://localhost:8090\n");+ writeFileSync(join(home, ".version-check.json"), JSON.stringify({ latest: "0.9.3" }));++ saveInvestigation("widget-check", bundleWith([makeClaim("renders to DOM", 0.9)]));++ expect(readdirSync(investigationsDir())).toEqual(["widget-check.json"]);+ expect(readdirSync(home).sort()).toEqual([".version-check.json", "config.yaml", "investigations"]);+ });++ it("refuses to resume a missing or malformed investigation", () => {+ expect(loadInvestigation("does-not-exist")).toBeUndefined();+ // The fixture has to sit where the loader actually looks, or this passes+ // because the file is absent rather than because it is malformed — and+ // would keep passing with the JSON guard deleted.+ mkdirSync(investigationsDir(), { recursive: true });+ writeFileSync(join(investigationsDir(), "broken.json"), "not json", "utf8");+ expect(existsSync(join(investigationsDir(), "broken.json"))).toBe(true);+ expect(loadInvestigation("broken")).toBeUndefined();+ });++ it("refuses to save a bundle that does not match the versioned contract", () => {+ const malformed = { ...bundleWith([]), entities: "not-an-array" } as unknown as ReturnType<typeof buildBundle>;+ saveInvestigation("bad-shape", malformed);+ expect(loadInvestigation("bad-shape")).toBeUndefined();+ expect(existsSync(join(investigationsDir(), "bad-shape.json"))).toBe(false);+ });++ it("computes a deterministic delta between saved and fresh state", () => {+ const saved = bundleWith([makeClaim("renders to DOM", 0.9)]);+ saveInvestigation("widget-check", saved);+ const stored = loadInvestigation("widget-check")!;++ // Fresh state: one extra entity + one new claim; one relationship removed.+ const fresh = buildBundle({+ resolved: { id: "entity-1", name: "Widget", kind: "class", resolutionMode: "exact" },+ facts: makeFacts(),+ context: makeContext({+ claims: [makeClaim("renders to DOM", 0.9), makeClaim("mounts to DOM", 0.7)],+ nodes: [+ {+ id: "entity-2",+ kind: "method",+ name: "render",+ attrs: {},+ provenance: { sourceUri: "src/widget.ts", extractor: "tree-sitter", sourceType: "source", observedAt: "2026-01-01T00:00:00Z" },+ createdRev: 1,+ createdAt: "2026-01-01T00:00:00Z",+ updatedAt: "2026-01-01T00:00:00Z",+ },+ {+ id: "entity-3",+ kind: "method",+ name: "mount",+ attrs: {},+ provenance: { sourceUri: "src/widget.ts", extractor: "tree-sitter", sourceType: "source", observedAt: "2026-01-01T00:00:00Z" },+ createdRev: 2,+ createdAt: "2026-01-01T00:00:00Z",+ updatedAt: "2026-01-01T00:00:00Z",+ },+ ],+ }),+ provenance: { sourceType: "source", extractor: "tree-sitter", observedAt: "2026-01-01T00:00:00Z" },+ asOfRev: undefined,+ depth: undefined,+ budgets: { maxEntities: 50, maxRelationships: 100, maxEvidence: 25, maxChars: 12000 },+ });++ const diff = diffInvestigations(stored, fresh);++ expect(diff.schema).toBe("ix-investigation-diff/1");+ expect(diff.investigation).toBe("widget-check");+ expect(diff.added.entities.map((e) => e.id)).toContain("entity-3");+ expect(diff.removed.entities).toHaveLength(0);+ expect(diff.added.claims.map((c) => c.id)).toContain("claim-mounts to DOM");+ expect(diff.removed.claims).toHaveLength(0);++ const { generatedAt: _g, ...diffStatic } = diff;+ expect(diffStatic).toEqual({ ...diffStatic });+ });++ it("surfaces staleness changes in the delta", () => {+ const saved = bundleWith([makeClaim("renders to DOM", 0.9)], false);+ saveInvestigation("widget-check", saved);+ const stored = loadInvestigation("widget-check")!;+ const fresh = bundleWith([makeClaim("renders to DOM", 0.9)], true);++ const diff = diffInvestigations(stored, fresh);+ expect(diff.freshness.previous.classification).toBe("current");+ expect(diff.freshness.current.classification).toBe("stale");+ });++ it("preserves saved revision and depth for --diff unless explicitly overridden", () => {+ const bundle = bundleWith([makeClaim("renders to DOM", 0.9)]);+ bundle.metadata.asOfRev = 7;+ bundle.metadata.depth = "2";+ saveInvestigation("widget-check", bundle);+ const stored = loadInvestigation("widget-check")!;++ expect(mergeDiffOptions(stored, {})).toEqual({ asOfRev: "7", depth: "2" });+ expect(mergeDiffOptions(stored, { asOfRev: "3" })).toEqual({ asOfRev: "3", depth: "2" });+ expect(mergeDiffOptions(stored, { depth: "4" })).toEqual({ asOfRev: "7", depth: "4" });+ expect(mergeDiffOptions(stored, { asOfRev: "3", depth: "4" })).toEqual({ asOfRev: "3", depth: "4" });+ });++ it("never collides or escapes for hostile investigation ids", () => {+ const a = bundleWith([makeClaim("renders to DOM", 0.9)]);+ const b = bundleWith([makeClaim("mounts to DOM", 0.9)]);+ saveInvestigation("a/b", a);+ saveInvestigation("a?b", b);+ saveInvestigation("../../escape", a);+ saveInvestigation(".version-check", b);++ expect(loadInvestigation("a/b")?.bundle.evidence).toEqual(a.evidence);+ expect(loadInvestigation("a?b")?.bundle.evidence).toEqual(b.evidence);+ expect(loadInvestigation("../../escape")?.bundle.target.name).toBe("Widget");+ expect(loadInvestigation(".version-check")?.bundle.evidence).toEqual(b.evidence);++ // Every hostile id lands as one single-segment file inside the+ // investigations directory; nothing is written outside it, and nothing+ // becomes a dotfile that could shadow real Ix state.+ const jsonFiles = readdirSync(investigationsDir()).filter((f) => f.endsWith(".json"));+ expect(jsonFiles).toHaveLength(4);+ for (const f of jsonFiles) {+ expect(f).not.toContain("/");+ expect(f.startsWith(".")).toBe(false);+ }+ expect(existsSync(join(home, "..", "escape.json"))).toBe(false);+ expect(existsSync(join(home, ".version-check.json"))).toBe(false);+ });+});diff --git a/ix-cli/src/cli/__tests__/context.test.ts b/ix-cli/src/cli/__tests__/context.test.tsnew file mode 100644index 00000000..ee472d56--- /dev/null+++ b/ix-cli/src/cli/__tests__/context.test.ts@@ -0,0 +1,268 @@+import { describe, expect, it } from "vitest";++import type {+ ConflictReport,+ DecisionReport,+ GraphEdge,+ GraphNode,+ IntentReport,+ ScoredClaim,+} from "../../client/types.js";+import type { EntityFacts } from "../explain/facts.js";+import { buildBundle, sanitizeId } from "../commands/context.js";++function makeFacts(overrides: Partial<EntityFacts> = {}): EntityFacts {+ return {+ id: "entity-1",+ name: "Widget",+ kind: "class",+ members: ["render", "mount"],+ memberCount: 2,+ callerCount: 3,+ calleeCount: 2,+ dependentCount: 4,+ importerCount: 1,+ downstreamDependents: 6,+ downstreamDepth: 2,+ topCallers: ["App", "Panel", "Shell"],+ topDependents: ["App", "Panel", "Shell", "Frame"],+ historyLength: 5,+ introducedRev: 3,+ stale: false,+ diagnostics: [],+ ...overrides,+ };+}++function makeClaim(statement: string, relevance: number): ScoredClaim {+ return {+ claim: { id: `claim-${statement}`, entityId: "entity-1", statement, status: "active" },+ relevance,+ finalScore: relevance,+ confidence: {+ baseAuthority: { value: 0.5, reason: "base" },+ verification: { value: 0.5, reason: "verify" },+ recency: { value: 0.5, reason: "recent" },+ corroboration: { value: 0.5, reason: "corroborate" },+ conflictPenalty: { value: 0.5, reason: "penalty" },+ intentAlignment: { value: 0.5, reason: "intent" },+ score: 0.5,+ },+ };+}++function makeContext(overrides: Partial<{+ claims: ScoredClaim[];+ conflicts: ConflictReport[];+ decisions: DecisionReport[];+ intents: IntentReport[];+ nodes: GraphNode[];+ edges: GraphEdge[];+}> = {}) {+ return {+ claims: overrides.claims ?? [makeClaim("renders to DOM", 0.9)],+ conflicts: overrides.conflicts ?? [],+ decisions: overrides.decisions ?? [],+ intents: overrides.intents ?? [],+ nodes:+ overrides.nodes ??+ ([+ {+ id: "entity-2",+ kind: "method",+ name: "render",+ attrs: {},+ provenance: { sourceUri: "src/widget.ts", extractor: "tree-sitter", sourceType: "source", observedAt: "2026-01-01T00:00:00Z" },+ createdRev: 3,+ createdAt: "2026-01-01T00:00:00Z",+ updatedAt: "2026-01-01T00:00:00Z",+ },+ ] as GraphNode[]),+ edges:+ overrides.edges ??+ ([+ { id: "edge-1", src: "entity-1", dst: "entity-2", predicate: "calls", attrs: {}, createdRev: 3 },+ ] as GraphEdge[]),+ metadata: { query: "Widget", seedEntities: ["entity-1"], hopsExpanded: 1, asOfRev: 3 },+ };+}++function input() {+ return {+ resolved: { id: "entity-1", name: "Widget", kind: "class", resolutionMode: "exact" },+ facts: makeFacts(),+ context: makeContext(),+ provenance: { sourceType: "source", extractor: "tree-sitter", observedAt: "2026-01-01T00:00:00Z" },+ asOfRev: undefined,+ depth: undefined,+ budgets: { maxEntities: 50, maxRelationships: 100, maxEvidence: 25, maxChars: 12000 },+ };+}++describe("ix context bundle", () => {+ it("is deterministic for identical input apart from the declared timestamp", () => {+ const first = buildBundle(input());+ const second = buildBundle(input());++ // The only permitted time-dependent field.+ expect(first.generatedAt).toBeTypeOf("string");+ const { generatedAt: _g1, ...firstStatic } = first;+ const { generatedAt: _g2, ...secondStatic } = second;+ expect(firstStatic).toEqual(secondStatic);+ });++ it("orders evidence by the deterministic tier and a stable id tiebreaker", () => {+ const bundle = buildBundle(input());+ const scores = bundle.evidence.map((item) => item.score);++ expect(scores).toEqual([...scores].sort((a, b) => a - b));+ // The resolved target is the most relevant item.+ expect(bundle.evidence[0]?.kind).toBe("target");+ // Direct structural facts rank above context claims.+ expect(bundle.evidence[1]?.kind).toBe("structural");+ const claimItem = bundle.evidence.find((item) => item.kind === "claim");+ expect(claimItem?.source).toBe("context.claims");+ });++ it("enforces budgets and reports explicit truncation", () => {+ const bundle = buildBundle({+ ...input(),+ budgets: { maxEntities: 1, maxRelationships: 0, maxEvidence: 2, maxChars: 12000 },+ });++ expect(bundle.entities).toHaveLength(1);+ expect(bundle.truncation.entitiesTruncated).toBeGreaterThan(0);+ expect(bundle.relationships).toHaveLength(0);+ expect(bundle.truncation.relationshipsTruncated).toBe(1);+ expect(bundle.evidence.length).toBeLessThanOrEqual(2);+ expect(bundle.truncation.evidenceTruncated).toBeGreaterThanOrEqual(0);+ });++ it("asks about each entity's own staleness instead of copying the target's", () => {+ // `freshness` is the target's, from the facts collector. Every other entity+ // has its own source file and its own answer — stamping the target's onto+ // all of them reported untouched dependencies as stale whenever the target+ // was, which is the field an agent reads to decide what to trust.+ const asked: string[] = [];+ const bundle = buildBundle({+ ...input(),+ facts: makeFacts({ stale: true, path: "src/widget.ts" }),+ isStale: (path) => {+ asked.push(path);+ return false; // the dependency is current even though the target is not+ },+ });++ const target = bundle.entities.find((e) => e.id === "entity-1");+ const dependency = bundle.entities.find((e) => e.id === "entity-2");+ expect(target?.stale).toBe(true);+ expect(dependency?.stale).toBe(false);+ expect(bundle.freshness).toEqual({ stale: true, classification: "stale" });+ // The target is not re-probed; its answer was already collected.+ expect(asked).toEqual(["src/widget.ts"]);+ });++ it("probes no more entities than the budget keeps", () => {+ const nodes = Array.from({ length: 40 }, (_, i) => ({+ id: `n-${i}`,+ kind: "method",+ name: `m${i}`,+ attrs: {},+ provenance: { sourceUri: `src/f${i}.ts`, extractor: "tree-sitter", sourceType: "source", observedAt: "2026-01-01T00:00:00Z" },+ createdRev: 1,+ createdAt: "2026-01-01T00:00:00Z",+ updatedAt: "2026-01-01T00:00:00Z",+ })) as GraphNode[];+ let probes = 0;++ buildBundle({+ ...input(),+ context: makeContext({ nodes }),+ budgets: { maxEntities: 5, maxRelationships: 100, maxEvidence: 25, maxChars: 12000 },+ isStale: () => { probes += 1; return false; },+ });++ // 5 kept, minus the target whose answer is already known.+ expect(probes).toBe(4);+ });++ it("classifies staleness from the collected facts", () => {+ const stale = buildBundle({ ...input(), facts: makeFacts({ stale: true }) });+ expect(stale.freshness).toEqual({ stale: true, classification: "stale" });++ const current = buildBundle({ ...input(), facts: makeFacts({ stale: false }) });+ expect(current.freshness).toEqual({ stale: false, classification: "current" });+ });++ it("orders claims, decisions, conflicts, and intents deterministically", () => {+ const decisions: DecisionReport[] = [+ { title: "zeta", rationale: "late", entityId: "entity-1", rev: 1 },+ { title: "alpha", rationale: "second", entityId: "entity-1", rev: 1 },+ { title: "alpha", rationale: "first", entityId: "entity-1", rev: 2 },+ ];+ const conflicts: ConflictReport[] = [+ { id: "c-1", claimA: "zeta claim", claimB: "delta claim", reason: "r", recommendation: "rec" },+ { id: "c-2", claimA: "alpha claim", claimB: "beta claim", reason: "r", recommendation: "rec" },+ ];+ const intents: IntentReport[] = [+ { id: "i-2", statement: "zeta intent", status: "active", confidence: 0.5 },+ { id: "i-1", statement: "alpha intent", status: "active", confidence: 0.5 },+ ];+ const claims = [makeClaim("zeta statement", 0.5), makeClaim("alpha one", 0.9), makeClaim("alpha two", 0.7)];+ const shuffled = {+ claims: [...claims].reverse(),+ conflicts: [...conflicts].reverse(),+ decisions: [...decisions].reverse(),+ intents: [...intents].reverse(),+ };++ const first = buildBundle({ ...input(), context: makeContext(shuffled) });+ const second = buildBundle({ ...input(), context: makeContext({ ...shuffled }) });++ expect(first.claims.map((c) => c.statement)).toEqual(["alpha one", "alpha two", "zeta statement"]);+ expect(first.decisions.map((d) => d.title)).toEqual(["alpha", "alpha", "zeta"]);+ expect(first.conflicts.map((c) => c.claimA)).toEqual(["alpha claim", "zeta claim"]);+ expect(first.intents.map((i) => i.statement)).toEqual(["alpha intent", "zeta intent"]);+ // Same data in any input order produces the same bundle sections.+ expect(second.claims).toEqual(first.claims);+ expect(second.decisions).toEqual(first.decisions);+ expect(second.conflicts).toEqual(first.conflicts);+ expect(second.intents).toEqual(first.intents);+ });++ it("bounds evidence by the exact serialized representation, not an estimate", () => {+ const claims = Array.from({ length: 60 }, (_, i) => makeClaim(`statement number ${i} with some padding text`, 0.5));+ const budgets = { maxEntities: 50, maxRelationships: 100, maxEvidence: 25, maxChars: 500 };++ const bundle = buildBundle({ ...input(), context: makeContext({ claims }), budgets });++ // maxChars bounds the sum of the serialized JSON sizes of the kept items.+ const keptSerialized = bundle.evidence.reduce((sum, item) => sum + JSON.stringify(item).length, 0);+ expect(keptSerialized).toBeLessThanOrEqual(500);+ expect(bundle.evidence.length).toBeLessThan(25); // the char budget bit before the count budget+ expect(bundle.truncation.evidenceTruncated).toBeGreaterThan(0);+ expect(bundle.truncation.charactersTruncated).toBeGreaterThan(0);+ // Identical inputs produce an identical budgeted list.+ expect(bundle.evidence).toEqual(+ buildBundle({ ...input(), context: makeContext({ claims }), budgets }).evidence,+ );+ });++ it("encodes investigation ids injectively so distinct ids never collide", () => {+ expect(sanitizeId("widget-check")).toBe("widget-check");+ expect(sanitizeId("a/b")).not.toBe(sanitizeId("a?b"));+ expect(sanitizeId("a/b")).not.toBe(sanitizeId("a:b"));+ expect(sanitizeId("a?b")).not.toBe(sanitizeId("a~2Fb"));+ expect(sanitizeId("~")).toBe("~7E");+ expect(sanitizeId("../../etc/passwd")).not.toContain("/");+ expect(sanitizeId("C:\\Windows")).not.toContain("\\");+ expect(sanitizeId("")).toBe("unnamed");+ // No id may produce a dotfile, and encoding the dot only in first position+ // keeps the mapping injective.+ expect(sanitizeId(".version-check")).toBe("~2Eversion-check");+ expect(sanitizeId(".version-check")).not.toBe(sanitizeId("~2Eversion-check"));+ expect(sanitizeId("a.b")).toBe("a.b");+ const names = ["a/b", "a?b", "a:b", "a~2Fb", "C:\\Windows", "../..", "~"].map(sanitizeId);+ expect(new Set(names).size).toBe(names.length);+ });+});diff --git a/ix-cli/src/cli/__tests__/mcp.test.ts b/ix-cli/src/cli/__tests__/mcp.test.tsindex 0416fcef..6eed589b 100644--- a/ix-cli/src/cli/__tests__/mcp.test.ts+++ b/ix-cli/src/cli/__tests__/mcp.test.ts@@ -28,6 +28,34 @@ async function connect(runIx: IxRunner, proAvailable = false): Promise<Client> {return client;}+/**+ * A complete `ix-context-bundle/1`.+ *+ * `ix_context` declares an outputSchema, and the MCP SDK validates+ * structuredContent against it, so any stub short of a whole bundle comes back+ * as an output-validation error rather than a result. Tests that only meant to+ * assert on argv still need a valid one.+ */+function contextBundle() {+ return {+ schema: "ix-context-bundle/1",+ generatedAt: "2026-01-01T00:00:00Z",+ target: { id: "e1", name: "Widget", kind: "class", resolutionMode: "exact" },+ entities: [{ id: "e1", name: "Widget", kind: "class", stale: false }],+ relationships: [],+ claims: [],+ decisions: [],+ conflicts: [],+ intents: [],+ provenance: {},+ freshness: { stale: false, classification: "current" },+ evidence: [],+ budgets: { maxEntities: 50, maxRelationships: 100, maxEvidence: 25, maxChars: 12000 },+ truncation: { entitiesTruncated: 0, relationshipsTruncated: 0, evidenceTruncated: 0, charactersTruncated: 0 },+ metadata: { rankingRule: "deterministic-tier" },+ };+}+describe("ix mcp", () => {it("exposes only the OSS catalog when Pro is not installed", async () => {const client = await connect(async () => ({ ok: true, stdout: "ok", stderr: "" }));@@ -79,6 +107,88 @@ describe("ix mcp", () => {expect(result.content).toEqual([{ type: "text", text: "match name=Widget" }]);});+ it("forwards ix_context target and bounded budgets as the CLI contract", async () => {+ const calls: string[][] = [];+ const client = await connect(async (args) => {+ calls.push(args);+ // A whole bundle, not `{schema}` alone: ix_context declares an+ // outputSchema, and the SDK rejects structuredContent that does not match+ // it. Stubbing a partial bundle made this pass on a tool call that had+ // actually returned isError with an output-validation failure.+ return { ok: true, stdout: JSON.stringify(contextBundle()), stderr: "" };+ });++ const result = await client.callTool({+ name: "ix_context",+ arguments: { target: "Widget", max_entities: 20, max_evidence: 5 },+ });++ expect(result.isError).toBeFalsy();+ expect(calls).toEqual([+ ["context", "--max-entities=20", "--max-evidence=5", "--format=json", "--", "Widget"],+ ]);+ });++ it("surfaces an output-schema violation instead of passing it off as a result", async () => {+ // The guard the test above used to lack: a bundle missing required fields+ // must not reach the caller looking like a successful call.+ const client = await connect(async () => ({+ ok: true,+ stdout: JSON.stringify({ schema: "ix-context-bundle/1" }),+ stderr: "",+ }));++ const result = await client.callTool({ name: "ix_context", arguments: { target: "Widget" } });++ expect(result.isError).toBe(true);+ });++ it("forwards ix_context max_chars to the CLI contract", async () => {+ const calls: string[][] = [];+ const client = await connect(async (args) => {+ calls.push(args);+ return { ok: true, stdout: JSON.stringify(contextBundle()), stderr: "" };+ });++ const result = await client.callTool({ name: "ix_context", arguments: { target: "Widget", max_evidence: 3, max_chars: 5000 } });++ expect(result.isError).toBeFalsy();+ expect(calls).toEqual([["context", "--max-evidence=3", "--max-chars=5000", "--format=json", "--", "Widget"]]);+ });++ it("returns ix_context structuredContent with the parsed bundle", async () => {+ const bundle = contextBundle();+ const client = await connect(async () => ({ ok: true, stdout: JSON.stringify(bundle), stderr: "" }));++ const result = await client.callTool({ name: "ix_context", arguments: { target: "Widget" } });++ expect(result.structuredContent).toEqual(bundle);+ expect(result.content).toEqual([{ type: "text", text: JSON.stringify(bundle) }]);+ });++ it("marks an unparseable bundle output as an MCP error", async () => {+ const client = await connect(async () => ({ ok: true, stdout: "not json at all", stderr: "" }));++ const result = await client.callTool({ name: "ix_context", arguments: { target: "Widget" } });++ expect(result.isError).toBe(true);+ expect(result.structuredContent).toBeUndefined();+ expect(result.content).toEqual([{ type: "text", text: "not json at all" }]);+ });++ it("omits unset context budgets rather than sending empty flags", async () => {+ const calls: string[][] = [];+ const client = await connect(async (args) => {+ calls.push(args);+ return { ok: true, stdout: JSON.stringify(contextBundle()), stderr: "" };+ });++ const result = await client.callTool({ name: "ix_context", arguments: { target: "src/main.ts" } });++ expect(result.isError).toBeFalsy();+ expect(calls).toEqual([["context", "--format=json", "--", "src/main.ts"]]);+ });+it("marks Ix command failures as MCP errors", async () => {const client = await connect(async () => ({ok: false,diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.tsnew file mode 100644index 00000000..d2ee39bb--- /dev/null+++ b/ix-cli/src/cli/commands/context.ts@@ -0,0 +1,827 @@+import type { Command } from "commander";+import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";+import { homedir } from "node:os";+import { dirname, join, resolve } from "node:path";++import { contextBundleSchema } from "../context-bundle-schema.js";++import { IxClient } from "../../client/api.js";+import type {+ ConflictReport,+ DecisionReport,+ GraphNode,+ IntentReport,+ StructuredContext,+} from "../../client/types.js";+import { getEndpoint } from "../config.js";+import { collectFacts, type EntityFacts } from "../explain/facts.js";+import { printLlmLines } from "../llm.js";+import { resolveFileOrEntity } from "../resolve.js";+import { createStaleProbe } from "../stale.js";+import { renderNote, renderSection, renderWarning } from "../ui.js";++/**+ * Schema version for the deterministic bundle shape. Bump only on a breaking+ * shape change, never per run.+ */+const BUNDLE_SCHEMA = "ix-context-bundle/1";++interface ContextOptions {+ kind?: string;+ path?: string;+ pick?: string;+ depth?: string;+ asOfRev?: string;+ maxEntities?: string;+ maxRelationships?: string;+ maxEvidence?: string;+ maxChars?: string;+ out?: string;+ save?: string;+ resume?: string;+ diff?: string;+ format: string;+}++/** Stable evidence kinds, ordered by relevance tier (lower is more relevant). */+type EvidenceKind =+ | "target"+ | "structural"+ | "claim"+ | "decision"+ | "conflict"+ | "intent"+ | "relationship"+ | "provenance";++interface EvidenceItem {+ id: string;+ kind: EvidenceKind;+ source: string;+ title: string;+ /** Deterministic relevance score: tier plus a stable tiebreaker. */+ score: number;+ reason: string;+ refs: string[];+}++interface ContextBundle {+ schema: typeof BUNDLE_SCHEMA;+ /** The one explicitly declared time-dependent field. */+ generatedAt: string;+ target: { id: string; name: string; kind: string; resolutionMode: string };+ entities: Array<{ id: string; name: string; kind: string; path?: string; stale: boolean }>;+ relationships: Array<{ src: string; dst: string; predicate: string }>;+ claims: Array<{ id: string; entityId: string; statement: string; status: string }>;+ decisions: DecisionReport[];+ conflicts: ConflictReport[];+ intents: IntentReport[];+ provenance: {+ sourceUri?: string;+ sourceHash?: string;+ extractor?: string;+ sourceType?: string;+ observedAt?: string;+ introducedRev?: number;+ historyLength: number;+ stale: boolean;+ };+ freshness: { stale: boolean; classification: "current" | "stale" | "unverified" };+ evidence: EvidenceItem[];+ budgets: { maxEntities: number; maxRelationships: number; maxEvidence: number; maxChars: number };+ truncation: {+ entitiesTruncated: number;+ relationshipsTruncated: number;+ evidenceTruncated: number;+ charactersTruncated: number;+ };+ metadata: {+ asOfRev?: number;+ depth?: string;+ rankingRule: "deterministic-tier";+ };+}++/**+ * Build a bounded, deterministic context bundle for one target.+ *+ * This composes Ix's existing intelligence rather than re-deriving it: the+ * target is resolved through the same resolver as `ix explain`, structural+ * facts come from the same collector, and claims/conflicts/decisions/intents+ * come from the same `/v1/context` service. The only new thing here is the+ * bundling, budgeting, and deterministic ranking.+ */+export function registerContextCommand(program: Command): void {+ program+ .command("context [target]")+ .description(+ "Build a bounded, deterministic context bundle for a symbol, file, or entity (or resume/diff a saved investigation without a target)",+ )+ .option("--kind <kind>", "Filter target entity by kind")+ .option("--path <path>", "Prefer symbols from files matching this path substring")+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")+ .option("--depth <depth>", "Context-graph expansion depth")+ .option("--as-of-rev <n>", "Historical context as of a graph revision")+ .option("--max-entities <n>", "Maximum entities in the bundle", "50")+ .option("--max-relationships <n>", "Maximum relationships in the bundle", "100")+ .option("--max-evidence <n>", "Maximum evidence items in the bundle", "25")+ .option("--max-chars <n>", "Maximum characters of evidence output", "12000")+ .option("--format <fmt>", "Output format (text|json|llm)", "text")+ .option("--out <path>", "Write the JSON bundle to this file instead of stdout")+ .option("--save <id>", "Persist the bundle as a resumable investigation state")+ .option("--resume <id>", "Render a saved investigation state without a backend")+ .option("--diff <id>", "Diff a saved investigation against a fresh build of the same target")+ .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",+ )+ .action(async (target: string | undefined, opts: ContextOptions) => {+ if (opts.resume) {+ renderSavedInvestigation(opts.resume, opts.format);+ return;+ }+ if (opts.diff) {+ const saved = loadInvestigation(opts.diff);+ if (!saved) return;+ const fresh = await buildFreshBundle(+ target ?? saved.bundle.target.name,+ { ...opts, ...mergeDiffOptions(saved, opts) },+ saved.bundle.budgets,+ );+ if (!fresh) return;+ renderInvestigationDiff(saved, fresh, opts.format);+ return;+ }+ if (!target) {+ renderWarning("ix context requires a target unless --resume <id> or --diff <id> is given.");+ return;+ }++ const client = new IxClient(getEndpoint());++ const resolved = await resolveFileOrEntity(client, target, {+ kind: opts.kind,+ path: opts.path,+ pick: opts.pick ? parseInt(opts.pick, 10) : undefined,+ });+ if (!resolved) return;++ const asOfRev = opts.asOfRev ? parseInt(opts.asOfRev, 10) : undefined;+ const maxEntities = clampInt(opts.maxEntities, 1, 500, 50);+ const maxRelationships = clampInt(opts.maxRelationships, 1, 1000, 100);+ const maxEvidence = clampInt(opts.maxEvidence, 1, 200, 25);+ const maxChars = clampInt(opts.maxChars, 1000, 1_000_000, 12_000);++ const [facts, context, provenance] = await Promise.all([+ collectFacts(client, resolved.id, resolved.name, resolved.kind),+ client.query(resolved.name, {+ asOfRev,+ depth: opts.depth,+ }),+ client.provenance(resolved.id),+ ]);++ const bundle = buildBundle({+ resolved,+ facts,+ context,+ provenance,+ asOfRev,+ depth: opts.depth,+ budgets: { maxEntities, maxRelationships, maxEvidence, maxChars },+ });++ 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") {+ renderWarning("--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) {+ renderWarning(`--out "${out}" refused: the bundle does not match the ${BUNDLE_SCHEMA} schema (${parsed.error.issues.length} issue(s)).`);+ 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 {+ if (fs.statSync(targetPath).isDirectory()) {+ renderWarning(`--out "${out}" is a directory; refusing to write the bundle there.`);+ return;+ }+ } catch { /* target may not exist; fall through to rethrow */ }+ }+ 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,+ opts: { kind?: string; path?: string; pick?: string; depth?: string; asOfRev?: string },+ budgets: { maxEntities: number; maxRelationships: number; maxEvidence: number; maxChars: number },+): Promise<ContextBundle | undefined> {+ const client = new IxClient(getEndpoint());+ const resolved = await resolveFileOrEntity(client, target, {+ kind: opts.kind,+ path: opts.path,+ pick: opts.pick ? parseInt(opts.pick, 10) : undefined,+ });+ if (!resolved) return undefined;++ const asOfRev = opts.asOfRev ? parseInt(opts.asOfRev, 10) : undefined;+ const [facts, context, provenance] = await Promise.all([+ collectFacts(client, resolved.id, resolved.name, resolved.kind),+ client.query(resolved.name, { asOfRev, depth: opts.depth }),+ client.provenance(resolved.id),+ ]);++ return buildBundle({ resolved, facts, context, provenance, asOfRev, depth: opts.depth, budgets });+}+}+++/** Saved investigation state lives under ~/.ix/investigations. */+function investigationDir(): string {+ // IX_HOME is the Ix home *directory*, not the investigations directory —+ // backend-status.ts, docker.ts and upgrade.ts all read it as `IX_HOME ||+ // ~/.ix` and then join their own subdirectory onto it. Putting the subdirectory+ // only in the fallback made the two branches disagree: with IX_HOME set, saved+ // investigations landed loose in the Ix home beside config.yaml, bin/ and cli/,+ // and `investigations/` was never created at all.+ return join(process.env.IX_HOME || join(homedir(), ".ix"), "investigations");+}++function investigationPath(id: string): string {+ return join(investigationDir(), `${sanitizeId(id)}.json`);+}++/**+ * Encode an investigation id into a filesystem-safe file name, injectively.+ *+ * `[A-Za-z0-9._-]` passes through unchanged; every other UTF-16 code unit —+ * including the escape marker `~` itself — is hex-encoded as `~HH`. Two+ * different logical ids can therefore never map to the same file, and a raw+ * `~` in user input cannot be confused with an encoding: `a/b`, `a?b`, and+ * `a~2Fb` all land in distinct, single-segment files under the investigation+ * directory instead of silently colliding or escaping it.+ *+ * A leading `.` is encoded too, so no id can produce a dotfile. `.` is otherwise+ * an ordinary character here, and encoding it only in first position keeps the+ * mapping injective: `.a` becomes `~2Ea`, which no other id can also produce.+ */+export function sanitizeId(id: string): string {+ let out = "";+ for (const ch of id) {+ out += /[A-Za-z0-9._-]/.test(ch) ? ch : `~${ch.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`;+ }+ if (out.startsWith(".")) out = `~2E${out.slice(1)}`;+ return out || "unnamed";+}++export function saveInvestigation(id: string, bundle: ContextBundle): void {+ const dir = investigationDir();+ mkdirSync(dir, { recursive: true });+ // Refuse to persist a bundle that does not match the versioned contract:+ // network-derived investigation state is validated before it reaches disk+ // (CodeQL js/network-data-written-to-file).+ const parsed = contextBundleSchema.safeParse(bundle);+ if (!parsed.success) {+ renderWarning(`Refusing to save investigation "${id}": the bundle does not match the ${BUNDLE_SCHEMA} schema (${parsed.error.issues.length} issue(s)).`);+ return;+ }+ const state = {+ schema: "ix-investigation/1",+ id: sanitizeId(id),+ savedAt: new Date().toISOString(),+ bundle: parsed.data,+ };+ // Atomic write (temp + rename in the same directory), matching the config+ // writer, so a saved investigation is never partially written (CodeQL+ // js/file-system-race).+ const path = investigationPath(id);+ const tmpPath = join(dirname(path), `.${process.pid}.${Date.now().toString(36)}.tmp`);+ writeFileSync(tmpPath, JSON.stringify(state, null, 2) + "\n", "utf8");+ try {+ renameSync(tmpPath, path);+ } catch (err) {+ try { rmSync(tmpPath, { force: true }); } catch { /* best effort */ }+ throw err;+ }+}++interface SavedInvestigation {+ schema: string;+ id: string;+ savedAt: string;+ bundle: ContextBundle;+}++/**+ * Carry the saved investigation's revision and depth into a fresh `--diff`+ * build unless the caller explicitly overrides them, so a plain+ * `ix context --diff <id>` compares like-for-like instead of silently+ * re-basing the saved state onto current HEAD.+ */+export function mergeDiffOptions(+ saved: SavedInvestigation,+ opts: { asOfRev?: string; depth?: string },+): { asOfRev?: string; depth?: string } {+ const savedRev = saved.bundle.metadata.asOfRev;+ return {+ asOfRev: opts.asOfRev ?? (savedRev === undefined ? undefined : String(savedRev)),+ depth: opts.depth ?? saved.bundle.metadata.depth,+ };+}++export function loadInvestigation(id: string): SavedInvestigation | undefined {+ const path = investigationPath(id);+ if (!existsSync(path)) {+ renderWarning(`No saved investigation "${id}" at ${path}`);+ return undefined;+ }+ try {+ const parsed = JSON.parse(readFileSync(path, "utf8")) as SavedInvestigation;+ if (parsed.schema !== "ix-investigation/1" || !parsed.bundle) {+ renderWarning(`Saved investigation "${id}" has an unknown schema; refusing to resume.`);+ return undefined;+ }+ return parsed;+ } catch {+ renderWarning(`Saved investigation "${id}" is not valid JSON; refusing to resume.`);+ return undefined;+ }+}++function renderSavedInvestigation(id: string, format: string): void {+ const saved = loadInvestigation(id);+ if (!saved) return;+ if (format === "json") {+ console.log(JSON.stringify(saved, null, 2));+ return;+ }+ renderNote(`Resumed investigation "${saved.id}" saved ${saved.savedAt}`);+ renderBundle(saved.bundle, format);+}++export function diffInvestigations(saved: SavedInvestigation, fresh: ContextBundle): InvestigationDiff {+ const prev = saved.bundle;+ const addedEntities = fresh.entities.filter((e) => !prev.entities.some((p) => p.id === e.id));+ const removedEntities = prev.entities.filter((p) => !fresh.entities.some((e) => e.id === p.id));+ const addedRelationships = fresh.relationships.filter(+ (r) => !prev.relationships.some((p) => p.src === r.src && p.dst === r.dst && p.predicate === r.predicate),+ );+ const removedRelationships = prev.relationships.filter(+ (p) => !fresh.relationships.some((r) => r.src === p.src && r.dst === p.dst && r.predicate === p.predicate),+ );+ const addedEvidence = fresh.evidence.filter((e) => !prev.evidence.some((p) => p.id === e.id));+ const removedEvidence = prev.evidence.filter((p) => !fresh.evidence.some((e) => e.id === p.id));+ const addedClaims = fresh.claims.filter((c) => !prev.claims.some((p) => p.id === c.id));+ const removedClaims = prev.claims.filter((p) => !fresh.claims.some((c) => c.id === p.id));++ return {+ schema: "ix-investigation-diff/1",+ investigation: saved.id,+ savedAt: saved.savedAt,+ generatedAt: new Date().toISOString(),+ target: fresh.target,+ freshness: { previous: prev.freshness, current: fresh.freshness },+ added: {+ entities: addedEntities,+ relationships: addedRelationships,+ evidence: addedEvidence,+ claims: addedClaims,+ },+ removed: {+ entities: removedEntities,+ relationships: removedRelationships,+ evidence: removedEvidence,+ claims: removedClaims,+ },+ };+}++interface InvestigationDiff {+ schema: string;+ investigation: string;+ savedAt: string;+ generatedAt: string;+ target: ContextBundle["target"];+ freshness: { previous: ContextBundle["freshness"]; current: ContextBundle["freshness"] };+ added: { entities: ContextBundle["entities"]; relationships: ContextBundle["relationships"]; evidence: EvidenceItem[]; claims: ContextBundle["claims"] };+ removed: { entities: ContextBundle["entities"]; relationships: ContextBundle["relationships"]; evidence: EvidenceItem[]; claims: ContextBundle["claims"] };+}++function renderInvestigationDiff(saved: SavedInvestigation, fresh: ContextBundle, format: string): void {+ const prev = saved.bundle;+ const diff = diffInvestigations(saved, fresh);++ if (format === "json") {+ console.log(JSON.stringify(diff, null, 2));+ return;+ }++ renderSection(`Investigation diff: ${saved.id}`);+ console.log(` freshness: ${prev.freshness.classification} -> ${fresh.freshness.classification}`);+ console.log(` entities: -${diff.removed.entities.length} +${diff.added.entities.length}`);+ console.log(` relationships: -${diff.removed.relationships.length} +${diff.added.relationships.length}`);+ console.log(` evidence: -${diff.removed.evidence.length} +${diff.added.evidence.length}`);+ console.log(` claims: -${diff.removed.claims.length} +${diff.added.claims.length}`);+ if (diff.added.entities.length > 0) {+ renderSection("Added entities");+ for (const e of diff.added.entities) console.log(` ${e.name} (${e.kind})`);+ }+ if (diff.removed.entities.length > 0) {+ renderSection("Removed entities");+ for (const e of diff.removed.entities) console.log(` ${e.name} (${e.kind})`);+ }+ if (diff.added.evidence.length > 0) {+ renderSection("Added evidence");+ for (const e of diff.added.evidence) console.log(` [${e.score}] ${e.kind} - ${e.title}`);+ }+ if (diff.removed.evidence.length > 0) {+ renderSection("Removed evidence");+ for (const e of diff.removed.evidence) console.log(` [${e.score}] ${e.kind} - ${e.title}`);+ }+ console.log();+}++interface BuildInput {+ resolved: { id: string; name: string; kind: string; resolutionMode: string };+ facts: EntityFacts;+ context: StructuredContext;+ provenance: unknown;+ asOfRev?: number;+ depth?: string;+ budgets: { maxEntities: number; maxRelationships: number; maxEvidence: number; maxChars: number };+ /**+ * Per-entity staleness probe. Injected so buildBundle stays a pure function+ * under test; production passes nothing and gets the real baseline-backed one.+ */+ isStale?: (path: string) => boolean;+}++export function buildBundle(input: BuildInput): ContextBundle {+ const { resolved, facts, context, provenance, asOfRev, depth, budgets } = input;++ const stale = facts.stale;+ const classification = stale ? "stale" : "current";+ const prov = asRecord(provenance);++ // Entities: the target itself plus every referenced node, deduped by id and+ // ordered deterministically (kind, name, id) before budgeting.+ // `stale` here is the TARGET's staleness, from the facts collector. It is+ // right for the bundle-level `freshness`, but every other entity has to be+ // asked about separately — stamping the target's answer onto all of them+ // reported an untouched dependency as stale whenever the target was, and a+ // genuinely stale one as current whenever the target was not. Staleness is+ // the field an agent reads to decide whether to trust the rest, so a wrong+ // one is worse than none.+ const seen = new Set<string>([resolved.id]);+ const entities: ContextBundle["entities"] = [+ {+ id: resolved.id,+ name: resolved.name,+ kind: resolved.kind,+ path: facts.path,+ stale,+ },+ ];+ for (const node of orderedNodes(context.nodes)) {+ if (seen.has(node.id)) continue;+ seen.add(node.id);+ entities.push({+ id: node.id,+ name: node.name,+ kind: node.kind,+ path: node.provenance?.sourceUri,+ stale: false, // replaced below, for the entities that survive the budget+ });+ }++ // Relationships: graph edges, ordered deterministically.+ const relationships = [...context.edges]+ .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 });++ const bundle: ContextBundle = {+ schema: BUNDLE_SCHEMA,+ generatedAt: new Date().toISOString(),+ target: {+ id: resolved.id,+ name: resolved.name,+ kind: resolved.kind,+ resolutionMode: resolved.resolutionMode,+ },+ entities: [],+ relationships: [],+ claims: [...context.claims]+ .sort(+ (a, b) =>+ cmp(a.claim.entityId, b.claim.entityId) ||+ cmp(a.claim.statement, b.claim.statement) ||+ cmp(a.claim.id, b.claim.id),+ )+ .map((scored) => ({+ id: scored.claim.id,+ entityId: scored.claim.entityId,+ statement: scored.claim.statement,+ status: scored.claim.status,+ })),+ decisions: [...context.decisions].sort((a, b) => cmp(a.title, b.title) || a.rev - b.rev || cmp(a.rationale, b.rationale)),+ conflicts: [...context.conflicts].sort((a, b) => cmp(a.claimA, b.claimA) || cmp(a.claimB, b.claimB) || cmp(a.id, b.id)),+ intents: [...context.intents].sort((a, b) => cmp(a.statement, b.statement) || cmp(a.id, b.id)),+ provenance: {+ sourceUri: asString(prov.sourceUri) ?? facts.path,+ sourceHash: asString(prov.sourceHash),+ extractor: asString(prov.extractor),+ sourceType: asString(prov.sourceType),+ observedAt: asString(prov.observedAt),+ introducedRev: facts.introducedRev,+ historyLength: facts.historyLength,+ stale,+ },+ freshness: { stale, classification },+ evidence: [],+ budgets,+ truncation: {+ entitiesTruncated: 0,+ relationshipsTruncated: 0,+ evidenceTruncated: 0,+ charactersTruncated: 0,+ },+ metadata: {+ asOfRev,+ depth,+ rankingRule: "deterministic-tier",+ },+ };++ // Apply budgets with explicit truncation metadata. Ordering is already+ // deterministic, so cutting from the tail is stable across runs.+ const entityLimit = Math.min(entities.length, budgets.maxEntities);+ // Probe staleness after budgeting, so the cost is bounded by maxEntities+ // rather than by however many nodes the context service returned. The target+ // keeps the answer the facts collector already produced for it.+ const probeStale = input.isStale ?? createStaleProbe();+ bundle.entities = entities.slice(0, entityLimit).map((entity) =>+ entity.id === resolved.id || !entity.path+ ? entity+ : { ...entity, stale: probeStale(entity.path) },+ );+ bundle.truncation.entitiesTruncated = entities.length - entityLimit;++ const relLimit = Math.min(relationships.length, budgets.maxRelationships);+ bundle.relationships = relationships.slice(0, relLimit);+ bundle.truncation.relationshipsTruncated = relationships.length - relLimit;++ // Evidence is ordered by relevance, so keep the highest-priority prefix and+ // drop the tail when either the count or the character budget is exceeded.+ // maxChars bounds the serialized JSON size of the evidence list exactly as it+ // is emitted in the bundle (each item's JSON.stringify length, in the item's+ // deterministic key order), so the budget matches the actual representation+ // rather than an estimate from metadata lengths.+ const sizedEvidence = evidence.map((item) => ({ item, size: JSON.stringify(item).length }));+ let chars = 0;+ let kept = 0;+ for (const entry of sizedEvidence) {+ if (kept >= budgets.maxEvidence || chars + entry.size > budgets.maxChars) break;+ chars += entry.size;+ kept += 1;+ }+ bundle.evidence = evidence.slice(0, kept);+ bundle.truncation.evidenceTruncated = evidence.length - kept;+ const fullChars = sizedEvidence.reduce((sum, entry) => sum + entry.size, 0);+ bundle.truncation.charactersTruncated = Math.max(0, fullChars - chars);++ return bundle;+}++/** Deterministic evidence ranking: tier, then a stable id tiebreaker. */+function rankEvidence(input: {+ resolved: { id: string; name: string; kind: string };+ facts: EntityFacts;+ context: StructuredContext;+ relationships: Array<{ src: string; dst: string; predicate: string }>;+ prov: Record<string, unknown>;+}): EvidenceItem[] {+ const items: EvidenceItem[] = [];++ const target = input.resolved;+ items.push({+ id: `target:${target.id}`,+ kind: "target",+ source: "resolution",+ title: `${target.name} (${target.kind})`,+ score: 0,+ reason: "resolved target — the bundle is centered on this entity",+ refs: [target.id],+ });++ const structural: Array<{ id: string; source: string; title: string; refs: string[] }> = [];+ if (input.facts.container) {+ structural.push({+ id: `container:${input.facts.container.name}`,+ source: "facts.container",+ title: `container ${input.facts.container.name} (${input.facts.container.kind})`,+ refs: [],+ });+ }+ for (const name of input.facts.topCallers) {+ structural.push({ id: `caller:${name}`, source: "facts.callers", title: `caller ${name}`, refs: [] });+ }+ for (const name of input.facts.topDependents) {+ structural.push({+ id: `dependent:${name}`,+ source: "facts.dependents",+ title: `dependent ${name}`,+ refs: [],+ });+ }+ for (const name of input.facts.members.slice(0, 10)) {+ structural.push({ id: `member:${name}`, source: "facts.members", title: `member ${name}`, refs: [] });+ }+ structural.forEach((item, index) => {+ items.push({ ...item, kind: "structural", score: 10 + index, reason: "direct structural relationship" });+ });++ for (const scored of input.context.claims) {+ items.push({+ id: `claim:${scored.claim.id}`,+ kind: "claim",+ source: "context.claims",+ title: scored.claim.statement,+ score: 20,+ reason: `context claim (relevance ${scored.relevance}, confidence ${scored.confidence?.score ?? "n/a"})`,+ refs: [scored.claim.entityId],+ });+ }+ for (const decision of input.context.decisions) {+ items.push({+ id: `decision:${decision.title}`,+ kind: "decision",+ source: "context.decisions",+ title: decision.title,+ score: 21,+ reason: decision.rationale,+ refs: decision.entityId ? [decision.entityId] : [],+ });+ }+ for (const conflict of input.context.conflicts) {+ items.push({+ id: `conflict:${conflict.id}`,+ kind: "conflict",+ source: "context.conflicts",+ title: `${conflict.claimA} vs ${conflict.claimB}`,+ score: 22,+ reason: conflict.reason,+ refs: [],+ });+ }+ for (const intent of input.context.intents) {+ items.push({+ id: `intent:${intent.id}`,+ kind: "intent",+ source: "context.intents",+ title: intent.statement,+ score: 23,+ reason: `intent status ${intent.status}`,+ refs: [],+ });+ }++ input.relationships.slice(0, 50).forEach((edge, index) => {+ items.push({+ id: `relationship:${edge.src}:${edge.dst}:${edge.predicate}`,+ kind: "relationship",+ source: "context.edges",+ title: `${edge.src} --${edge.predicate}--> ${edge.dst}`,+ score: 30 + Math.min(index, 10),+ reason: "graph relationship from the context service",+ refs: [edge.src, edge.dst],+ });+ });++ items.push({+ id: `provenance:${target.id}`,+ kind: "provenance",+ source: "provenance + facts.history",+ title: `history length ${input.facts.historyLength}, introduced rev ${input.facts.introducedRev ?? "unknown"}`,+ score: 40,+ reason: `provenance ${input.prov.sourceType ?? "unknown"}, extractor ${input.prov.extractor ?? "unknown"}`,+ refs: [target.id],+ });++ // Stable full ordering: score, then id.+ return items.sort((a, b) => a.score - b.score || cmp(a.id, b.id));+}++function renderBundle(bundle: ContextBundle, format: string): void {+ if (format === "json") {+ console.log(JSON.stringify(bundle, null, 2));+ return;+ }+ if (format === "llm") {+ printLlmLines([+ `target=${bundle.target.name}`,+ `target_kind=${bundle.target.kind}`,+ `stale=${bundle.freshness.stale}`,+ `classification=${bundle.freshness.classification}`,+ `entities=${bundle.entities.length}`,+ `relationships=${bundle.relationships.length}`,+ `claims=${bundle.claims.length}`,+ `decisions=${bundle.decisions.length}`,+ `conflicts=${bundle.conflicts.length}`,+ `intents=${bundle.intents.length}`,+ `evidence=${bundle.evidence.length}`,+ `truncated_entities=${bundle.truncation.entitiesTruncated}`,+ `truncated_relationships=${bundle.truncation.relationshipsTruncated}`,+ `truncated_evidence=${bundle.truncation.evidenceTruncated}`,+ `truncated_chars=${bundle.truncation.charactersTruncated}`,+ ...bundle.evidence.map(+ (item) => `evidence ${item.score} ${item.kind} ${item.title.replaceAll("\n", " ")}`,+ ),+ ]);+ return;+ }++ renderSection(`Context: ${bundle.target.name}`);+ console.log(` kind: ${bundle.target.kind}`);+ console.log(` classification:${bundle.freshness.classification}`);+ console.log(` entities: ${bundle.entities.length}`);+ console.log(` relationships: ${bundle.relationships.length}`);+ console.log(` claims: ${bundle.claims.length}`);+ console.log(` decisions: ${bundle.decisions.length}`);+ console.log(` conflicts: ${bundle.conflicts.length}`);+ console.log(` intents: ${bundle.intents.length}`);+ if (bundle.freshness.stale) {+ renderWarning("Source has changed since last ingest. Run ix map to update.");+ }++ if (bundle.evidence.length > 0) {+ renderSection("Evidence (highest relevance first)");+ for (const item of bundle.evidence) {+ console.log(` [${item.score}] ${item.kind} — ${item.title}`);+ console.log(` ${item.reason}`);+ }+ }++ const trunc = bundle.truncation;+ if (trunc.entitiesTruncated + trunc.relationshipsTruncated + trunc.evidenceTruncated > 0) {+ renderNote(+ `Truncated: ${trunc.entitiesTruncated} entities, ${trunc.relationshipsTruncated} relationships, ${trunc.evidenceTruncated} evidence items. Rerun with larger --max-* budgets for more.`,+ );+ }+ console.log();+}++function orderedNodes(nodes: GraphNode[]): GraphNode[] {+ return [...nodes].sort((a, b) => cmp(a.kind, b.kind) || cmp(a.name, b.name) || cmp(a.id, b.id));+}++function asRecord(value: unknown): Record<string, unknown> {+ return value !== null && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};+}++function asString(value: unknown): string | undefined {+ return typeof value === "string" ? value : undefined;+}++function clampInt(raw: string | undefined, min: number, max: number, fallback: number): number {+ const parsed = raw ? parseInt(raw, 10) : NaN;+ if (Number.isNaN(parsed)) return fallback;+ return Math.min(max, Math.max(min, parsed));+}++function cmp(a: string, b: string): number {+ return a < b ? -1 : a > b ? 1 : 0;+}diff --git a/ix-cli/src/cli/context-bundle-schema.ts b/ix-cli/src/cli/context-bundle-schema.tsnew file mode 100644index 00000000..ab54b03e--- /dev/null+++ b/ix-cli/src/cli/context-bundle-schema.ts@@ -0,0 +1,40 @@+import { z } from "zod";++/**+ * Versioned contract for the deterministic context bundle produced by+ * `ix context` (schema `ix-context-bundle/1`).+ *+ * This is the single source of truth for the bundle's shape. The MCP server+ * uses it as the `ix_context` output schema so agents get a structured+ * contract, and the CLI validates every bundle with it before persisting it+ * (investigation save and `--out`), so a malformed or unexpected backend+ * payload can never be written to disk as if it were a valid bundle.+ *+ * Nested report objects (claims/decisions/conflicts/intents) keep their own+ * internal shapes and are typed loosely here; the bundle's versioned `schema`+ * field remains the authoritative marker.+ */+export const contextBundleSchema = z.object({+ schema: z.string(),+ generatedAt: z.string(),+ target: z.object({+ id: z.string(),+ name: z.string(),+ kind: z.string(),+ resolutionMode: z.string(),+ }),+ entities: z.array(+ z.object({ id: z.string(), name: z.string(), kind: z.string(), path: z.string().optional(), stale: z.boolean() }),+ ),+ relationships: z.array(z.object({ src: z.string(), dst: z.string(), predicate: z.string() })),+ claims: z.array(z.record(z.string(), z.unknown())),+ decisions: z.array(z.record(z.string(), z.unknown())),+ conflicts: z.array(z.record(z.string(), z.unknown())),+ intents: z.array(z.record(z.string(), z.unknown())),+ provenance: z.record(z.string(), z.unknown()),+ freshness: z.object({ stale: z.boolean(), classification: z.string() }),+ evidence: z.array(z.record(z.string(), z.unknown())),+ budgets: z.record(z.string(), z.number()),+ truncation: z.record(z.string(), z.number()),+ metadata: z.record(z.string(), z.unknown()),+});diff --git a/ix-cli/src/cli/register/oss.ts b/ix-cli/src/cli/register/oss.tsindex 4c54a9eb..c6defe3a 100644--- a/ix-cli/src/cli/register/oss.ts+++ b/ix-cli/src/cli/register/oss.ts@@ -36,6 +36,7 @@ import { registerViewCommand } from "../commands/view.js";import { registerSavingsCommand } from "../commands/savings.js";import { registerPatchesCommand } from "../commands/patches.js";import { registerMcpCommand } from "../commands/mcp.js";+import { registerContextCommand } from "../commands/context.js";const PRO_COMMANDS: { name: string; desc: string }[] = [{ name: "briefing", desc: "Session-resume briefing" },@@ -102,6 +103,7 @@ export function registerOssCommands(program: Command): void {registerSavingsCommand(program);registerPatchesCommand(program);registerMcpCommand(program);+ registerContextCommand(program);// Hide advanced commands from default helpconst advancedSet = new Set(ADVANCED_COMMANDS);diff --git a/ix-cli/src/cli/stale.ts b/ix-cli/src/cli/stale.tsindex a0512135..35dd9545 100644--- a/ix-cli/src/cli/stale.ts+++ b/ix-cli/src/cli/stale.ts@@ -136,25 +136,41 @@ export function detectStaleFiles(* this used to need was once a backend round-trip per file.*/export function isFileStale(filePath: string): boolean {+ return createStaleProbe()(filePath);+}++/**+ * A staleness predicate that loads the ingest baseline once.+ *+ * `isFileStale` re-reads and re-parses the whole mtime cache on every call,+ * which is fine for the handful of results `ix explain` / `ix locate` /+ * `ix read` check but not for a caller asking about many files at once — that+ * turns one JSON parse of a file holding every ingested path into N of them.+ * Callers with a list should take a probe and reuse it.+ */+export function createStaleProbe(): (filePath: string) => boolean {const workspaceRoot = path.resolve(resolveWorkspaceRoot());const baseline = loadIngestBaseline(workspaceRoot);- if (!baseline) return false;- const absolutePath = path.isAbsolute(filePath)- ? path.resolve(filePath)- : path.resolve(workspaceRoot, filePath);- if (!fs.existsSync(absolutePath)) {- return baseline.files.has(absolutePath) || baseline.files.has(filePath);- }+ return (filePath: string): boolean => {+ if (!baseline) return false;- try {- return differsFromIngestBaseline(- absolutePath,- fs.statSync(absolutePath).mtimeMs,- baseline.files,- baseline.lastIngestAt,- );- } catch {- return false;- }+ const absolutePath = path.isAbsolute(filePath)+ ? path.resolve(filePath)+ : path.resolve(workspaceRoot, filePath);+ if (!fs.existsSync(absolutePath)) {+ return baseline.files.has(absolutePath) || baseline.files.has(filePath);+ }++ try {+ return differsFromIngestBaseline(+ absolutePath,+ fs.statSync(absolutePath).mtimeMs,+ baseline.files,+ baseline.lastIngestAt,+ );+ } catch {+ return false;+ }+ };}diff --git a/ix-cli/src/mcp/server.ts b/ix-cli/src/mcp/server.tsindex 02b872dd..7d199d93 100644--- a/ix-cli/src/mcp/server.ts+++ b/ix-cli/src/mcp/server.ts@@ -2,6 +2,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";import type { CallToolResult, ToolAnnotations } from "@modelcontextprotocol/sdk/types.js";import { z } from "zod";+import { contextBundleSchema } from "../cli/context-bundle-schema.js";import {createProtocolStdout,@@ -45,6 +46,7 @@ export const IX_MCP_OSS_TOOL_NAMES = ["ix_stats","ix_subsystems","ix_history",+ "ix_context","ix_ingest",] as const;@@ -132,6 +134,9 @@ const TOOL_ANNOTATIONS: Record<(typeof IX_MCP_TOOL_NAMES)[number], ToolAnnotatioix_subsystems: { ...READ_ONLY, title: "List graph-derived subsystems" },ix_history: { ...READ_ONLY, title: "Show provenance and patch history" },ix_ingest: { ...WRITE_OPEN_WORLD, title: "Ingest a path or GitHub repository into the graph" },+ // Reads the graph and composes a bundle; the CLI's --save and --out, which are+ // the only parts of `ix context` that write anything, are not exposed here.+ ix_context: { ...READ_ONLY, title: "Build a bounded context bundle for a target" },// Implemented in @ix/pro, so nothing here can check these are true.ix_briefing: UNVERIFIED("Load the Ix Pro session briefing"),ix_decisions: UNVERIFIED("List Ix Pro architecture decisions"),@@ -174,7 +179,12 @@ interface CreateServerOptions {type ToolInput = Record<string, unknown>;/**- * One Ix invocation, with its options kept apart from its positional values.+ * `ix_context` output schema — shared contract from the CLI bundle module so+ * the MCP surface and persisted investigation state validate the same shape.+ */++/**+ * One Ix invocationation, with its options kept apart from its positional values.** The split is what lets every positional go behind a `--` separator. Appending* them as bare tokens let commander read any value beginning with `-` as a@@ -388,6 +398,36 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer{ target: z.string().min(1) },async (input) => runFormatted(runIx, "ix_history", ix("history", [stringArg(input, "target")])),);+ registerTool(+ server,+ "ix_context",+ "Build a bounded, deterministic context bundle for a symbol, file, or entity",+ {+ target: z.string().min(1),+ as_of_rev: z.number().int().nonnegative().optional().describe("graph revision for historical context"),+ max_entities: z.number().int().min(1).max(500).optional(),+ max_relationships: z.number().int().min(1).max(1000).optional(),+ max_evidence: z.number().int().min(1).max(200).optional(),+ max_chars: z+ .number()+ .int()+ .min(1000)+ .max(1_000_000)+ .optional()+ .describe("exact serialized-character budget for the evidence list"),+ },+ async (input) => {+ const options: string[] = [];+ if (typeof input.as_of_rev === "number") options.push(`--as-of-rev=${numberArg(input, "as_of_rev")}`);+ if (typeof input.max_entities === "number") options.push(`--max-entities=${numberArg(input, "max_entities")}`);+ if (typeof input.max_relationships === "number")+ options.push(`--max-relationships=${numberArg(input, "max_relationships")}`);+ if (typeof input.max_evidence === "number") options.push(`--max-evidence=${numberArg(input, "max_evidence")}`);+ if (typeof input.max_chars === "number") options.push(`--max-chars=${numberArg(input, "max_chars")}`);+ return runJsonStructured(runIx, "ix_context", ix("context", [stringArg(input, "target")], options));+ },+ contextBundleSchema,+ );registerTool(server,"ix_ingest",@@ -473,6 +513,7 @@ function registerTool(description: string,inputSchema: z.ZodRawShape,handler: (input: ToolInput) => Promise<CallToolResult>,+ outputSchema?: z.ZodType,): void {server.registerTool(name,@@ -480,7 +521,9 @@ function registerTool(description,inputSchema,annotations: TOOL_ANNOTATIONS[name as keyof typeof TOOL_ANNOTATIONS],- outputSchema: TOOL_OUTPUT_SCHEMA[name as keyof typeof TOOL_OUTPUT_SCHEMA],+ // ix_context passes its schema as an argument rather than through the+ // table, because the shape is owned by the CLI bundle module.+ outputSchema: outputSchema ?? TOOL_OUTPUT_SCHEMA[name as keyof typeof TOOL_OUTPUT_SCHEMA],},async (input) => handler(input as ToolInput),);@@ -526,6 +569,39 @@ function declaresOutputSchema(tool: string): boolean {return tool in TOOL_OUTPUT_SCHEMA;}+/**+ * Run a command in JSON format and surface the parsed result as MCP+ * `structuredContent` alongside the text payload. The context bundle carries+ * its own versioned schema (`ix-context-bundle/1`), so the structured copy is+ * stable across releases; when the output does not parse into a usable object+ * we omit structured content and keep the text result authoritative rather+ * than throwing.+ */+async function runJsonStructured(+ runIx: IxRunner,+ tool: string,+ argv: IxArgv,+): Promise<CallToolResult> {+ const result = await runIx(toArgv(argv, "json"), DEFAULT_TIMEOUT_MS);+ if (!result.ok) {+ const detail = result.stderr.trim() || result.stdout.trim() || `${argv.command} failed without output`;+ return textResult(JSON.stringify({ error: detail, tool }), true);+ }+ const text = result.stdout.trim() || "{}";+ const parsed = parseJsonOutput(text);+ // The CLI contract for `--format=json` is a parseable bundle; when stdout is+ // not a usable object the tool genuinely failed, and returning an MCP error+ // is more truthful than inventing a bundle (the output schema requires+ // schema-valid structured content on every result).+ if (!isRecord(parsed) || Object.keys(parsed).length === 0) {+ return textResult(text || JSON.stringify({ error: `${argv.command} produced no parseable JSON`, tool }), true);+ }+ return {+ content: [{ type: "text", text }],+ structuredContent: parsed,+ };+}+async function runCommand(runIx: IxRunner,tool: string,diff --git a/skills/ix/SKILL.md b/skills/ix/SKILL.mdindex f74e7783..c428094a 100644--- a/skills/ix/SKILL.md+++ b/skills/ix/SKILL.md@@ -51,6 +51,7 @@ Map → Explain → Trace → Impact|---|---|---|| Build/refresh the graph | `ix map` | `ix map .` || Understand a component | `ix explain` | `ix explain IngestionService` |+| Bounded deterministic context | `ix context` | `ix context IngestionService --max-entities 20` || Trace a flow | `ix trace` | `ix trace user_login_flow` || Analyze impact | `ix impact` | `ix impact verify_token --format llm` |diff --git a/skills/ix/references/commands.md b/skills/ix/references/commands.mdindex 017e9716..e281fcaa 100644--- a/skills/ix/references/commands.md+++ b/skills/ix/references/commands.md@@ -12,6 +12,7 @@ These aggregate multiple graph operations into single bounded responses.| Blast radius / impact | `ix impact` | `ix impact UserService --format llm` || Hotspot discovery | `ix rank` | `ix rank --by dependents --kind class --top 10 --format llm` || One-shot summary | `ix overview` | `ix overview IngestionService --format llm` |+| Deterministic context bundle | `ix context` | `ix context IngestionService --format llm` || Scoped entity listing | `ix inventory` | `ix inventory --kind function --path auth.py --format llm` |## Finding & Understanding Code