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): add `ix verify` to compare the graph with a re-parse (CL-24A) (#838)
Ian Hock4dd1b441af20
diff --git a/docs-site/src/content/docs/reference/commands.md b/docs-site/src/content/docs/reference/commands.mdindex c4c1e7fc..ba339499 100644--- a/docs-site/src/content/docs/reference/commands.md+++ b/docs-site/src/content/docs/reference/commands.md@@ -86,6 +86,7 @@ before it exits: `ix map` re-ingests the workspace, and so does `ix ingest` when|---|---|| `ix status` | Checks the backend is reachable || `ix doctor` | Checks server, database and graph integrity |+| `ix verify` | Compares the graph's nodes to a fresh re-parse of a sample of files (nodes only, not edges) || `ix docker start` / `stop` / `restart` | Starts, stops or restarts the local backend containers || `ix docker start --local-token` | Makes the local backend require a bearer token, which the CLI stores and sends (`--no-local-token` turns it off). See [Local token](/reference/configuration/#local-token) || `ix docker status` / `logs` | Shows container health, or tails the backend's logs |diff --git a/docs/llm-format.md b/docs/llm-format.mdindex 8807c8b8..593e66bb 100644--- a/docs/llm-format.md+++ b/docs/llm-format.md@@ -655,6 +655,61 @@ Two deliberate exceptions remain:backend, a slow stats read). `stale=false` says no file changed since thelast ingest; it does not vouch for the graph.+ When a whole-root `ix verify` (no paths) has run for this workspace, the+ `status` record ends with what it found: `verified_at` (ISO),+ `verified_files`, `verified_diverged`, `verified_outdated` and+ `verified_graph` (`clean`, `stale`, `diverged` or `unverified`; a stale or+ unverified record's `verified_diverged=0` is not a pass). Only that+ command saves the record: `ix verify <path>` and `ix doctor` do not.+ `verified_outdated=true` means the workspace was ingested after that verify+ ran, so its counts describe an earlier graph; run `ix verify` again rather+ than act on them. `status` only reads the record; it never runs a verify.+ With no record the five fields are absent and the line is unchanged.++`verify` answers whether the graph's nodes match the source they came from. One+`verify` record, then one `file` record per file that is not clean:++```+verify graph=diverged files=20 clean=18 stale=1 diverged=1 unverified=0 fix="ix reset --workspace --yes --ingest"+file path=src/a.ts state=stale reason=changed_since_ingest missing=0 extra=1 changed=2+file path=src/b.ts state=diverged missing=3 extra=0 changed=0+```++`graph` is the first of these that holds: `diverged` when any file diverged;+`stale` (fix `ix map`) when any file is stale, even beside clean ones, since a+stale file's nodes could not be checked against its source; `clean` when at+least one file was judged clean; otherwise `unverified` (with a `reason`: `not_mapped`,+`extractor_changed`, `parser_unavailable`, `no_files` when nothing could be+sampled, `no_file_verified` when nothing sampled could be judged, `timed_out`+when `ix doctor`'s time budget ran out before any file was judged).++A file is judged by its nodes and by the backend's source hash for it, which+is the hash of the file's newest stored patch:++- `diverged`: the nodes do not match a re-parse, and the graph claims these+ bytes: the stored hash equals the disk hash (nodes left behind or lost), or+ the last map listed the file as not applied (`not_applied` in `status`, F-01:+ a revert the backend answered `Idempotent`, so the newest patch is still the+ edit in between) and it has not changed since (`reason=replayed_not_applied`).+- `stale` (`reason=changed_since_ingest`): the stored hash is not the disk hash.+ Usually an edit since the last map, fixed by `ix map`. An F-01 revert that the+ last map did not record as not applied looks exactly like this, so verify+ reports it as stale, not diverged. `missing_on_disk` is a deleted file the+ graph still has; `not_file` is a path the graph has that is now a+ directory or another non-regular file.+- `unverified`, with a `reason`: `not_in_graph` (no stored hash and no nodes:+ ingest skips some files), `parse_timed_out` (the last map's parse ran out of+ budget), `too_large` (over ingest's 1 MB limit), `missing_on_disk` (a named+ path that does not exist), `not_file` (a named path that is a directory or+ another non-regular file), `unsupported_language`,+ `no_parse`, `list_failed`, `truncated`, `hash_unknown` (the hash lookup+ failed and the nodes differ), `no_comparison`.++A stale file does not make the graph diverged, and does not let it be clean.+Unverified files beside clean ones do not stop a `clean` verdict; they are+counted. Nodes only: edges are not compared. The command exits 0 for every+verdict.+Still routing to `text`: `diff --content` (verbatim hunks) and `ingest`, ahidden implementation-detail command whose output is a completion summary.diff --git a/ix-cli/src/cli/__tests__/bounded-read.test.ts b/ix-cli/src/cli/__tests__/bounded-read.test.tsindex 1b24c3a2..f1e5694d 100644--- a/ix-cli/src/cli/__tests__/bounded-read.test.ts+++ b/ix-cli/src/cli/__tests__/bounded-read.test.ts@@ -5,7 +5,7 @@ import * as fs from "node:fs";import * as os from "node:os";import * as nodePath from "node:path";-import { readBoundedFile, readCapped } from "../bounded-read.js";+import { readBoundedBytes, readBoundedFile, readCapped } from "../bounded-read.js";/*** `readBoundedFile` stands between ingestion and a file whose path AND contents@@ -138,6 +138,51 @@ describe("readCapped", () => {});});+/**+ * The Buffer variant `ix verify` hashes. Same handle and checks as+ * `readBoundedFile`, but it says why it refused, and a missing file throws, so+ * "too large to judge" and "not on disk" stay two different answers.+ */+describe("readBoundedBytes", () => {+ let root: string;++ beforeAll(() => {+ root = fs.mkdtempSync(nodePath.join(os.tmpdir(), "ix-bounded-bytes-"));+ });++ afterAll(() => {+ fs.rmSync(root, { recursive: true, force: true });+ });++ it("returns the raw bytes, undecoded", () => {+ const p = nodePath.join(root, "raw.bin");+ const raw = Buffer.from([0xef, 0xbb, 0xbf, 0x61, 0xff, 0x0d, 0x0a]);+ fs.writeFileSync(p, raw);+ const read = readBoundedBytes(p);+ expect("bytes" in read && read.bytes.equals(raw)).toBe(true);+ });++ it("refuses a file over the cap as too_large, and reads it under a cap that admits it", () => {+ const p = nodePath.join(root, "big.ts");+ fs.writeFileSync(p, "x".repeat(4096));+ expect(readBoundedBytes(p, 1024)).toEqual({ refused: "too_large" });+ expect(readBoundedBytes(p, 4096)).toMatchObject({ bytes: expect.any(Buffer) });+ });++ it("refuses a directory as not_file", () => {+ const p = nodePath.join(root, "adir");+ fs.mkdirSync(p, { recursive: true });+ // Windows refuses to open a directory at all; either way it is not read.+ let result: ReturnType<typeof readBoundedBytes> | "threw";+ try { result = readBoundedBytes(p); } catch { result = "threw"; }+ expect(result === "threw" || ("refused" in result && result.refused === "not_file")).toBe(true);+ });++ it("throws for a file that does not exist", () => {+ expect(() => readBoundedBytes(nodePath.join(root, "absent.ts"))).toThrow(/ENOENT/);+ });+});+/*** The case the fstat size check cannot catch, and the reason the read is capped* separately. A `/proc` entry is a REGULAR file — `isFile()` true — that reportsdiff --git a/ix-cli/src/cli/__tests__/help-coverage.test.ts b/ix-cli/src/cli/__tests__/help-coverage.test.tsindex ab12b408..95975cfd 100644--- a/ix-cli/src/cli/__tests__/help-coverage.test.ts+++ b/ix-cli/src/cli/__tests__/help-coverage.test.ts@@ -20,7 +20,7 @@ const REQUIRED_COMMANDS = ["search", "locate", "explain", "impact", "overview", "watch","read", "inventory", "rank", "history", "diff", "smells", "subsystems","map", "trace", "status", "stats", "doctor", "docker",- "mcp",+ "mcp", "verify",];describe("help coverage", () => {diff --git a/ix-cli/src/cli/__tests__/llm-tier5.test.ts b/ix-cli/src/cli/__tests__/llm-tier5.test.tsindex 1b320bcb..e6e245f8 100644--- a/ix-cli/src/cli/__tests__/llm-tier5.test.ts+++ b/ix-cli/src/cli/__tests__/llm-tier5.test.ts@@ -193,6 +193,31 @@ describe("status --format llm", () => {expect(lines).toEqual(["status backend=ok endpoint=http://localhost:8090"]);});++ it("is byte-identical with no verify record, and appends the last verify when there is one", () => {+ const staleInfo = {+ graphCompleted: true, mapCompleted: true,+ currentRev: 11, lastIngestAt: null, staleFiles: 0, sampleChangedFiles: [],+ };+ const without = renderStatusLlm("ok", "http://localhost:8090", staleInfo);+ expect(renderStatusLlm("ok", "http://localhost:8090", staleInfo, undefined, null)).toEqual(without);+ expect(without[0]).not.toContain("verified_");++ const lines = renderStatusLlm("ok", "http://localhost:8090", staleInfo, undefined, {+ root: "/r", at: "2026-10-11T00:00:00.000Z", lastIngestAt: null, graph: "diverged",+ files: 20, stale: 1, diverged: 2, unverified: 0, divergedFiles: ["a.ts", "b.ts"], fix: "ix reset --workspace --yes --ingest",+ });+ expect(lines[0]).toBe(`${without[0]} verified_at=2026-10-11T00:00:00.000Z verified_files=20 verified_diverged=2 verified_outdated=false verified_graph=diverged`);+ expect(lines.slice(1)).toEqual(without.slice(1));++ // Ingested since that verify ran: its counts describe an earlier graph.+ const later = renderStatusLlm("ok", "http://localhost:8090", { ...staleInfo, lastIngestAt: "2026-10-12T00:00:00.000Z" } as any,+ undefined, {+ root: "/r", at: "2026-10-11T00:00:00.000Z", lastIngestAt: "2026-10-10T00:00:00.000Z", graph: "diverged",+ files: 20, stale: 0, diverged: 2, unverified: 0, divergedFiles: ["a.ts", "b.ts"], fix: "ix reset --workspace --yes --ingest",+ });+ expect(later[0]).toMatch(/ verified_diverged=2 verified_outdated=true verified_graph=diverged$/);+ });});describe("doctor --format llm", () => {diff --git a/ix-cli/src/cli/__tests__/status-doctor-honest.test.ts b/ix-cli/src/cli/__tests__/status-doctor-honest.test.tsindex 841e71b3..c978cfc4 100644--- a/ix-cli/src/cli/__tests__/status-doctor-honest.test.ts+++ b/ix-cli/src/cli/__tests__/status-doctor-honest.test.ts@@ -2,7 +2,7 @@import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { createServer, type Server } from "node:http";-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { Command } from "commander";@@ -17,6 +17,7 @@ import { Command } from "commander";// A backend whose /v1/stats answer each test sets.let stats: unknown = { nodes: { total: 0 }, edges: { total: 0 } };let rev = 1;+let healthDegraded = false;let server: Server;let endpoint: string;@@ -29,6 +30,7 @@ beforeAll(async () => {res.writeHead(status, { "content-type": "application/json" });res.end(JSON.stringify(body));};+ if (url.startsWith("/v1/health") && healthDegraded) return send(503, { status: "degraded", database: "unreachable" });if (url.startsWith("/v1/health")) return send(200, { status: "ok", schema_version: 3, database: "reachable" });if (url.startsWith("/v1/revisions/current")) return send(200, { rev });if (url.startsWith("/v1/stats")) return send(200, stats);@@ -55,6 +57,7 @@ let out: string[];beforeEach(() => {vi.resetModules();rev += 1; // a new backend revision: no cached graph verdict carries over+ healthDegraded = false;home = mkdtempSync(join(tmpdir(), "ix-honest-"));repo = join(home, "repo");mkdirSync(repo);@@ -78,6 +81,8 @@ afterEach(() => {else process.env[k] = v;}vi.restoreAllMocks();+ vi.doUnmock("../commands/ingestion-loader.js");+ vi.doUnmock("../backend-status.js");rmSync(home, { recursive: true, force: true });});@@ -86,6 +91,20 @@ function registerRepo(): void {`endpoint: ${endpoint}\nformat: text\nworkspaces:\n - workspace_id: "ws1"\n workspace_name: repo\n root_path: ${repo}\n default: true\n`);}+/**+ * A full `ix doctor` run asks docker about the backend container. On the+ * Windows runner `docker ps` hangs until its 10 s timeout, and what it leaves+ * running still has the test repo as its cwd, so the repo cannot be deleted+ * (EBUSY). These tests are not about docker: answer "no container".+ */+function mockNoDocker(): void {+ vi.doMock("../backend-status.js", async (orig) => ({+ ...(await orig<typeof import("../backend-status.js")>()),+ checkBackendImage: () => ({ kind: "not-running" }),+ dockerAvailable: () => false,+ }));+}+async function run(register: (p: Command) => void, args: string[]): Promise<string> {const program = new Command().exitOverride();register(program);@@ -99,11 +118,14 @@ const HOLLOW = {};describe("ix status", () => {+ let lastIngestAt: string | null = null;+ beforeEach(() => { lastIngestAt = null; });+async function status(...args: string[]): Promise<string> {vi.doMock("../stale.js", async (orig) => ({...(await orig<typeof import("../stale.js")>()),detectStaleFiles: () => ({- graphCompleted: true, mapCompleted: true, currentRev: 7, lastIngestAt: null,+ graphCompleted: true, mapCompleted: true, currentRev: 7, lastIngestAt,staleFiles: 0, sampleChangedFiles: [], replayedFiles: [], parseTimeouts: [],}),}));@@ -138,6 +160,97 @@ describe("ix status", () => {expect(llm).toMatch(/^graph status=empty reason=no_nodes/m);});+ it("shows the last ix verify, and warns when it found divergence", async () => {+ registerRepo();+ stats = HOLLOW;+ const { saveVerifyRecord } = await import("../verify.js");+ saveVerifyRecord({+ root: repo, at: new Date().toISOString(), lastIngestAt: null, graph: "diverged",+ files: 20, stale: 0, diverged: 1, unverified: 0, divergedFiles: ["a.ts"], fix: "ix reset --workspace --yes --ingest",+ });+ const text = await status();+ expect(text).toMatch(/Verified:?\s+\d+s ago, 20 files, 1 diverged/);+ expect(text).toMatch(/last ix verify found 1 file/);+ out.length = 0;+ const json = JSON.parse(await status("--format", "json"));+ expect(json.verify).toMatchObject({ graph: "diverged", files: 20, diverged: 1 });+ });++ it("a verify from before the last ingest is labelled, gives no Fix, and says outdated in llm and json", async () => {+ registerRepo();+ stats = HOLLOW;+ lastIngestAt = new Date().toISOString();+ const { saveVerifyRecord } = await import("../verify.js");+ saveVerifyRecord({+ root: repo, at: new Date(Date.now() - 60_000).toISOString(), lastIngestAt: "2026-10-01T00:00:00.000Z", graph: "diverged",+ files: 20, stale: 0, diverged: 1, unverified: 0, divergedFiles: ["a.ts"], fix: "ix reset --workspace --yes --ingest",+ });+ const text = await status();+ expect(text).toMatch(/Verified:?\s+.*1 diverged \(before last ingest\)/);+ expect(text).toMatch(/ingested since\. Run ix verify to check the graph as it is now/);+ expect(text).not.toMatch(/last ix verify found[^\n]*Fix:/);+ out.length = 0;+ expect(await status("--format", "llm")).toMatch(/verified_outdated=true/);+ out.length = 0;+ expect(JSON.parse(await status("--format", "json")).verify).toMatchObject({ outdated: true, diverged: 1 });+ });++ it("a verify from the current ingest is not outdated, and keeps its Fix", async () => {+ registerRepo();+ stats = HOLLOW;+ lastIngestAt = "2026-10-10T00:00:00.000Z";+ const { saveVerifyRecord } = await import("../verify.js");+ saveVerifyRecord({+ root: repo, at: new Date().toISOString(), lastIngestAt, graph: "diverged",+ files: 20, stale: 0, diverged: 1, unverified: 0, divergedFiles: ["a.ts"], fix: "ix reset --workspace --yes --ingest",+ });+ const text = await status();+ expect(text).not.toMatch(/before last ingest/);+ expect(text).toMatch(/last ix verify found 1 file[^\n]*Fix: ix reset --workspace --yes --ingest/);+ out.length = 0;+ expect(JSON.parse(await status("--format", "json")).verify).toMatchObject({ outdated: false });+ });++ it("an unverified record does not read as '0 diverged'", async () => {+ registerRepo();+ stats = HOLLOW;+ const { saveVerifyRecord } = await import("../verify.js");+ saveVerifyRecord({+ root: repo, at: new Date().toISOString(), lastIngestAt: null, graph: "unverified",+ files: 3, stale: 0, diverged: 0, unverified: 3, divergedFiles: [], fix: null,+ });+ const text = await status();+ expect(text).toMatch(/Verified:?\s+\d+s ago, 3 files, unverified \(no file verified\)/);+ expect(text).not.toMatch(/0 diverged/);+ out.length = 0;+ expect(await status("--format", "llm")).toMatch(/^status .*verified_graph=unverified/m);+ });++ it("a stale record does not read as a pass", async () => {+ registerRepo();+ stats = HOLLOW;+ const { saveVerifyRecord, loadVerifyRecord } = await import("../verify.js");+ saveVerifyRecord({+ root: repo, at: new Date().toISOString(), lastIngestAt: null, graph: "stale",+ files: 20, stale: 20, diverged: 0, unverified: 0, divergedFiles: [], fix: "ix map",+ });+ expect(loadVerifyRecord(repo)).toMatchObject({ graph: "stale", stale: 20 });+ const text = await status();+ expect(text).toMatch(/Verified:?\s+\d+s ago, 20 files, 0 diverged, 20 stale \(not verified clean\)/);+ out.length = 0;+ expect(await status("--format", "llm")).toMatch(/^status .*verified_graph=stale/m);+ out.length = 0;+ expect(JSON.parse(await status("--format", "json")).verify).toMatchObject({ graph: "stale", stale: 20, fix: "ix map" });+ });++ it("has verify: null and no Verified line without a record", async () => {+ registerRepo();+ stats = HOLLOW;+ expect(await status()).not.toMatch(/Verified/);+ out.length = 0;+ expect(JSON.parse(await status("--format", "json")).verify).toBeNull();+ });+it("says unverified, not ok, when the directory is in no workspace", async () => {stats = HOLLOW;const json = JSON.parse(await status("--format", "json"));@@ -202,6 +315,94 @@ describe("doctor checks", () => {expect(assessConfigFile("c.yaml", () => "- a\n- b\n")).toMatchObject({ ok: false });});+ it("Graph matches a re-parse: a warning at worst, never a failure", async () => {+ const { assessGraphVerify } = await import("../commands/doctor.js");+ const report = (graph: string, counts: Record<string, number>, extra: Record<string, unknown> = {}) => async () => ({+ at: "", root: "/r", lastIngestAt: null, graph, fix: null, sample: 20, seed: 24, files: [],+ counts: { files: 20, clean: 0, stale: 0, diverged: 0, unverified: 0, ...counts }, ...extra,+ }) as any;+ expect(await assessGraphVerify(report("clean", { clean: 20 }))).toMatchObject({ ok: true });+ // Stale is a note, never "N sampled files match": no file was vouched for.+ const stale = await assessGraphVerify(report("stale", { clean: 19, stale: 1 }));+ expect(stale).toEqual({ ok: true, detail: "not verified: 1 of 20 sampled files changed since the last ingest — run `ix map`" });+ expect((await assessGraphVerify(report("stale", { stale: 20 }))).detail).not.toMatch(/match/);+ // Only the files judged clean are said to match.+ expect(await assessGraphVerify(report("clean", { clean: 1, unverified: 19 })))+ .toEqual({ ok: true, detail: "1 of 20 sampled files match a re-parse (nodes only)" });+ const diverged = await assessGraphVerify(report("diverged", { clean: 19, diverged: 1 }, {+ fix: "ix reset --workspace --yes --ingest",+ files: [{ path: "src/a.ts", state: "diverged" }],+ }));+ expect(diverged).toEqual({+ ok: false, warn: true,+ detail: "1 of 20 sampled files diverged (src/a.ts). Fix: ix reset --workspace --yes --ingest",+ });+ expect(await assessGraphVerify(report("unverified", { unverified: 20 }, { reason: "not_mapped" })))+ .toEqual({ ok: true, detail: "not checked: not mapped" });+ expect(await assessGraphVerify(async () => { throw new Error("404: not found"); }))+ .toMatchObject({ ok: true, detail: expect.stringMatching(/^not checked/) });+ });++ it("Graph matches a re-parse: a partial run says so; a hung run gives up after the budget", async () => {+ const { assessGraphVerify } = await import("../commands/doctor.js");+ const partial = await assessGraphVerify(async () => ({+ at: "", root: "/r", lastIngestAt: null, graph: "clean", fix: null, sample: 5, seed: 24, files: [], partial: true,+ counts: { files: 2, clean: 2, stale: 0, diverged: 0, unverified: 0 },+ }) as any, 5_000);+ expect(partial).toEqual({ ok: true, detail: "2 sampled files match a re-parse (nodes only) (partial: 2 of 5 files checked within 5 s)" });+ const started = Date.now();+ const hung = await assessGraphVerify(() => new Promise(() => {}), 10);+ expect(hung).toMatchObject({ ok: true, detail: expect.stringMatching(/^not checked: timed out/) });+ expect(Date.now() - started).toBeLessThan(5_000);+ });++ it("ix doctor: the re-parse check parses nothing when the backend is not healthy", async () => {+ registerRepo();+ stats = HOLLOW;+ healthDegraded = true;+ let loads = 0;+ vi.doMock("../commands/ingestion-loader.js", async (orig) => {+ const real = await orig<typeof import("../commands/ingestion-loader.js")>();+ return { ...real, loadIngestionModules: async () => { loads++; return real.loadIngestionModules(); } };+ });+ const { loadIngestionModules } = await import("../commands/ingestion-loader.js");+ const [, { extractorName }] = await loadIngestionModules();+ loads = 0;+ writeFileSync(join(repo, "a.ts"), "export function a() { return 1; }\n");+ const { saveIngestBaseline } = await import("../ingest-baseline.js");+ saveIngestBaseline(repo, new Map([[join(repo, "a.ts"), 1]]), 3, new Date(), new Map(), extractorName());+ mockNoDocker();+ const { registerDoctorCommand } = await import("../commands/doctor.js");+ const json = JSON.parse(await run(registerDoctorCommand, ["doctor", "--format", "json"]));+ const check = json.checks.find((c: { name: string }) => c.name === "Graph matches a re-parse");+ expect(check).toEqual({ name: "Graph matches a re-parse", ok: true, detail: "not checked: backend degraded" });+ expect(loads).toBe(0);+ process.exitCode = undefined;+ });++ it("ix doctor: the re-parse check against a backend that 404s /v1/list is 'not checked'", async () => {+ registerRepo();+ stats = HOLLOW;+ const { loadIngestionModules } = await import("../commands/ingestion-loader.js");+ const [, { extractorName }] = await loadIngestionModules();+ writeFileSync(join(repo, "a.ts"), "export function a() { return 1; }\n");+ const { saveIngestBaseline } = await import("../ingest-baseline.js");+ saveIngestBaseline(repo, new Map([[join(repo, "a.ts"), 1]]), 3, new Date(), new Map(), extractorName());+ mockNoDocker();+ const { registerDoctorCommand } = await import("../commands/doctor.js");+ const json = JSON.parse(await run(registerDoctorCommand, ["doctor", "--format", "json"]));+ const check = json.checks.find((c: { name: string }) => c.name === "Graph matches a re-parse");+ expect(check).toMatchObject({ ok: true, detail: expect.stringMatching(/^not checked/) });+ // Doctor samples without saving: the record `ix status` shows is the last+ // whole-root `ix verify`'s alone.+ const { verifyRecordPath } = await import("../config.js");+ expect(existsSync(verifyRecordPath(repo))).toBe(false);+ // It adds no failure: healthy is decided by the other checks alone.+ const others = json.checks.filter((c: { name: string }) => c.name !== "Graph matches a re-parse");+ expect(json.healthy).toBe(!others.some((c: { ok: boolean; warn?: boolean }) => !c.ok && !c.warn));+ process.exitCode = undefined;+ });+it("ripgrep on PATH warns, never fails", async () => {const { checkRipgrep } = await import("../commands/doctor.js");expect(checkRipgrep(() => "ripgrep 15.1.0\n")).toEqual({ ok: true, detail: "ripgrep 15.1.0" });diff --git a/ix-cli/src/cli/__tests__/verify-command.test.ts b/ix-cli/src/cli/__tests__/verify-command.test.tsnew file mode 100644index 00000000..47e1a5bb--- /dev/null+++ b/ix-cli/src/cli/__tests__/verify-command.test.ts@@ -0,0 +1,238 @@+// Copyright 2026 Ix Infrastructure Inc.++import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { createServer, type Server } from "node:http";+import { createHash } from "node:crypto";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Command } from "commander";++/**+ * CL-24A: `ix verify` end to end against a fake backend serving /v1/list,+ * /v1/source-hashes and /v1/health. Every verdict exits 0; only a usage error+ * or an unreachable backend exits 1, the way `ix status` does.+ */++let rows: any[] = [];+let hashes: Array<{ workspaceId: string; uri: string; hash: string }> = [];+let listStatus = 200;+let server: Server;+let endpoint: string;++beforeAll(async () => {+ server = createServer((req, res) => {+ let body = "";+ req.on("data", (c) => { body += c; });+ req.on("end", () => {+ const url = req.url ?? "";+ const send = (status: number, payload: unknown) => {+ res.writeHead(status, { "content-type": "application/json" });+ res.end(JSON.stringify(payload));+ };+ if (url.startsWith("/v1/health")) return send(200, { status: "ok" });+ if (url.startsWith("/v1/source-hashes")) return send(200, hashes);+ if (url.startsWith("/v1/stats")) {+ const kinds = [...new Set(rows.map((r) => r.kind))];+ return send(200, { nodes: { total: rows.length, byKind: kinds.map((kind) => ({ kind, count: 1 })) }, edges: { total: 0 } });+ }+ if (url.startsWith("/v1/list")) {+ if (listStatus !== 200) return send(listStatus, { error: "nope" });+ const q = JSON.parse(body || "{}");+ return send(200, rows.filter((r) => r.kind === q.kind && r.provenance.sourceUri.includes(q.scope ?? "")));+ }+ send(404, { error: "not_found" });+ });+ });+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));+ const addr = server.address();+ endpoint = `http://127.0.0.1:${typeof addr === "object" && addr ? addr.port : 0}`;+});++afterAll(async () => {+ await new Promise<void>((r) => server.close(() => r()));+});++let home: string;+let repo: string;+let saved: Record<string, string | undefined>;+let cwd: string;+let out: string[];++beforeEach(() => {+ vi.resetModules();+ // realpathSync.native, as ingest canonicalizes its root: plain realpathSync+ // keeps a Windows 8.3 name (RUNNER~1) that `ix verify` expands.+ home = realpathSync.native(mkdtempSync(join(tmpdir(), "ix-verify-cmd-")));+ repo = join(home, "repo");+ mkdirSync(repo);+ saved = { IX_HOME: process.env.IX_HOME, IX_ENDPOINT: process.env.IX_ENDPOINT };+ process.env.IX_HOME = home;+ process.env.IX_ENDPOINT = endpoint;+ cwd = process.cwd();+ process.chdir(repo);+ out = [];+ rows = [];+ hashes = [];+ listStatus = 200;+ process.exitCode = undefined;+ vi.spyOn(console, "log").mockImplementation((...a: unknown[]) => { out.push(a.join(" ")); });+ vi.spyOn(console, "error").mockImplementation((...a: unknown[]) => { out.push(a.join(" ")); });+ vi.spyOn(process.stderr, "write").mockImplementation((s: string | Uint8Array) => { out.push(String(s)); return true; });+ vi.spyOn(process.stdout, "write").mockImplementation((s: string | Uint8Array) => { out.push(String(s)); return true; });+ vi.spyOn(process, "exit").mockImplementation(((code?: number) => { throw new Error(`exit ${code}`); }) as never);+});++afterEach(() => {+ process.chdir(cwd);+ for (const [k, v] of Object.entries(saved)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ process.exitCode = undefined;+ vi.restoreAllMocks();+ rmSync(home, { recursive: true, force: true });+});++const sha = (s: string) => createHash("sha256").update(Buffer.from(s)).digest("hex");++/** A mapped one-file workspace, with the backend holding what ingest would have written. */+async function mapped(opts: { dropFunction?: boolean; staleHash?: boolean } = {}): Promise<void> {+ writeFileSync(join(home, "config.yaml"),+ `endpoint: ${endpoint}\nformat: text\nworkspaces:\n - workspace_id: "ws1"\n workspace_name: repo\n root_path: ${repo}\n default: true\n`);+ const src = "export function greet() { return 'hi'; }\n";+ writeFileSync(join(repo, "a.ts"), src);+ const { loadIngestionModules } = await import("../commands/ingestion-loader.js");+ const [{ parseFile }, { buildPatchWithResolution, extractorName }] = await loadIngestionModules();+ const build = buildPatchWithResolution as (...a: unknown[]) => { ops: Array<Record<string, any>> };+ const patch = build(parseFile("a.ts", src), sha(src), "ws1", [], undefined, undefined);+ rows = patch.ops+ .filter((o) => o.type === "UpsertNode" && !(opts.dropFunction && o.kind === "function"))+ .map((o) => ({ id: o.id, kind: o.kind, name: o.name, attrs: o.attrs, provenance: { sourceUri: "a.ts" } }));+ hashes = [{ workspaceId: "ws1", uri: "a.ts", hash: opts.staleHash ? "older" : sha(src) }];+ const { saveIngestBaseline } = await import("../ingest-baseline.js");+ saveIngestBaseline(repo, new Map([[join(repo, "a.ts"), 1]]), 3, new Date(), new Map(), extractorName());+}++async function verify(...args: string[]): Promise<string> {+ const { registerVerifyCommand } = await import("../commands/verify.js");+ const program = new Command().exitOverride();+ registerVerifyCommand(program);+ await program.parseAsync(["verify", ...args], { from: "user" });+ return out.join("\n");+}++describe("ix verify output", () => {+ it("clean: one llm record, exit 0", async () => {+ await mapped();+ const llm = await verify("--format", "llm");+ expect(llm).toMatch(/^verify graph=clean files=1 clean=1 stale=0 diverged=0 unverified=0$/m);+ expect(llm).not.toMatch(/^file /m);+ expect(process.exitCode ?? 0).toBe(0);+ });++ it("stale: the file is listed, the graph is stale -- not diverged, not clean", async () => {+ await mapped({ staleHash: true });+ const llm = await verify("--format", "llm");+ expect(llm).toMatch(/^verify graph=stale files=1 clean=0 stale=1 diverged=0 unverified=0 fix="ix map"$/m);+ expect(llm).toMatch(/^file path=a\.ts state=stale/m);+ expect(process.exitCode ?? 0).toBe(0);+ });++ it("diverged: llm, json and text all name the fix, exit 0", async () => {+ await mapped({ dropFunction: true });+ const llm = await verify("--format", "llm");+ expect(llm).toMatch(/^verify graph=diverged files=1 clean=0 stale=0 diverged=1 unverified=0 fix="ix reset --workspace --yes --ingest"$/m);+ expect(llm).toMatch(/^file path=a\.ts state=diverged missing=1 extra=0 changed=0$/m);++ out.length = 0;+ const json = JSON.parse(await verify("--format", "json"));+ expect(json).toMatchObject({ graph: "diverged", counts: { diverged: 1 }, fix: "ix reset --workspace --yes --ingest" });+ expect(json.files[0].missing[0]).toMatchObject({ kind: "function", name: "greet" });++ out.length = 0;+ const text = await verify();+ expect(text).toMatch(/Graph:?\s+diverged/);+ expect(text).toMatch(/ix reset --workspace --yes --ingest/);+ expect(text).toMatch(/edges are not compared/);+ expect(process.exitCode ?? 0).toBe(0);+ });++ it("unverified/not_mapped with no workspace, exit 0", async () => {+ const llm = await verify("--format", "llm");+ expect(llm).toMatch(/^verify graph=unverified reason=not_mapped files=0 .*fix="ix map"/m);+ expect(process.exitCode ?? 0).toBe(0);+ });++ it("a 404 or 500 on /v1/list makes the file unverified, not a crash", async () => {+ for (const status of [404, 500]) {+ await mapped();+ listStatus = status;+ out.length = 0;+ const llm = await verify("--format", "llm");+ expect(llm).toMatch(/^file path=a\.ts state=unverified reason=list_failed/m);+ expect(process.exitCode ?? 0).toBe(0);+ }+ });++ it("writes the record ix status reads", async () => {+ await mapped({ dropFunction: true });+ await verify("--format", "llm");+ const { verifyRecordPath } = await import("../config.js");+ expect(JSON.parse(readFileSync(verifyRecordPath(repo), "utf-8"))).toMatchObject({ graph: "diverged", diverged: 1 });+ });+});++describe("ix verify roots and the record", () => {+ it("a named path does not replace the record ix status reads", async () => {+ await mapped({ dropFunction: true });+ await verify("a.ts", "--format", "llm");+ const { verifyRecordPath } = await import("../config.js");+ expect(existsSync(verifyRecordPath(repo))).toBe(false);+ });++ it("a deleted file named through a symlinked path is stale, not outside the workspace", async () => {+ await mapped();+ rmSync(join(repo, "a.ts"));+ // macOS's /tmp and /var are such links. realpath cannot resolve a path+ // that no longer exists, so its existing parent has to be resolved instead.+ const link = join(home, "link");+ symlinkSync(repo, link, "junction");+ expect(await verify(join(link, "a.ts"), "--format", "llm"))+ .toMatch(/^file path=a\.ts state=stale reason=missing_on_disk/m);+ });++ it("--root . and --root with a trailing slash find the mapped workspace", async () => {+ await mapped();+ for (const root of [".", `${repo}/`]) {+ out.length = 0;+ expect(await verify("--root", root, "--format", "llm")).toMatch(/^verify graph=clean files=1 clean=1/m);+ }+ });+});++describe("ix verify errors", () => {+ it("--sample 0 and --sample abc are usage errors through errors.ts", async () => {+ const { CliUsageError, renderCliError } = await import("../errors.js");+ for (const bad of ["0", "abc"]) {+ const err = await verify("--sample", bad).then(() => null, (e) => e);+ expect(err).toBeInstanceOf(CliUsageError);+ expect(() => renderCliError(err)).toThrow("exit 1");+ }+ expect(out.join("\n")).toMatch(/--sample/);+ expect(out.join("\n")).not.toMatch(/at .*verify\.ts/); // no stack trace+ });++ it("an unreachable backend gives the uniform llm error record and exit 1, like status", async () => {+ await mapped();+ // A port nothing listens on (port 1 is one fetch refuses to dial at all).+ const closed = createServer();+ await new Promise<void>((r) => closed.listen(0, "127.0.0.1", r));+ const port = (closed.address() as { port: number }).port;+ await new Promise<void>((r) => closed.close(() => r()));+ process.env.IX_ENDPOINT = `http://127.0.0.1:${port}`;+ const err = await verify("--format", "llm").then(() => null, (e) => e);+ expect(String(err)).toMatch(/exit 1/);+ expect(out.join("\n")).toMatch(/^error code=backend_unreachable message=/m);+ });+});diff --git a/ix-cli/src/cli/__tests__/verify.test.ts b/ix-cli/src/cli/__tests__/verify.test.tsnew file mode 100644index 00000000..0e0945b6--- /dev/null+++ b/ix-cli/src/cli/__tests__/verify.test.ts@@ -0,0 +1,649 @@+// 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 nodePath from "node:path";+import { createHash } from "node:crypto";+import { fileURLToPath } from "node:url";++import { saveIngestBaseline } from "../ingest-baseline.js";+import { fileIdentity, repoWorkspaceIdFor } from "../system.js";+import { canonicalWorkspacePath, verifyRecordPath } from "../config.js";+import { loadIngestionModules } from "../commands/ingestion-loader.js";+import { ingestFiles } from "../commands/ingest.js";+import { FakeBackend } from "./helpers/fake-backend.js";+import {+ classifyFile,+ diffNodes,+ expectedNodes,+ graphVerdict,+ loadVerifyRecord,+ pickVerifyFiles,+ recordFromReport,+ runVerify,+ saveVerifyRecord,+ storedNodes,+ VERIFY_DEFAULT_KINDS,+ verifyRecordOutdated,+ type VerifyNode,+ type VerifyReport,+} from "../verify.js";++/**+ * CL-24A: `ix verify` compares a re-parse with the stored nodes. These pin the+ * pure parts (sampling, node sets, the diff, the verdict) and, against a fake+ * client, the shapes that matter: stale vs diverged (F-01), multi-repo+ * identity, and the refusals.+ */++const node = (kind: string, name: string, lineStart: number | null = 1, lineEnd: number | null = 2): VerifyNode =>+ ({ kind, name, lineStart, lineEnd });++describe("pickVerifyFiles", () => {+ const root = "/w";+ const baseline = {+ files: new Map<string, number>([+ ["/w/a.ts", 1], ["/w/b.ts", 2], ["/w/c.ts", 3], ["/w/d.ts", 4], ["/w/e.ts", 5],+ ["/w/f.ts", 6], ["/w/g.ts", 7], ["/w/h.ts", 8], ["/w/slow.ts", 99], ["/w/x.unknown", 100],+ ]),+ replayedFiles: ["c.ts"],+ parseTimeouts: ["slow.ts"],+ };+ const supported = (rel: string) => !rel.endsWith(".unknown");++ it("is deterministic for a given seed", () => {+ const a = pickVerifyFiles(root, baseline, { sample: 6, seed: 7, supported });+ const b = pickVerifyFiles(root, baseline, { sample: 6, seed: 7, supported });+ expect(a).toEqual(b);+ expect(a).toHaveLength(6);+ });++ it("puts explicit paths first, then replayed files, then the newest", () => {+ const picked = pickVerifyFiles(root, baseline, { sample: 4, seed: 1, explicit: ["a.ts"], supported });+ expect(picked[0]).toBe("a.ts");+ expect(picked[1]).toBe("c.ts");+ // ceil(4/2) = 2 recent ones on top of the two already picked: h.ts is the newest eligible.+ expect(picked[2]).toBe("h.ts");+ expect(picked).toHaveLength(4);+ });++ it("skips parse timeouts and unsupported grammars", () => {+ const picked = pickVerifyFiles(root, baseline, { sample: 100, seed: 1, supported });+ expect(picked).not.toContain("slow.ts");+ expect(picked).not.toContain("x.unknown");+ expect(picked).toHaveLength(8);+ });++ it("reads workspace-relative baseline keys too", () => {+ const picked = pickVerifyFiles(root, { files: new Map([["src/a.ts", 1]]), replayedFiles: [], parseTimeouts: [] },+ { sample: 5, seed: 1 });+ expect(picked).toEqual(["src/a.ts"]);+ });+});++describe("expectedNodes", () => {+ it("drops chunk and external nodes, and maps section start_line/end_line", () => {+ const got = expectedNodes({ ops: [+ { type: "UpsertNode", id: "f", kind: "file", name: "a.md", attrs: { line_start: 1, line_end: 9 } },+ { type: "UpsertNode", id: "c", kind: "chunk", name: "body", attrs: { start_line: 1, end_line: 2 } },+ { type: "UpsertNode", id: "x", kind: "function", name: "ext", attrs: { external: true } },+ { type: "UpsertNode", id: "s", kind: "section", name: "Intro", attrs: { start_line: 3, end_line: 5 } },+ { type: "UpsertEdge", id: "e", src: "f", dst: "s", predicate: "CONTAINS" },+ ] });+ expect([...got.keys()]).toEqual(["f", "s"]);+ expect(got.get("s")).toEqual(node("section", "Intro", 3, 5));+ });+});++describe("storedNodes", () => {+ const row = (id: string, uri: string, extra: Record<string, unknown> = {}) => ({+ id, kind: "function", name: id, attrs: { line_start: 1, line_end: 2 }, provenance: { sourceUri: uri }, ...extra,+ });++ it("keeps an exact source path only, not a substring hit", () => {+ const got = storedNodes([row("a", "src/a.ts"), row("b", "src/a.ts.bak"), row("c", "lib/src/a.ts")], "src/a.ts");+ expect([...got.keys()]).toEqual(["a"]);+ });++ it("accepts both source_uri spellings and Windows separators", () => {+ const got = storedNodes([+ { id: "a", kind: "function", name: "a", attrs: {}, provenance: { source_uri: "src/a.ts" } } as any,+ row("b", "src\\a.ts"),+ ], "src\\a.ts");+ expect([...got.keys()].sort()).toEqual(["a", "b"]);+ });++ it("drops chunks, externals and tombstones", () => {+ const got = storedNodes([+ row("a", "a.ts", { kind: "chunk" }),+ row("b", "a.ts", { attrs: { external: true } }),+ row("c", "a.ts", { deletedRev: 4 }),+ row("d", "a.ts"),+ ], "a.ts");+ expect([...got.keys()]).toEqual(["d"]);+ });+});++describe("diffNodes", () => {+ it("reports missing, extra and changed name, kind and line spans", () => {+ const exp = new Map([["1", node("function", "f", 1, 5)], ["2", node("class", "C")], ["3", node("function", "g")]]);+ const got = new Map([["1", node("method", "f2", 2, 6)], ["2", node("class", "C")], ["4", node("function", "old")]]);+ const diff = diffNodes(exp, got);+ expect(diff.missing).toEqual([{ id: "3", kind: "function", name: "g" }]);+ expect(diff.extra).toEqual([{ id: "4", kind: "function", name: "old" }]);+ expect(diff.changed.map((c) => c.field).sort()).toEqual(["kind", "lineEnd", "lineStart", "name"]);+ });+});++describe("classifyFile", () => {+ const empty = { missing: [], extra: [], changed: [] };+ const missing = { missing: [{ id: "1", kind: "function", name: "f" }], extra: [], changed: [] };++ it("clean when hashes match and nodes match", () => {+ expect(classifyFile("h", "h", empty, false, 3)).toEqual({ state: "clean" });+ });+ it("stale when the bytes changed since ingest", () => {+ expect(classifyFile("h2", "h1", missing, false, 3).state).toBe("stale");+ });+ it("diverged when the hash is equal and nodes are missing", () => {+ expect(classifyFile("h", "h", missing, false, 0)).toEqual({ state: "diverged" });+ });+ it("F-01: the stored hash is the edit in between, so only a recorded replay makes it diverged", () => {+ // The backend's source hash is the newest stored patch's; an Idempotent+ // revert writes none, so the hashes differ even though nothing is pending.+ expect(classifyFile("h2", "h1", missing, false, 3, true)).toEqual({ state: "diverged", reason: "replayed_not_applied" });+ // Not recorded as replayed: indistinguishable from an edit since the map.+ expect(classifyFile("h2", "h1", missing, false, 3, false)).toEqual({ state: "stale", reason: "changed_since_ingest" });+ });+ it("unverified when truncated, with no comparison, or with no hash and no nodes", () => {+ expect(classifyFile("h", "h", empty, true).state).toBe("unverified");+ expect(classifyFile("h", "h", null, false).state).toBe("unverified");+ expect(classifyFile("h", undefined, missing, false, 0)).toEqual({ state: "unverified", reason: "not_in_graph" });+ });+ it("without a hash lookup, a match is still clean and a mismatch is not judged", () => {+ expect(classifyFile("h", null, empty, false, 1).state).toBe("clean");+ expect(classifyFile("h", null, missing, false, 1)).toEqual({ state: "unverified", reason: "hash_unknown" });+ });+});++describe("graphVerdict", () => {+ const map = "ix map";+ const rebuild = "ix reset --workspace --yes --ingest";+ // [clean, stale, diverged, unverified] -> verdict. `clean` only when some+ // file verified clean and none is stale or diverged.+ const cases: Array<[number, number, number, number, ReturnType<typeof graphVerdict>]> = [+ [0, 0, 0, 0, { graph: "unverified", fix: null, reason: "no_files" }],+ [20, 0, 0, 0, { graph: "clean", fix: null }],+ [1, 0, 0, 19, { graph: "clean", fix: null }],+ [0, 0, 0, 20, { graph: "unverified", fix: null, reason: "no_file_verified" }],+ // The two shapes from the review: nothing verified clean, nothing diverged.+ [0, 20, 0, 0, { graph: "stale", fix: map }],+ [0, 1, 0, 19, { graph: "stale", fix: map }],+ // A clean file beside a stale one still does not vouch for the stale one.+ [2, 1, 0, 0, { graph: "stale", fix: map }],+ [18, 1, 0, 1, { graph: "stale", fix: map }],+ // Stale files alone are not divergence; any diverged file is.+ [1, 1, 1, 0, { graph: "diverged", fix: rebuild }],+ [0, 0, 1, 19, { graph: "diverged", fix: rebuild }],+ [0, 5, 1, 0, { graph: "diverged", fix: rebuild }],+ [0, 0, 20, 0, { graph: "diverged", fix: rebuild }],+ ];+ it.each(cases)("clean=%i stale=%i diverged=%i unverified=%i", (clean, stale, diverged, unverified, want) => {+ const files = clean + stale + diverged + unverified;+ expect(graphVerdict({ files, clean, stale, diverged, unverified })).toEqual(want);+ });+});++// ── With a workspace on disk ────────────────────────────────────────────++let home: string;+let savedIxHome: string | undefined;++beforeEach(() => {+ // Canonical exactly as ingest makes its root (`canonicalWorkspacePath`, i.e.+ // realpathSync.native): plain realpathSync keeps a Windows 8.3 name like+ // RUNNER~1, which ingest -- and so verify -- expands.+ home = canonicalWorkspacePath(fs.mkdtempSync(nodePath.join(os.tmpdir(), "ix-verify-")));+ savedIxHome = process.env.IX_HOME;+ process.env.IX_HOME = home;+});++afterEach(() => {+ if (savedIxHome === undefined) delete process.env.IX_HOME;+ else process.env.IX_HOME = savedIxHome;+ fs.rmSync(home, { recursive: true, force: true });+});++function register(root: string, workspaceId = "ws1"): void {+ fs.writeFileSync(nodePath.join(home, "config.yaml"),+ `endpoint: http://127.0.0.1:1\nformat: text\nworkspaces:\n - workspace_id: "${workspaceId}"\n` ++ ` workspace_name: repo\n root_path: ${root}\n default: true\n`);+}++const sha = (s: string) => createHash("sha256").update(Buffer.from(s)).digest("hex");++/** What ingest would have stored for `rel`, as `/v1/list` rows. */+async function ingestedRows(root: string, rel: string, workspaceId: string) {+ const [{ parseFile }, { buildPatchWithResolution, extractorName }] = await loadIngestionModules();+ const src = fs.readFileSync(nodePath.join(root, rel), "utf-8");+ const { fileWorkspaceId, fileMultiRepo } = fileIdentity(root, workspaceId);+ const build = buildPatchWithResolution as (...a: unknown[]) => { ops: Array<Record<string, any>> };+ const patch = build(parseFile(rel, src), sha(src), fileWorkspaceId(rel), [], undefined, fileMultiRepo(rel));+ return {+ extractor: extractorName(),+ ws: fileWorkspaceId(rel),+ hash: sha(src),+ rows: patch.ops.filter((o) => o.type === "UpsertNode").map((o) => ({+ id: o.id, kind: o.kind, name: o.name, attrs: o.attrs, provenance: { sourceUri: rel, sourceHash: sha(src) },+ })),+ };+}++function fakeClient(store: { rows: any[]; hashes: Array<{ workspaceId: string; uri: string; hash: string }>; stats?: boolean }) {+ const calls: Array<{ kind: string; scope?: string; workspaceId?: string }> = [];+ return {+ calls,+ client: {+ // /v1/stats byKind: every kind the store holds, as the backend counts them.+ ...(store.stats ? {+ async stats() {+ const kinds = [...new Set(store.rows.map((r) => r.kind as string))];+ return { nodes: { total: store.rows.length, byKind: kinds.map((kind) => ({ kind, count: 1 })) } };+ },+ } : {}),+ async listByKind(kind: string, opts?: { scope?: string; workspaceId?: string }) {+ calls.push({ kind, scope: opts?.scope, workspaceId: opts?.workspaceId });+ return store.rows.filter((r) => r.kind === kind && r.provenance.sourceUri.includes(opts?.scope ?? ""));+ },+ async getSourceHashes() { return store.hashes; },+ } as any,+ };+}++describe("runVerify", () => {+ it("is unverified/not_mapped with no workspace, and suggests ix map", async () => {+ const root = nodePath.join(home, "nowhere");+ fs.mkdirSync(root);+ const report = await runVerify(fakeClient({ rows: [], hashes: [] }).client, root);+ expect(report).toMatchObject({ graph: "unverified", reason: "not_mapped", fix: "ix map" });+ });++ it("refuses to judge when the extractor changed", async () => {+ const root = nodePath.join(home, "repo");+ fs.mkdirSync(root);+ fs.writeFileSync(nodePath.join(root, "a.ts"), "export function a() { return 1; }\n");+ register(root);+ saveIngestBaseline(root, new Map([[nodePath.join(root, "a.ts"), 1]]), 3, new Date(), new Map(), "old-extractor/0");+ const report = await runVerify(fakeClient({ rows: [], hashes: [] }).client, root);+ expect(report).toMatchObject({ graph: "unverified", reason: "extractor_changed", fix: "ix map" });+ });++ it("clean, stale, and diverged (same bytes, nodes missing)", async () => {+ const root = nodePath.join(home, "repo");+ fs.mkdirSync(root);+ fs.writeFileSync(nodePath.join(root, "a.ts"), "export function a() { return 1; }\n");+ fs.writeFileSync(nodePath.join(root, "b.ts"), "export function b() { return 2; }\nexport class B {}\n");+ fs.writeFileSync(nodePath.join(root, "c.ts"), "export function c() { return 3; }\n");+ register(root);+ const a = await ingestedRows(root, "a.ts", "ws1");+ const b = await ingestedRows(root, "b.ts", "ws1");+ const c = await ingestedRows(root, "c.ts", "ws1");+ saveIngestBaseline(root, new Map(["a.ts", "b.ts", "c.ts"].map((f, i) => [nodePath.join(root, f), i])), 3,+ new Date(), new Map(), a.extractor);+ // b.ts: the graph lost its function (hash still current). c.ts: edited since ingest.+ const store = {+ rows: [...a.rows, ...b.rows.filter((r) => r.kind !== "function"), ...c.rows],+ hashes: [+ { workspaceId: "ws1", uri: "a.ts", hash: a.hash },+ { workspaceId: "ws1", uri: "b.ts", hash: b.hash },+ { workspaceId: "ws1", uri: "c.ts", hash: "older" },+ ],+ };+ const { client, calls } = fakeClient(store);+ const report = await runVerify(client, root, { sample: 10 });+ const state = Object.fromEntries(report.files.map((f) => [f.path, f.state]));+ expect(state).toEqual({ "a.ts": "clean", "b.ts": "diverged", "c.ts": "stale" });+ expect(report.graph).toBe("diverged");+ expect(report.fix).toBe("ix reset --workspace --yes --ingest");+ expect(report.files.find((f) => f.path === "b.ts")!.missing).toEqual([expect.objectContaining({ kind: "function", name: "b" })]);+ // Scoped, per-file workspace, never a chunk read.+ expect(calls.every((c) => c.workspaceId === "ws1" && c.kind !== "chunk")).toBe(true);+ // No edge fields anywhere in the report.+ expect(JSON.stringify(report)).not.toMatch(/edge|predicate|CONTAINS/i);+ // The record is saved for status/doctor.+ expect(loadVerifyRecord(root)).toMatchObject({ graph: "diverged", files: 3, diverged: 1, stale: 1, divergedFiles: ["b.ts"] });+ });++ it("diverged when the graph holds an extra node the re-parse does not (hash current)", async () => {+ const root = nodePath.join(home, "repo");+ fs.mkdirSync(root);+ fs.writeFileSync(nodePath.join(root, "a.ts"), "export function a() { return 1; }\n");+ register(root);+ const a = await ingestedRows(root, "a.ts", "ws1");+ saveIngestBaseline(root, new Map([[nodePath.join(root, "a.ts"), 1]]), 3, new Date(), new Map(), a.extractor);+ // A leftover from an older edit that was never retracted.+ const fn = a.rows.find((r) => r.kind === "function")!;+ const ghost = { ...fn, id: "ghost-node-id", name: "removedLongAgo" };+ const { client } = fakeClient({ rows: [...a.rows, ghost], hashes: [{ workspaceId: "ws1", uri: "a.ts", hash: a.hash }] });+ const report = await runVerify(client, root, { sample: 10 });+ expect(report.graph).toBe("diverged");+ expect(report.files[0]).toMatchObject({ path: "a.ts", state: "diverged", missing: [] });+ expect(report.files[0].extra).toEqual([expect.objectContaining({ id: "ghost-node-id", name: "removedLongAgo" })]);+ });++ it("F-01 end to end: a recorded not-applied revert is diverged, an unrecorded one is only stale", async () => {+ const root = nodePath.join(home, "repo");+ fs.mkdirSync(root);+ // On disk: the reverted bytes. In the graph: the edit in between, whose+ // patch is still the newest, so its hash is the stored one.+ fs.writeFileSync(nodePath.join(root, "a.ts"), "export function between() { return 2; }\n");+ register(root);+ const between = await ingestedRows(root, "a.ts", "ws1");+ fs.writeFileSync(nodePath.join(root, "a.ts"), "export function a() { return 1; }\n");+ const store = { rows: between.rows, hashes: [{ workspaceId: "ws1", uri: "a.ts", hash: between.hash }] };+ const ingestedAt = new Date(Date.now() + 5_000); // after the revert's mtime+ const files = new Map([[nodePath.join(root, "a.ts"), 1]]);++ saveIngestBaseline(root, files, 3, ingestedAt, new Map(), between.extractor, { replayedFiles: ["a.ts"] });+ const recorded = await runVerify(fakeClient(store).client, root, { sample: 5 });+ expect(recorded.files[0]).toMatchObject({ path: "a.ts", state: "diverged", reason: "replayed_not_applied" });+ expect(recorded.graph).toBe("diverged");++ saveIngestBaseline(root, files, 3, ingestedAt, new Map(), between.extractor);+ const unrecorded = await runVerify(fakeClient(store).client, root, { sample: 5 });+ expect(unrecorded.files[0]).toMatchObject({ path: "a.ts", state: "stale", reason: "changed_since_ingest" });+ expect(unrecorded.graph).toBe("stale");+ });++ it("reads every kind the workspace holds: a stored node of a kind the parse never produces is extra", async () => {+ const root = nodePath.join(home, "repo");+ fs.mkdirSync(root);+ fs.writeFileSync(nodePath.join(root, "a.ts"), "export function a() { return 1; }\n");+ register(root);+ const a = await ingestedRows(root, "a.ts", "ws1");+ saveIngestBaseline(root, new Map([[nodePath.join(root, "a.ts"), 1]]), 3, new Date(), new Map(), a.extractor);+ // `section` is neither in VERIFY_DEFAULT_KINDS nor anything a .ts parse makes.+ expect(VERIFY_DEFAULT_KINDS).not.toContain("section");+ expect([...expectedNodes({ ops: [] }).values()]).toEqual([]);+ const leftover = { id: "old-section-id", kind: "section", name: "Old heading", attrs: { start_line: 1, end_line: 1 },+ provenance: { sourceUri: "a.ts", sourceHash: a.hash } };+ const store = { rows: [...a.rows, leftover], hashes: [{ workspaceId: "ws1", uri: "a.ts", hash: a.hash }], stats: true };+ const { client, calls } = fakeClient(store);+ const report = await runVerify(client, root, { sample: 5 });+ expect(calls.some((c) => c.kind === "section" && c.scope === "a.ts")).toBe(true);+ expect(report.graph).toBe("diverged");+ expect(report.files[0]).toMatchObject({ path: "a.ts", state: "diverged", missing: [] });+ expect(report.files[0].extra).toEqual([{ id: "old-section-id", kind: "section", name: "Old heading" }]);+ });++ it("a named path whose parse timed out, or over ingest's size limit, is unverified and never parsed", async () => {+ const root = nodePath.join(home, "repo");+ fs.mkdirSync(root);+ fs.writeFileSync(nodePath.join(root, "slow.ts"), "export function slow() { return 1; }\n");+ fs.writeFileSync(nodePath.join(root, "big.ts"), `export const big = "${"x".repeat(1024 * 1024)}";\n`);+ register(root);+ const [parser, builder, languages] = await loadIngestionModules();+ let parsed = 0;+ const loadModules = async (): Promise<Awaited<ReturnType<typeof loadIngestionModules>>> => [+ { ...parser, parseFile: (...args: Parameters<typeof parser.parseFile>) => { parsed++; return parser.parseFile(...args); } },+ builder,+ languages,+ ];+ saveIngestBaseline(root, new Map(), 3, new Date(), new Map(), builder.extractorName(), { parseTimeouts: ["slow.ts"] });+ const report = await runVerify(fakeClient({ rows: [], hashes: [] }).client, root, { paths: ["slow.ts", "big.ts"], sample: 2, loadModules });+ expect(report.files).toEqual([+ expect.objectContaining({ path: "slow.ts", state: "unverified", reason: "parse_timed_out" }),+ expect.objectContaining({ path: "big.ts", state: "unverified", reason: "too_large" }),+ ]);+ expect(parsed).toBe(0);+ });++ it("only a whole-root run saves the status record; named paths and record:false do not", async () => {+ const root = nodePath.join(home, "repo");+ fs.mkdirSync(root);+ fs.writeFileSync(nodePath.join(root, "a.ts"), "export function a() { return 1; }\n");+ register(root);+ const a = await ingestedRows(root, "a.ts", "ws1");+ saveIngestBaseline(root, new Map([[nodePath.join(root, "a.ts"), 1]]), 3, new Date(), new Map(), a.extractor);+ const store = { rows: a.rows, hashes: [{ workspaceId: "ws1", uri: "a.ts", hash: a.hash }] };+ await runVerify(fakeClient(store).client, root, { paths: ["a.ts"] });+ await runVerify(fakeClient(store).client, root, { record: false });+ expect(fs.existsSync(verifyRecordPath(root))).toBe(false);+ await runVerify(fakeClient(store).client, root);+ expect(loadVerifyRecord(root)).toMatchObject({ graph: "clean", files: 1 });+ });++ it("a non-canonical root (trailing slash, '.', a symlink) finds the canonical baseline and record", async () => {+ const root = nodePath.join(home, "repo");+ fs.mkdirSync(root);+ fs.writeFileSync(nodePath.join(root, "a.ts"), "export function a() { return 1; }\n");+ register(root);+ const a = await ingestedRows(root, "a.ts", "ws1");+ saveIngestBaseline(root, new Map([[nodePath.join(root, "a.ts"), 1]]), 3, new Date(), new Map(), a.extractor);+ const link = nodePath.join(home, "link");+ fs.symlinkSync(root, link);+ const store = { rows: a.rows, hashes: [{ workspaceId: "ws1", uri: "a.ts", hash: a.hash }] };+ for (const input of [`${root}/`, `${root}/.`, link]) {+ const report = await runVerify(fakeClient(store).client, input);+ expect(report).toMatchObject({ root, graph: "clean" });+ expect(loadVerifyRecord(input)).toMatchObject({ root, graph: "clean" });+ }+ });++ it("a failed list makes that file unverified, not a crash", async () => {+ const root = nodePath.join(home, "repo");+ fs.mkdirSync(root);+ fs.writeFileSync(nodePath.join(root, "a.ts"), "export function a() { return 1; }\n");+ register(root);+ const a = await ingestedRows(root, "a.ts", "ws1");+ saveIngestBaseline(root, new Map([[nodePath.join(root, "a.ts"), 1]]), 3, new Date(), new Map(), a.extractor);+ const client = {+ async listByKind() { throw new Error("500: boom"); },+ async getSourceHashes() { throw new Error("404: not found"); },+ } as any;+ const report = await runVerify(client, root);+ expect(report.files).toEqual([expect.objectContaining({ path: "a.ts", state: "unverified", reason: "list_failed" })]);+ expect(report.graph).toBe("unverified");+ });++ it("a named directory is not_file, not missing_on_disk", async () => {+ const root = nodePath.join(home, "repo");+ fs.mkdirSync(nodePath.join(root, "dir.ts"), { recursive: true });+ register(root);+ const [, builder] = await loadIngestionModules();+ saveIngestBaseline(root, new Map(), 3, new Date(), new Map(), builder.extractorName());+ const report = await runVerify(fakeClient({ rows: [], hashes: [] }).client, root, { paths: ["dir.ts"], sample: 1 });+ expect(report.files).toEqual([expect.objectContaining({ path: "dir.ts", state: "unverified", reason: "not_file" })]);+ });++ it("budgetMs: stops starting reads when it runs out, leaves unjudged files out, and saves no record", async () => {+ const root = nodePath.join(home, "repo");+ fs.mkdirSync(root);+ const rels = ["a.ts", "b.ts", "c.ts"];+ for (const [i, rel] of rels.entries()) fs.writeFileSync(nodePath.join(root, rel), `export function f${i}() { return ${i}; }\n`);+ register(root);+ const [, builder] = await loadIngestionModules();+ saveIngestBaseline(root, new Map(rels.map((r) => [nodePath.join(root, r), 1])), 3, new Date(), new Map(), builder.extractorName());+ let lists = 0;+ const slow = {+ async listByKind() { lists++; await new Promise((r) => setTimeout(r, 40)); return []; },+ async getSourceHashes() { return []; },+ } as any;+ const report = await runVerify(slow, root, { sample: 3, budgetMs: 60 });+ expect(report.partial).toBe(true);+ // 11 default kinds x 3 files without a budget; a few reads at most with one.+ expect(lists).toBeLessThan(11 * 3);+ expect(report.files.length).toBeLessThan(3);+ expect(fs.existsSync(verifyRecordPath(root))).toBe(false);++ // Out of budget before anything is judged: unverified, and says why.+ const none = await runVerify(slow, root, { sample: 3, budgetMs: 0 });+ expect(none).toMatchObject({ graph: "unverified", reason: "timed_out", partial: true, files: [] });++ // No budget: complete, no `partial` key.+ const full = await runVerify(fakeClient({ rows: [], hashes: [] }).client, root, { sample: 3, record: false });+ expect(full.files).toHaveLength(3);+ expect("partial" in full).toBe(false);+ });++ it("multi-repo: per-repo workspace ids and member-relative ids, as ingest builds them", async () => {+ const root = nodePath.join(home, "system");+ for (const repo of ["repo-a", "repo-b"]) {+ fs.mkdirSync(nodePath.join(root, repo, ".git"), { recursive: true });+ fs.mkdirSync(nodePath.join(root, repo, "src"), { recursive: true });+ fs.writeFileSync(nodePath.join(root, repo, "package.json"), `{"name":"${repo}"}`);+ fs.writeFileSync(nodePath.join(root, repo, "src", "x.ts"), "export function x() { return 1; }\n");+ }+ const { fileWorkspaceId, fileMultiRepo } = fileIdentity(root, "system-ws");+ expect(fileWorkspaceId("repo-a/src/x.ts")).toBe(repoWorkspaceIdFor(root, "repo-a"));+ expect(fileWorkspaceId("repo-b/src/x.ts")).toBe(repoWorkspaceIdFor(root, "repo-b"));+ expect(fileMultiRepo("repo-a/src/x.ts")).toMatchObject({ repoId: "repo-a", systemId: expect.any(String) });++ // A member's node ids are the ids its own solo ingest gives it.+ const coIngested = await ingestedRows(root, "repo-a/src/x.ts", "system-ws");+ const solo = await ingestedRows(nodePath.join(root, "repo-a"), "src/x.ts", repoWorkspaceIdFor(root, "repo-a"));+ expect(coIngested.rows.map((r) => r.id).sort()).toEqual(solo.rows.map((r) => r.id).sort());+ expect(coIngested.ws).toBe(solo.ws);++ // And verify, run over the system, finds them clean.+ register(root, "system-ws");+ saveIngestBaseline(root, new Map([[nodePath.join(root, "repo-a/src/x.ts"), 1]]), 3, new Date(), new Map(), coIngested.extractor);+ const { client, calls } = fakeClient({+ rows: coIngested.rows,+ hashes: [{ workspaceId: coIngested.ws, uri: "repo-a/src/x.ts", hash: coIngested.hash }],+ });+ const report = await runVerify(client, root);+ expect(report.files).toEqual([expect.objectContaining({ path: "repo-a/src/x.ts", state: "clean" })]);+ expect(calls.every((c) => c.workspaceId === repoWorkspaceIdFor(root, "repo-a"))).toBe(true);+ });+});++describe("verify record", () => {+ const report: VerifyReport = {+ at: "2026-10-11T00:00:00.000Z", root: "/r", lastIngestAt: "2026-10-10T00:00:00.000Z",+ graph: "diverged", fix: "ix reset --workspace --yes --ingest", sample: 20, seed: 24,+ counts: { files: 2, clean: 1, stale: 0, diverged: 1, unverified: 0 },+ files: [+ { path: "a.ts", state: "clean", expectedNodes: 1, storedNodes: 1, missing: [], extra: [], changed: [] },+ { path: "b.ts", state: "diverged", expectedNodes: 2, storedNodes: 1, missing: [], extra: [], changed: [] },+ ],+ };++ it("round-trips", () => {+ expect(saveVerifyRecord(recordFromReport(report))).toBe(true);+ expect(loadVerifyRecord("/r")).toEqual(recordFromReport(report));+ expect(loadVerifyRecord("/other")).toBeNull();+ });++ it("is outdated once the workspace has been ingested after it ran", () => {+ const record = recordFromReport(report);+ expect(verifyRecordOutdated(record, report.lastIngestAt)).toBe(false);+ expect(verifyRecordOutdated(record, "2026-10-12T00:00:00.000Z")).toBe(true);+ expect(verifyRecordOutdated(record, null)).toBe(false);+ expect(verifyRecordOutdated({ lastIngestAt: null }, "2026-10-12T00:00:00.000Z")).toBe(true);+ });++ it("reads a corrupt record as null", () => {+ fs.writeFileSync(verifyRecordPath("/r"), "{not json");+ expect(loadVerifyRecord("/r")).toBeNull();+ });+});++describe("docs/llm-format.md", () => {+ // Every reason verify can emit is documented: a consumer branching on+ // `reason=` must not meet an undocumented value (e.g. `no_files`).+ it("lists every reason verify.ts emits", () => {+ const here = nodePath.dirname(fileURLToPath(import.meta.url));+ const src = fs.readFileSync(nodePath.join(here, "..", "verify.ts"), "utf-8");+ const doc = fs.readFileSync(nodePath.join(here, "..", "..", "..", "..", "docs", "llm-format.md"), "utf-8");+ const reasons = new Set<string>();+ for (const re of [/reason: "([a-z_]+)"/g, /unverified\("([a-z_]+)"/g, /"(?:unverified|stale|diverged)", "([a-z_]+)"\)/g]) {+ for (const m of src.matchAll(re)) reasons.add(m[1]);+ }+ expect(reasons).toContain("no_files");+ expect(reasons).toContain("parse_timed_out");+ for (const reason of reasons) expect(doc, reason).toMatch(new RegExp(`[\`=]${reason}\``));+ });+});++// ── Against a real ingest ───────────────────────────────────────────────++describe("runVerify after a real ingestFiles run", () => {+ // A real ingest: discovery, the parse pool and HTTP commits to a fake backend.+ vi.setConfig({ testTimeout: 30_000, hookTimeout: 30_000 });++ const envKeys = ["HOME", "USERPROFILE", "IX_ENDPOINT", "IX_LOCK_DIR"] as const;+ const savedEnv: Record<string, string | undefined> = {};+ let backend: FakeBackend;+ let endpoint: string;++ beforeEach(async () => {+ for (const k of envKeys) savedEnv[k] = process.env[k];+ backend = new FakeBackend();+ backend.rememberHashes = true;+ endpoint = await backend.start();+ process.env.HOME = home;+ process.env.USERPROFILE = home;+ process.env.IX_ENDPOINT = endpoint;+ process.env.IX_LOCK_DIR = nodePath.join(home, "locks");+ });++ afterEach(async () => {+ for (const k of envKeys) {+ if (savedEnv[k] === undefined) delete process.env[k];+ else process.env[k] = savedEnv[k];+ }+ await backend.stop();+ });++ /** What the fake backend holds after the run, as verify's client reads it. */+ async function storedByIngest() {+ const uris = [...backend.lastOps.keys()];+ const res = await fetch(`${endpoint}/v1/source-hashes`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ uris }),+ });+ const hashes = (await res.json()) as Array<{ workspaceId: string; uri: string; hash: string }>;+ const hashOf = new Map(hashes.map((h) => [h.uri, h.hash]));+ const rows = uris.flatMap((uri) => (backend.lastOps.get(uri) ?? [])+ .filter((o) => o.type === "UpsertNode")+ .map((o) => ({ id: o.id, kind: o.kind, name: o.name, attrs: o.attrs, provenance: { sourceUri: uri, sourceHash: hashOf.get(uri) } })));+ return { rows, hashes };+ }++ // Not built from verify's own identity code: the rows are what ingestFiles+ // actually committed, so verify and ingest drifting apart on a system+ // workspace (per-repo workspace id, repoId, systemId) turns this red.+ it("multi-repo: every file ingest committed verifies clean, under its member repo's workspace id", async () => {+ const root = nodePath.join(home, "system");+ const files = { "repo-a": "src/alpha.ts", "repo-b": "src/beta.ts" } as const;+ for (const [repo, rel] of Object.entries(files)) {+ fs.mkdirSync(nodePath.join(root, repo, ".git"), { recursive: true });+ fs.mkdirSync(nodePath.join(root, repo, "src"), { recursive: true });+ fs.writeFileSync(nodePath.join(root, repo, "package.json"), `{"name":"${repo}"}`);+ fs.writeFileSync(nodePath.join(root, repo, rel),+ `export function ${repo.replace("-", "_")}() { return 1; }\nexport class C${repo.slice(-1)} {}\n`);+ }++ await ingestFiles(root, { format: "text", force: true, suppressOutput: true, printSummary: false, mapMode: true });+ const store = await storedByIngest();+ const sourceFiles = Object.entries(files).map(([repo, rel]) => `${repo}/${rel}`);+ expect([...backend.lastOps.keys()]).toEqual(expect.arrayContaining(sourceFiles));+ // The premise: ingest really did key each member under its own workspace.+ for (const repo of Object.keys(files)) {+ expect(store.hashes).toContainEqual(expect.objectContaining({+ uri: `${repo}/${files[repo as keyof typeof files]}`, workspaceId: repoWorkspaceIdFor(root, repo),+ }));+ }++ const { client, calls } = fakeClient(store);+ const report = await runVerify(client, root, { paths: sourceFiles, sample: sourceFiles.length, record: false });+ expect(report.files.map((f) => [f.path, f.state]).sort()).toEqual(sourceFiles.map((p) => [p, "clean"]).sort());+ expect(report.graph).toBe("clean");+ for (const repo of Object.keys(files)) {+ expect(calls.some((c) => c.workspaceId === repoWorkspaceIdFor(root, repo))).toBe(true);+ }+ });+});diff --git a/ix-cli/src/cli/bounded-read.ts b/ix-cli/src/cli/bounded-read.tsindex b74074d0..1a5a9f26 100644--- a/ix-cli/src/cli/bounded-read.ts+++ b/ix-cli/src/cli/bounded-read.ts@@ -53,6 +53,11 @@ const MAX_REPO_FILE_BYTES = 1024 * 1024;* point.*/export function readCapped(handle: number, maxBytes: number): string | null {+ return readCappedBytes(handle, maxBytes)?.toString("utf8") ?? null;+}++/** {@link readCapped} without the decode: the bytes, or null when the file holds more. */+function readCappedBytes(handle: number, maxBytes: number): Buffer | null {const chunks: Buffer[] = [];const chunk = Buffer.allocUnsafe(64 * 1024);let total = 0;@@ -63,7 +68,7 @@ export function readCapped(handle: number, maxBytes: number): string | null {if (total > maxBytes) return null;chunks.push(Buffer.from(chunk.subarray(0, bytes)));}- return Buffer.concat(chunks, total).toString("utf8");+ return Buffer.concat(chunks, total);}/**@@ -106,3 +111,28 @@ export function readBoundedFile(return null;}}++/**+ * A bounded read that says why it refused: the bytes, or `too_large` / `not_file`.+ *+ * For a caller that hashes raw bytes and must tell "too big to judge" from+ * "not there" (`ix verify`). The same single handle as {@link readBoundedFile}+ * -- `O_NONBLOCK` open, `fstat` on the handle, `isFile()`, the size check and a+ * capped read -- but a failed open, fstat or read (a missing file, say) throws+ * instead of returning null, so the caller can tell it apart.+ */+export function readBoundedBytes(+ filePath: string,+ maxBytes: number = MAX_REPO_FILE_BYTES,+): { bytes: Buffer } | { refused: "too_large" | "not_file" } {+ const handle = fs.openSync(filePath, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK);+ try {+ const stats = fs.fstatSync(handle);+ if (!stats.isFile()) return { refused: "not_file" };+ if (stats.size > maxBytes) return { refused: "too_large" };+ const bytes = readCappedBytes(handle, maxBytes);+ return bytes === null ? { refused: "too_large" } : { bytes };+ } finally {+ fs.closeSync(handle);+ }+}diff --git a/ix-cli/src/cli/commands/doctor.ts b/ix-cli/src/cli/commands/doctor.tsindex fcaef0c0..a147871c 100644--- a/ix-cli/src/cli/commands/doctor.ts+++ b/ix-cli/src/cli/commands/doctor.ts@@ -41,6 +41,7 @@ import { loadIngestBaseline } from "../ingest-baseline.js";import { isCloudReady } from "../remote.js";import { hasCompletedMapBaseline } from "../stale.js";import { printJson } from "../format.js";+import { runVerify, type VerifyReport } from "../verify.js";import { healthFromError } from "../database-probe.js";import type { CapabilitiesResponse, HealthResponse } from "../../client/types.js";@@ -358,6 +359,62 @@ export function checkRipgrep(run: () => string = () => execFileSync("rg", ["--ve}}+/**+ * "Graph matches a re-parse": the last line of defence for a graph whose+ * counts look fine and whose nodes do not (see `verify.ts`).+ *+ * Never a failure. A diverged sample is a warning with the fix, and anything+ * that stops the comparison -- no workspace, an old backend that 404s, a+ * parser that will not load, any throw at all -- is "not checked", so this+ * check cannot give `ix doctor` an exit code it did not have.+ */+/** `ix doctor`'s verify: a few files, and never more than about this long. */+export const DOCTOR_VERIFY_SAMPLE = 5;+export const DOCTOR_VERIFY_BUDGET_MS = 5_000;+/** Past the budget, how long an in-flight read may still take before doctor gives up. */+const DOCTOR_VERIFY_GRACE_MS = 2_000;++export async function assessGraphVerify(run: () => Promise<VerifyReport>, budgetMs?: number): Promise<CheckResult> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ // The budget stops new work; this stops a read that never returns.+ const report = budgetMs === undefined ? await run() : await Promise.race([+ run(),+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error(`timed out after ${Math.round(budgetMs / 1000)} s`)), budgetMs + DOCTOR_VERIFY_GRACE_MS);+ timer.unref?.();+ }),+ ]);+ const { files, clean, diverged, stale } = report.counts;+ // "partial: 3 of 5" — a run that ran out of budget says how much it saw.+ const partial = report.partial ? ` (partial: ${files} of ${report.sample} files checked within ${Math.round((budgetMs ?? 0) / 1000)} s)` : "";+ if (report.graph === "diverged") {+ const paths = report.files.filter((f) => f.state === "diverged").map((f) => f.path);+ const shown = paths.slice(0, 3).join(", ") + (paths.length > 3 ? `, and ${paths.length - 3} more` : "");+ return {+ ok: false,+ warn: true,+ detail: `${diverged} of ${files} sampled files diverged (${shown})${partial}. Fix: ${report.fix}`,+ };+ }+ if (report.graph === "unverified") {+ return { ok: true, detail: `not checked: ${(report.reason ?? "nothing to compare").replace(/_/g, " ")}${partial}` };+ }+ // Stale is not a pass, but it is what any edit since the last map looks+ // like, so it stays a note (as `ix status` treats changed files).+ if (report.graph === "stale") {+ return { ok: true, detail: `not verified: ${stale} of ${files} sampled files changed since the last ingest${partial} — run \`ix map\`` };+ }+ // Only files judged clean "match"; unverified ones are not counted as such.+ const of = clean === files ? `${files}` : `${clean} of ${files}`;+ return { ok: true, detail: `${of} sampled files match a re-parse (nodes only)${partial}` };+ } catch (e: any) {+ return { ok: true, detail: `not checked: ${e?.message ?? String(e)}` };+ } finally {+ if (timer) clearTimeout(timer);+ }+}+export function registerDoctorCommand(program: Command): void {program.command("doctor")@@ -620,6 +677,29 @@ export function registerDoctorCommand(program: Command): void {}},},+ {+ // Counts can all be healthy while a file's nodes are not what its+ // source says (F-01). A small sampled re-parse; see verify.ts.+ name: "Graph matches a re-parse",+ run: async () => {+ if (configBroken) return CONFIG_NOT_CHECKED;+ if (!matchedWorkspace) return { ok: true, detail: "not checked: no local workspace" };+ // Parsing costs nothing to report when nobody can answer the+ // reads, so ask the (already memoized) health first.+ try {+ const h = await health();+ if (h.status !== "ok") return { ok: true, detail: `not checked: backend ${h.status}` };+ } catch {+ return { ok: true, detail: "not checked: backend not reachable" };+ }+ return assessGraphVerify(+ () => runVerify(client, resolvePath(matchedWorkspace.root_path), {+ sample: DOCTOR_VERIFY_SAMPLE, record: false, budgetMs: DOCTOR_VERIFY_BUDGET_MS,+ }),+ DOCTOR_VERIFY_BUDGET_MS,+ );+ },+ },{name: "No unresolved conflicts",run: async () => {diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.tsindex 405b7d8c..c4fe12dc 100644--- a/ix-cli/src/cli/commands/ingest.ts+++ b/ix-cli/src/cli/commands/ingest.ts@@ -33,7 +33,7 @@ import {changedNames, findDependents, importsChanged, loadIngestSymbols, resolutionHash, saveIngestSymbols,type StoredSummary, type SymbolEntry,} from '../ingest-symbols.js';-import { detectSystem, repoWorkspaceIdFor, lookupPackage, readPackageNames, readPackageDeps } from '../system.js';+import { detectSystem, fileIdentity, lookupPackage, readPackageNames, readPackageDeps } from '../system.js';import { CLIENT_EXPECTED_SCHEMA_VERSION } from '../backend-status.js';import { admitStitchWaiting, connectionNeverEstablished, type StitchRefusal } from '../stitch-guard.js';import {@@ -2239,22 +2239,17 @@ export async function ingestFiles(// system_id, and each file carries its repoId. A cross-repo edge's dst id is// resolved in the dst repo's workspace namespace by core-ingestion.const detectedSystem = detectSystem(workspaceRoot);- const systemId: string | undefined = detectedSystem?.systemId;- const repoOf = (relPath: string): string => (relPath.split('/')[0] || '.');- const repoWsCache = new Map<string, string>();- const repoWorkspaceId = (repo: string): string => {- let ws = repoWsCache.get(repo);- if (!ws) { ws = repoWorkspaceIdFor(workspaceRoot, repo); repoWsCache.set(repo, ws); }- return ws;- };- const repoWorkspaceOf = systemId ? (relPath: string) => repoWorkspaceId(repoOf(relPath)) : undefined;// Per-file workspace id + multi-repo context fed to buildPatchWithResolution.- const fileWorkspaceId = (relPath: string): string => systemId ? repoWorkspaceId(repoOf(relPath)) : workspaceId;+ // Shared with `ix verify` (system.ts fileIdentity), which must agree exactly.+ const {+ systemId,+ repoOf,+ fileWorkspaceId,+ fileMultiRepo,+ } = fileIdentity(workspaceRoot, workspaceId, detectedSystem?.systemId);// The workspace_id a file's nodes are folded under (same value the patch builder// stamps on source.workspaceId) — used to scope the baseline hash lookup per file.const sourceWorkspaceIdOf = (absPath: string): string => fileWorkspaceId(toWorkspaceRelative(absPath));- const fileMultiRepo = (relPath: string) =>- systemId ? { systemId, repoId: repoOf(relPath), repoWorkspaceOf } : undefined;// Cross-repo dependency gate: map an import module name to the member repo that// publishes that package (exact, or prefix at a package boundary for scoped /// sub-module / sub-path imports like "@babel/types/lib/x", "tokio::sync",diff --git a/ix-cli/src/cli/commands/status.ts b/ix-cli/src/cli/commands/status.tsindex d96ce0a9..8965c2b7 100644--- a/ix-cli/src/cli/commands/status.ts+++ b/ix-cli/src/cli/commands/status.ts@@ -12,6 +12,7 @@ import { printJson } from "../format.js";import {checkGraphHealth,describeReplayedChanges,+ GRAPH_REBUILD_FIX,graphHealthJson,graphHealthLlmFields,graphHealthProse,@@ -20,6 +21,7 @@ import {type GraphHealthScope,} from "../graph-health.js";import { detectSystem } from "../system.js";+import { loadVerifyRecord, verifyRecordOutdated, type VerifyRecord } from "../verify.js";interface StatusStaleInfo {graphCompleted: boolean;@@ -43,13 +45,18 @@ interface StatusStaleInfo {* a sampled file list. The `stale` field answers it directly, and* `last_ingest_at` stays ISO so the consumer can do its own arithmetic instead* of parsing prose. `map_complete` separately reports whether an architecture- * hierarchy exists for that source revision.+ * hierarchy exists for that source revision. `verified_*` come from the last+ * whole-root `ix verify`, and are absent when there has been none+ * (`verified_graph` is its verdict: clean, stale, diverged or unverified);+ * `verified_outdated=true` says the workspace was ingested after it ran, so+ * its counts describe an earlier graph.*/export function renderStatusLlm(backend: string,endpoint: string,staleInfo: StatusStaleInfo | null,graph?: GraphHealth,+ verified?: VerifyRecord | null,): string[] {const lines = [llmLine("status", [["backend", backend],@@ -66,6 +73,12 @@ export function renderStatusLlm(? (!staleInfo.graphCompleted || staleInfo.staleFiles > 0 || (staleInfo.replayedFiles?.length ?? 0) > 0|| (staleInfo.parseTimeouts?.length ?? 0) > 0 ? "true" : "false"): null],+ ["verified_at", verified?.at ?? null],+ ["verified_files", verified ? String(verified.files) : null],+ ["verified_diverged", verified ? String(verified.diverged) : null],+ ["verified_outdated", verified ? String(verifyRecordOutdated(verified, staleInfo?.lastIngestAt)) : null],+ // Last, so the fields before it keep their place.+ ["verified_graph", verified?.graph ?? null],])];if (graph && isUnhealthy(graph)) lines.push(llmLine("graph", graphHealthLlmFields(graph)));for (const f of staleInfo?.sampleChangedFiles ?? []) {@@ -137,9 +150,12 @@ export function registerStatusCommand(program: Command): void {}const graph = await graphCheck;+ // The last whole-root `ix verify`, if any. Read only: status never runs one.+ const verified = loadVerifyRecord(root);+ const verifiedOutdated = verified !== null && verifyRecordOutdated(verified, staleInfo?.lastIngestAt);if (opts.format === "llm") {- printLlmLines(renderStatusLlm(health.status, getEndpoint(), staleInfo ?? null, graph));+ printLlmLines(renderStatusLlm(health.status, getEndpoint(), staleInfo ?? null, graph, verified));} else if (opts.format === "json") {const result: any = {backend: health.status,@@ -152,6 +168,11 @@ export function registerStatusCommand(program: Command): void {replayedFiles: staleInfo?.replayedFiles ?? [],parseTimeouts: staleInfo?.parseTimeouts ?? [],graphHealth: { ...graphHealthJson(graph), status: graphHealthWord(graph) },+ verify: verified+ ? { at: verified.at, graph: verified.graph, files: verified.files, diverged: verified.diverged,+ stale: verified.stale, unverified: verified.unverified, lastIngestAt: verified.lastIngestAt,+ outdated: verifiedOutdated, fix: verified.fix }+ : null,};printJson(result);} else {@@ -197,6 +218,27 @@ export function registerStatusCommand(program: Command): void {}}if (isUnhealthy(graph)) renderWarning(graphHealthProse(graph));+ if (verified) {+ // A verify from before the last ingest describes a graph that has+ // since been written to (perhaps by the very fix it suggested):+ // show it, labelled, and ask for a new verify instead of a fix.+ const before = verifiedOutdated ? " (before last ingest)" : "";+ // An unverified record judged no file, so "0 diverged" would read+ // as a pass: name the verdict instead.+ const outcome = verified.graph === "unverified"+ ? `unverified (${verified.files === 0 ? "no files sampled" : "no file verified"})`+ : verified.graph === "stale"+ ? `0 diverged, ${verified.stale} stale (not verified clean)`+ : `${verified.diverged} diverged`;+ renderKeyValue("Verified", `${timeSince(verified.at)}, ${verified.files} files, ${outcome}${before}`);+ if (verified.diverged > 0 && verifiedOutdated) {+ renderNote(`The last ix verify found ${verified.diverged} file(s) whose nodes did not match their source, ` ++ "but the workspace has been ingested since. Run ix verify to check the graph as it is now.");+ } else if (verified.diverged > 0) {+ renderWarning(`The last ix verify found ${verified.diverged} file(s) whose nodes do not match their source. ` ++ `Fix: ${verified.fix ?? GRAPH_REBUILD_FIX}`);+ }+ }}} catch (err) {// Only a transport failure is "not reachable". Anything else — a 500diff --git a/ix-cli/src/cli/commands/verify.ts b/ix-cli/src/cli/commands/verify.tsnew file mode 100644index 00000000..7c5e2aae--- /dev/null+++ b/ix-cli/src/cli/commands/verify.ts@@ -0,0 +1,166 @@+// Copyright 2026 Ix Infrastructure Inc.++import type { Command } from "commander";+import * as fs from "node:fs";+import * as nodePath from "node:path";+import { renderSection, renderKeyValue, renderWarning, renderNote, renderSuccess } from "../ui.js";+import { createClient } from "../../client/factory.js";+import { canonicalWorkspacePath, getEndpoint, resolveWorkspaceRoot } from "../config.js";+import { llmError, llmLine, printLlmLines } from "../llm.js";+import { backendUnreachableError, CliUsageError, isBackendUnreachable } from "../errors.js";+import { printJson } from "../format.js";+import { normalizePathSeparators } from "../path-match.js";+import {+ DEFAULT_VERIFY_SAMPLE,+ DEFAULT_VERIFY_SEED,+ runVerify,+ type VerifyFileResult,+ type VerifyReport,+} from "../verify.js";++/**+ * `ix verify --format llm`: one `verify` record with the verdict and the fix,+ * then one `file` record per file that is not clean. Clean files are counted,+ * not listed: on a healthy graph the answer is one line.+ */+export function renderVerifyLlm(report: VerifyReport): string[] {+ const lines = [llmLine("verify", [+ ["graph", report.graph],+ ["reason", report.reason ?? null],+ ["files", report.counts.files],+ ["clean", report.counts.clean],+ ["stale", report.counts.stale],+ ["diverged", report.counts.diverged],+ ["unverified", report.counts.unverified],+ ["fix", report.fix],+ ])];+ for (const f of report.files) {+ if (f.state === "clean") continue;+ lines.push(llmLine("file", [+ ["path", f.path],+ ["state", f.state],+ ["reason", f.reason ?? null],+ ["missing", f.missing.length],+ ["extra", f.extra.length],+ ["changed", f.changed.length],+ ]));+ }+ return lines;+}++function describeFile(f: VerifyFileResult): string {+ const parts: string[] = [f.state];+ if (f.reason) parts.push(f.reason.replace(/_/g, " "));+ if (f.missing.length > 0) parts.push(`${f.missing.length} missing`);+ if (f.extra.length > 0) parts.push(`${f.extra.length} extra`);+ if (f.changed.length > 0) parts.push(`${f.changed.length} changed`);+ return parts.join(", ");+}++function renderVerifyText(report: VerifyReport): void {+ renderSection("Verify");+ renderKeyValue("Graph", report.graph);+ if (report.reason) renderKeyValue("Reason", report.reason.replace(/_/g, " "));+ const c = report.counts;+ renderKeyValue("Files", `${c.files} checked: ${c.clean} clean, ${c.stale} stale, ${c.diverged} diverged, ${c.unverified} unverified`);+ for (const f of report.files) {+ if (f.state === "clean") continue;+ console.log(` ${f.path} — ${describeFile(f)}`);+ }+ if (report.graph === "diverged") {+ renderWarning(`${c.diverged} file(s) hold nodes that do not match their own source. Fix: ${report.fix}`);+ } else if (report.graph === "unverified") {+ renderNote(report.fix ? `Not verified. Run ${report.fix} first.` : "Not verified: nothing could be compared.");+ } else if (report.graph === "stale") {+ renderNote(`Not verified clean: ${c.stale} file(s) changed since the last ingest. Run ${report.fix}, then ix verify again.`);+ } else {+ renderSuccess("Every checked file's nodes match a re-parse.");+ }+ // Said every time, so a clean verdict is not read as covering edges.+ renderNote("Nodes only: edges are not compared yet.");+}++function parseCount(flag: string, value: string | undefined, fallback: number, min: number): number {+ if (value === undefined) return fallback;+ const normalized = String(value).trim();+ const n = /^\+?\d+$/.test(normalized) ? Number(normalized) : Number.NaN;+ if (!Number.isSafeInteger(n) || n < min) {+ throw new CliUsageError(+ `option '${flag}' must be ${min > 0 ? "a positive" : "a non-negative"} integer, got '${value}'.`,+ `For example: ix verify ${flag} ${min > 0 ? DEFAULT_VERIFY_SAMPLE : DEFAULT_VERIFY_SEED}`,+ );+ }+ return n;+}++/**+ * `canonicalWorkspacePath` for a path that may no longer exist: realpath only+ * resolves an existing path, so resolve the nearest existing ancestor and put+ * the rest back. A deleted file is exactly what verify reports as stale.+ */+function canonicalMaybeMissing(abs: string): string {+ const tail: string[] = [];+ let dir = abs;+ while (!fs.existsSync(dir)) {+ const parent = nodePath.dirname(dir);+ if (parent === dir) return abs;+ tail.unshift(nodePath.basename(dir));+ dir = parent;+ }+ return nodePath.join(canonicalWorkspacePath(dir), ...tail);+}++/** A path the caller typed, as the workspace-relative POSIX path the graph stores. */+function toWorkspaceRel(root: string, input: string): string {+ // Canonical like the root, so a path typed through a symlink still lands inside it.+ const rel = normalizePathSeparators(nodePath.relative(root, canonicalMaybeMissing(nodePath.resolve(process.cwd(), input))));+ if (rel === "" || rel === ".." || rel.startsWith("../") || nodePath.isAbsolute(rel)) {+ throw new CliUsageError(`'${input}' is not a file inside the workspace at ${root}.`);+ }+ return rel;+}++export function registerVerifyCommand(program: Command): void {+ program+ .command("verify [paths...]")+ .description("Compare the graph's nodes to a fresh re-parse of a sample of files")+ .option("--sample <n>", `How many files to check (default ${DEFAULT_VERIFY_SAMPLE}, or the number of paths given)`)+ .option("--seed <n>", `Seed for the random part of the sample (default ${DEFAULT_VERIFY_SEED})`)+ .option("--root <dir>", "Workspace root directory")+ .option("--format <fmt>", "Output format (text|json|llm)", "text")+ .action(async (paths: string[] | undefined, opts: { format: string; root?: string; sample?: string; seed?: string }) => {+ const named = paths ?? [];+ const sample = parseCount("--sample", opts.sample, named.length > 0 ? named.length : DEFAULT_VERIFY_SAMPLE, 1);+ const seed = parseCount("--seed", opts.seed, DEFAULT_VERIFY_SEED, 0);+ // Canonical, as ingest records it: `--root .`, `--root dir/` and a+ // symlinked or registered non-canonical path all name the same root.+ const root = canonicalWorkspacePath(resolveWorkspaceRoot(opts.root ? nodePath.resolve(opts.root) : undefined));+ const explicit = named.map((p) => toWorkspaceRel(root, p));+ const client = createClient();+ let report: VerifyReport;+ try {+ report = await runVerify(client, root, { sample, seed, paths: explicit });+ } catch (err) {+ // As `ix status` does: only a transport failure is "not reachable";+ // anything else reaches the shared boundary in errors.ts.+ if (!isBackendUnreachable(err)) throw err;+ const unreachable = backendUnreachableError(getEndpoint());+ if (opts.format === "llm") {+ console.log(llmError(unreachable.error, unreachable.message, [["hint", unreachable.next ?? null]]));+ } else {+ console.error(unreachable.message);+ if (unreachable.next) console.error(unreachable.next);+ }+ process.exit(1);+ }++ // Exit 0 for every verdict: diverged is an answer, not a failure to run.+ if (opts.format === "llm") {+ printLlmLines(renderVerifyLlm(report));+ } else if (opts.format === "json") {+ printJson(report);+ } else {+ renderVerifyText(report);+ }+ });+}diff --git a/ix-cli/src/cli/config.ts b/ix-cli/src/cli/config.tsindex e8039859..764d455c 100644--- a/ix-cli/src/cli/config.ts+++ b/ix-cli/src/cli/config.ts@@ -84,6 +84,16 @@ export function mapBaselinePath(projectRoot: string): string {return join(ixHome(), `map_baseline_${key}.json`);}+/**+ * Path to the last `ix verify` result for one project root (see `verify.ts`).+ * Deliberately not cleared with the baselines: `ix status` labels a record+ * older than the last ingest instead of losing it.+ */+export function verifyRecordPath(projectRoot: string): string {+ const key = rootKey(projectRoot);+ return join(ixHome(), `verify_${key}.json`);+}+/*** Path to the last `/v1/map` response for one project root, which a map that* ingested nothing reuses instead of asking again (see `map-result-cache.ts`).diff --git a/ix-cli/src/cli/help-text.ts b/ix-cli/src/cli/help-text.tsindex 484a3a49..378b4af9 100644--- a/ix-cli/src/cli/help-text.ts+++ b/ix-cli/src/cli/help-text.ts@@ -44,6 +44,7 @@ const OSS_HELP = [` status Check status`,` stats Show stats`,` doctor Diagnose issues`,+ ` verify Compare graph to a re-parse`,` mcp [install|doctor] Serve agent tools over MCP`,` docker <action> Manage backend`,` view Open visualizer`,diff --git a/ix-cli/src/cli/register/oss-table.ts b/ix-cli/src/cli/register/oss-table.tsindex d6d5d95e..23561884 100644--- a/ix-cli/src/cli/register/oss-table.ts+++ b/ix-cli/src/cli/register/oss-table.ts@@ -66,6 +66,7 @@ export const OSS_COMMAND_TABLE: Readonly<Record<string, () => Promise<RegisterCocontext: async () => (await import("../commands/context.js")).registerContextCommand,around: async () => (await import("../commands/around.js")).registerAroundCommand,hook: async () => (await import("../commands/hook.js")).registerHookCommand,+ verify: async () => (await import("../commands/verify.js")).registerVerifyCommand,};/**diff --git a/ix-cli/src/cli/register/oss.ts b/ix-cli/src/cli/register/oss.tsindex 8f48ece8..f737a3b0 100644--- a/ix-cli/src/cli/register/oss.ts+++ b/ix-cli/src/cli/register/oss.ts@@ -41,6 +41,7 @@ import { registerMcpCommand } from "../commands/mcp.js";import { registerContextCommand } from "../commands/context.js";import { registerAroundCommand } from "../commands/around.js";import { registerHookCommand } from "../commands/hook.js";+import { registerVerifyCommand } from "../commands/verify.js";import { applyOssSetup } from "./oss-setup.js";export { registerProStubs } from "./pro-stubs.js";@@ -95,6 +96,7 @@ export function registerOssCommands(program: Command): void {registerContextCommand(program);registerAroundCommand(program);registerHookCommand(program);+ registerVerifyCommand(program);applyOssSetup(program);}diff --git a/ix-cli/src/cli/system.ts b/ix-cli/src/cli/system.tsindex 76d5dbbd..b8198811 100644--- a/ix-cli/src/cli/system.ts+++ b/ix-cli/src/cli/system.ts@@ -462,3 +462,61 @@ export function workspaceIdForPath(absPath: string): string {export function repoWorkspaceIdFor(rootPath: string, repoDir: string): string {return workspaceIdForPath(nodePath.resolve(rootPath, repoDir));}++/** The multi-repo context a member file's patch is built with. */+export interface MultiRepoContext {+ systemId: string;+ repoId: string;+ repoWorkspaceOf: (relPath: string) => string;+}++/** Per-file identity for one ingest root; see {@link fileIdentity}. */+export interface FileIdentity {+ /** The system id when the root holds two or more member repos, else undefined. */+ systemId: string | undefined;+ /** The member repo a workspace-relative path belongs to (its first segment). */+ repoOf: (relPath: string) => string;+ /** A member file's repo workspace id; undefined outside a system. */+ repoWorkspaceOf: ((relPath: string) => string) | undefined;+ /** The workspace_id a file's nodes are folded under (its patch's source.workspaceId). */+ fileWorkspaceId: (relPath: string) => string;+ /** The multi-repo context passed to buildPatchWithResolution; undefined outside a system. */+ fileMultiRepo: (relPath: string) => MultiRepoContext | undefined;+}++/**+ * The workspace id and multi-repo context each file of `workspaceRoot` is+ * ingested under (Ix#225 Path 1). Inside a system every member repo keeps its+ * OWN stable workspace id, so its node ids match whether it is ingested alone+ * or in the system; outside one every file uses `workspaceId`.+ *+ * Shared by `ix map`/`ix ingest` and `ix verify`: verify re-builds each file's+ * patch to compare with the graph, and any disagreement here would read as+ * divergence on every file of a system workspace.+ */+export function fileIdentity(+ workspaceRoot: string,+ workspaceId: string,+ systemId: string | undefined = detectSystem(workspaceRoot)?.systemId,+): FileIdentity {+ const repoOf = (relPath: string): string => (relPath.split("/")[0] || ".");+ const repoWsCache = new Map<string, string>();+ const repoWorkspaceId = (repo: string): string => {+ let ws = repoWsCache.get(repo);+ if (!ws) { ws = repoWorkspaceIdFor(workspaceRoot, repo); repoWsCache.set(repo, ws); }+ return ws;+ };+ if (!systemId) {+ return {+ systemId: undefined, repoOf, repoWorkspaceOf: undefined,+ fileWorkspaceId: () => workspaceId,+ fileMultiRepo: () => undefined,+ };+ }+ const repoWorkspaceOf = (relPath: string): string => repoWorkspaceId(repoOf(relPath));+ return {+ systemId, repoOf, repoWorkspaceOf,+ fileWorkspaceId: repoWorkspaceOf,+ fileMultiRepo: (relPath) => ({ systemId, repoId: repoOf(relPath), repoWorkspaceOf }),+ };+}diff --git a/ix-cli/src/cli/verify.ts b/ix-cli/src/cli/verify.tsnew file mode 100644index 00000000..12e5ff5c--- /dev/null+++ b/ix-cli/src/cli/verify.ts@@ -0,0 +1,704 @@+// Copyright 2026 Ix Infrastructure Inc.++/**+ * `ix verify`: re-parse a sample of files and compare what the parser says+ * they hold against the nodes the graph stores for them.+ *+ * Everything else that reports on the graph's health (`ix status`, `ix doctor`,+ * graph-health.ts) reads counts or mtimes, so a graph whose nodes quietly stop+ * matching the source -- nodes an earlier ingest left behind, a lost write --+ * passes every one of them. This is the only check that looks at the nodes+ * themselves.+ *+ * Node-level only. Each file is read from disk, parsed and built into the same+ * patch ingest would build (no edges), and its UpsertNode ops are the expected+ * set. The stored set comes from `/v1/list` scoped reads, one per node kind the+ * workspace holds (`/v1/stats` byKind, plus the parse's own kinds), filtered to+ * rows whose `provenance.sourceUri` is exactly that file.+ *+ * What the source hash can and cannot say. `/v1/source-hashes` answers with+ * the sourceHash of the file's newest stored patch (highest rev). A patch the+ * backend answers `Idempotent` writes no patch, so after a revert or a restore+ * (F-01) the newest patch is still the edit in between and its hash is not the+ * disk hash. A hash mismatch alone therefore cannot tell "edited since the last+ * map" from "reverted, and the revert was not applied". Verify tells them apart+ * only with the ingest baseline's `replayedFiles`, the files the last map saw+ * answered `Idempotent`:+ * - stored hash == disk hash, nodes differ: diverged. The graph claims these+ * bytes and holds other nodes (left-behind nodes, a lost write).+ * - stored hash != disk hash, the file is in `replayedFiles` and unchanged+ * since that map, nodes differ: diverged (F-01, `replayed_not_applied`).+ * - stored hash != disk hash otherwise: stale (`ix map`). That includes an+ * F-01 revert the baseline does not list (a baseline from an older CLI):+ * verify cannot see it, and does not claim to.+ *+ * TODO(CL-24, F-03/F-06): edge comparison. Edges -- CONTAINS and every+ * cross-file edge -- are deliberately not compared, and no partial edge check+ * is made: what a file's edges should resolve to depends on the rest of the+ * graph, and the ingest-lane fixes F-03/F-06 change exactly that. Until they+ * land, an edge comparison would report ingest's known gaps as divergence.+ * Externals (`attrs.external`) are left out on both sides for the same reason:+ * they exist only because of an edge.+ */++import * as fs from "node:fs";+import * as nodePath from "node:path";+import { createHash } from "node:crypto";+import type { IxClient } from "../client/api.js";+import type { GraphNode } from "../client/types.js";+import { mapLimit } from "../client/request-memo.js";+import { canonicalWorkspacePath, findWorkspaceForCwd, verifyRecordPath } from "./config.js";+import { extractorChanged, loadIngestBaseline, type IngestBaseline } from "./ingest-baseline.js";+import { fileIdentity } from "./system.js";+import { normalizePathSeparators } from "./path-match.js";+import { readBoundedBytes } from "./bounded-read.js";+import { GRAPH_MAP_FIX, GRAPH_REBUILD_FIX } from "./graph-health.js";+import { isBackendUnreachable } from "./errors.js";+import { loadIngestionModules } from "./commands/ingestion-loader.js";++export const DEFAULT_VERIFY_SAMPLE = 20;+export const DEFAULT_VERIFY_SEED = 24;+/** Rows per `/v1/list` read. A file with this many of one kind is not judged. */+export const VERIFY_LIST_LIMIT = 5000;+/**+ * Kinds always read. The kinds `/v1/stats` reports for the workspace are read+ * too (that list is what makes an extra node of any kind visible); these cover+ * a stats read that fails or lags.+ */+export const VERIFY_DEFAULT_KINDS: readonly string[] = ["file", "function", "method", "class", "interface", "module", "constant", "variable", "trait", "enum", "type"];+const VERIFY_CONCURRENCY = 4;+/** Ingest skips files over this many bytes (`MAX_FILE_BYTES` in ingest.ts), so verify does too. */+const VERIFY_MAX_FILE_BYTES = 1024 * 1024;+/** Bound on the `/v1/stats` read that lists the workspace's kinds. */+const VERIFY_STATS_TIMEOUT_MS = 15_000;++export type VerifyFileState = "clean" | "stale" | "diverged" | "unverified";+/**+ * The graph's verdict from its sampled files. `stale` (no file diverged, at+ * least one changed since the last ingest) is not divergence, and not a pass+ * either: the sample cannot vouch for files whose graph is behind the disk.+ */+export type VerifyGraphVerdict = "clean" | "stale" | "diverged" | "unverified";+/** Every graph verdict, for validating a saved record. */+export const VERIFY_GRAPH_VERDICTS: readonly VerifyGraphVerdict[] = ["clean", "stale", "diverged", "unverified"];++export interface VerifyNode {+ kind: string;+ name: string;+ lineStart: number | null;+ lineEnd: number | null;+}++export interface VerifyNodeRef {+ id: string;+ kind: string;+ name: string;+}++export interface VerifyNodeChange {+ id: string;+ field: "kind" | "name" | "lineStart" | "lineEnd";+ expected: string | number | null;+ stored: string | number | null;+}++export interface NodeDiff {+ missing: VerifyNodeRef[];+ extra: VerifyNodeRef[];+ changed: VerifyNodeChange[];+}++export interface VerifyFileResult {+ path: string;+ state: VerifyFileState;+ /** Why a file is unverified or stale; absent when clean or diverged. */+ reason?: string;+ expectedNodes: number;+ storedNodes: number;+ missing: VerifyNodeRef[];+ extra: VerifyNodeRef[];+ changed: VerifyNodeChange[];+}++export interface VerifyCounts {+ files: number;+ clean: number;+ stale: number;+ diverged: number;+ unverified: number;+}++export interface VerifyReport {+ at: string;+ root: string;+ lastIngestAt: string | null;+ graph: VerifyGraphVerdict;+ /** Why the graph is unverified; absent otherwise. */+ reason?: string;+ /** What to run, or null when there is nothing to fix. */+ fix: string | null;+ sample: number;+ seed: number;+ counts: VerifyCounts;+ files: VerifyFileResult[];+ /**+ * True when `budgetMs` ran out first: `files` holds only the files judged+ * in time. Absent on a run that finished.+ */+ partial?: boolean;+}++/** What `ix status` reads back: the last whole-root verify, without per-file detail. */+export interface VerifyRecord {+ root: string;+ at: string;+ lastIngestAt: string | null;+ graph: VerifyGraphVerdict;+ files: number;+ stale: number;+ diverged: number;+ unverified: number;+ divergedFiles: string[];+ fix: string | null;+}++// ── Sampling ─────────────────────────────────────────────────────────────++/** A small seeded PRNG, so the same seed picks the same files. */+function mulberry32(seed: number): () => number {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++/** A baseline key (absolute, or already workspace-relative) as a POSIX workspace-relative path. */+export function baselineRelPath(root: string, key: string): string | null {+ const rel = nodePath.isAbsolute(key) ? nodePath.relative(root, key) : key;+ const posix = normalizePathSeparators(rel);+ if (posix === "" || posix === ".." || posix.startsWith("../") || nodePath.isAbsolute(posix)) return null;+ return posix;+}++export interface PickVerifyOptions {+ sample: number;+ seed: number;+ /** Workspace-relative paths the caller named. Always picked, first. */+ explicit?: readonly string[];+ /** Whether a grammar handles this path; files it rejects are never sampled. */+ supported?: (rel: string) => boolean;+}++/**+ * Which files to verify, in order: the ones named, then the ones the last run+ * could not get applied (`replayedFiles`, the F-01 suspects), then the most+ * recently changed up to half the sample, then a seeded shuffle of the rest.+ * Files whose parse timed out are not in the graph by design and are not+ * sampled; a named one is still picked, and `runVerify` reports it unverified+ * (`parse_timed_out`) without parsing it.+ */+export function pickVerifyFiles(+ root: string,+ baseline: Pick<IngestBaseline, "files" | "replayedFiles" | "parseTimeouts">,+ { sample, seed, explicit = [], supported = () => true }: PickVerifyOptions,+): string[] {+ const picked: string[] = [];+ const seen = new Set<string>();+ const add = (rel: string): void => {+ if (seen.has(rel)) return;+ seen.add(rel);+ picked.push(rel);+ };+ for (const rel of explicit) add(normalizePathSeparators(rel));++ const timedOut = new Set(baseline.parseTimeouts.map(normalizePathSeparators));+ const eligible = (rel: string): boolean => !timedOut.has(rel) && !seen.has(rel) && supported(rel);++ const known = new Map<string, number>();+ for (const [key, mtime] of baseline.files) {+ const rel = baselineRelPath(root, key);+ if (rel !== null) known.set(rel, mtime);+ }++ for (const rel of baseline.replayedFiles.map(normalizePathSeparators)) {+ if (picked.length >= sample) return picked;+ if (eligible(rel)) add(rel);+ }++ const candidates = [...known.keys()].filter(eligible).sort();+ const newestFirst = [...candidates].sort((a, b) => (known.get(b)! - known.get(a)!) || a.localeCompare(b));+ const recentTarget = Math.min(sample, picked.length + Math.ceil(sample / 2));+ for (const rel of newestFirst) {+ if (picked.length >= recentTarget) break;+ add(rel);+ }++ const rest = candidates.filter((rel) => !seen.has(rel));+ const random = mulberry32(seed);+ for (let i = rest.length - 1; i > 0; i--) {+ const j = Math.floor(random() * (i + 1));+ [rest[i], rest[j]] = [rest[j], rest[i]];+ }+ for (const rel of rest) {+ if (picked.length >= sample) break;+ add(rel);+ }+ return picked;+}++// ── Node sets ────────────────────────────────────────────────────────────++const numberOrNull = (value: unknown): number | null =>+ typeof value === "number" && Number.isFinite(value) ? value : null;++/** Kinds left out on both sides: chunks (`ix map` strips them) and edge-born externals. */+function comparable(kind: unknown, attrs: Record<string, unknown> | undefined): boolean {+ return typeof kind === "string" && kind !== "chunk" && attrs?.external !== true;+}++function lineSpan(attrs: Record<string, unknown> | undefined): { lineStart: number | null; lineEnd: number | null } {+ return {+ lineStart: numberOrNull(attrs?.line_start ?? attrs?.start_line),+ lineEnd: numberOrNull(attrs?.line_end ?? attrs?.end_line),+ };+}++/** The nodes a freshly built patch upserts, keyed by id. */+export function expectedNodes(patch: { ops: ReadonlyArray<Record<string, unknown>> }): Map<string, VerifyNode> {+ const out = new Map<string, VerifyNode>();+ for (const op of patch.ops) {+ if (op.type !== "UpsertNode" || typeof op.id !== "string") continue;+ const attrs = (op.attrs ?? {}) as Record<string, unknown>;+ if (!comparable(op.kind, attrs) || out.has(op.id)) continue;+ out.set(op.id, { kind: op.kind as string, name: String(op.name ?? ""), ...lineSpan(attrs) });+ }+ return out;+}++/**+ * The stored nodes of one file, keyed by id. The backend's `scope` is a+ * substring match, so `src/a.ts` also brings back `lib/src/a.ts` and+ * `src/a.ts.bak`; only an exact source path counts.+ */+export function storedNodes(rows: ReadonlyArray<Record<string, unknown>>, rel: string): Map<string, VerifyNode> {+ const want = normalizePathSeparators(rel);+ const out = new Map<string, VerifyNode>();+ for (const row of rows) {+ const prov = (row.provenance ?? {}) as Record<string, unknown>;+ const uri = prov.sourceUri ?? prov.source_uri;+ if (typeof uri !== "string" || normalizePathSeparators(uri) !== want) continue;+ if (typeof row.id !== "string" || (row.deletedRev !== undefined && row.deletedRev !== null)) continue;+ const attrs = (row.attrs ?? {}) as Record<string, unknown>;+ if (!comparable(row.kind, attrs) || out.has(row.id)) continue;+ out.set(row.id, { kind: row.kind as string, name: String(row.name ?? ""), ...lineSpan(attrs) });+ }+ return out;+}++const ref = (id: string, node: VerifyNode): VerifyNodeRef => ({ id, kind: node.kind, name: node.name });++export function diffNodes(expected: Map<string, VerifyNode>, stored: Map<string, VerifyNode>): NodeDiff {+ const missing: VerifyNodeRef[] = [];+ const extra: VerifyNodeRef[] = [];+ const changed: VerifyNodeChange[] = [];+ for (const [id, exp] of expected) {+ const got = stored.get(id);+ if (!got) { missing.push(ref(id, exp)); continue; }+ for (const field of ["kind", "name", "lineStart", "lineEnd"] as const) {+ if (exp[field] !== got[field]) changed.push({ id, field, expected: exp[field], stored: got[field] });+ }+ }+ for (const [id, got] of stored) {+ if (!expected.has(id)) extra.push(ref(id, got));+ }+ return { missing, extra, changed };+}++const isEmptyDiff = (diff: NodeDiff): boolean =>+ diff.missing.length === 0 && diff.extra.length === 0 && diff.changed.length === 0;++/**+ * One file's verdict.+ *+ * `storedHash` is the backend's source hash for the file: undefined when it has+ * none, null when the lookup itself failed. `diff` is null when there was+ * nothing to compare (no parse, a failed read of the stored nodes).+ *+ * - stale: the stored hash is not the disk hash and nothing says why. Usually+ * an edit since the last map (`ix map` fixes it); see the module comment+ * for the F-01 revert this cannot be told apart from.+ * - diverged: the nodes disagree with bytes the graph should hold: the stored+ * hash equals the disk hash, or `replayed` (the last map sent these bytes,+ * the backend answered Idempotent, so the stored hash is the edit in+ * between) and the file has not changed since.+ * - unverified: no judgement was possible. A file with no stored hash and no+ * stored nodes is here too: ingest skips some files on purpose (empty,+ * minified-looking), and that is not something a re-map would change.+ */+export function classifyFile(+ diskHash: string,+ storedHash: string | null | undefined,+ diff: NodeDiff | null,+ truncated: boolean,+ storedCount = 0,+ replayed = false,+): { state: VerifyFileState; reason?: string } {+ if (truncated) return { state: "unverified", reason: "truncated" };+ if (!diff) return { state: "unverified", reason: "no_comparison" };+ if (storedHash === undefined && storedCount === 0) return { state: "unverified", reason: "not_in_graph" };+ // F-01: the last ingest sent these very bytes and the backend answered+ // Idempotent (it holds a patch with this id) and wrote no patch, so the+ // newest stored patch, and the hash, are the edit in between. Not fixed by+ // `ix map`, which sends the same patch id again.+ if (replayed && storedHash !== null && storedHash !== diskHash && !isEmptyDiff(diff)) {+ return { state: "diverged", reason: "replayed_not_applied" };+ }+ if (storedHash !== null && storedHash !== diskHash) return { state: "stale", reason: "changed_since_ingest" };+ if (isEmptyDiff(diff)) return { state: "clean" };+ if (storedHash === null) return { state: "unverified", reason: "hash_unknown" };+ return { state: "diverged" };+}++export function countStates(files: readonly VerifyFileResult[]): VerifyCounts {+ const counts: VerifyCounts = { files: files.length, clean: 0, stale: 0, diverged: 0, unverified: 0 };+ for (const f of files) counts[f.state]++;+ return counts;+}++/**+ * The graph's verdict from its files, first match wins:+ * - diverged: any file diverged (stale files alone are not divergence);+ * - unverified (`no_files`): nothing was sampled;+ * - stale: any file changed since the last ingest. Even beside clean files:+ * a stale file's nodes could not be compared with its source, so the+ * sample does not show the graph matches it. `ix map` is the fix;+ * - unverified (`no_file_verified`): no file was judged clean;+ * - clean: at least one file verified clean and none stale or diverged.+ * Unverified files beside them (an unsupported language, a file ingest+ * skips) do not stop a clean verdict; they are counted.+ */+export function graphVerdict(counts: VerifyCounts): { graph: VerifyGraphVerdict; fix: string | null; reason?: string } {+ if (counts.diverged > 0) return { graph: "diverged", fix: GRAPH_REBUILD_FIX };+ if (counts.files === 0) return { graph: "unverified", fix: null, reason: "no_files" };+ if (counts.stale > 0) return { graph: "stale", fix: GRAPH_MAP_FIX };+ if (counts.clean === 0) return { graph: "unverified", fix: null, reason: "no_file_verified" };+ return { graph: "clean", fix: null };+}++// ── Record ───────────────────────────────────────────────────────────────++export function recordFromReport(report: VerifyReport): VerifyRecord {+ return {+ root: report.root,+ at: report.at,+ lastIngestAt: report.lastIngestAt,+ graph: report.graph,+ files: report.counts.files,+ stale: report.counts.stale,+ diverged: report.counts.diverged,+ unverified: report.counts.unverified,+ divergedFiles: report.files.filter((f) => f.state === "diverged").map((f) => f.path),+ fix: report.fix,+ };+}++/** The last verify for this root, or null. Never throws. */+export function loadVerifyRecord(projectRoot: string): VerifyRecord | null {+ try {+ const data = JSON.parse(fs.readFileSync(verifyRecordPath(projectRoot), "utf-8")) as Partial<VerifyRecord>;+ if (typeof data.root !== "string" || typeof data.at !== "string") return null;+ // Canonical on both sides: `--root .`, a trailing slash or a symlinked+ // path names the same root as the canonical one `ix verify` saved.+ if (canonicalWorkspacePath(data.root) !== canonicalWorkspacePath(projectRoot)) return null;+ if (!VERIFY_GRAPH_VERDICTS.includes(data.graph as VerifyGraphVerdict)) return null;+ const count = (v: unknown): number => (typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : 0);+ return {+ root: data.root,+ at: data.at,+ lastIngestAt: typeof data.lastIngestAt === "string" ? data.lastIngestAt : null,+ graph: data.graph as VerifyGraphVerdict,+ files: count(data.files),+ stale: count(data.stale),+ diverged: count(data.diverged),+ unverified: count(data.unverified),+ divergedFiles: Array.isArray(data.divergedFiles) ? data.divergedFiles.filter((p): p is string => typeof p === "string") : [],+ fix: typeof data.fix === "string" ? data.fix : null,+ };+ } catch {+ return null;+ }+}++/**+ * Whether `record` describes an older graph than the one there is now: the+ * workspace has been ingested since it ran. `ix status` then shows it as+ * history, not as advice. Unknown (no current ingest time) is not outdated.+ */+export function verifyRecordOutdated(record: Pick<VerifyRecord, "lastIngestAt">, lastIngestAt: string | null | undefined): boolean {+ return typeof lastIngestAt === "string" && record.lastIngestAt !== lastIngestAt;+}++/** Best-effort, like the other per-root state files: a failed write costs a status line. */+export function saveVerifyRecord(record: VerifyRecord): boolean {+ try {+ const target = verifyRecordPath(record.root);+ fs.mkdirSync(nodePath.dirname(target), { recursive: true });+ const tmp = `${target}.${process.pid}.tmp`;+ try {+ fs.writeFileSync(tmp, JSON.stringify(record));+ fs.renameSync(tmp, target);+ } catch (err) {+ fs.rmSync(tmp, { force: true });+ throw err;+ }+ return true;+ } catch {+ return false;+ }+}++// ── Run ──────────────────────────────────────────────────────────────────++export interface RunVerifyOptions {+ sample?: number;+ seed?: number;+ /** Workspace-relative paths to verify first. */+ paths?: readonly string[];+ /** For tests: stands in for `loadIngestionModules`. */+ loadModules?: () => Promise<Awaited<ReturnType<typeof loadIngestionModules>>>;+ now?: () => Date;+ /**+ * Save the record `ix status` reads (default true). Only a whole-root run+ * does: a run given `paths` never saves, and `ix doctor` passes false.+ */+ record?: boolean;+ /**+ * Stop starting new work after this many ms (`ix doctor`). Files not judged+ * by then are left out and the report is `partial`. Never saves a record.+ */+ budgetMs?: number;+}++type VerifyClient = Pick<IxClient, "listByKind" | "getSourceHashes"> & Partial<Pick<IxClient, "stats">>;++const sha256 = (bytes: Buffer): string => createHash("sha256").update(bytes).digest("hex");++const fileResult = (path: string, state: VerifyFileState, reason?: string): VerifyFileResult => ({+ path, state, ...(reason ? { reason } : {}), expectedNodes: 0, storedNodes: 0, missing: [], extra: [], changed: [],+});++/**+ * Verify `root`'s graph against a re-parse of a sample of its files.+ *+ * Never throws for a verdict: no workspace, no baseline, a changed extractor or+ * a parser that will not load are all `graph: "unverified"` with a reason. A+ * backend nobody answers at is rethrown, so the caller can report it the way+ * every read command does; any other failed read only makes its file+ * unverified.+ */+export async function runVerify(client: VerifyClient, rootInput: string, opts: RunVerifyOptions = {}): Promise<VerifyReport> {+ // Ingest saves its baseline under the canonical root (`resolveIngestRoot`),+ // and `loadIngestBaseline` compares the string exactly.+ const root = canonicalWorkspacePath(rootInput);+ const sample = opts.sample ?? DEFAULT_VERIFY_SAMPLE;+ const seed = opts.seed ?? DEFAULT_VERIFY_SEED;+ const at = (opts.now?.() ?? new Date()).toISOString();+ const startedMs = Date.now();+ const overBudget = (): boolean => opts.budgetMs !== undefined && Date.now() - startedMs >= opts.budgetMs;+ let partial = false;+ const unverified = (reason: string, fix: string | null, lastIngestAt: string | null = null): VerifyReport => ({+ at, root, lastIngestAt, graph: "unverified", reason, fix, sample, seed,+ counts: { files: 0, clean: 0, stale: 0, diverged: 0, unverified: 0 }, files: [],+ });++ // Read-only lookup: `workspaceStateFor` registers and migrates as it goes.+ const workspace = findWorkspaceForCwd(root);+ const baseline = workspace ? loadIngestBaseline(root) : null;+ if (!workspace || !baseline) return unverified("not_mapped", GRAPH_MAP_FIX);++ let modules: Awaited<ReturnType<typeof loadIngestionModules>>;+ try {+ modules = await (opts.loadModules ?? loadIngestionModules)();+ } catch {+ return unverified("parser_unavailable", null, baseline.lastIngestAt);+ }+ const [{ parseFile, isGrammarSupported }, { buildPatchWithResolution, extractorName }] = modules;+ // A re-parse by another extractor would disagree with every file for a+ // reason that is not the graph's fault, and `ix map` re-extracts anyway.+ if (extractorChanged(baseline, extractorName())) {+ return unverified("extractor_changed", GRAPH_MAP_FIX, baseline.lastIngestAt);+ }++ const { fileWorkspaceId, fileMultiRepo } = fileIdentity(root, workspace.workspace_id);+ const supported = (rel: string): boolean => {+ try { return isGrammarSupported(rel); } catch { return false; }+ };+ const rels = pickVerifyFiles(root, baseline, { sample, seed, explicit: opts.paths, supported });+ const known = new Set<string>();+ for (const key of baseline.files.keys()) {+ const rel = baselineRelPath(root, key);+ if (rel !== null) known.add(rel);+ }++ const timedOut = new Set(baseline.parseTimeouts.map(normalizePathSeparators));++ // Files the last ingest replayed (F-01 suspects) that have not changed since.+ const replayedSet = new Set(baseline.replayedFiles.map(normalizePathSeparators));+ const ingestMs = Date.parse(baseline.lastIngestAt);+ const replayedUnchanged = (rel: string): boolean => {+ if (!replayedSet.has(rel) || Number.isNaN(ingestMs)) return false;+ try { return fs.statSync(nodePath.join(root, rel)).mtimeMs <= ingestMs; } catch { return false; }+ };++ interface Parsed { rel: string; ws: string; hash: string; replayed: boolean; expected: Map<string, VerifyNode> }+ const done = new Map<string, VerifyFileResult>();+ const parsed: Parsed[] = [];+ for (const rel of rels) {+ if (overBudget()) { partial = true; break; }+ // Only a named path gets here: ingest gave up on its parse, so it is not in+ // the graph, and parsing it on this thread would have no budget at all.+ if (timedOut.has(rel)) { done.set(rel, fileResult(rel, "unverified", "parse_timed_out")); continue; }+ // One handle for the size check and the read (no stat-then-read race).+ // Ingest's own size gate: such a file is not in the graph, and the cap+ // bounds the in-process parse of a named one.+ let read: ReturnType<typeof readBoundedBytes> | null;+ try {+ read = readBoundedBytes(nodePath.join(root, rel), VERIFY_MAX_FILE_BYTES);+ } catch {+ // Windows will not open a directory at all; it is still not a file,+ // which is not the same as missing.+ let exists = false;+ try { exists = fs.statSync(nodePath.join(root, rel)) !== undefined; } catch { /* missing */ }+ read = exists ? { refused: "not_file" } : null;+ }+ if (read && "refused" in read && read.refused === "too_large") {+ done.set(rel, fileResult(rel, "unverified", "too_large"));+ continue;+ }+ if (read && "refused" in read && read.refused === "not_file") {+ // A directory or other non-regular file where the graph may have had a+ // file: present, so not missing_on_disk.+ done.set(rel, known.has(rel) ? fileResult(rel, "stale", "not_file") : fileResult(rel, "unverified", "not_file"));+ continue;+ }+ if (!read || !("bytes" in read)) {+ // In the baseline, gone from disk: the graph has not caught up with a+ // deletion, which is what `ix map` is for.+ done.set(rel, known.has(rel) ? fileResult(rel, "stale", "missing_on_disk") : fileResult(rel, "unverified", "missing_on_disk"));+ continue;+ }+ const bytes = read.bytes;+ if (!supported(rel)) { done.set(rel, fileResult(rel, "unverified", "unsupported_language")); continue; }+ const hash = sha256(bytes);+ try {+ const result = parseFile(rel, bytes.toString("utf-8"));+ if (!result) { done.set(rel, fileResult(rel, "unverified", "no_parse")); continue; }+ // The 6th argument is ingest's multi-repo context; the loader's type predates it.+ const build = buildPatchWithResolution as (...args: unknown[]) => { ops: Array<Record<string, unknown>> };+ const patch = build(result, hash, fileWorkspaceId(rel), [], undefined, fileMultiRepo(rel));+ parsed.push({ rel, ws: fileWorkspaceId(rel), hash, replayed: replayedUnchanged(rel), expected: expectedNodes(patch) });+ } catch {+ done.set(rel, fileResult(rel, "unverified", "no_parse"));+ }+ }++ // Out of budget already: no network reads for files that could not finish.+ if (overBudget() && parsed.length > 0) { partial = true; parsed.length = 0; }++ // One call for every file. null = the lookup failed, so stale and diverged+ // cannot be told apart; a file that matches is still clean.+ let storedHashes: Map<string, string> | null = new Map();+ if (parsed.length > 0) {+ try {+ const rows = await client.getSourceHashes(+ [...new Set(parsed.map((p) => p.rel))],+ [...new Set(parsed.map((p) => p.ws))],+ );+ for (const r of rows) storedHashes.set(`${r.workspaceId ?? ""}\u0000${r.uri}`, r.hash);+ } catch (err) {+ if (isBackendUnreachable(err)) throw err;+ storedHashes = null;+ }+ }++ // Every kind each workspace holds, so a stored node of a kind the parse no+ // longer produces (and the default list lacks) is still read and seen as+ // extra. `/v1/list` needs a kind, and the backend accepts any kind string.+ const wsKinds = new Map<string, string[]>();+ for (const ws of new Set(parsed.map((p) => p.ws))) {+ try {+ const stats = await client.stats?.({ workspaceId: ws, timeoutMs: VERIFY_STATS_TIMEOUT_MS });+ const byKind = stats?.nodes?.byKind;+ if (Array.isArray(byKind)) {+ wsKinds.set(ws, byKind.map((k: { kind?: unknown }) => k?.kind).filter((k): k is string => typeof k === "string"));+ }+ } catch (err) {+ if (isBackendUnreachable(err)) throw err;+ }+ }++ const reads = parsed.flatMap((p) => {+ const kinds = new Set([...VERIFY_DEFAULT_KINDS, ...(wsKinds.get(p.ws) ?? [])]);+ for (const node of p.expected.values()) kinds.add(node.kind);+ kinds.delete("chunk");+ return [...kinds].sort().map((kind) => ({ p, kind }));+ });+ const results = await mapLimit(reads, VERIFY_CONCURRENCY, async ({ p, kind }) => {+ if (overBudget()) {+ partial = true;+ return { rel: p.rel, rows: [] as GraphNode[], failed: false, skipped: true };+ }+ try {+ const rows = await client.listByKind(kind, { scope: p.rel, workspaceId: p.ws, limit: VERIFY_LIST_LIMIT });+ return { rel: p.rel, rows: Array.isArray(rows) ? rows : [], failed: false, skipped: false };+ } catch (err) {+ if (isBackendUnreachable(err)) throw err;+ return { rel: p.rel, rows: [] as GraphNode[], failed: true, skipped: false };+ }+ });+ // A file with any kind left unread is not judged at all: half its nodes+ // would read as missing.+ const skipped = new Set(results.filter((r) => r.skipped).map((r) => r.rel));+ const byFile = new Map<string, { rows: GraphNode[]; failed: boolean; truncated: boolean }>();+ for (const r of results) {+ const entry = byFile.get(r.rel) ?? { rows: [], failed: false, truncated: false };+ entry.rows.push(...r.rows);+ entry.failed ||= r.failed;+ entry.truncated ||= r.rows.length >= VERIFY_LIST_LIMIT;+ byFile.set(r.rel, entry);+ }++ for (const p of parsed) {+ if (skipped.has(p.rel)) continue;+ const read = byFile.get(p.rel) ?? { rows: [], failed: true, truncated: false };+ if (read.failed) { done.set(p.rel, fileResult(p.rel, "unverified", "list_failed")); continue; }+ const stored = storedNodes(read.rows as unknown as Array<Record<string, unknown>>, p.rel);+ const diff = diffNodes(p.expected, stored);+ const storedHash = storedHashes === null ? null : storedHashes.get(`${p.ws}\u0000${p.rel}`);+ const { state, reason } = classifyFile(p.hash, storedHash, diff, read.truncated, stored.size, p.replayed);+ done.set(p.rel, {+ path: p.rel, state, ...(reason ? { reason } : {}),+ expectedNodes: p.expected.size, storedNodes: stored.size,+ ...diff,+ });+ }++ const files = rels.map((rel) => done.get(rel)!).filter(Boolean);+ const counts = countStates(files);+ const verdict = graphVerdict(counts);+ // Nothing judged before the budget ran out says so, not "no files".+ if (partial && verdict.graph === "unverified") Object.assign(verdict, { reason: "timed_out" });+ const report: VerifyReport = {+ at, root, lastIngestAt: baseline.lastIngestAt,+ graph: verdict.graph, ...(verdict.reason ? { reason: verdict.reason } : {}), fix: verdict.fix,+ sample, seed, counts, files, ...(partial ? { partial: true } : {}),+ };+ // A partial run (named files, or a caller that opts out) must not replace+ // the sampled record `ix status` shows.+ if (opts.record !== false && !partial && !(opts.paths && opts.paths.length > 0)) saveVerifyRecord(recordFromReport(report));+ return report;+}diff --git a/ix-cli/test/e2e/scenarios.e2e.ts b/ix-cli/test/e2e/scenarios.e2e.tsindex 61578bd5..c2ddee29 100644--- a/ix-cli/test/e2e/scenarios.e2e.ts+++ b/ix-cli/test/e2e/scenarios.e2e.ts@@ -216,6 +216,41 @@ describe("incremental equals fresh", () => {});});+describe("ix verify (CL-24A)", () => {+ // Nodes only: the graph is compared with a re-parse of the files on disk.+ it("a fresh map verifies clean; an unmapped edit is stale, not diverged", async () => {+ const co = checkout("polyglot");+ map(env, co);+ const clean = ix(env, co, ["verify", "--format", "llm", "--sample", "50"]);+ expect(clean.status).toBe(0);+ expect(clean.stdout).toMatch(/^verify graph=clean .*diverged=0/m);+ expect(clean.stdout).not.toMatch(/state=diverged/);++ edit(co, "app/services.py", (t) => t + "\n\ndef added_after_map():\n return 1\n");+ const stale = ix(env, co, ["verify", "app/services.py", "--format", "llm"]);+ expect(stale.status).toBe(0);+ expect(stale.stdout).toMatch(/^verify graph=stale .*stale=1 .*diverged=0/m);+ expect(stale.stdout).toMatch(/^file path=app\/services\.py state=stale/m);+ });++ // The F-01 shape (rename a file, map, rename it back, map) was expected to+ // leave the file diverged. On backend 1.0.34 it does not: the last map+ // leaves replayedFiles empty and every node of the file stored with the+ // current hash (checked live, 2026-10-11), so verify must say clean.+ // Divergence itself is pinned by the fake-backend tests in verify.test.ts.+ it("a rename and rename back verifies clean", async () => {+ const co = checkout("polyglot");+ map(env, co);+ renameSync(join(co.dir, "app/pricing.py"), join(co.dir, "app/pricing_moved.py"));+ map(env, co);+ renameSync(join(co.dir, "app/pricing_moved.py"), join(co.dir, "app/pricing.py"));+ map(env, co);+ const out = ix(env, co, ["verify", "app/pricing.py", "--format", "llm"]);+ expect(out.status).toBe(0);+ expect(out.stdout).toMatch(/^verify graph=clean files=1 clean=1 .*diverged=0/m);+ });+});+// The outcome contract agents route on (ix-cli/src/cli/outcome.ts), against a// real backend: `clamp` is defined in app/utils.py and web/src/math.ts, and// app/pricing.py imports it (`from app.utils import clamp`, a one-line modulediff --git a/skills/ix/references/commands.md b/skills/ix/references/commands.mdindex 53143731..2c8727b1 100644--- a/skills/ix/references/commands.md+++ b/skills/ix/references/commands.md@@ -98,6 +98,7 @@ mapped one, pass `--graph-root <mapped>` and `--worktree <agent checkout>`.| Ingest GitHub data | `ix ingest` | `ix ingest --github owner/repo --limit 50` || Backend health | `ix status` | `ix status` || System doctor | `ix doctor` | `ix doctor` |+| Is the graph actually right? (nodes vs a re-parse) | `ix verify` | `ix verify --sample 20` or `ix verify src/auth.py` || Start backend | `ix docker start` | `ix docker start` || Graph statistics | `ix stats` | `ix stats` |diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.mdindex a8a9343e..eaa72c0a 100644--- a/skills/ix/references/flags.md+++ b/skills/ix/references/flags.md@@ -865,6 +865,20 @@ Upgrade ix CLI, backend, and components to the latest version.|---|---|---|---|| `--check` | — | off | Only check for updates, don't install |+### `ix verify [paths...]`++Compare the graph's nodes to a fresh re-parse of a sample of files. Nodes only: edges are not compared yet.++| Flag | Value | Default | Effect |+|---|---|---|---|+| `--sample` | `<n>` | `20` (or the number of paths given) | How many files to check: named paths first, then files the last map could not apply, then the most recently changed, then a seeded random pick |+| `--seed` | `<n>` | `24` | Seed for the random part of the sample; the same seed checks the same files |+| `--root` | `<dir>` | — | Workspace root directory |+| `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |+| `--quiet` | — | off | Drop headers, section titles and advisory hints |+| `--fields` | `<list>` | — | Keep only these fields on each row, in this order (e.g. `name,path,lines`) |+### `ix view`Open the Ix System Compass visualizer.diff --git a/skills/ix/references/troubleshooting.md b/skills/ix/references/troubleshooting.mdindex e7a8dec8..e9aa7160 100644--- a/skills/ix/references/troubleshooting.md+++ b/skills/ix/references/troubleshooting.md@@ -41,6 +41,8 @@ again.| Slow or stale results | Re-run `ix map --silent` to refresh the graph || `error code=workspace_not_mapped` | The directory is in no registered workspace. Graph reads no longer fall back to the `default: true` workspace (an unrelated repo) or to every workspace on the backend. Run `ix map` in the repo (the error names the root it would map), or run from inside a mapped one || `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 |+| `verify graph=diverged` | Some files' stored nodes do not match a re-parse of the bytes on disk, though the graph claims those bytes: either the stored source hash equals the disk hash (nodes an earlier ingest left behind, or a lost write), or the last map could not apply the file (F-01: a revert the backend answered `Idempotent`; `ix status` shows it as `not_applied`, and verify gives `reason=replayed_not_applied`). `ix map` does not repair it; `ix reset --workspace --yes --ingest` (this workspace only) does. A file reported `state=stale` has a stored hash that is not the disk hash: usually an edit since the last map, which `ix map` fixes. If it is still stale after `ix map` (for example a revert the map did not record as not applied), rebuild as above. `ix verify` compares nodes only, not edges |+| `verify graph=stale` | No sampled file diverged, but at least one changed since the last ingest, so the sample cannot vouch for the graph (it is not `clean`). Run `ix map`, then `ix verify` again. If the same files stay stale after a map, treat it as `graph=diverged` above || Reads under one subdirectory find almost nothing, while the repo root answers | A stray workspace registered for that subdirectory, left by an older `ix ingest <subdir or file>`. `ix doctor` names it under "No stray nested workspaces" with the repair: `ix reset --workspace --yes` from inside it, then delete its entry from `config.yaml` || `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. |