Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
fix: preserve source graph after map failure (#535)
Hiro-Chibac9f5225cc7b0
diff --git a/ix-cli/src/cli/__tests__/context.test.ts b/ix-cli/src/cli/__tests__/context.test.tsindex a62442e7..7baf3fe7 100644--- a/ix-cli/src/cli/__tests__/context.test.ts+++ b/ix-cli/src/cli/__tests__/context.test.ts@@ -225,12 +225,8 @@ describe("ix context bundle", () => {]);});- it("classifies a workspace with no completed map baseline as unverified", () => {- // Ix#506: the backend answers from graph patches an initial map committed- // before it failed. `ix status` already reported mapCompleted:false while- // the bundle said current, so an agent reading the bundle trusted a graph- // the CLI knew was half-built.- const bundle = buildBundle({ ...input(), mapCompleted: false });+ it("classifies a workspace with no completed source graph as unverified", () => {+ const bundle = buildBundle({ ...input(), graphCompleted: false });expect(bundle.freshness.classification).toBe("unverified");});@@ -239,9 +235,9 @@ describe("ix context bundle", () => {// `stale` is a claim that a file changed since ingest. Without a baseline// nothing is known to have changed, so the two states stay distinguishable:// an agent can re-map on unverified without being told its files are dirty.- const unverified = buildBundle({ ...input(), mapCompleted: false });+ const unverified = buildBundle({ ...input(), graphCompleted: false });const stale = buildBundle({- ...input(), mapCompleted: true, facts: makeFacts({ stale: true }),+ ...input(), graphCompleted: true, facts: makeFacts({ stale: true }),});expect(unverified.freshness.classification).toBe("unverified");diff --git a/ix-cli/src/cli/__tests__/llm-tier5.test.ts b/ix-cli/src/cli/__tests__/llm-tier5.test.tsindex 29cad797..e16addb7 100644--- a/ix-cli/src/cli/__tests__/llm-tier5.test.ts+++ b/ix-cli/src/cli/__tests__/llm-tier5.test.ts@@ -137,6 +137,7 @@ describe("read --format llm", () => {describe("status --format llm", () => {it("answers 'can I trust the graph' in one field", () => {const lines = renderStatusLlm("ok", "http://localhost:8090", {+ graphCompleted: true,mapCompleted: true,currentRev: 11, lastIngestAt: "2026-08-09T12:00:00.000Z",staleFiles: 2, sampleChangedFiles: ["src/a.ts", "src/b.ts"],@@ -151,6 +152,7 @@ describe("status --format llm", () => {it("says stale=false rather than omitting it when the graph is current", () => {const lines = renderStatusLlm("ok", "http://localhost:8090", {+ graphCompleted: true,mapCompleted: true,currentRev: 11, lastIngestAt: null, staleFiles: 0, sampleChangedFiles: [],});@@ -159,16 +161,30 @@ describe("status --format llm", () => {expect(lines[0]).toContain("stale_files=0");});- it("does not call a workspace current before any map completed", () => {+ it("does not call a workspace current before any source graph completed", () => {const lines = renderStatusLlm("ok", "http://localhost:8090", {+ graphCompleted: false,mapCompleted: false,currentRev: 0, lastIngestAt: null, staleFiles: 0, sampleChangedFiles: [],});expect(lines[0]).toContain("map_complete=false");+ expect(lines[0]).toContain("graph_complete=false");expect(lines[0]).toContain("stale=true");});+ it("keeps a current source graph usable when only the hierarchy is incomplete", () => {+ const lines = renderStatusLlm("ok", "http://localhost:8090", {+ graphCompleted: true,+ mapCompleted: false,+ currentRev: 11, lastIngestAt: null, staleFiles: 0, sampleChangedFiles: [],+ });++ expect(lines[0]).toContain("graph_complete=true");+ expect(lines[0]).toContain("map_complete=false");+ expect(lines[0]).toContain("stale=false");+ });+it("omits the staleness fields entirely when there is no baseline to read", () => {const lines = renderStatusLlm("ok", "http://localhost:8090", null);diff --git a/ix-cli/src/cli/__tests__/map-auto-skip.test.ts b/ix-cli/src/cli/__tests__/map-auto-skip.test.tsindex e567221e..ec3ce6e6 100644--- a/ix-cli/src/cli/__tests__/map-auto-skip.test.ts+++ b/ix-cli/src/cli/__tests__/map-auto-skip.test.ts@@ -115,7 +115,7 @@ describe('describeEmptyCompletedMap', () => {expect(message).toContain('mapped 0 files after local ingest found 260 supported source files');expect(message).toContain('(260 patches committed)');expect(message).toContain('no architecture hierarchy was created');- expect(message).toContain("the next 'ix map' re-parses every file");+ expect(message).toContain("the next 'ix map' can reuse unchanged files");});it('does not reject an actually empty workspace', () => {@@ -185,7 +185,7 @@ describe('describeEmptyCompletedMap', () => {})).toBeUndefined();});- it('invalidates the current workspace baseline, including on an unchanged retry', () => {+ it('invalidates the architecture baseline, including on an unchanged retry', () => {const invalidate = vi.fn();const message = invalidateBaselineForEmptyCompletedMap(emptyResult, {filesDiscovered: 260,@@ -195,6 +195,7 @@ describe('describeEmptyCompletedMap', () => {}, '/workspace/account', invalidate);expect(message).toContain('(0 patches committed)');+ expect(message).toContain('source ingest baseline was preserved');expect(invalidate).toHaveBeenCalledOnce();expect(invalidate).toHaveBeenCalledWith('/workspace/account');});diff --git a/ix-cli/src/cli/__tests__/map-baseline.test.ts b/ix-cli/src/cli/__tests__/map-baseline.test.tsnew file mode 100644index 00000000..3a3ff020--- /dev/null+++ b/ix-cli/src/cli/__tests__/map-baseline.test.ts@@ -0,0 +1,87 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import * as fs from "node:fs";+import * as os from "node:os";+import * as path from "node:path";++import { persistIngestBaselineIfClean } from "../commands/ingest.js";+import { persistCompletedMapBaseline } from "../commands/map.js";+import { loadMapBaseline } from "../map-baseline.js";+import { hasCompletedMapBaseline } from "../stale.js";++let home: string;+let savedHome: string | undefined;+let savedProfile: string | undefined;++beforeEach(() => {+ home = fs.mkdtempSync(path.join(os.tmpdir(), "ix-map-baseline-"));+ savedHome = process.env.HOME;+ savedProfile = process.env.USERPROFILE;+ process.env.HOME = home;+ process.env.USERPROFILE = home;+});++afterEach(() => {+ process.env.HOME = savedHome;+ process.env.USERPROFILE = savedProfile;+ fs.rmSync(home, { recursive: true, force: true });+});++describe("architecture map baseline", () => {+ it("records a non-empty completed map against its source revision", () => {+ const root = path.join(home, "workspace");+ const filePath = path.join(root, "index.php");+ fs.mkdirSync(root, { recursive: true });+ fs.writeFileSync(filePath, "<?php function value() { return 1; }\n");+ persistIngestBaselineIfClean(+ root,+ new Map([[filePath, fs.statSync(filePath).mtimeMs]]),+ 12,+ 0,+ 0,+ );++ expect(+ persistCompletedMapBaseline(+ {+ file_count: 1,+ region_count: 1,+ regions: [],+ outcome: "full_local_completed",+ },+ root,+ ),+ ).toBe(true);++ expect(loadMapBaseline(root)).toEqual({ sourceRev: 12 });+ expect(hasCompletedMapBaseline(root)).toBe(true);+ });++ it.each(["local_map_too_large", "local_map_not_recommended"])(+ "does not record the guardrail outcome %s",+ (outcome) => {+ const root = path.join(home, "workspace");+ const filePath = path.join(root, "index.js");+ fs.mkdirSync(root, { recursive: true });+ fs.writeFileSync(filePath, "export const value = 1;\n");+ persistIngestBaselineIfClean(+ root,+ new Map([[filePath, fs.statSync(filePath).mtimeMs]]),+ 1,+ 0,+ 0,+ );+ expect(+ persistCompletedMapBaseline(+ {+ file_count: 1,+ region_count: 0,+ regions: [],+ outcome,+ },+ root,+ ),+ ).toBe(false);+ expect(loadMapBaseline(root)).toBeNull();+ },+ );+});diff --git a/ix-cli/src/cli/__tests__/stale-workspace.test.ts b/ix-cli/src/cli/__tests__/stale-workspace.test.tsindex 965d05ec..a777cd50 100644--- a/ix-cli/src/cli/__tests__/stale-workspace.test.ts+++ b/ix-cli/src/cli/__tests__/stale-workspace.test.ts@@ -3,10 +3,17 @@ import * as fs from "node:fs";import * as os from "node:os";import * as path from "node:path";-import { clearIngestMtimeCache, ingestMtimeCachePath, saveConfig } from "../config.js";+import { clearIngestMtimeCache, clearMapBaseline, ingestMtimeCachePath, saveConfig } from "../config.js";import { loadIngestBaseline } from "../ingest-baseline.js";+import { saveMapBaseline } from "../map-baseline.js";import { persistIngestBaselineIfClean } from "../commands/ingest.js";-import { createStaleProbe, detectStaleFiles, hasCompletedMapBaseline, isFileStale } from "../stale.js";+import {+ createStaleProbe,+ detectStaleFiles,+ hasCompletedMapBaseline,+ hasCompletedSourceGraphBaseline,+ isFileStale,+} from "../stale.js";let home: string;let savedHome: string | undefined;@@ -61,7 +68,8 @@ describe("workspace-scoped staleness", () => {moveMtimeForward(fileA);const beforeB = detectStaleFiles(rootA);expect(beforeB).toEqual({- mapCompleted: true,+ graphCompleted: true,+ mapCompleted: false,lastIngestAt: ingestedA.toISOString(),currentRev: 11,staleFiles: 1,@@ -123,6 +131,7 @@ describe("workspace-scoped staleness", () => {});expect(detectStaleFiles(root)).toEqual({+ graphCompleted: false,mapCompleted: false,lastIngestAt: null,currentRev: 0,@@ -138,7 +147,7 @@ describe("workspace-scoped staleness", () => {expect(createStaleProbe()(filePath)).toBe(false);});- it("reports a completed baseline as verified", async () => {+ it("distinguishes a clean source graph from a completed architecture map", async () => {const root = path.join(home, "verified");const filePath = writeSource(root, "verified.js", "export const value = 1;\n");persistIngestBaselineIfClean(@@ -150,10 +159,22 @@ describe("workspace-scoped staleness", () => {new Date("2026-08-24T12:00:00.000Z"),);+ expect(hasCompletedSourceGraphBaseline(root)).toBe(true);+ expect(hasCompletedMapBaseline(root)).toBe(false);+ expect(detectStaleFiles(root)).toMatchObject({+ graphCompleted: true,+ mapCompleted: false,+ });++ expect(saveMapBaseline(root, 7)).toBe(true);expect(hasCompletedMapBaseline(root)).toBe(true);+ expect(detectStaleFiles(root)).toMatchObject({+ graphCompleted: true,+ mapCompleted: true,+ });});- it("returns the unmapped state after an empty completed map invalidates a prior baseline", () => {+ it("preserves the source graph after an empty completed map invalidates hierarchy", () => {const root = path.join(home, "empty-completed-map");const filePath = writeSource(root, "index.php", "<?php function value() { return 1; }\n");persistIngestBaselineIfClean(@@ -164,20 +185,57 @@ describe("workspace-scoped staleness", () => {0,new Date("2026-08-24T12:00:00.000Z"),);+ saveMapBaseline(root, 26);expect(detectStaleFiles(root).mapCompleted).toBe(true);- clearIngestMtimeCache(root);+ clearMapBaseline(root);- expect(loadIngestBaseline(root)).toBeNull();+ expect(loadIngestBaseline(root)?.currentRev).toBe(26);expect(detectStaleFiles(root)).toEqual({+ graphCompleted: true,mapCompleted: false,- lastIngestAt: null,- currentRev: 0,+ lastIngestAt: "2026-08-24T12:00:00.000Z",+ currentRev: 26,staleFiles: 0,sampleChangedFiles: [],});});+ it("invalidates a completed map when the source revision advances", () => {+ const root = path.join(home, "new-source-revision");+ const filePath = writeSource(root, "index.js", "export const value = 1;\n");+ const mtimes = new Map([[filePath, fs.statSync(filePath).mtimeMs]]);+ persistIngestBaselineIfClean(root, mtimes, 4, 0, 0);+ saveMapBaseline(root, 4);+ expect(hasCompletedMapBaseline(root)).toBe(true);++ persistIngestBaselineIfClean(root, mtimes, 5, 0, 0);++ expect(detectStaleFiles(root)).toMatchObject({+ graphCompleted: true,+ mapCompleted: false,+ currentRev: 5,+ });+ });++ it("clears both baselines when the source graph is reset", () => {+ const root = path.join(home, "reset");+ const filePath = writeSource(root, "index.js", "export const value = 1;\n");+ persistIngestBaselineIfClean(+ root,+ new Map([[filePath, fs.statSync(filePath).mtimeMs]]),+ 3,+ 0,+ 0,+ );+ saveMapBaseline(root, 3);++ clearIngestMtimeCache(root);++ expect(hasCompletedSourceGraphBaseline(root)).toBe(false);+ expect(hasCompletedMapBaseline(root)).toBe(false);+ });+it("reports a mapped file that was deleted after ingest", async () => {const root = path.join(home, "deleted-file");const filePath = writeSource(root, "deleted.js", "export const value = 1;\n");@@ -206,7 +264,8 @@ describe("workspace-scoped staleness", () => {fs.unlinkSync(filePath);expect(detectStaleFiles(root)).toEqual({- mapCompleted: true,+ graphCompleted: true,+ mapCompleted: false,lastIngestAt: ingestedAt.toISOString(),currentRev: 14,staleFiles: 1,diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.tsindex ea9f3e8c..b694f01b 100644--- a/ix-cli/src/cli/commands/context.ts+++ b/ix-cli/src/cli/commands/context.ts@@ -21,7 +21,7 @@ import { collectFacts, type EntityFacts } from "../explain/facts.js";import { llmLine, printLlmLines } from "../llm.js";import { parseBudgetOption, parsePickOption, parseRevisionOption } from "../options.js";import { resolveFileOrEntity } from "../resolve.js";-import { createStaleProbe, hasCompletedMapBaseline } from "../stale.js";+import { createStaleProbe, hasCompletedSourceGraphBaseline } from "../stale.js";import { renderNote, renderSection, renderWarning, renderWarningErr, reportFailure, reportUnresolvedTarget } from "../ui.js";/** The four `--max-*` knobs that bound a bundle. */@@ -337,7 +337,7 @@ export function registerContextCommand(program: Command): void {asOfRev,depth: opts.depth,budgets,- mapCompleted: hasCompletedMapBaseline(),+ graphCompleted: hasCompletedSourceGraphBaseline(),});if (opts.save) {@@ -422,7 +422,7 @@ async function buildFreshBundle(return buildBundle({resolved, facts, context, provenance, asOfRev, depth: opts.depth, budgets,- mapCompleted: hasCompletedMapBaseline(),+ graphCompleted: hasCompletedSourceGraphBaseline(),});}}@@ -1334,27 +1334,26 @@ interface BuildInput {*/isStale?: (path: string) => boolean;/**- * Whether the workspace has a completed map baseline. Injected for the same+ * Whether the workspace has a completed source graph baseline. Injected for the same* reason as `isStale`: it is a filesystem question, and buildBundle stays* pure under test. Both production callers pass the real answer; the default* is the optimistic one so a bundle built from injected facts alone is not* silently reclassified.*/- mapCompleted?: boolean;+ graphCompleted?: boolean;}export function buildBundle(input: BuildInput): ContextBundle {const { resolved, facts, context, provenance, asOfRev, depth, budgets } = input;const stale = facts.stale;- // Three states, not two. Without a completed map baseline the backend can- // still answer from graph patches an initial map committed before it failed,- // and calling that `current` is what let agents trust a half-built graph- // (#506). It is not `stale` either — nothing is known to have changed. The+ // Three states, not two. Without a completed source graph baseline the+ // backend may still answer from partially committed graph patches. It is not+ // `stale` either — nothing is known to have changed. The// freshness union has carried `unverified` for exactly this case since it was// written; this is the first thing to produce it.- const mapCompleted = input.mapCompleted ?? true;- const classification = !mapCompleted ? "unverified" : stale ? "stale" : "current";+ const graphCompleted = input.graphCompleted ?? true;+ const classification = !graphCompleted ? "unverified" : stale ? "stale" : "current";const prov = asRecord(provenance);// Entities: the target itself plus every referenced node, deduped by id anddiff --git a/ix-cli/src/cli/commands/map.ts b/ix-cli/src/cli/commands/map.tsindex c5ad8c8d..6ad01158 100644--- a/ix-cli/src/cli/commands/map.ts+++ b/ix-cli/src/cli/commands/map.ts@@ -2,7 +2,7 @@ import { resolve } from "node:path";import { type Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";-import { clearIngestMtimeCache, getEndpoint } from "../config.js";+import { clearMapBaseline, getEndpoint } from "../config.js";import { roundFloat } from "../format.js";import { llmLine, llmError } from "../llm.js";import { bootstrap, resolveWorkspaceId } from "../bootstrap.js";@@ -12,6 +12,8 @@ import { detectSystem } from "../system.js";import { getRemoteRunner, isCloudReady } from "../remote.js";import { acquireMapLock } from "../single-flight.js";import { canRenderProgress } from "../stderr.js";+import { loadIngestBaseline } from "../ingest-baseline.js";+import { saveMapBaseline } from "../map-baseline.js";// Hard wall-clock budget for a single `ix map`. Past this, the shared deadline// signal aborts every in-flight request and the command exits, so a single@@ -159,32 +161,38 @@ export function describeEmptyCompletedMap(const sourceFiles = ingest.filesDiscovered;const patches = ingest.patchesApplied;- return `Backend reported ${result.outcome}, but mapped 0 files after local ingest found ${sourceFiles} supported source ${sourceFiles === 1 ? "file" : "files"} (${patches} ${patches === 1 ? "patch" : "patches"} committed). The source graph was ingested, but no architecture hierarchy was created. The active backend may not map this source language yet. The ingest cache has been cleared, so the next 'ix map' re-parses every file.`;+ return `Backend reported ${result.outcome}, but mapped 0 files after local ingest found ${sourceFiles} supported source ${sourceFiles === 1 ? "file" : "files"} (${patches} ${patches === 1 ? "patch" : "patches"} committed). The source graph was ingested, but no architecture hierarchy was created. The active backend may not map this source language yet. The source ingest baseline was preserved, so the next 'ix map' can reuse unchanged files.`;}/**- * An empty completed map invalidates the local completion baseline. Keeping it+ * An empty completed map invalidates the architecture completion baseline. Keeping it* would make `ix status` report mapCompleted=true for a hierarchy that does not* exist. The next run may hash-skip unchanged files, so detection is based on* discovered supported sources rather than only newly committed patches.*/-/**- * Clearing the mtime cache is what invalidates the baseline — the baseline is- * stored in it — and it costs a full re-parse on the next run. That is the- * intended trade: a workspace whose hierarchy does not exist should not also be- * carrying a completion record that makes `ix status` claim it does.- */export function invalidateBaselineForEmptyCompletedMap(result: Pick<MapResult, "file_count" | "region_count" | "regions" | "outcome">,ingest: Pick<IngestFilesSummary, "filesDiscovered" | "patchesApplied" | "parseErrors" | "commitErrors"> | undefined,projectRoot: string,- invalidate: (root: string) => void = clearIngestMtimeCache,+ invalidate: (root: string) => void = clearMapBaseline,): string | undefined {const message = describeEmptyCompletedMap(result, ingest);if (message) invalidate(projectRoot);return message;}+/** Persist hierarchy completion only when a non-empty map was actually produced. */+export function persistCompletedMapBaseline(+ result: Pick<MapResult, "file_count" | "region_count" | "regions" | "outcome">,+ projectRoot: string,+): boolean {+ if (result.outcome && !COMPLETED_MAP_OUTCOMES.has(result.outcome)) return false;+ if (result.file_count === 0 && result.region_count === 0 && result.regions.length === 0) return false;+ const sourceBaseline = loadIngestBaseline(projectRoot);+ if (!sourceBaseline) return false;+ return saveMapBaseline(projectRoot, sourceBaseline.currentRev);+}+type MapSortMode = "importance" | "confidence" | "size" | "alpha";export interface MapTextRenderOptions {level?: string;@@ -409,6 +417,7 @@ Examples:process.exitCode = 1;return;}+ persistCompletedMapBaseline(result, cwd);if (silent) {const systems = result.regions.filter(r => r.label_kind === "system").length;diff --git a/ix-cli/src/cli/commands/status.ts b/ix-cli/src/cli/commands/status.tsindex f0848a36..b7c3d5a9 100644--- a/ix-cli/src/cli/commands/status.ts+++ b/ix-cli/src/cli/commands/status.ts@@ -7,6 +7,7 @@ import { detectStaleFiles } from "../stale.js";import { llmError, llmLine, printLlmLines } from "../llm.js";interface StatusStaleInfo {+ graphCompleted: boolean;mapCompleted: boolean;currentRev: number;lastIngestAt: string | null;@@ -18,11 +19,12 @@ interface StatusStaleInfo {* `ix status --format llm`.** The reason to call `status` from an agent is to decide one thing: is the- * graph current enough to trust, or does it need `ix map` first. `text` buries+ * source graph current enough to trust, or does it need `ix map` first. `text` buries* that behind section headers, a "Last ingest" field humanised to "3h ago", and* 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.+ * of parsing prose. `map_complete` separately reports whether an architecture+ * hierarchy exists for that source revision.*/export function renderStatusLlm(backend: string,@@ -32,11 +34,12 @@ export function renderStatusLlm(const lines = [llmLine("status", [["backend", backend],["endpoint", endpoint],+ ["graph_complete", staleInfo ? String(staleInfo.graphCompleted) : null],["map_complete", staleInfo ? String(staleInfo.mapCompleted) : null],["rev", staleInfo ? String(staleInfo.currentRev) : null],["last_ingest_at", staleInfo?.lastIngestAt ?? null],["stale_files", staleInfo ? String(staleInfo.staleFiles) : null],- ["stale", staleInfo ? (!staleInfo.mapCompleted || staleInfo.staleFiles > 0 ? "true" : "false") : null],+ ["stale", staleInfo ? (!staleInfo.graphCompleted || staleInfo.staleFiles > 0 ? "true" : "false") : null],])];for (const f of staleInfo?.sampleChangedFiles ?? []) {lines.push(llmLine("changed", [["path", f]]));@@ -69,6 +72,7 @@ export function registerStatusCommand(program: Command): void {} else if (opts.format === "json") {const result: any = {backend: health.status,+ graphCompleted: staleInfo?.graphCompleted ?? null,mapCompleted: staleInfo?.mapCompleted ?? null,currentRev: staleInfo?.currentRev ?? null,lastIngestAt: staleInfo?.lastIngestAt ?? null,@@ -86,8 +90,8 @@ export function registerStatusCommand(program: Command): void {const ago = timeSince(staleInfo.lastIngestAt);renderKeyValue("Last ingest", ago);}- if (!staleInfo.mapCompleted) {- renderWarning("No completed map is recorded for this workspace.");+ if (!staleInfo.graphCompleted) {+ renderWarning("No completed source graph ingest is recorded for this workspace.");renderNote("Run ix map to build a trustworthy graph.");} else if (staleInfo.staleFiles > 0) {renderWarning(`${staleInfo.staleFiles} file(s) changed since last ingest:`);@@ -101,6 +105,10 @@ export function registerStatusCommand(program: Command): void {} else {renderSuccess("Graph is up to date.");}+ if (staleInfo.graphCompleted && !staleInfo.mapCompleted) {+ renderWarning("No completed architecture map is recorded for this source revision.");+ renderNote("Source graph reads remain available, but hierarchy views may be incomplete.");+ }}}} catch (err) {diff --git a/ix-cli/src/cli/config.ts b/ix-cli/src/cli/config.tsindex ac547f8a..cbbc2591 100644--- a/ix-cli/src/cli/config.ts+++ b/ix-cli/src/cli/config.ts@@ -16,6 +16,12 @@ export function ingestMtimeCachePath(projectRoot: string): string {return join(homedir(), ".ix", `ingest_mtimes_${key}.json`);}+/** Path to the architecture-map completion marker for one project root. */+export function mapBaselinePath(projectRoot: string): string {+ const key = createHash("sha256").update(projectRoot).digest("hex").slice(0, 12);+ return join(homedir(), ".ix", `map_baseline_${key}.json`);+}+/*** Path to the cached answer to "is this workspace stitched into a System?".*@@ -68,9 +74,20 @@ export function clearStitchScopeCache(workspaceId: string): void {try { rmSync(stitchScopeCachePath(workspaceId), { force: true }); } catch { /* non-critical */ }}-/** Remove the ingest mtime cache so the next map re-ingests every file. Best-effort. */+/** Remove only the architecture-map completion marker. Best-effort. */+export function clearMapBaseline(projectRoot: string): void {+ try { rmSync(mapBaselinePath(projectRoot), { force: true }); } catch { /* non-critical */ }+}++/**+ * Remove all local graph baselines so the next map re-ingests every file.+ *+ * Reset and workspace migration invalidate both the source graph and the+ * hierarchy. A failed hierarchy build clears only `clearMapBaseline` instead.+ */export function clearIngestMtimeCache(projectRoot: string): void {try { rmSync(ingestMtimeCachePath(projectRoot), { force: true }); } catch { /* non-critical */ }+ clearMapBaseline(projectRoot);}export interface WorkspaceConfig {diff --git a/ix-cli/src/cli/map-baseline.ts b/ix-cli/src/cli/map-baseline.tsnew file mode 100644index 00000000..352e47dd--- /dev/null+++ b/ix-cli/src/cli/map-baseline.ts@@ -0,0 +1,46 @@+import * as fs from "node:fs";+import * as path from "node:path";+import { mapBaselinePath } from "./config.js";+import { isRev } from "./ingest-baseline.js";++interface SerializedMapBaseline {+ root: string;+ sourceRev: number;+}++export interface MapBaseline {+ sourceRev: number;+}++export function loadMapBaseline(projectRoot: string): MapBaseline | null {+ try {+ const data = JSON.parse(+ fs.readFileSync(mapBaselinePath(projectRoot), "utf-8"),+ ) as SerializedMapBaseline;+ if (data.root !== projectRoot || !isRev(data.sourceRev)) {+ return null;+ }+ return { sourceRev: data.sourceRev };+ } catch {+ return null;+ }+}++export function saveMapBaseline(projectRoot: string, sourceRev: number): boolean {+ if (!isRev(sourceRev)) return false;+ try {+ const data: SerializedMapBaseline = {+ root: projectRoot,+ sourceRev,+ };+ fs.mkdirSync(path.dirname(mapBaselinePath(projectRoot)), { recursive: true });+ fs.writeFileSync(mapBaselinePath(projectRoot), JSON.stringify(data));+ return true;+ } catch {+ return false;+ }+}++export function hasCurrentMapBaseline(projectRoot: string, sourceRev: number): boolean {+ return loadMapBaseline(projectRoot)?.sourceRev === sourceRev;+}diff --git a/ix-cli/src/cli/stale.ts b/ix-cli/src/cli/stale.tsindex e6775802..ccdf4160 100644--- a/ix-cli/src/cli/stale.ts+++ b/ix-cli/src/cli/stale.ts@@ -2,9 +2,11 @@ import * as fs from "node:fs";import * as path from "node:path";import { resolveWorkspaceRoot } from "./config.js";import { loadIngestBaseline } from "./ingest-baseline.js";+import { hasCurrentMapBaseline } from "./map-baseline.js";import { SUPPORTED_EXTENSIONS } from "./supported-extensions.js";export interface StaleInfo {+ graphCompleted: boolean;mapCompleted: boolean;lastIngestAt: string | null;currentRev: number;@@ -91,6 +93,7 @@ export function detectStaleFiles(const baseline = loadIngestBaseline(workspaceRoot);if (!baseline) {return {+ graphCompleted: false,mapCompleted: false,lastIngestAt: null,currentRev: 0,@@ -128,7 +131,8 @@ export function detectStaleFiles(}return {- mapCompleted: true,+ graphCompleted: true,+ mapCompleted: hasCurrentMapBaseline(workspaceRoot, baseline.currentRev),lastIngestAt: baseline.lastIngestAt,currentRev: baseline.currentRev,staleFiles: changedFiles.length,@@ -139,16 +143,23 @@ export function detectStaleFiles(/*** Whether the active workspace has a completed map baseline.*- * A baseline is written only by a local ingest that finished with no parse or- * commit errors, so its absence means one of three things: no map has been run,- * the initial map committed graph patches but never completed, or the workspace- * was ingested through the cloud runner, which writes no local baseline. In all- * three the backend may still answer reads from partially committed data (#506).- * None of them justify calling an individual file stale — that is a claim about- * a file having changed — so callers use this to report the *result set* as- * unverified rather than dressing up every file as modified.+ * The marker is written only after a non-empty hierarchy response and is tied+ * to the source revision it mapped. A later clean ingest therefore leaves the+ * source graph usable while making the prior hierarchy incomplete for the new+ * revision.*/export function hasCompletedMapBaseline(root?: string): boolean {+ try {+ const workspaceRoot = path.resolve(root ?? resolveWorkspaceRoot());+ const baseline = loadIngestBaseline(workspaceRoot);+ return baseline !== null && hasCurrentMapBaseline(workspaceRoot, baseline.currentRev);+ } catch {+ return false;+ }+}++/** Whether source ingestion completed cleanly for the active workspace. */+export function hasCompletedSourceGraphBaseline(root?: string): boolean {try {return loadIngestBaseline(path.resolve(root ?? resolveWorkspaceRoot())) !== null;} catch {