Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
feat(cli): detect a hollowed graph and stop answering from it with confidence
KageBinarye25a5f3a7881
diff --git a/CLAUDE.md b/CLAUDE.mdindex e0879cc1..3081f304 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -40,8 +40,9 @@ ix map --silent # refresh the graph after code chang- **`ix reset` is GLOBAL.** `ix reset` / `ix reset --code` take no workspace_idand wipe **every** workspace's graph in the shared backend (Ix + packwise +- any other). The only scoped variant is `/v1/reset/workspace`, which the CLI- does not expose. After a reset, re-map each workspace.+ any other). The only scoped variant is `/v1/reset/workspace`, exposed as+ `ix reset --workspace` (the registered workspace containing cwd, nothing+ else). After a global reset, re-map each workspace.- **The OSS↔Pro command boundary is derived at runtime, not declared.**`main.ts` snapshots `ossCmdNames` right after `registerOssCommands()`; thePro probe diffs against it. Adding a command to `oss.ts` silently makes itdiff --git a/docs/llm-format.md b/docs/llm-format.mdindex 3d0b0fb5..2de7d88b 100644--- a/docs/llm-format.md+++ b/docs/llm-format.md@@ -67,6 +67,27 @@ which value it ignored, on stderr, when a person is there to read it.is a wire detail and is translated on the way out, so a consumer never seesboth.)+## Graph health++`explain` and `context` check that the graph they answer from still has its+structure (`ix-cli/src/cli/graph-health.ts`). When it does not, a `graph`+record comes first (right after the header for `context`), the `context`+header carries `graph=degraded classification=degraded` instead of `stale=`,+and `explain` withholds what it would infer from the missing edges:++```+graph status=degraded reason=hollow message="9243 nodes but 387 edges: 1% of symbols are attached to a file (healthy: ~100%), so callers, callees and members are missing, not zero. ..." fix="ix reset --workspace --yes --ingest"+entity id=9dbdebd9 name=parseBudgetOption kind=function path=ix-cli/src/cli/options.ts rev=1243+role role=unknown confidence=none reason=graph_degraded+importance level=unknown reason=graph_degraded+edges callers=unknown callees=unknown dependents=unknown importers=unknown members=unknown downstream=unknown depth=1 history=1 complete=false+```++A non-zero count on a degraded graph is still an edge that exists, so it is a+floor; a zero is `unknown`. `reason=orphaned_target` is the same verdict for+one entity whose file lost its edges while the rest of the graph looks fine.+`--format json` carries the verdict as a top-level `graph` object.+## HierarchiesHierarchical data (e.g. `ix map` regions) is emitted flat, one record per line,diff --git a/ix-cli/src/cli/__tests__/graph-health-render.test.ts b/ix-cli/src/cli/__tests__/graph-health-render.test.tsnew file mode 100644index 00000000..4562c879--- /dev/null+++ b/ix-cli/src/cli/__tests__/graph-health-render.test.ts@@ -0,0 +1,145 @@+// Copyright 2026 Ix Infrastructure Inc.++import { describe, expect, it } from "vitest";++import { renderExplainLlm } from "../explain/llm.js";+import { buildBundle, renderBundle } from "../commands/context.js";+import { contextBundleSchema } from "../context-bundle-schema.js";+import { assessGraphStats, assessTargetStructure } from "../graph-health.js";+import type { ContextFacts, EntityFacts } from "../explain/facts.js";++/**+ * On a hollowed graph (every node, almost no edge), `ix explain` used to say+ * `callers=0 role=localized-helper importance=low` and `ix context` said+ * `stale=false classification=current` -- confident, and wrong: the healthy+ * graph of the same commit has a caller. These pin what they say instead.+ */++const DEGRADED = assessGraphStats({+ nodes: { total: 9243, byKind: [{ kind: "file", count: 333 }, { kind: "function", count: 8910 }] },+ edges: { total: 387, byPredicate: [{ predicate: "CONTAINS", count: 38 }, { predicate: "DEFINES", count: 38 }, { predicate: "CONTAINS_CHUNK", count: 39 }, { predicate: "CALLS", count: 222 }] },+});++function explainFacts(over: Partial<EntityFacts> = {}): EntityFacts {+ return {+ id: "9dbdebd9-0000", name: "parseBudgetOption", kind: "function", path: "ix-cli/src/cli/options.ts",+ members: [], memberCount: 0,+ callerCount: 0, calleeCount: 0, dependentCount: 0, importerCount: 0,+ downstreamDependents: 0, downstreamDepth: 1,+ topCallers: [], topDependents: [],+ historyLength: 1, introducedRev: 1243, stale: false, diagnostics: [],+ ...over,+ };+}++const role = { role: "localized-helper" as const, confidence: "low" as const, reasons: [] };+const importance = { level: "low" as const, category: "localized-helper" as const, reasons: [] };+const rendered = { explanation: "", context: "", usedBy: "", usedByIsNameList: true, whyItMatters: "", notes: [] };++describe("ix explain on a degraded graph", () => {+ it("says so first and withholds what it would infer from missing edges", () => {+ const lines = renderExplainLlm(explainFacts(), role, importance, rendered, DEGRADED);++ expect(lines[0]).toMatch(/^graph status=degraded reason=hollow message=".*9243 nodes but 387 edges.*" fix="ix reset --workspace --yes --ingest"$/);+ expect(lines).toContain("role role=unknown confidence=none reason=graph_degraded");+ expect(lines).toContain("importance level=unknown reason=graph_degraded");+ expect(lines.join("\n")).not.toContain("localized-helper");+ // A zero from a graph without edges is not "no callers".+ expect(lines).toContain(+ "edges callers=unknown callees=unknown dependents=unknown importers=unknown members=unknown downstream=unknown depth=1 history=1 complete=false",+ );+ });++ it("keeps a non-zero count: an edge that survived is still a floor", () => {+ const line = renderExplainLlm(explainFacts({ callerCount: 2 }), role, importance, rendered, DEGRADED)+ .find((l) => l.startsWith("edges "));+ expect(line).toContain("callers=2 ");+ });++ it("is unchanged on a healthy graph, or when the check could not run", () => {+ for (const health of [undefined, { status: "ok" as const }, { status: "unknown" as const }]) {+ const lines = renderExplainLlm(explainFacts(), role, importance, rendered, health);+ expect(lines[0]).toMatch(/^entity /);+ expect(lines).toContain("role role=localized-helper confidence=low");+ expect(lines.find((l) => l.startsWith("edges "))).toBe(+ "edges callers=0 callees=0 dependents=0 importers=0 members=0 downstream=0 depth=1 history=1",+ );+ }+ });++ it("flags a target no file contains even when the workspace looks fine", () => {+ const orphan = assessTargetStructure({ name: "parseBudgetOption", kind: "function", path: "ix-cli/src/cli/options.ts" });+ const lines = renderExplainLlm(explainFacts(), role, importance, rendered, orphan);+ expect(lines[0]).toContain("reason=orphaned_target");+ });+});++function contextFacts(): ContextFacts {+ return {+ id: "t-1", name: "parseBudgetOption", kind: "function", path: "ix-cli/src/cli/options.ts",+ members: [], memberRefs: [], memberCount: 0,+ callerCount: 0, calleeCount: 0, dependentCount: 0, importerCount: 0,+ topCallers: [], topDependents: [],+ historyLength: 1, introducedRev: 1243, stale: false, diagnostics: [],+ };+}++function bundle(graphHealth?: Parameters<typeof buildBundle>[0]["graphHealth"]) {+ return buildBundle({+ resolved: { id: "t-1", name: "parseBudgetOption", kind: "function", resolutionMode: "exact" },+ facts: contextFacts(),+ context: {+ claims: [], conflicts: [], decisions: [], intents: [], nodes: [], edges: [],+ metadata: { query: "", seedEntities: [], hopsExpanded: 1, asOfRev: 1 },+ } as never,+ provenance: {},+ budgets: { maxEntities: 50, maxRelationships: 100, maxEvidence: 25, maxTokens: 1500, maxChars: 12000 },+ isStale: () => false,+ graphCompleted: true,+ graphHealth,+ });+}++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;+}++describe("ix context on a degraded graph", () => {+ it("does not call the bundle current, and carries the verdict", () => {+ const b = bundle(DEGRADED);+ expect(b.freshness.classification).toBe("degraded");+ expect(b.graph).toMatchObject({ status: "degraded", reason: "hollow", fix: "ix reset --workspace --yes --ingest" });+ // It survives --save / --out: the schema declares it.+ expect(contextBundleSchema.parse(b).graph?.status).toBe("degraded");+ });++ it("drops stale=false from the llm header and puts the graph record right after it", () => {+ const lines = captureLog(() => renderBundle(bundle(DEGRADED), "llm"));+ expect(lines[0]).toContain("graph=degraded classification=degraded");+ expect(lines[0]).not.toContain("stale=");+ expect(lines[1]).toMatch(/^graph status=degraded reason=hollow /);+ });++ it("warns a person in text", () => {+ const text = captureLog(() => renderBundle(bundle(DEGRADED), "text")).join("\n");+ expect(text).toContain("Graph is degraded.");+ expect(text).toContain("Fix: ix reset --workspace --yes --ingest");+ });++ it("is unchanged on a healthy graph", () => {+ const b = bundle({ status: "ok" });+ expect(b.freshness.classification).toBe("current");+ expect(b.graph).toBeUndefined();+ const lines = captureLog(() => renderBundle(b, "llm"));+ expect(lines[0]).toContain("stale=false classification=current");+ expect(lines.some((l) => l.startsWith("graph "))).toBe(false);+ });+});diff --git a/ix-cli/src/cli/__tests__/graph-health.test.ts b/ix-cli/src/cli/__tests__/graph-health.test.tsnew file mode 100644index 00000000..6cf14c27--- /dev/null+++ b/ix-cli/src/cli/__tests__/graph-health.test.ts@@ -0,0 +1,222 @@+// Copyright 2026 Ix Infrastructure Inc.++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import * as fs from "node:fs";+import * as os from "node:os";+import * as path from "node:path";++import {+ assessGraphStats,+ assessTargetStructure,+ checkGraphHealth,+ clearGraphHealthCache,+ GRAPH_REBUILD_FIX,+ resetGraphHealthMemo,+ worseHealth,+} from "../graph-health.js";++// `/v1/stats` bodies measured on the local backend: the ix-bench graph for+// checkout 37f98b16 (healthy) and for 5e611d17 (hollowed by another checkout's+// ingest, Ix-memory#211). Same repository, a few commits apart.+const HEALTHY = {+ nodes: {+ total: 9064,+ byKind: [+ { kind: "chunk", count: 4050 }, { kind: "function", count: 1284 }, { kind: "module", count: 1186 },+ { kind: "config_entry", count: 859 }, { kind: "constant", count: 532 }, { kind: "file", count: 317 },+ { kind: "heading", count: 275 }, { kind: "section", count: 275 }, { kind: "interface", count: 155 },+ { kind: "method", count: 105 }, { kind: "class", count: 22 }, { kind: "frontmatter", count: 4 },+ ],+ },+ edges: {+ total: 23263,+ byPredicate: [+ { predicate: "CALLS", count: 9238 }, { predicate: "CONTAINS_CHUNK", count: 3770 },+ { predicate: "DEFINES", count: 3726 }, { predicate: "CONTAINS", count: 2942 },+ { predicate: "NEXT", count: 1821 }, { predicate: "IMPORTS", count: 1189 },+ { predicate: "REFERENCES", count: 565 }, { predicate: "EXTENDS", count: 12 },+ ],+ },+};++const HOLLOW = {+ nodes: {+ total: 9243,+ byKind: [+ { kind: "chunk", count: 4109 }, { kind: "function", count: 1315 }, { kind: "module", count: 1241 },+ { kind: "config_entry", count: 860 }, { kind: "constant", count: 538 }, { kind: "file", count: 333 },+ { kind: "heading", count: 275 }, { kind: "section", count: 275 }, { kind: "interface", count: 156 },+ { kind: "method", count: 115 }, { kind: "class", count: 22 }, { kind: "frontmatter", count: 4 },+ ],+ },+ edges: {+ total: 387,+ byPredicate: [+ { predicate: "CALLS", count: 222 }, { predicate: "CONTAINS_CHUNK", count: 39 },+ { predicate: "CONTAINS", count: 38 }, { predicate: "DEFINES", count: 38 },+ { predicate: "IMPORTS", count: 35 }, { predicate: "NEXT", count: 14 }, { predicate: "REFERENCES", count: 1 },+ ],+ },+};++describe("assessGraphStats", () => {+ it("passes a healthy graph", () => {+ const health = assessGraphStats(HEALTHY);+ expect(health.status).toBe("ok");+ expect(health.structuralEdges).toBe(3770 + 3726 + 2942);+ expect(health.symbols).toBe(9064 - 317);+ });++ it("calls a graph that kept its nodes and lost its edges degraded, with the repair", () => {+ const health = assessGraphStats(HOLLOW);+ expect(health.status).toBe("degraded");+ expect(health.reason).toBe("hollow");+ expect(health.fix).toBe(GRAPH_REBUILD_FIX);+ expect(health.message).toContain("9243 nodes but 387 edges");+ expect(health.message).toContain("1% of symbols");+ });++ it("calls a small graph with symbols and no edge at all degraded", () => {+ // What a hollowed three-file workspace looks like: 13 nodes, 0 edges.+ const health = assessGraphStats({+ nodes: { total: 13, byKind: [{ kind: "function", count: 6 }, { kind: "file", count: 3 }, { kind: "module", count: 2 }, { kind: "class", count: 1 }, { kind: "method", count: 1 }] },+ edges: { total: 0, byPredicate: [] },+ });+ expect(health.status).toBe("degraded");+ });++ it("does not judge a graph too small to judge", () => {+ const health = assessGraphStats({+ nodes: { total: 3, byKind: [{ kind: "file", count: 2 }, { kind: "function", count: 1 }] },+ edges: { total: 0, byPredicate: [] },+ });+ expect(health.status).toBe("ok");+ });++ it("reports a registered workspace with no nodes as empty, fixed by a map", () => {+ const health = assessGraphStats({ nodes: { total: 0, byKind: [] }, edges: { total: 0, byPredicate: [] } });+ expect(health).toMatchObject({ status: "empty", reason: "no_nodes", fix: "ix map" });+ });++ it("says nothing when the body carries no breakdown to judge by", () => {+ // An older backend or a stub: a missing breakdown must not read as zero edges.+ expect(assessGraphStats({ nodes: { total: 7717 }, edges: { total: 16983 } }).status).toBe("unknown");+ expect(assessGraphStats(undefined).status).toBe("unknown");+ expect(assessGraphStats({ error: "nope" }).status).toBe("unknown");+ });+});++describe("assessTargetStructure", () => {+ it("flags a definition no file contains", () => {+ const health = assessTargetStructure({ name: "parseBudgetOption", kind: "function", path: "ix-cli/src/cli/options.ts" });+ expect(health).toMatchObject({ status: "degraded", reason: "orphaned_target", fix: GRAPH_REBUILD_FIX });+ expect(health?.message).toContain("parseBudgetOption (function) in ix-cli/src/cli/options.ts");+ });++ it("says nothing about a contained definition, or a kind that is not always contained", () => {+ expect(assessTargetStructure({ name: "f", kind: "function", container: { id: "file-1" } })).toBeUndefined();+ expect(assessTargetStructure({ name: "options.ts", kind: "file" })).toBeUndefined();+ expect(assessTargetStructure({ name: "Intro", kind: "heading" })).toBeUndefined();+ });+});++describe("worseHealth", () => {+ it("keeps the worse verdict", () => {+ const ok = { status: "ok" as const };+ const bad = assessTargetStructure({ name: "f", kind: "function" });+ expect(worseHealth(ok, bad)).toBe(bad);+ expect(worseHealth({ status: "unknown" }, bad)).toBe(bad);+ expect(worseHealth(ok, undefined)).toBe(ok);+ expect(worseHealth(bad!, ok)).toBe(bad);+ });+});++describe("checkGraphHealth", () => {+ let home: string;++ beforeEach(() => {+ home = fs.mkdtempSync(path.join(os.tmpdir(), "ix-graph-health-"));+ process.env.IX_HOME = home;+ resetGraphHealthMemo();+ });++ afterEach(() => {+ delete process.env.IX_HOME;+ fs.rmSync(home, { recursive: true, force: true });+ });++ function client(revisions: unknown[], statsBody: unknown = HOLLOW) {+ let call = 0;+ return {+ endpoint: "http://backend.test",+ currentRevision: vi.fn(async () => revisions[Math.min(call++, revisions.length - 1)]),+ stats: vi.fn(async () => statsBody),+ };+ }++ it("asks for stats once per backend revision, bounded by its timeout", async () => {+ const c = client([3217, 3217]);+ const first = await checkGraphHealth(c, { workspaceId: "e4e3a3d1" }, {});+ const second = await checkGraphHealth(c, { workspaceId: "e4e3a3d1" }, {});+ expect(first.status).toBe("degraded");+ expect(second).toEqual(first);+ expect(c.stats).toHaveBeenCalledTimes(1);+ expect(c.stats).toHaveBeenCalledWith({ workspaceId: "e4e3a3d1", timeoutMs: 2000 });+ });++ it("asks again once the head moves -- an ingest elsewhere is what hollows a graph", async () => {+ const c = client([3217, 3218]);+ await checkGraphHealth(c, { workspaceId: "e4e3a3d1" }, {});+ await checkGraphHealth(c, { workspaceId: "e4e3a3d1" }, {});+ expect(c.stats).toHaveBeenCalledTimes(2);+ });++ it("answers a fresh process from the disk cache at the same revision", async () => {+ await checkGraphHealth(client([3217]), { workspaceId: "e4e3a3d1" }, {});+ resetGraphHealthMemo(); // a new CLI process+ const next = client([3217]);+ const health = await checkGraphHealth(next, { workspaceId: "e4e3a3d1" }, {});+ expect(health.status).toBe("degraded");+ expect(next.stats).not.toHaveBeenCalled();+ expect(fs.readdirSync(home).some((f) => f.startsWith("graph_health_"))).toBe(true);+ });++ it("is forgotten by a reset, which does not move the head revision", async () => {+ // Measured on backend 1.0.30: /v1/reset/workspace deletes the data and+ // leaves /v1/revisions/current where it was.+ await checkGraphHealth(client([3217], HEALTHY), { workspaceId: "w" }, {});+ clearGraphHealthCache();+ const after = client([3217], { nodes: { total: 0, byKind: [] }, edges: { total: 0, byPredicate: [] } });+ expect((await checkGraphHealth(after, { workspaceId: "w" }, {})).status).toBe("empty");+ expect(fs.readdirSync(home).filter((f) => f.startsWith("graph_health_"))).toHaveLength(1);+ });++ it("keeps workspaces apart", async () => {+ const c = client([3217]);+ await checkGraphHealth(c, { workspaceId: "e4e3a3d1" }, {});+ await checkGraphHealth(c, { workspaceId: "a2ebc094" }, {});+ expect(c.stats).toHaveBeenCalledTimes(2);+ });++ it("never throws: a failing backend is `unknown`, and nothing is cached", async () => {+ const c = { endpoint: "x", currentRevision: vi.fn(async () => 1), stats: vi.fn(async () => { throw new Error("aborted"); }) };+ expect((await checkGraphHealth(c, { workspaceId: "w" }, {})).status).toBe("unknown");+ expect((await checkGraphHealth(c, { workspaceId: "w" }, {})).status).toBe("unknown");+ expect(c.stats).toHaveBeenCalledTimes(2);+ // A stub without the methods (every mocked client in this suite) is the same.+ expect((await checkGraphHealth({} as never, { workspaceId: "w" }, {})).status).toBe("unknown");+ });++ it("does nothing without a scope, or when turned off", async () => {+ const c = client([1]);+ expect((await checkGraphHealth(c, {}, {})).status).toBe("unknown");+ expect((await checkGraphHealth(c, { workspaceId: "w" }, { IX_GRAPH_HEALTH: "0" })).status).toBe("unknown");+ expect(c.currentRevision).not.toHaveBeenCalled();+ });++ it("honours IX_GRAPH_HEALTH_TIMEOUT_MS", async () => {+ const c = client([1]);+ await checkGraphHealth(c, { systemId: "sys-1" }, { IX_GRAPH_HEALTH_TIMEOUT_MS: "250" });+ expect(c.stats).toHaveBeenCalledWith({ systemId: "sys-1", timeoutMs: 250 });+ });+});diff --git a/ix-cli/src/cli/__tests__/reset-workspace.test.ts b/ix-cli/src/cli/__tests__/reset-workspace.test.tsnew file mode 100644index 00000000..a0ca4f83--- /dev/null+++ b/ix-cli/src/cli/__tests__/reset-workspace.test.ts@@ -0,0 +1,111 @@+// Copyright 2026 Ix Infrastructure Inc.++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import * as fs from "node:fs";+import * as os from "node:os";+import * as path from "node:path";+import { Command } from "commander";++const calls = vi.hoisted(() => ({ deleteWorkspace: [] as string[], reset: 0, resetCode: 0 }));++vi.mock("../../client/api.js", () => ({+ IxClient: class {+ async deleteWorkspace(id: string) { calls.deleteWorkspace.push(id); }+ async reset() { calls.reset++; return { ok: true, message: "" }; }+ async resetCode() { calls.resetCode++; return { ok: true, message: "" }; }+ },+}));++import { registerResetCommand } from "../commands/reset.js";+import { ingestMtimeCachePath, saveConfig } from "../config.js";++/**+ * `ix reset --workspace`: the repair a degraded graph points at. It must touch+ * exactly one workspace -- the registered one the caller stands in -- because+ * `ix reset` without it wipes every workspace on a shared backend.+ */++let home: string;+let mine: string;+let theirs: string;+let savedCwd: string;+let out: string[];+let err: string[];++async function run(args: string[]): Promise<void> {+ const program = new Command();+ program.name("ix").exitOverride();+ registerResetCommand(program);+ await program.parseAsync(["reset", ...args], { from: "user" });+}++beforeEach(() => {+ home = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "ix-reset-ws-")));+ process.env.IX_HOME = path.join(home, ".ix");+ mine = path.join(home, "mine");+ theirs = path.join(home, "theirs");+ fs.mkdirSync(mine, { recursive: true });+ fs.mkdirSync(theirs, { recursive: true });+ saveConfig({+ endpoint: "http://localhost:8090",+ format: "text",+ workspaces: [+ { workspace_id: "aaaa0001", workspace_name: "theirs", root_path: theirs, default: true },+ { workspace_id: "bbbb0002", workspace_name: "mine", root_path: mine, default: false },+ ],+ });+ calls.deleteWorkspace.length = 0;+ calls.reset = 0;+ calls.resetCode = 0;+ savedCwd = process.cwd();+ out = [];+ err = [];+ vi.spyOn(console, "log").mockImplementation((...a) => void out.push(a.join(" ")));+ vi.spyOn(console, "error").mockImplementation((...a) => void err.push(a.join(" ")));+});++afterEach(() => {+ vi.restoreAllMocks();+ process.chdir(savedCwd);+ process.exitCode = undefined;+ delete process.env.IX_HOME;+ fs.rmSync(home, { recursive: true, force: true });+});++describe("ix reset --workspace", () => {+ it("deletes only the workspace containing cwd, and forgets its ingest state", async () => {+ const cache = ingestMtimeCachePath(mine);+ fs.mkdirSync(path.dirname(cache), { recursive: true });+ fs.writeFileSync(cache, "{}");+ process.chdir(path.join(mine));++ await run(["--workspace", "--yes"]);++ expect(calls.deleteWorkspace).toEqual(["bbbb0002"]);+ expect(calls.reset + calls.resetCode).toBe(0);+ // Left in place, the rebuild would skip every file as unchanged.+ expect(fs.existsSync(cache)).toBe(false);+ expect(out.join("\n")).toContain("Workspace 'mine' wiped. Other workspaces untouched.");+ expect(process.exitCode).toBeUndefined();+ });++ it("refuses a directory no workspace covers, rather than resetting the default one", async () => {+ const elsewhere = path.join(home, "elsewhere");+ fs.mkdirSync(elsewhere);+ process.chdir(elsewhere);++ await run(["--workspace", "--yes"]);++ expect(calls.deleteWorkspace).toEqual([]);+ expect(err.join("\n")).toContain("is not inside a registered workspace; nothing to reset.");+ expect(process.exitCode).toBe(1);+ });++ it("refuses --code alongside it", async () => {+ process.chdir(mine);+ await run(["--workspace", "--code", "--yes"]);+ expect(calls.deleteWorkspace).toEqual([]);+ expect(calls.resetCode).toBe(0);+ expect(process.exitCode).toBe(1);+ });+});diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.tsindex 8eac3d7b..cc8ed2bb 100644--- a/ix-cli/src/cli/commands/context.ts+++ b/ix-cli/src/cli/commands/context.ts@@ -42,6 +42,9 @@ import { activeReadScope, ensureReadScope, resolveFileOrReport } from "../resolvimport { createStaleProbe, hasCompletedSourceGraphBaseline } from "../stale.js";import { renderNote, renderSection, renderWarning, renderWarningErr, reportFailure } from "../ui.js";import { printJson, relativePath } from "../format.js";+import {+ assessTargetStructure, checkGraphHealth, graphHealthJson, isUnhealthy, worseHealth, type GraphHealth,+} from "../graph-health.js";/** The `--max-*` knobs that bound a bundle. */interface BudgetSnapshot {@@ -283,7 +286,14 @@ interface ContextBundle {historyLength: number;stale: boolean;};- freshness: { stale: boolean; classification: "current" | "stale" | "unverified" };+ /**+ * `degraded` when the graph has lost its structural edges (see+ * graph-health.ts): nothing is known to have changed on disk, but the+ * bundle's members, callers and neighbours are missing, not absent.+ */+ freshness: { stale: boolean; classification: "current" | "stale" | "unverified" | "degraded" };+ /** Present only for a degraded or empty graph: what is wrong and the fix. */+ graph?: Record<string, unknown>;evidence: EvidenceItem[];budgets: BudgetSnapshot;truncation: {@@ -443,7 +453,7 @@ export function registerContextCommand(program: Command): void {const budgets = clampBudgets(opts);const asOfRev = opts.asOfRev;- const [facts, context] = await Promise.all([+ const [facts, context, workspaceHealth] = await Promise.all([// Also carries the provenance response: `collectFacts` needs it for the// history length, and fetching it again here doubled one of the// slowest calls the command makes (~1.3s on the Ix repo's graph).@@ -457,6 +467,9 @@ export function registerContextCommand(program: Command): void {asOfRev,depth: opts.depth,}),+ // Cached per backend revision (graph-health.ts); in parallel, so free+ // on a warm cache.+ checkGraphHealth(client, activeReadScope()),]);const provenance = facts.provenance;@@ -469,6 +482,7 @@ export function registerContextCommand(program: Command): void {depth: opts.depth,budgets,graphCompleted: hasCompletedSourceGraphBaseline(),+ graphHealth: bundleGraphHealth(workspaceHealth, resolved, facts),});await emitBundle(bundle, opts);@@ -551,14 +565,16 @@ async function buildFreshBundle(if (!resolved) return undefined;const asOfRev = opts.asOfRev;- const [facts, context] = await Promise.all([+ const [facts, context, workspaceHealth] = await Promise.all([collectContextFacts(client, resolved),client.contextForNode(resolved.id, { asOfRev, depth: opts.depth }),+ checkGraphHealth(client, activeReadScope()),]);return buildBundle({resolved, facts, context, provenance: facts.provenance, asOfRev, depth: opts.depth, budgets,graphCompleted: hasCompletedSourceGraphBaseline(),+ graphHealth: bundleGraphHealth(workspaceHealth, resolved, facts),});}}@@ -1511,6 +1527,12 @@ interface BuildInput {* silently reclassified.*/graphCompleted?: boolean;+ /**+ * The graph-health verdict (graph-health.ts), workspace-wide. The target's+ * own structure is judged here from `facts`. Absent under test and when the+ * check could not run, which says nothing.+ */+ graphHealth?: GraphHealth;/** Set by `--from-issue`: the starting points and the ranked files. */issue?: IssueBundleInput;}@@ -1669,10 +1691,11 @@ async function buildIssueBundle(return undefined;}const resolved = { id: centre.id!, name: centre.name, kind: centre.kind, resolutionMode: "issue" };- const [facts, context, around] = await Promise.all([+ const [facts, context, around, workspaceHealth] = 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))),+ checkGraphHealth(client, scope),]);const near = new Map<string, Closeness>();@@ -1697,6 +1720,7 @@ async function buildIssueBundle(depth: opts.depth,budgets,graphCompleted: hasCompletedSourceGraphBaseline(),+ graphHealth: bundleGraphHealth(workspaceHealth, resolved, facts),issue: {startingPoints: starts,unresolved: plan.unresolved,@@ -1799,6 +1823,21 @@ async function collectTextRelated(})));}+/**+ * The workspace verdict, made worse by the target's own structure when a+ * definition no file contains shows its edges are gone even though the+ * workspace as a whole looks fine (only some files re-ingested elsewhere).+ */+function bundleGraphHealth(+ workspace: GraphHealth,+ resolved: { name: string; kind: string },+ facts: { path?: string; container?: unknown },+): GraphHealth {+ return worseHealth(workspace, assessTargetStructure({+ name: resolved.name, kind: resolved.kind, path: facts.path, container: facts.container,+ }));+}+export function buildBundle(input: BuildInput): ContextBundle {const { resolved, facts, context, provenance, asOfRev, depth, budgets } = input;@@ -1809,7 +1848,11 @@ export function buildBundle(input: BuildInput): ContextBundle {// freshness union has carried `unverified` for exactly this case since it was// written; this is the first thing to produce it.const graphCompleted = input.graphCompleted ?? true;- const classification = !graphCompleted ? "unverified" : stale ? "stale" : "current";+ // A hollowed graph outranks all three: "current" would vouch for a bundle+ // whose members and callers the graph has lost.+ const health = input.graphHealth;+ const degraded = isUnhealthy(health);+ const classification = degraded ? "degraded" : !graphCompleted ? "unverified" : stale ? "stale" : "current";const prov = provenanceSource(provenance);// Entities: the target itself plus every referenced node, deduped by id and@@ -1982,6 +2025,7 @@ export function buildBundle(input: BuildInput): ContextBundle {stale,},freshness: { stale, classification },+ ...(degraded ? { graph: graphHealthJson(health) } : {}),evidence: [],budgets,truncation: {@@ -2337,7 +2381,10 @@ export function renderBundle(bundle: ContextBundle, format: string): void {target: bundle.target.name,target_kind: bundle.target.kind,target_path: bundle.target.path,- stale: bundle.freshness.stale,+ // Not on a degraded graph: `stale=false` there reads as a clean bill+ // of health for a bundle the graph has hollowed out.+ graph: bundle.graph ? String(bundle.graph.status) : undefined,+ stale: bundle.graph ? undefined : bundle.freshness.stale,classification: bundle.freshness.classification,entities: bundle.entities.length,relationships: bundle.relationships.length,@@ -2351,6 +2398,13 @@ export function renderBundle(bundle: ContextBundle, format: string): void {truncated_evidence: bundle.truncation.evidenceTruncated,truncated_chars: bundle.truncation.charactersTruncated,}),+ // First after the header: everything below is drawn from this graph.+ bundle.graph ? llmLine("graph", {+ status: asString(bundle.graph.status),+ reason: asString(bundle.graph.reason),+ message: asString(bundle.graph.message),+ fix: asString(bundle.graph.fix),+ }) : null,// What the budget dropped, and the cheapest command that gets it back.// The header's `truncated_*` counters say how much went; without this the// caller's only move is a bigger budget for the same query, which is the@@ -2393,6 +2447,12 @@ export function renderBundle(bundle: ContextBundle, format: string): void {);if (bundle.issue.fallback) renderNote(ISSUE_FALLBACK_NOTE);}+ if (bundle.graph) {+ const g = bundle.graph;+ renderWarning(+ `Graph is ${String(g.status)}. ${g.message ? String(g.message) : ""}${g.fix ? ` Fix: ${String(g.fix)}` : ""}`.trim(),+ );+ }if (bundle.freshness.stale) {renderWarning("Source has changed since last ingest. Run ix map to update.");}diff --git a/ix-cli/src/cli/commands/doctor.ts b/ix-cli/src/cli/commands/doctor.tsindex 86307000..1a801460 100644--- a/ix-cli/src/cli/commands/doctor.ts+++ b/ix-cli/src/cli/commands/doctor.ts@@ -6,6 +6,7 @@ import { renderSection, renderSuccess, renderError } from "../ui.js";import { IxClient } from "../../client/api.js";import { findWorkspaceForCwd, getDefaultWorkspace, getEndpoint } from "../config.js";import { resolveReadSystemId } from "../resolve.js";+import { assessGraphStats } from "../graph-health.js";import { llmLine, printLlmLines } from "../llm.js";import { existsSync, readFileSync } from "node:fs";import { join as pathJoin, resolve as resolvePath, win32 as winPath } from "node:path";@@ -299,6 +300,34 @@ export function registerDoctorCommand(program: Command): void {}},},+ {+ // A graph can keep every node and lose nearly every edge (another+ // checkout's ingest, Ix-memory#211): both counts above stay non-zero+ // and every answer is quietly wrong. Same judgement as the query+ // paths use (graph-health.ts), from the stats already fetched.+ name: "Graph structure intact",+ run: async () => {+ try {+ const { stats, scope } = await sharedStats();+ const health = assessGraphStats(stats);+ if (health.status === "degraded") {+ return { ok: false, detail: `${scope}: ${health.message} Fix: ${health.fix}` };+ }+ if (health.status === "ok") {+ return {+ ok: true,+ detail: `${health.structuralEdges} structural edges for ${health.symbols} symbols in ${scope}`,+ };+ }+ // Empty (which "Graph has nodes" already fails) or a stats body+ // without the per-predicate breakdown: nothing to judge by, and+ // not a second failure for one problem.+ return { ok: true, detail: `not judged: no ${health.status === "empty" ? "nodes" : "edge breakdown"} in ${scope}` };+ } catch (e: any) {+ return { ok: false, detail: e.message ?? "stats failed" };+ }+ },+ },{name: "No unresolved conflicts",run: async () => {diff --git a/ix-cli/src/cli/commands/explain.ts b/ix-cli/src/cli/commands/explain.tsindex 521eed96..ec6a3c68 100644--- a/ix-cli/src/cli/commands/explain.ts+++ b/ix-cli/src/cli/commands/explain.ts@@ -4,7 +4,7 @@ import type { Command } from "commander";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { formatExplain, relativePath, printJson, type ExplainResult, type EntityRef, type Diagnostic } from "../format.js";-import { resolveFileOrReport, isRawId } from "../resolve.js";+import { resolveFileOrReport, isRawId, activeReadScope } from "../resolve.js";import { isFileStale } from "../stale.js";import { collectFacts } from "../explain/facts.js";import { inferRole } from "../explain/role-inference.js";@@ -14,6 +14,9 @@ import { renderExplainLlm, renderExplainRawLlm } from "../explain/llm.js";import { printLlmLines } from "../llm.js";import { parsePickOption } from "../options.js";import { renderSection, renderWarning, renderNote } from "../ui.js";+import {+ assessTargetStructure, checkGraphHealth, graphHealthJson, graphHealthProse, isUnhealthy, worseHealth,+} from "../graph-health.js";export function registerExplainCommand(program: Command): void {program@@ -36,14 +39,33 @@ export function registerExplainCommand(program: Command): void {return;}- // New pipeline: collect facts → infer role → infer importance → render+ // New pipeline: collect facts → infer role → infer importance → render.+ // The workspace health check runs alongside: cached per backend+ // revision, so on a warm cache it is one ~10 ms request in parallel.+ const healthCheck = checkGraphHealth(client, activeReadScope());const facts = await collectFacts(client, target.id, target.name, target.kind);- const role = inferRole(facts);- const importance = inferImportance(facts);+ const health = worseHealth(await healthCheck, assessTargetStructure(facts));+ const degraded = isUnhealthy(health);+ let role = inferRole(facts);+ let importance = inferImportance(facts);const rendered = renderExplanation(facts, role, importance);+ if (degraded) {+ // Every inference below is drawn from edge counts the graph has lost,+ // so "localized-helper, low importance, 0 callers" would be a confident+ // wrong answer. Withheld, with the reason attached.+ const why = `graph degraded: ${health.reason}`;+ role = { role: "unknown", confidence: "low", reasons: [why] };+ importance = { level: "low", category: "normal", reasons: [why] };+ rendered.explanation =+ `\`${facts.name}\` is a ${facts.kind}${facts.path ? ` in ${facts.path}` : ""}; its role cannot be ` ++ "inferred from this graph." + (facts.signature ? ` Signature: \`${facts.signature}\`.` : "");+ rendered.whyItMatters =+ "Unknown: the graph for this workspace is missing structural edges, so callers, callees and " ++ "dependents cannot be counted. Counts shown here are floors, and a zero means unknown.";+ }if (opts.format === "llm") {- printLlmLines(renderExplainLlm(facts, role, importance, rendered));+ printLlmLines(renderExplainLlm(facts, role, importance, rendered, health));} else if (opts.format === "json") {const output: any = {resolvedTarget: { kind: target.kind, name: target.name },@@ -52,9 +74,17 @@ export function registerExplainCommand(program: Command): void {importance,rendered,};+ if (degraded) {+ output.graph = graphHealthJson(health);+ // Not a level the type can hold on purpose: nothing downstream may+ // mistake it for a real `low`.+ output.importance = { level: "unknown", category: "unknown", reasons: importance.reasons };+ facts.diagnostics.unshift({ code: "graph_degraded", message: graphHealthProse(health) });+ }if (facts.diagnostics.length > 0) output.diagnostics = facts.diagnostics;printJson(output);} else {+ if (degraded) renderWarning(graphHealthProse(health));if (facts.stale) {renderWarning("Source has changed since last ingest. Run ix map to update.");}diff --git a/ix-cli/src/cli/commands/reset.ts b/ix-cli/src/cli/commands/reset.tsindex 56c27c6a..7e6375b0 100644--- a/ix-cli/src/cli/commands/reset.ts+++ b/ix-cli/src/cli/commands/reset.ts@@ -4,10 +4,11 @@ import type { Command } from "commander";import chalk from "chalk";import { spawnSync } from "child_process";import { IxClient } from "../../client/api.js";-import { getEndpoint, clearIngestMtimeCache, clearStitchScopeCache } from "../config.js";+import { getEndpoint, clearIngestMtimeCache, clearStitchScopeCache, findWorkspaceForCwd } from "../config.js";import { canRenderProgress } from "../stderr.js";import { resolveWorkspaceId } from "../bootstrap.js";import { clearStitchCooldown } from "../stitch-guard.js";+import { clearGraphHealthCache } from "../graph-health.js";/*** Drop this workspace's cached "am I stitched into a system?" answer.@@ -28,7 +29,21 @@ export function registerResetCommand(program: Command): void {.option("-y, --yes", "Skip confirmation prompt").option("--code", "Reset only code graph (files, functions, classes, regions); preserve goals, plans, tasks, bugs, and decisions").option("--ingest", "Re-run ix map after wiping (rebuilds the code graph)")- .action(async (opts: { yes?: boolean; code?: boolean; ingest?: boolean }) => {+ .option(+ "--workspace",+ "Wipe only the workspace this directory belongs to (every other workspace on the backend is untouched). " ++ "With --ingest, this is the repair for a graph that has lost its edges",+ )+ .action(async (opts: { yes?: boolean; code?: boolean; ingest?: boolean; workspace?: boolean }) => {+ if (opts.workspace) {+ if (opts.code) {+ console.error(chalk.red("Error:"), "--workspace and --code cannot be combined: a workspace reset already keeps every other workspace.");+ process.exitCode = 1;+ return;+ }+ await resetThisWorkspace(opts);+ return;+ }const scope = opts.code ? "code graph" : "all graph data";const warning = opts.code? "This will delete all code nodes and edges (files, functions, classes, regions).\nPlanning artifacts (goals, plans, tasks, bugs, decisions) will be preserved."@@ -73,6 +88,7 @@ export function registerResetCommand(program: Command): void {// Clear the mtime cache so the next ix map re-ingests all filesclearIngestMtimeCache(process.cwd());clearStitchScopeCacheForCwd();+ clearGraphHealthCache();// Ix#568: and the stitch cooldown. The re-ingest below is the one// run that can re-register this workspace, and a live cooldown would// refuse exactly it -- leaving the workspace unregistered with@@ -93,6 +109,7 @@ export function registerResetCommand(program: Command): void {stopSpinner();clearIngestMtimeCache(process.cwd());clearStitchScopeCacheForCwd();+ clearGraphHealthCache();// Ix#568: and the stitch cooldown. The re-ingest below is the one// run that can re-register this workspace, and a live cooldown would// refuse exactly it -- leaving the workspace unregistered with@@ -125,3 +142,69 @@ export function registerResetCommand(program: Command): void {}});}++/**+ * `ix reset --workspace`: delete one workspace's graph through the scoped+ * `/v1/reset/workspace`, then (with `--ingest`) map it again.+ *+ * This is the only repair for a hollowed graph (see graph-health.ts): `ix map`+ * skips unchanged files and `ix ingest --force` re-sends patches the backend+ * already recorded, so neither re-creates the lost edges. The backend clears+ * the workspace's patch idempotency keys with its data, which is what makes+ * the re-ingest real.+ *+ * Scoped by the directory, strictly: the registered workspace containing cwd,+ * never a pinned or default one, because this deletes data and the target+ * must be the one the user is standing in.+ */+async function resetThisWorkspace(opts: { yes?: boolean; ingest?: boolean }): Promise<void> {+ const ws = findWorkspaceForCwd(process.cwd());+ if (!ws) {+ console.error(chalk.red("Error:"), `${process.cwd()} is not inside a registered workspace; nothing to reset.`);+ console.error(chalk.dim("Run `ix map` here to map it instead."));+ process.exitCode = 1;+ return;+ }+ if (!opts.yes) {+ console.log(chalk.yellow(+ `This deletes the graph of workspace '${ws.workspace_name}' (${ws.root_path}) and nothing else.`,+ ));+ process.stdout.write(chalk.yellow(`Reset workspace '${ws.workspace_name}'? (y/N) `));+ const answer = await new Promise<string>(resolve => {+ process.stdin.setEncoding("utf8");+ process.stdin.once("data", (chunk: string) => resolve(chunk.trim()));+ });+ process.stdin.destroy();+ if (answer.toLowerCase() !== "y") {+ console.log(chalk.dim("Aborted."));+ return;+ }+ }++ const client = new IxClient(getEndpoint());+ try {+ await client.deleteWorkspace(ws.workspace_id);+ } catch (err: any) {+ console.error(chalk.red("Error:"), err.message);+ process.exitCode = 1;+ return;+ }+ // The local "already ingested" state describes the graph just deleted: left+ // in place, the map below would skip every file as unchanged.+ clearIngestMtimeCache(ws.root_path);+ clearStitchScopeCache(ws.workspace_id);+ clearGraphHealthCache();+ clearStitchCooldown(getEndpoint());+ console.log(chalk.green("✓") + ` Workspace '${ws.workspace_name}' wiped. Other workspaces untouched.`);++ if (!opts.ingest) {+ console.log(chalk.dim(" Run `ix map` to rebuild it."));+ return;+ }+ console.log(chalk.dim("Rebuilding..."));+ const result = spawnSync(process.argv[0], [process.argv[1], "map"], {+ stdio: "inherit",+ cwd: ws.root_path,+ });+ if (result.status !== 0) process.exitCode = result.status ?? 1;+}diff --git a/ix-cli/src/cli/context-bundle-schema.ts b/ix-cli/src/cli/context-bundle-schema.tsindex f20a66a2..6f3be6f1 100644--- a/ix-cli/src/cli/context-bundle-schema.ts+++ b/ix-cli/src/cli/context-bundle-schema.ts@@ -106,6 +106,18 @@ export const contextBundleSchema = z.object({}).catchall(z.unknown()),freshness: z.object({ stale: z.boolean(), classification: z.string() }),+ // Only when the graph the bundle was drawn from is degraded or empty (see+ // graph-health.ts). Optional and additive, like `issue`; declared so zod+ // does not strip it on the way to disk.+ graph: z+ .object({+ status: z.string(),+ reason: z.string().optional(),+ message: z.string().optional(),+ fix: z.string().optional(),+ })+ .catchall(z.unknown())+ .optional(),evidence: z.array(z.object({id: z.string(),diff --git a/ix-cli/src/cli/explain/llm.ts b/ix-cli/src/cli/explain/llm.tsindex 3034688b..86809335 100644--- a/ix-cli/src/cli/explain/llm.ts+++ b/ix-cli/src/cli/explain/llm.ts@@ -6,6 +6,7 @@ import type { EntityFacts, EntityLocation } from "./facts.js";import type { RoleInference } from "./role-inference.js";import type { ImportanceInference } from "./importance.js";import type { ExplanationOutput } from "./render.js";+import { isUnhealthy, graphHealthLlmFields, type GraphHealth } from "../graph-health.js";/*** `ix explain --format llm`.@@ -39,8 +40,15 @@ export function renderExplainLlm(role: RoleInference,importance: ImportanceInference,rendered: ExplanationOutput,+ health?: GraphHealth,): string[] {const lines: string[] = [];+ // A hollowed graph answers every count below with 0, and the role and+ // importance are inferred from those counts. First, so it is read before+ // any of them; and the conclusions drawn from missing edges are withheld+ // rather than stated (see graph-health.ts).+ const degraded = isUnhealthy(health);+ if (degraded) lines.push(llmLine("graph", graphHealthLlmFields(health)));lines.push(llmLine("entity", [["id", llmShortId(facts.id)],@@ -51,27 +59,36 @@ export function renderExplainLlm(["stale", facts.stale ? "true" : null],]));- lines.push(llmLine("role", [- ["role", role.role],- ["confidence", role.confidence],- ]));+ if (degraded) {+ lines.push(llmLine("role", [["role", "unknown"], ["confidence", "none"], ["reason", "graph_degraded"]]));+ lines.push(llmLine("importance", [["level", "unknown"], ["reason", "graph_degraded"]]));+ } else {+ lines.push(llmLine("role", [+ ["role", role.role],+ ["confidence", role.confidence],+ ]));- lines.push(llmLine("importance", [- ["level", importance.level],- ["category", importance.category],- ]));+ lines.push(llmLine("importance", [+ ["level", importance.level],+ ["category", importance.category],+ ]));+ }// Zeroes are meaningful here, so they are stringified rather than passed as- // numbers — llmField drops "" but keeps "0".+ // numbers — llmField drops "" but keeps "0". On a degraded graph a zero is+ // an edge that may simply be missing, so it is `unknown` there; a non-zero+ // count is still an edge that exists, i.e. a floor.+ const count = (n: number) => (degraded && n === 0 ? "unknown" : String(n));lines.push(llmLine("edges", [- ["callers", String(facts.callerCount)],- ["callees", String(facts.calleeCount)],- ["dependents", String(facts.dependentCount)],- ["importers", String(facts.importerCount)],- ["members", String(facts.memberCount)],- ["downstream", String(facts.downstreamDependents)],- ["depth", String(facts.downstreamDepth)],+ ["callers", count(facts.callerCount)],+ ["callees", count(facts.calleeCount)],+ ["dependents", count(facts.dependentCount)],+ ["importers", count(facts.importerCount)],+ ["members", count(facts.memberCount)],+ ["downstream", count(facts.downstreamDependents)],+ ["depth", count(facts.downstreamDepth)],["history", String(facts.historyLength)],+ ["complete", degraded ? "false" : null],]));if (facts.container) {diff --git a/ix-cli/src/cli/format.ts b/ix-cli/src/cli/format.tsindex f09c98d7..3f00b7b9 100644--- a/ix-cli/src/cli/format.ts+++ b/ix-cli/src/cli/format.ts@@ -845,7 +845,8 @@ export type DiagnosticCode =| "no_edges"| "text_fallback_used"| "stale_source"- | "unfiltered_search";+ | "unfiltered_search"+ | "graph_degraded";export interface Diagnostic {code: DiagnosticCode;diff --git a/ix-cli/src/cli/graph-health.ts b/ix-cli/src/cli/graph-health.tsnew file mode 100644index 00000000..61a73e70--- /dev/null+++ b/ix-cli/src/cli/graph-health.ts@@ -0,0 +1,333 @@+// Copyright 2026 Ix Infrastructure Inc.++import { readFileSync, writeFileSync, mkdirSync, readdirSync, rmSync } from "node:fs";+import { join } from "node:path";+import { createHash } from "node:crypto";+import type { IxClient } from "../client/api.js";+import { ixHome } from "./ix-home.js";+import { revisionToken } from "./map-result-cache.js";++/**+ * Is the graph a command is about to answer from structurally intact?+ *+ * A graph can hold every node of a repository and almost none of its edges.+ * Every answer drawn from it then looks normal and is wrong: `ix explain`+ * reports `callers=0 role=localized-helper` for a function with a caller, and+ * `ix context` says `stale=false` about a bundle with no members in it. The+ * failure is silent because nodes are what resolution needs, and nodes are+ * what survives.+ *+ * The state is produced by the backend. Re-ingesting a file retires the edges+ * that file produced earlier, matched by its `source_uri` -- a path relative to+ * the workspace root, and therefore the same string in every checkout of one+ * repository. Up to at least backend 1.0.30 that sweep is not filtered by+ * workspace (fix open as ix-infrastructure/Ix-memory#211), so ingesting one+ * checkout tombstones the CONTAINS / CALLS / IMPORTS edges of every other+ * checkout of the same repository on that backend. Node ids are namespaced by+ * workspace, so the other checkouts' nodes survive; their edges do not. A+ * plain `ix map` or `ix ingest --force` does not repair it: unchanged files are+ * skipped, and forced patches carry the same ids as the recorded ones and are+ * replayed as already applied. Only deleting the workspace's data first makes+ * the re-ingest real -- hence {@link GRAPH_REBUILD_FIX}.+ *+ * Two checks, both cheap:+ *+ * - {@link assessGraphStats}: workspace-wide, from `/v1/stats`. Every symbol a+ * parser emits is attached to its file by a CONTAINS / DEFINES /+ * CONTAINS_CHUNK edge, so a healthy graph has at least one such edge per+ * non-file node (measured: 1.19 on the Ix repo); a hollowed one has almost+ * none (0.01, 0.00, 0.00 on three hollowed checkouts of the same repo).+ * Cached per scope and backend revision, see {@link checkGraphHealth}.+ * - {@link assessTargetStructure}: for one entity, from facts a command has+ * already fetched. A definition no file contains has lost its edges even+ * when the rest of the graph is fine -- which is the common case when only+ * a few files were re-ingested elsewhere. Sampled: 0 of 60 functions+ * orphaned in a healthy graph, 59 of 60 in a hollowed one.+ */++export type GraphHealthStatus = "ok" | "degraded" | "empty" | "unknown";++export interface GraphHealth {+ status: GraphHealthStatus;+ /** Stable slug for the cause: `hollow`, `orphaned_target`, `no_nodes`. */+ reason?: string;+ /** One sentence saying what is wrong, for a person or an agent. */+ message?: string;+ /** The command that repairs it. */+ fix?: string;+ nodes?: number;+ edges?: number;+ /** CONTAINS + DEFINES + CONTAINS_CHUNK edges. */+ structuralEdges?: number;+ /** Non-file nodes, each of which should have a structural edge. */+ symbols?: number;+}++/**+ * The repair for a hollowed graph: delete this workspace's data (and only+ * this workspace's), then map it again. See the module comment for why+ * nothing short of that works.+ */+export const GRAPH_REBUILD_FIX = "ix reset --workspace --yes --ingest";++/** For a registered workspace the backend holds nothing for. */+export const GRAPH_MAP_FIX = "ix map";++const STRUCTURAL_PREDICATES = new Set(["CONTAINS", "DEFINES", "CONTAINS_CHUNK"]);++/** Below this many symbols the coverage ratio is too noisy to judge by. */+const MIN_SYMBOLS_FOR_RATIO = 50;+/** Structural edges per symbol below which a graph is called hollow. Healthy: ~1.2. */+const MIN_STRUCTURAL_COVERAGE = 0.2;+/** A graph with at least this many symbols and no structural edge at all is hollow. */+const MIN_SYMBOLS_FOR_ZERO = 5;++const UNKNOWN: GraphHealth = { status: "unknown" };++const LIKELY_CAUSE =+ "Likely cause: another checkout of this repository was ingested into the same backend later (Ix-memory#211).";++function countOf(rows: unknown, key: string, match: (name: string) => boolean): number {+ if (!Array.isArray(rows)) return 0;+ let total = 0;+ for (const row of rows) {+ const name = (row as Record<string, unknown>)?.[key];+ const count = (row as Record<string, unknown>)?.count;+ if (typeof name === "string" && typeof count === "number" && match(name)) total += count;+ }+ return total;+}++/**+ * Judge a `/v1/stats` body. Pure; `unknown` for anything it cannot read.+ */+export function assessGraphStats(stats: unknown): GraphHealth {+ const s = stats as { nodes?: { total?: unknown; byKind?: unknown }; edges?: { total?: unknown; byPredicate?: unknown } } | null;+ const nodes = s?.nodes?.total;+ const edges = s?.edges?.total;+ if (typeof nodes !== "number" || typeof edges !== "number") return UNKNOWN;++ if (nodes === 0) {+ return {+ status: "empty",+ reason: "no_nodes",+ message: "The backend holds no graph for this workspace: it is registered but has not been mapped (or its data was reset).",+ fix: GRAPH_MAP_FIX,+ nodes,+ edges,+ };+ }++ // Without the breakdowns there is nothing to judge structure by -- an older+ // backend, or a stub -- and a missing breakdown must not read as zero edges.+ if (!Array.isArray(s?.nodes?.byKind) || !Array.isArray(s?.edges?.byPredicate)) return UNKNOWN;+ const files = countOf(s?.nodes?.byKind, "kind", (k) => k === "file");+ const structuralEdges = countOf(s?.edges?.byPredicate, "predicate", (p) => STRUCTURAL_PREDICATES.has(p));+ const symbols = Math.max(nodes - files, 0);+ const counts = { nodes, edges, structuralEdges, symbols };++ const hollow =+ (symbols >= MIN_SYMBOLS_FOR_ZERO && structuralEdges === 0) ||+ (symbols >= MIN_SYMBOLS_FOR_RATIO && structuralEdges / symbols < MIN_STRUCTURAL_COVERAGE);+ if (!hollow) return { status: "ok", ...counts };++ const coverage = symbols > 0 ? Math.round((structuralEdges / symbols) * 100) : 0;+ return {+ status: "degraded",+ reason: "hollow",+ message:+ `${nodes} nodes but ${edges} edges: ${coverage}% of symbols are attached to a file (healthy: ~100%), ` ++ "so callers, callees and members are missing, not zero. " + LIKELY_CAUSE,+ fix: GRAPH_REBUILD_FIX,+ ...counts,+ };+}++/** Kinds a parser always attaches to a file (or to a class inside one). */+const ATTACHED_KINDS = new Set([+ "function", "method", "class", "interface", "trait", "object", "struct", "enum",+ "constant", "type", "type_alias", "variable",+]);++/**+ * Judge one entity from facts already in hand: a definition no file contains+ * has lost its edges. Returns undefined when there is nothing to say -- a kind+ * that is not always contained, or a target that is.+ */+export function assessTargetStructure(target: {+ name: string;+ kind: string;+ path?: string;+ container?: unknown;+}): GraphHealth | undefined {+ if (!ATTACHED_KINDS.has(target.kind) || target.container) return undefined;+ const where = target.path ? ` in ${target.path}` : "";+ return {+ status: "degraded",+ reason: "orphaned_target",+ message:+ `${target.name} (${target.kind})${where} is not attached to its file in the graph: that file's edges ` ++ "are gone, so its callers, callees and dependents are missing, not zero. " + LIKELY_CAUSE,+ fix: GRAPH_REBUILD_FIX,+ };+}++const SEVERITY: Record<GraphHealthStatus, number> = { unknown: 0, ok: 1, degraded: 2, empty: 3 };++/** The worse of two verdicts; a workspace-wide one wins a tie, since it says more. */+export function worseHealth(a: GraphHealth, b: GraphHealth | undefined): GraphHealth {+ if (!b) return a;+ return SEVERITY[b.status] > SEVERITY[a.status] ? b : a;+}++/** Whether answers drawn from this graph should be withheld or hedged. */+export function isUnhealthy(health: GraphHealth | undefined): health is GraphHealth & { status: "degraded" | "empty" } {+ return health?.status === "degraded" || health?.status === "empty";+}++// ── The cached, bounded workspace check ─────────────────────────────────────++export interface GraphHealthScope {+ workspaceId?: string;+ systemId?: string;+}++type HealthClient = Pick<IxClient, "currentRevision" | "stats"> & { endpoint?: string };++interface CacheEntry {+ key: string;+ revision: string;+ health: GraphHealth;+}++/**+ * One process's answers, for `ix mcp`, which runs many commands in one+ * process. The disk copy below is what a one-shot CLI process hits.+ */+const memo = new Map<string, CacheEntry>();++/** Test hook: forget the in-process answers. */+export function resetGraphHealthMemo(): void {+ memo.clear();+}++/**+ * Forget every cached verdict. For `ix reset`: `/v1/reset/workspace` deletes a+ * workspace's data without moving the backend's head revision (measured on+ * 1.0.30), so a verdict keyed by revision would outlive the data it described.+ */+export function clearGraphHealthCache(): void {+ memo.clear();+ try {+ for (const name of readdirSync(ixHome())) {+ if (name.startsWith("graph_health_") && name.endsWith(".json")) rmSync(join(ixHome(), name), { force: true });+ }+ } catch { /* nothing cached, or nowhere to cache it */ }+}++function cacheKey(endpoint: string | undefined, scope: GraphHealthScope): string | undefined {+ if (scope.systemId) return JSON.stringify([endpoint ?? "", "system", scope.systemId]);+ if (scope.workspaceId) return JSON.stringify([endpoint ?? "", "workspace", scope.workspaceId]);+ return undefined;+}++export function graphHealthCachePath(key: string): string {+ const digest = createHash("sha256").update(key).digest("hex").slice(0, 12);+ return join(ixHome(), `graph_health_${digest}.json`);+}++function readCached(key: string, revision: string): GraphHealth | undefined {+ const inMemory = memo.get(key);+ if (inMemory && inMemory.revision === revision) return inMemory.health;+ try {+ const entry = JSON.parse(readFileSync(graphHealthCachePath(key), "utf-8")) as Partial<CacheEntry>;+ if (entry.key !== key || entry.revision !== revision) return undefined;+ const health = entry.health;+ if (!health || typeof health.status !== "string" || !(health.status in SEVERITY)) return undefined;+ memo.set(key, { key, revision, health });+ return health;+ } catch {+ return undefined;+ }+}++function writeCached(key: string, revision: string, health: GraphHealth): void {+ memo.set(key, { key, revision, health });+ try {+ mkdirSync(ixHome(), { recursive: true });+ writeFileSync(graphHealthCachePath(key), JSON.stringify({ key, revision, health }) + "\n", "utf8");+ } catch { /* a cache that cannot be written is not an error */ }+}++/** How long the stats probe may take before the answer goes out without it. */+export function graphHealthTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {+ const raw = Number(env.IX_GRAPH_HEALTH_TIMEOUT_MS);+ return Number.isFinite(raw) && raw > 0 ? raw : 2000;+}++/**+ * The workspace-wide verdict for a read scope. Never throws: a check that+ * cannot run answers `unknown`, which every caller treats as "say nothing".+ *+ * Cached per (endpoint, scope, backend head revision). The head revision is+ * global, and that is the point: what hollows a graph is an ingest into some+ * *other* workspace, which moves the global head, so a cached `ok` cannot+ * outlive the write that invalidated it. The revision read is one indexed+ * lookup (~10 ms); `/v1/stats` (~65 ms on a 9k-node workspace, seconds on a+ * very large one) runs only when the head has moved, and is bounded by+ * {@link graphHealthTimeoutMs}. Callers start this alongside their own+ * requests and await it last, so on a warm cache it costs nothing visible.+ *+ * `IX_GRAPH_HEALTH=0` turns the check off.+ */+export async function checkGraphHealth(+ client: HealthClient,+ scope: GraphHealthScope,+ env: NodeJS.ProcessEnv = process.env,+): Promise<GraphHealth> {+ if (env.IX_GRAPH_HEALTH === "0") return UNKNOWN;+ const key = cacheKey(client.endpoint, scope);+ if (!key) return UNKNOWN;+ try {+ const revision = revisionToken(await client.currentRevision());+ if (revision === undefined) return UNKNOWN;+ const cached = readCached(key, revision);+ if (cached) return cached;+ const stats = await client.stats({ ...scope, timeoutMs: graphHealthTimeoutMs(env) });+ const health = assessGraphStats(stats);+ if (health.status !== "unknown") writeCached(key, revision, health);+ return health;+ } catch {+ return UNKNOWN;+ }+}++// ── Rendering ───────────────────────────────────────────────────────────────++/** The `graph` record every llm renderer emits for an unhealthy graph. */+export function graphHealthLlmFields(health: GraphHealth): Array<[string, string | number | undefined]> {+ return [+ ["status", health.status],+ ["reason", health.reason],+ ["message", health.message],+ ["fix", health.fix],+ ];+}++/** The same verdict for `--format json`: only what a consumer acts on. */+export function graphHealthJson(health: GraphHealth): Record<string, unknown> {+ const out: Record<string, unknown> = { status: health.status };+ if (health.reason) out.reason = health.reason;+ if (health.message) out.message = health.message;+ if (health.fix) out.fix = health.fix;+ for (const k of ["nodes", "edges", "structuralEdges", "symbols"] as const) {+ if (typeof health[k] === "number") out[k] = health[k];+ }+ return out;+}++/** One line for a person, e.g. under a warning banner. */+export function graphHealthProse(health: GraphHealth): string {+ const head = health.status === "empty" ? "Graph is empty." : "Graph is degraded.";+ return `${head} ${health.message ?? ""}${health.fix ? ` Fix: ${health.fix}` : ""}`.trim();+}diff --git a/ix-cli/src/client/api.ts b/ix-cli/src/client/api.tsindex 11554823..f5bdbd8f 100644--- a/ix-cli/src/client/api.ts+++ b/ix-cli/src/client/api.ts@@ -628,12 +628,15 @@ export class IxClient {return resp.json();}- async stats(opts?: { workspaceId?: string; systemId?: string }): Promise<any> {+ async stats(opts?: { workspaceId?: string; systemId?: string; timeoutMs?: number }): Promise<any> {const params = new URLSearchParams();if (opts?.workspaceId) params.set("workspace_id", opts.workspaceId);if (opts?.systemId) params.set("system_id", opts.systemId);const qs = params.toString();- return this.get(`/v1/stats${qs ? `?${qs}` : ""}`);+ // `timeoutMs` bounds a probe (the graph-health check) that must never hold+ // up the answer it rides along with; the request is aborted, not abandoned,+ // so a slow backend does not keep a finished CLI process alive either.+ return this.get(`/v1/stats${qs ? `?${qs}` : ""}`, opts?.timeoutMs);}async health(): Promise<HealthResponse> {@@ -666,9 +669,9 @@ export class IxClient {return parseOrThrowWithStatus<T>(resp);}- private async get<T>(path: string): Promise<T> {+ private async get<T>(path: string, timeoutMs = 2 * 60 * 1000): Promise<T> {const resp = await fetch(`${this.endpoint}${path}`, {- signal: this.signalFor(2 * 60 * 1000),+ signal: this.signalFor(timeoutMs),});if (!resp.ok) {const text = await resp.text();diff --git a/skills/ix/references/commands.md b/skills/ix/references/commands.mdindex e42035eb..a4d29b24 100644--- a/skills/ix/references/commands.md+++ b/skills/ix/references/commands.md@@ -176,9 +176,10 @@ ix inventory --kind function --path auth.pythe cwd only decides which mtime cache gets cleared. Running`ix reset -y --code` in one repo also destroys the graphs of every othermapped workspace (e.g. packwise) and empties the `--all` combined view;- re-run `ix map` per workspace to rebuild. A workspace-scoped endpoint- (`/v1/reset/workspace`, via `deleteWorkspace`) exists server-side, but the- CLI does not expose it.+ re-run `ix map` per workspace to rebuild. The workspace-scoped reset is+ `ix reset --workspace` (`/v1/reset/workspace` for the registered workspace+ containing cwd, nothing else); with `--ingest` it is the repair for a+ degraded graph.- **The OSS↔Pro command boundary is derived at runtime, not declared.**`main.ts` snapshots `ossCmdNames` immediately after `registerOssCommands()`;diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.mdindex 970f83e1..6059b7a4 100644--- a/skills/ix/references/flags.md+++ b/skills/ix/references/flags.md@@ -40,7 +40,8 @@ surfaces (#575).rejected on its own; each combination errors with which flag to drop.- **`ix reset` is global.** `--code` narrows *what kind* of data goes, notwhich workspace — see the Gotchas section of [commands.md](commands.md)- before running it in a shared backend.+ before running it in a shared backend. `--workspace` is the one that+ narrows *which* workspace: only the registered one containing cwd.- **`--detailed` on `ix subsystems` requires `--list`**, and the reverseconstraint bites harder: `--limit`, `--offset`, `--regions`, `--edge-cap` and`--member-file-cap` all *require* `--detailed`, so `ix subsystems --listdiff --git a/skills/ix/references/troubleshooting.md b/skills/ix/references/troubleshooting.mdindex d188e3fc..2c87832a 100644--- a/skills/ix/references/troubleshooting.md+++ b/skills/ix/references/troubleshooting.md@@ -38,6 +38,7 @@ again.| `Compass UI not found` on `ix view` | Run `ix upgrade` to fetch Compass. Re-running the installer wipes the Compass assets, so bootstrap auto-restores them with `ix upgrade`; skip with `IX_SKIP_COMPASS=1` || Compass shows "Compass not connected to a codebase" | The scoped workspace has no graph — run `ix map .` from the repo root, then reload the tab || Slow or stale results | Re-run `ix map --silent` to refresh the graph |+| `graph status=degraded` / `classification=degraded` | The graph kept its nodes but lost its edges, so zero callers/members mean *unknown*, not none. Usually another checkout of the same repo was ingested into this backend later (Ix-memory#211). `ix map` and `ix ingest --force` do not repair it; `ix reset --workspace --yes --ingest` (this workspace only) does. It hollows the other checkout in turn until the backend fix ships || `Commits against <endpoint> kept failing` | Commits kept failing, so `ix map` gave up rather than sending one doomed request per file. Read the `Last error` line it prints — the CLI cannot tell the two causes apart, because the memory layer answers 500 for both. **A saturated database:** `ix doctor` still passes (it asks whether the backend is reachable and the graph consistent, and an ArangoDB too busy to begin a transaction is both), so check `docker stats` and `GET /_db/<db>/_api/query/current`, then re-map once it is idle. **Patches the backend will not accept:** the error names the patch or the field; re-map after fixing it, or `IX_COMMIT_FAILURE_LIMIT=0` to send the rest regardless. |## Environment flags@@ -49,6 +50,8 @@ again.- `IX_COMMIT_FAILURE_LIMIT=N` — consecutive failed commits before `ix map`stops sending more (default 5). `0` sends every patch regardless, which isthe pre-#560 behaviour.+- `IX_GRAPH_HEALTH=0` — skip the graph-structure check `ix explain` / `ix context`+ run alongside their queries; `IX_GRAPH_HEALTH_TIMEOUT_MS` bounds it (default 2000).- `IX_COMMIT_BASE_REV_RETRIES=N` — how many times a commit is re-sent afteranother writer (a second `ix map` on the same backend) moved the graphrevision under it (default 8). Only a commit that loses every retry is