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
fix(context): consume summarized graph results, and warn rather than fail on unknown --depth (#493)
KageBinary222283e85099
diff --git a/ix-cli/src/cli/__tests__/context-pick-validation.test.ts b/ix-cli/src/cli/__tests__/context-pick-validation.test.tsindex 9601982f..a748a463 100644--- a/ix-cli/src/cli/__tests__/context-pick-validation.test.ts+++ b/ix-cli/src/cli/__tests__/context-pick-validation.test.ts@@ -8,7 +8,7 @@ vi.mock("../resolve.js", async (importOriginal) => ({resolveFileOrEntity,}));-import { registerContextCommand } from "../commands/context.js";+import { parseContextDepthOption, registerContextCommand } from "../commands/context.js";async function runContext(args: string[]): Promise<{ error?: CommanderError; stderr: string }> {const stderr: string[] = [];@@ -148,6 +148,73 @@ describe("ix context --as-of-rev validation", () => {});});+describe("ix context --depth validation", () => {+ beforeEach(() => {+ resolveFileOrEntity.mockReset().mockResolvedValue(undefined);+ });++ it.each(["compact", "standard", "full", "shallow", "deep", "FULL"])("accepts depth %j", async (depth) => {+ const result = await runContext(["--depth", depth]);++ expect(result.error).toBeUndefined();+ expect(resolveFileOrEntity).toHaveBeenCalledOnce();+ });++ it.each([+ ["compact", "compact"],+ ["FULL", "full"],+ [" Deep ", "deep"],+ ])("normalizes a known depth %j to %j", (input, expected) => {+ expect(parseContextDepthOption(input)).toBe(expected);+ });++ /**+ * An unrecognized depth must NOT exit 1.+ *+ * The backend's limit selection ends in a `case _` that lands every+ * unrecognized value on the standard tier, so `--depth 2` has always run a+ * standard-depth query rather than failing. Anything already passing one is+ * a working pipeline, and turning it into a non-zero exit inside a patch+ * release breaks it on upgrade for no gain.+ */+ it.each(["2", "wide", "standard-ish"])("falls back to standard for %j instead of exiting", (depth) => {+ const warn = vi.spyOn(console, "error").mockImplementation(() => {});+ try {+ expect(parseContextDepthOption(depth)).toBe("standard");+ expect(warn).toHaveBeenCalledOnce();+ expect(warn.mock.calls[0].join(" ")).toContain(`--depth ${depth}`);+ expect(warn.mock.calls[0].join(" ")).toContain("using standard");+ } finally {+ warn.mockRestore();+ }+ });++ it.each(["2", "wide"])("still resolves the target after an unknown depth %j", async (depth) => {+ const warn = vi.spyOn(console, "error").mockImplementation(() => {});+ try {+ const result = await runContext(["--depth", depth]);++ expect(result.error).toBeUndefined();+ expect(resolveFileOrEntity).toHaveBeenCalledOnce();+ } finally {+ warn.mockRestore();+ }+ });++ it("warns on stderr, never stdout, so --format json stays parseable", () => {+ const out = vi.spyOn(console, "log").mockImplementation(() => {});+ const warn = vi.spyOn(console, "error").mockImplementation(() => {});+ try {+ parseContextDepthOption("nonsense");+ expect(warn).toHaveBeenCalledOnce();+ expect(out).not.toHaveBeenCalled();+ } finally {+ out.mockRestore();+ warn.mockRestore();+ }+ });+});+describe("ix context refusals reach the caller that asked for records", () => {beforeEach(() => {resolveFileOrEntity.mockReset().mockResolvedValue(undefined);diff --git a/ix-cli/src/cli/__tests__/context.test.ts b/ix-cli/src/cli/__tests__/context.test.tsindex ee472d56..c9df9e50 100644--- a/ix-cli/src/cli/__tests__/context.test.ts+++ b/ix-cli/src/cli/__tests__/context.test.ts@@ -3,9 +3,11 @@ import { describe, expect, it } from "vitest";import type {ConflictReport,DecisionReport,+ EdgeSummary,GraphEdge,GraphNode,IntentReport,+ NodeSummary,ScoredClaim,} from "../../client/types.js";import type { EntityFacts } from "../explain/facts.js";@@ -58,6 +60,8 @@ function makeContext(overrides: Partial<{intents: IntentReport[];nodes: GraphNode[];edges: GraphEdge[];+ nodeSummaries: NodeSummary[];+ edgeSummaries: EdgeSummary[];}> = {}) {return {claims: overrides.claims ?? [makeClaim("renders to DOM", 0.9)],@@ -83,6 +87,8 @@ function makeContext(overrides: Partial<{([{ id: "edge-1", src: "entity-1", dst: "entity-2", predicate: "calls", attrs: {}, createdRev: 3 },] as GraphEdge[]),+ nodeSummaries: overrides.nodeSummaries,+ edgeSummaries: overrides.edgeSummaries,metadata: { query: "Widget", seedEntities: ["entity-1"], hopsExpanded: 1, asOfRev: 3 },};}@@ -138,6 +144,35 @@ describe("ix context bundle", () => {expect(bundle.truncation.evidenceTruncated).toBeGreaterThanOrEqual(0);});+ it("builds entities and relationships from compact graph summaries", () => {+ const bundle = buildBundle({+ ...input(),+ context: makeContext({+ nodes: [],+ edges: [],+ nodeSummaries: [+ { id: "entity-1", kind: "class", name: "Widget", rev: 3, sourceUri: "src/widget.ts" },+ { id: "entity-2", kind: "method", name: "render", rev: 3, sourceUri: "src/widget.ts" },+ { id: "entity-3", kind: "method", name: "mount", rev: 3, sourceUri: "src/widget.ts" },+ ],+ edgeSummaries: [+ { id: "edge-1", src: "entity-1", dst: "entity-2", predicate: "calls", rev: 3 },+ { id: "edge-2", src: "entity-1", dst: "entity-3", predicate: "calls", rev: 3 },+ ],+ }),+ });++ expect(bundle.entities).toEqual([+ { id: "entity-1", name: "Widget", kind: "class", stale: false },+ { id: "entity-3", name: "mount", kind: "method", path: "src/widget.ts", stale: false },+ { id: "entity-2", name: "render", kind: "method", path: "src/widget.ts", stale: false },+ ]);+ expect(bundle.relationships).toEqual([+ { src: "entity-1", dst: "entity-2", predicate: "calls" },+ { src: "entity-1", dst: "entity-3", predicate: "calls" },+ ]);+ });+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 ontodiff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.tsindex c59aef91..7abb7806 100644--- a/ix-cli/src/cli/commands/context.ts+++ b/ix-cli/src/cli/commands/context.ts@@ -13,7 +13,6 @@ import { IxClient } from "../../client/api.js";import type {ConflictReport,DecisionReport,- GraphNode,IntentReport,StructuredContext,} from "../../client/types.js";@@ -120,6 +119,37 @@ interface ContextOptions extends Partial<BudgetSnapshot> {format: string;}+const CONTEXT_DEPTHS = ["compact", "standard", "full", "shallow", "deep"] as const;++/**+ * The depth vocabulary the backend understands, and what to do about anything+ * else.+ *+ * `ContextService` normalizes `shallow`->`compact` and `deep`->`full`, then+ * picks its limits with a `case _` that lands every unrecognized value on the+ * `standard` tier. So `--depth 2` was never an error: it silently ran a+ * standard-depth query, and scripts have been passing values like it.+ *+ * Rejecting those outright would be a breaking change in a patch release, for+ * a flag whose wrong values were previously harmless. So this warns and does+ * exactly what the backend already did with them — the typo still gets+ * surfaced, on stderr so `--format json` and `--format llm` stay parseable,+ * but nobody's pipeline starts exiting 1 on upgrade.+ *+ * Deliberately not an `InvalidArgumentError`, unlike `--pick` and `--as-of-rev`+ * next to it: those reject values that have no defined meaning, whereas this+ * one has a defined meaning and it is `standard`.+ */+export function parseContextDepthOption(value: string): string {+ const normalized = value.trim().toLowerCase();+ if ((CONTEXT_DEPTHS as readonly string[]).includes(normalized)) return normalized;++ renderWarningErr(+ `--depth ${value} is not one of ${CONTEXT_DEPTHS.join(", ")}; using standard.`+ );+ return "standard";+}+/** Stable evidence kinds, ordered by relevance tier (lower is more relevant). */type EvidenceKind =| "target"@@ -197,7 +227,11 @@ export function registerContextCommand(program: Command): void {.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)", parsePickOption)- .option("--depth <depth>", "Context-graph expansion depth")+ .option(+ "--depth <depth>",+ `Context-graph expansion depth (${CONTEXT_DEPTHS.join("|")})`,+ parseContextDepthOption,+ ).option("--as-of-rev <n>", "Historical context as of a graph revision", parseRevisionOption)// No Commander default on the --max-* flags, so `parseRequestedBudgets`// can tell an absent flag from one set to the default value. The defaults@@ -1315,20 +1349,37 @@ export function buildBundle(input: BuildInput): ContextBundle {stale,},];- for (const node of orderedNodes(context.nodes)) {+ // Compact and standard backend responses omit the full graph arrays and+ // carry the same graph as summaries. Falling back here keeps the default+ // context mode from collapsing to a target-only bundle.+ const contextNodes = context.nodes.length > 0+ ? context.nodes.map((node) => ({+ id: node.id,+ name: node.name,+ kind: node.kind,+ path: node.provenance?.sourceUri,+ }))+ : (context.nodeSummaries ?? []).map((node) => ({+ id: node.id,+ name: node.name,+ kind: node.kind,+ path: node.sourceUri ?? undefined,+ }));+ for (const node of orderedNodes(contextNodes)) {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,+ path: node.path,stale: false, // replaced below, for the entities that survive the budget});}// Relationships: graph edges, ordered deterministically.- const relationships = [...context.edges]+ const contextEdges = context.edges.length > 0 ? context.edges : (context.edgeSummaries ?? []);+ const relationships = [...contextEdges].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 }));@@ -1616,7 +1667,7 @@ export function renderBundle(bundle: ContextBundle, format: string): void {console.log();}-function orderedNodes(nodes: GraphNode[]): GraphNode[] {+function orderedNodes<T extends { id: string; kind: string; name: string }>(nodes: T[]): T[] {return [...nodes].sort((a, b) => cmp(a.kind, b.kind) || cmp(a.name, b.name) || cmp(a.id, b.id));}diff --git a/ix-cli/src/client/types.ts b/ix-cli/src/client/types.tsindex 32e66f49..aed12a00 100644--- a/ix-cli/src/client/types.ts+++ b/ix-cli/src/client/types.ts@@ -100,6 +100,22 @@ export interface GraphEdge {deletedRev?: number;}+export interface NodeSummary {+ id: string;+ kind: string;+ name: string;+ rev: number;+ sourceUri?: string | null;+}++export interface EdgeSummary {+ id: string;+ src: string;+ dst: string;+ predicate: string;+ rev: number;+}+export interface ContextMetadata {query: string;seedEntities: string[];@@ -116,6 +132,8 @@ export interface StructuredContext {intents: IntentReport[];nodes: GraphNode[];edges: GraphEdge[];+ nodeSummaries?: NodeSummary[];+ edgeSummaries?: EdgeSummary[];metadata: ContextMetadata;}