Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

perf(map): take /v1/map off the edit path; region readers refresh lazily (CL-13) (#841)

Ian Hockc3116099f3ba
diff --git a/docs/api/README.md b/docs/api/README.md
index 52ac9c72..d517339e 100644
--- a/docs/api/README.md
+++ b/docs/api/README.md
@@ -679,8 +679,9 @@ backend:
with `x-ix-workspace` and `x-ix-system` headers baked in at launch, so the
browser app never knows about workspaces. `--all` opts out of scoping.
2. **`POST /__ix/remap`** — rebuild the code map for the workspace this
- visualizer is scoped to, by running `ix map <workspace-root> --silent` with
- a 30-minute timeout. Responds `{ "ok": true }` on success, or a `500` with
+ visualizer is scoped to, by running
+ `ix map <workspace-root> --silent --remap` with a 30-minute timeout
+ (`--remap`, so it always recomputes, even while the map is stale). Responds `{ "ok": true }` on success, or a `500` with
`{ "ok": false, "error": ... }` when the map command fails.
The workspace root is resolved once, by `ix view start`, and baked into the
diff --git a/docs/llm-format.md b/docs/llm-format.md
index 593e66bb..0da0f5f7 100644
--- a/docs/llm-format.md
+++ b/docs/llm-format.md
@@ -417,6 +417,26 @@ and `files_too_large_paths`, and has them on every map: zero and an empty list
when no file was too large. `ix map --silent` adds `too_large=N` to its one
line.
+An `ix map` you (or an agent) run always computes the map, and clears a
+stale one. The automatic `ix map` the editor/agent hooks and `ix watch` run
+after an edit (they set `IX_AUTO_MAP=1`) ingests the change but defers the
+map itself: it prints the last computed map's regions and marks the `map` record
+`map_stale=true` (only when true, so a fresh map says nothing). `files`,
+`regions`, `levels`, `rev`, `outcome` and the `region` records are then the
+last map's, not this ingest's, and `regions_as_of_rev` and
+`regions_as_of_files` name that map (both only when stale). A
+`diagnostic code=map_stale` record follows the `map` record and says the
+same in a sentence. The next region view (`overview`, `subsystems`,
+`locate`, `impact`, `explain`, `view`) never maps inline: it answers from
+the last map, says so in one line on stderr
+(`ix: architecture map is stale (<why>); ...`), and starts a detached
+background refresh unless one ran moments ago or another `ix map` holds the
+lock. `ix map --remap` recomputes the map at once, even from an automatic
+run; `IX_MAP_EAGER=1` makes automatic runs compute too, as before; `IX_MAP_BACKGROUND_REFRESH=0` stops region
+views starting a refresh. `--format json` carries `map_stale` on every map (`false` when fresh) and
+`regions_as_of` (`{map_rev, file_count}` of the last map, `null` when
+fresh); `ix map --silent` ends its line with `· map=stale`.
+
`ix stats`:
```
@@ -648,6 +668,11 @@ Two deliberate exceptions remain:
`graph_complete`, not `map_complete`: it is a claim about files having
changed, and a missing hierarchy does not make a file out of date.
+ `map_stale=true` (only when true) says why `map_complete` is false right
+ after an edit: the last automatic `ix map` deferred the map, and the
+ hierarchy is the last computed one until the next region view or `ix map`
+ refreshes it. `--format json` carries it as `mapStale`, always present.
+
`graph_health` is a third, separate question: whether the graph the backend
holds for this workspace is whole (`ok`), has nodes but lost their edges
(`degraded`, followed by a `graph` record with the fix), holds nothing
diff --git a/ix-cli/src/cli/__tests__/llm-renderers.test.ts b/ix-cli/src/cli/__tests__/llm-renderers.test.ts
index 4562399c..f8569200 100644
--- a/ix-cli/src/cli/__tests__/llm-renderers.test.ts
+++ b/ix-cli/src/cli/__tests__/llm-renderers.test.ts
@@ -98,6 +98,20 @@ describe("renderMapLlm", () => {
const clean = captureLog(() => renderMapLlm(result, [], { parseErrors: 0, commitErrors: 0, filesTooLarge: 0, filesTooLargePaths: [] }));
expect(clean).toEqual(["map files=1 regions=0 levels=1 rev=1 outcome=ok"]);
});
+
+ it("says map_stale=true only for a deferred map (CL-13)", () => {
+ const result: MapResult = { file_count: 1, region_count: 1, levels: 1, map_rev: 1, outcome: "ok", regions: [], hierarchy: [] };
+ const stale = captureLog(() => renderMapLlm(result, [], { parseErrors: 0, commitErrors: 0 }, { mapStale: true }));
+ expect(stale[0]).toBe("map files=1 regions=0 levels=1 rev=1 outcome=ok map_stale=true");
+ const fresh = captureLog(() => renderMapLlm(result, [], { parseErrors: 0, commitErrors: 0 }, { mapStale: false }));
+ expect(fresh[0]).toBe("map files=1 regions=0 levels=1 rev=1 outcome=ok");
+ const named = captureLog(() => renderMapLlm(result, [], undefined, { mapStale: true, regionsAsOf: { map_rev: 1, file_count: 1 } }));
+ expect(named[0]).toBe("map files=1 regions=0 levels=1 rev=1 outcome=ok map_stale=true regions_as_of_rev=1 regions_as_of_files=1");
+ expect(named[1]).toBe('diagnostic code=map_stale message="Stale map: not recomputed after this edit. Every count and region here is from the last map (map rev 1, 1 files). Run ix map --remap to recompute it now; region views refresh it in the background."');
+ expect(named).toHaveLength(2);
+ const notStale = captureLog(() => renderMapLlm(result, [], undefined, { regionsAsOf: { map_rev: 1, file_count: 1 } }));
+ expect(notStale).toEqual(["map files=1 regions=0 levels=1 rev=1 outcome=ok"]);
+ });
});
describe("renderSubsystemScoreLlm", () => {
diff --git a/ix-cli/src/cli/__tests__/map-baseline.test.ts b/ix-cli/src/cli/__tests__/map-baseline.test.ts
index e4515bb6..86a93694 100644
--- a/ix-cli/src/cli/__tests__/map-baseline.test.ts
+++ b/ix-cli/src/cli/__tests__/map-baseline.test.ts
@@ -59,6 +59,23 @@ describe("architecture map baseline", () => {
expect(hasCompletedMapBaseline(root)).toBe(true);
});
+ it("finds a map recorded under either spelling of its root, the given one or the canonical one", () => {
+ // macOS's /var -> /private/var and Windows's RUNNER~1 short names: a
+ // baseline stored as given must still be found as given, and one stored
+ // canonically (as `ix map` stores it) must be found from an alias.
+ const real = path.join(home, "real");
+ const alias = path.join(home, "alias");
+ fs.mkdirSync(real, { recursive: true });
+ fs.symlinkSync(real, alias, "junction");
+ for (const [stored, asked] of [[alias, alias], [fs.realpathSync.native(real), alias]] as const) {
+ const filePath = path.join(stored, "index.ts");
+ fs.writeFileSync(filePath, "export const one = 1;\n");
+ persistIngestBaselineIfClean(stored, new Map([[filePath, fs.statSync(filePath).mtimeMs]]), 3, 0, 0);
+ expect(persistCompletedMapBaseline({ file_count: 1, region_count: 1, regions: [], outcome: "full_local_completed" }, stored)).toBe(true);
+ expect(hasCompletedMapBaseline(asked), `stored under ${stored === alias ? "the alias" : "the real path"}`).toBe(true);
+ }
+ });
+
it("records a one-file workspace that has no regions to build", () => {
// The E2E fixture: one Python file, mapped as `1 files · 0s/0ss/0m
// regions`. There is no hierarchy to build over a single file and no
@@ -202,6 +219,13 @@ describe("silentSummaryLine", () => {
expect(line).toBe("map: 12 files · 1s/2ss/3m regions · 40ms · stitch_skipped_rule=cooling · too_large=2\n");
expect(line.split("\n")).toHaveLength(2);
});
+
+ it("ends with map=stale only when the map was deferred (CL-13)", () => {
+ expect(silentSummaryLine({ ...base, mapStale: false })).toBe("map: 12 files · 1s/2ss/3m regions · 40ms\n");
+ expect(silentSummaryLine({ ...base, mapMs: 0, mapStale: true })).toBe("map: 12 files · 1s/2ss/3m regions · 0ms · map=stale\n");
+ expect(silentSummaryLine({ ...base, stitch: " · stitch_skipped_rule=cooling", filesTooLarge: 2, mapStale: true }))
+ .toBe("map: 12 files · 1s/2ss/3m regions · 40ms · stitch_skipped_rule=cooling · too_large=2 · map=stale\n");
+ });
});
describe("mapJsonPayload", () => {
@@ -226,6 +250,27 @@ describe("mapJsonPayload", () => {
expect(remote.files_too_large_paths).toEqual([]);
expect(JSON.parse(JSON.stringify(remote))).toHaveProperty("files_too_large_paths");
});
+
+ it("always carries map_stale, false unless the map was deferred, beside every existing key (CL-13)", () => {
+ const keys = ["file_count", "region_count", "levels", "map_rev", "outcome", "parse_errors", "commit_errors",
+ "stitch_skipped", "stitch_skipped_rule", "files_too_large", "files_too_large_paths", "regions"];
+ const fresh = mapJsonPayload(result, [], undefined);
+ expect(fresh.map_stale).toBe(false);
+ for (const k of keys) expect(fresh).toHaveProperty(k);
+ expect(mapJsonPayload(result, [], undefined, { mapStale: false }).map_stale).toBe(false);
+ const stale = mapJsonPayload(result, [], undefined, { mapStale: true });
+ expect(stale.map_stale).toBe(true);
+ expect(stale).toMatchObject({ file_count: 3, map_rev: 9, outcome: "ok" });
+ });
+
+ it("names the map a deferred payload comes from in regions_as_of, null when fresh (CL-13)", () => {
+ const fresh = mapJsonPayload(result, [], undefined);
+ expect(JSON.parse(JSON.stringify(fresh))).toHaveProperty("regions_as_of", null);
+ const stale = mapJsonPayload(result, [], undefined, { mapStale: true, regionsAsOf: { map_rev: 9, file_count: 3 } });
+ expect(stale.regions_as_of).toEqual({ map_rev: 9, file_count: 3 });
+ // Never claimed without map_stale.
+ expect(mapJsonPayload(result, [], undefined, { regionsAsOf: { map_rev: 9, file_count: 3 } }).regions_as_of).toBeNull();
+ });
});
describe("listTooLargeFiles", () => {
diff --git a/ix-cli/src/cli/__tests__/map-freshness.test.ts b/ix-cli/src/cli/__tests__/map-freshness.test.ts
new file mode 100644
index 00000000..adb87184
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/map-freshness.test.ts
@@ -0,0 +1,621 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createServer, type Server, type ServerResponse } from "node:http";
+import type { AddressInfo } from "node:net";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { Command } from "commander";
+
+import { registerMapCommand } from "../commands/map.js";
+import { canonicalWorkspacePath, mapResultCachePath, mapStalePath } from "../config.js";
+import {
+ ensureFreshMap,
+ MAP_REFRESH_ARG,
+ mapBackgroundRefreshEnabled,
+ mapBackgroundTimeoutMs,
+ mapRefreshDebounceMs,
+ mapRefreshInvocation,
+ markMapStale,
+ readMapRefreshOutcome,
+ readMapStale,
+ runBackgroundMapRefresh,
+ type MapRefreshOutcome,
+} from "../map-freshness.js";
+import { acquireMapLock, lockPathForTest, mapLockHeld, requestMapRerun, takeMapRerun } from "../single-flight.js";
+import { hasCompletedMapBaseline } from "../stale.js";
+import { registerRemoteRunner } from "../remote.js";
+
+/**
+ * The lazy half of a deferred `ix map` (CL-13). These drive the real `ix map`
+ * against a fake backend to get a deferred map, then check the two halves:
+ *
+ * - `ensureFreshMap`, run by every region view: never maps inline, answers
+ * at once, and starts at most one background refresh (the spawner is
+ * injected; no test starts a real process);
+ * - `runBackgroundMapRefresh`, what that detached process runs: at most one
+ * `/v1/map` under the map lock, the outcome recorded, and never the
+ * caller's exit code.
+ */
+
+/** A backend that answers what `ix map` and a refresh touch, and records the paths. */
+class FakeBackend {
+ readonly requests: string[] = [];
+ readonly unknownPaths: string[] = [];
+ rev = 0;
+ /** uri -> the row `/v1/source-hashes` answers with. */
+ readonly hashes = new Map<string, { workspaceId: string | null; uri: string; hash: string }>();
+ /** The status `/v1/map` answers with; 200 serves a map. */
+ mapStatus = 200;
+ /** Delay before `/v1/map` answers, in ms. */
+ mapDelayMs = 0;
+ /** The outcome a 200 from `/v1/map` reports. */
+ mapOutcome = "full_local_completed";
+ /** Answer `/v1/map` with an empty map: no files, no regions. */
+ emptyMap = false;
+ /** Run when `/v1/map` is asked, before it answers. */
+ onMap: (() => void) | undefined;
+ private readonly patches = new Map<string, unknown[]>();
+ private server: Server | undefined;
+
+ mapRequests(): number {
+ return this.requests.filter(p => p === "/v1/map").length;
+ }
+
+ async start(): Promise<string> {
+ this.server = createServer((req, res) => {
+ const chunks: Buffer[] = [];
+ req.on("data", (c: Buffer) => chunks.push(c));
+ req.on("end", () => this.route(req.url ?? "/", Buffer.concat(chunks).toString("utf8"), res));
+ });
+ await new Promise<void>((resolve, reject) => {
+ this.server!.once("error", reject);
+ this.server!.listen(0, "127.0.0.1", resolve);
+ });
+ return `http://127.0.0.1:${(this.server!.address() as AddressInfo).port}`;
+ }
+
+ async stop(): Promise<void> {
+ if (!this.server) return;
+ const server = this.server;
+ server.closeAllConnections();
+ await new Promise<void>(resolve => server.close(() => resolve()));
+ }
+
+ private route(url: string, body: string, res: ServerResponse): void {
+ const path = new URL(url, "http://x").pathname;
+ this.requests.push(path);
+ const send = (code: number, payload: unknown): void => {
+ if (res.writableEnded) return;
+ res.writeHead(code, { "Content-Type": "application/json" });
+ res.end(JSON.stringify(payload));
+ };
+
+ if (path === "/v1/patches/bulk" || path === "/v1/patch") {
+ type SentPatch = { patchId?: string; source?: { uri?: string; sourceHash?: string; workspaceId?: string }; intent?: string; ops?: unknown[] };
+ let patches: SentPatch[] = [];
+ try {
+ const parsed = JSON.parse(body) as { patches?: SentPatch[] };
+ patches = parsed.patches ?? [parsed as SentPatch];
+ } catch { /* a body we cannot read is still a request */ }
+ this.rev += patches.length || 1;
+ for (const { patchId, source, intent, ops } of patches) {
+ if (patchId) this.patches.set(patchId, ops ?? []);
+ if (!source?.uri) continue;
+ if (intent?.startsWith("Deleted ")) this.hashes.delete(source.uri);
+ else if (source.sourceHash) {
+ this.hashes.set(source.uri, { workspaceId: source.workspaceId ?? null, uri: source.uri, hash: source.sourceHash });
+ }
+ }
+ return send(200, path === "/v1/patches/bulk"
+ ? { rev: this.rev, applied: patches.length, status: "Ok" }
+ : { rev: this.rev, status: "Ok" });
+ }
+ if (path === "/v1/health") return send(200, { status: "ok", schema_version: 3, release_version: "1.0.30" });
+ if (path === "/v1/revisions/current") return send(200, this.rev);
+ if (path === "/v1/source-hashes") {
+ let uris: string[] = [];
+ try { uris = (JSON.parse(body) as { uris?: string[] }).uris ?? []; } catch { /* none */ }
+ return send(200, uris.filter(u => this.hashes.has(u)).map(u => this.hashes.get(u)));
+ }
+ // A changed file reconciles against the patch it replaces.
+ if (path.startsWith("/v1/patches/")) {
+ const ops = this.patches.get(decodeURIComponent(path.slice("/v1/patches/".length)));
+ return ops ? send(200, { data: { ops } }) : send(404, { error: "Patch not found" });
+ }
+ if (path.startsWith("/v1/entity/")) return send(200, { node: { kind: "function" }, edges: [] });
+ if (path.startsWith("/v1/stitch/system/")) return send(200, { systemId: null });
+ if (path === "/v1/stitch") return send(200, { stitched: 0, systemId: null, edges: [] });
+ if (path === "/v1/map") {
+ const hook = this.onMap;
+ this.onMap = undefined;
+ hook?.();
+ const answer = (): void => {
+ if (this.mapStatus !== 200) return send(this.mapStatus, { error: "map failed" });
+ const files = this.emptyMap ? 0 : this.hashes.size;
+ send(200, {
+ file_count: files,
+ region_count: this.emptyMap ? 0 : 1,
+ levels: 1,
+ map_rev: this.rev,
+ outcome: this.mapOutcome,
+ regions: this.emptyMap ? [] : [{
+ id: "r-mod", label: `Module of ${files}`, label_kind: "module", level: 1, file_count: files,
+ child_region_count: 0, parent_id: null, cohesion: 0.5, external_coupling: 0.1, boundary_ratio: 1,
+ confidence: 0.8, crosscut_score: 0, dominant_signals: ["imports"], interface_node_count: 0,
+ }],
+ edges: [],
+ hierarchy: [],
+ });
+ };
+ if (this.mapDelayMs > 0) setTimeout(answer, this.mapDelayMs);
+ else answer();
+ return;
+ }
+ this.unknownPaths.push(path);
+ return send(404, { error: `404: no such endpoint ${path}` });
+ }
+}
+
+const hashOf = (text: string) => createHash("sha256").update(Buffer.from(text, "utf8")).digest("hex");
+
+describe("map refresh", () => {
+ vi.setConfig({ testTimeout: 60_000, hookTimeout: 30_000 });
+
+ let home = "";
+ let repo = "";
+ let backend: FakeBackend;
+ const saved: Record<string, string | undefined> = {};
+
+ /** Run `ix map <repo> --silent` in-process. */
+ async function map(...args: string[]): Promise<void> {
+ const write = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ const log = vi.spyOn(console, "log").mockImplementation(() => {});
+ try {
+ const program = new Command();
+ registerMapCommand(program);
+ await program.parseAsync(["node", "ix", "map", repo, "--silent", ...args]);
+ } finally {
+ write.mockRestore();
+ error.mockRestore();
+ log.mockRestore();
+ // Released on process exit, which an in-process run never reaches.
+ rmSync(lockPathForTest(repo), { force: true });
+ }
+ expect(process.exitCode ?? 0).toBe(0);
+ }
+
+ /**
+ * A mapped repo whose last `ix map` deferred the map after an edit: an
+ * automatic one (IX_AUTO_MAP=1, as the hooks run it), since only those defer.
+ */
+ async function deferred(): Promise<void> {
+ await map();
+ writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");
+ process.env.IX_AUTO_MAP = "1";
+ try { await map(); } finally { delete process.env.IX_AUTO_MAP; }
+ expect(readMapStale(repo), "the edit's map was deferred").not.toBeNull();
+ backend.requests.length = 0;
+ }
+
+ /** Captures stdout and stderr around `fn`. */
+ async function captured<T>(fn: () => Promise<T>): Promise<{ value: T; out: string; err: string }> {
+ const out: string[] = [];
+ const err: string[] = [];
+ const log = vi.spyOn(console, "log").mockImplementation((...a: unknown[]) => { out.push(a.map(String).join(" ")); });
+ const write = vi.spyOn(process.stdout, "write").mockImplementation((chunk: unknown) => { out.push(String(chunk)); return true; });
+ const ewrite = vi.spyOn(process.stderr, "write").mockImplementation((chunk: unknown) => { err.push(String(chunk)); return true; });
+ try {
+ const value = await fn();
+ return { value, out: out.join(""), err: err.join("") };
+ } finally {
+ log.mockRestore();
+ write.mockRestore();
+ ewrite.mockRestore();
+ }
+ }
+
+ /** Roots the injected spawner was asked to refresh. */
+ let spawned: string[] = [];
+ /** What the injected spawner does besides recording; nothing by default. */
+ let onSpawn: (root: string) => void = () => {};
+
+ /** A region view's `ensureFreshMap` for the fixture. */
+ async function read(now?: () => number) {
+ const r = await captured(() => ensureFreshMap({
+ root: repo,
+ now,
+ spawn: (root) => { spawned.push(root); onSpawn(root); },
+ }));
+ return { stale: r.value, out: r.out, err: r.err };
+ }
+
+ /** The detached child's work, run in-process. */
+ async function child(opts: Parameters<typeof runBackgroundMapRefresh>[1] = {}) {
+ const r = await captured(() => runBackgroundMapRefresh(repo, opts));
+ return { outcome: r.value, out: r.out, err: r.err };
+ }
+
+ beforeEach(async () => {
+ backend = new FakeBackend();
+ spawned = [];
+ onSpawn = () => {};
+ home = realpathSync(mkdtempSync(join(tmpdir(), "ix-freshness-home-")));
+ repo = realpathSync(mkdtempSync(join(tmpdir(), "ix-freshness-repo-")));
+ const endpoint = await backend.start();
+ for (const k of [
+ "HOME", "USERPROFILE", "IX_HOME", "IX_ENDPOINT", "IX_LOCK_DIR", "IX_AUTO_MAP", "IX_MAP_EAGER",
+ "IX_MAP_FULL_INGEST", "IX_MAP_DEADLINE_MS", "IX_MAP_REFRESH_DEBOUNCE_MS",
+ "IX_MAP_BACKGROUND_REFRESH", "IX_MAP_BACKGROUND_TIMEOUT_MS",
+ "IX_STITCH_COOLDOWN_MS", "IX_STITCH_WAIT_MS",
+ ]) {
+ saved[k] = process.env[k];
+ delete process.env[k];
+ }
+ process.env.HOME = home;
+ process.env.USERPROFILE = home;
+ process.env.IX_HOME = join(home, ".ix");
+ process.env.IX_ENDPOINT = endpoint;
+ process.env.IX_LOCK_DIR = join(home, "locks");
+ mkdirSync(join(repo, "src"), { recursive: true });
+ for (let i = 0; i < 3; i++) {
+ writeFileSync(join(repo, "src", `m${i}.ts`), `export function f${i}(): number { return ${i}; }\n`, "utf8");
+ }
+ execFileSync("git", ["init", "-q"], { cwd: repo, stdio: "ignore" });
+ execFileSync("git", ["add", "-A"], { cwd: repo, stdio: "ignore" });
+ });
+
+ afterEach(async () => {
+ try {
+ expect(backend.unknownPaths, "endpoints the fake does not implement").toEqual([]);
+ } finally {
+ process.exitCode = undefined;
+ await backend.stop();
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ for (const dir of [home, repo]) if (dir) rmSync(dir, { recursive: true, force: true });
+ home = "";
+ repo = "";
+ }
+ });
+
+ describe("ensureFreshMap (the reader)", () => {
+ it("makes no request and starts nothing without a marker", async () => {
+ await map();
+ backend.requests.length = 0;
+ const r = await read();
+ expect(r.stale).toBe(false);
+ expect(r.err).toBe("");
+ expect(backend.requests).toEqual([]);
+ expect(spawned).toEqual([]);
+ });
+
+ it("answers at once, maps nothing inline, and starts one background refresh", async () => {
+ await deferred();
+ const r = await read(() => 1_000_000);
+ expect(r.stale).toBe(true);
+ expect(r.out, "nothing on stdout").toBe("");
+ expect(backend.mapRequests(), "no /v1/map from the reader").toBe(0);
+ // The canonical root, which on Windows CI is the long form of the
+ // 8.3 temp path (RUNNER~1) that `realpathSync` leaves as it is.
+ expect(spawned).toEqual([canonicalWorkspacePath(repo)]);
+ expect(r.err).toBe("ix: architecture map is stale (refreshing in background); regions shown may predate recent edits. Run ix map --remap to refresh.\n");
+ expect(readMapStale(repo)?.lastAttemptAt, "the start is recorded for the debounce").toBe(1_000_000);
+ expect(mapLockHeld(repo), "the reader does not keep the lock").toBe(false);
+ });
+
+ it("returns without waiting for the refresh it started", async () => {
+ await deferred();
+ // A map slower than any hook budget, run as the child would run it.
+ backend.mapDelayMs = 3_000;
+ let running: Promise<unknown> | undefined;
+ onSpawn = (root) => { running = runBackgroundMapRefresh(root); };
+ const t0 = Date.now();
+ const r = await read();
+ const took = Date.now() - t0;
+ expect(r.stale).toBe(true);
+ expect(took, "the reader did not wait for the 3 s map").toBeLessThan(2_000);
+ expect(readMapStale(repo), "the refresh has not finished yet").not.toBeNull();
+
+ // Meanwhile another reader sees the refresh holding the lock.
+ await new Promise(resolve => setTimeout(resolve, 200));
+ const second = await read(() => Date.now() + 60_000);
+ expect(second.err).toMatch(/\(another ix map is running\)/);
+ expect(spawned, "and starts no second one").toHaveLength(1);
+
+ const outcome = await running as MapRefreshOutcome;
+ expect(outcome.ok).toBe(true);
+ expect(readMapStale(repo), "it cleared the marker").toBeNull();
+ expect(hasCompletedMapBaseline(repo)).toBe(true);
+ expect(backend.mapRequests()).toBe(1);
+ });
+
+ it("starts no refresh inside the debounce window, and one after it", async () => {
+ await deferred();
+ let clock = 1_000_000;
+ const now = () => clock;
+ await read(now);
+ expect(spawned).toHaveLength(1);
+
+ clock += 10_000;
+ const debounced = await read(now);
+ expect(spawned, "within 30 s of the start").toHaveLength(1);
+ expect(debounced.stale).toBe(true);
+ expect(debounced.err).toMatch(/^ix: architecture map is stale \(a refresh was tried moments ago\)/);
+
+ clock += 30_000;
+ await read(now);
+ expect(spawned, "after the window").toHaveLength(2);
+ expect(backend.mapRequests()).toBe(0);
+ });
+
+ it("starts no refresh while another process holds the map lock, and keeps the marker", async () => {
+ await deferred();
+ const marker = readMapStale(repo);
+ const holder = acquireMapLock(repo, "holder")!;
+ let r;
+ try {
+ r = await read();
+ } finally {
+ holder.release();
+ }
+ expect(spawned).toEqual([]);
+ expect(backend.requests).toEqual([]);
+ expect(readMapStale(repo)).toEqual(marker);
+ expect(r.stale).toBe(true);
+ expect(r.err).toMatch(/^ix: architecture map is stale \(another ix map is running\)/);
+ expect(r.err.trim().split("\n"), "one line").toHaveLength(1);
+ });
+
+ it("says why when the last background refresh failed and the retry is debounced", async () => {
+ await deferred();
+ backend.mapStatus = 500;
+ await child({ now: () => 1_000_000 });
+ const r = await read(() => 1_000_000 + 5_000);
+ expect(spawned).toEqual([]);
+ expect(r.err).toMatch(/^ix: architecture map is stale \(its last background refresh failed\)/);
+ });
+
+ it("never refreshes with IX_MAP_BACKGROUND_REFRESH=0, and says the map is stale", async () => {
+ await deferred();
+ process.env.IX_MAP_BACKGROUND_REFRESH = "0";
+ const r = await read();
+ expect(spawned).toEqual([]);
+ expect(backend.requests).toEqual([]);
+ expect(r.stale).toBe(true);
+ expect(r.err).toMatch(/^ix: architecture map is stale \(background refresh is off\)/);
+ expect(readMapStale(repo)?.lastAttemptAt, "nothing was attempted").toBeUndefined();
+ });
+
+ it("never throws or sets an exit code when the refresh cannot start", async () => {
+ await deferred();
+ onSpawn = () => { throw new Error("EAGAIN"); };
+ process.exitCode = undefined;
+ const r = await read();
+ expect(r.stale).toBe(true);
+ expect(r.err).toMatch(/\(its refresh could not start\)/);
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it("reads the marker again under the lock, and starts nothing for a map just refreshed", async () => {
+ await deferred();
+ const seen = readMapStale(repo)!;
+ writeFileSync(mapStalePath(repo), JSON.stringify({ ...seen, lastAttemptAt: 1 }));
+ // Between this reader's first look and its taking the lock, a refresh
+ // finishes and removes the marker. The debounce reads the clock at that
+ // first look, so the race is staged there.
+ let calls = 0;
+ const r = await read(() => {
+ if (calls++ === 0) rmSync(mapStalePath(repo), { force: true });
+ return 1_000_000;
+ });
+ expect(spawned).toEqual([]);
+ expect(r.stale).toBe(false);
+ expect(r.err).toBe("");
+ });
+
+ it("starts nothing for a workspace fed by a cloud runner", async () => {
+ await deferred();
+ registerRemoteRunner({ runIngestion: async () => {}, isReady: async () => true });
+ try {
+ await read();
+ } finally {
+ registerRemoteRunner({ runIngestion: async () => {}, isReady: async () => false });
+ }
+ expect(spawned).toEqual([]);
+ expect(backend.requests).toEqual([]);
+ expect(readMapStale(repo)).not.toBeNull();
+ });
+
+ it("treats a malformed marker as none", async () => {
+ await map();
+ mkdirSync(join(home, ".ix"), { recursive: true });
+ writeFileSync(mapStalePath(repo), "{not json");
+ expect(readMapStale(repo)).toBeNull();
+ writeFileSync(mapStalePath(repo), JSON.stringify({ since: "yesterday", ingestRev: 1 }));
+ expect(readMapStale(repo)).toBeNull();
+ backend.requests.length = 0;
+ await read();
+ expect(backend.requests).toEqual([]);
+ expect(spawned).toEqual([]);
+ });
+ });
+
+ describe("runBackgroundMapRefresh (the detached child)", () => {
+ it("maps once when the marker is set, records the map, clears the marker and the outcome", async () => {
+ await deferred();
+ expect(hasCompletedMapBaseline(repo)).toBe(false);
+ rmSync(mapResultCachePath(repo), { force: true });
+
+ const r = await child();
+ expect(r.out, "nothing on stdout").toBe("");
+ expect(backend.mapRequests()).toBe(1);
+ expect(readMapStale(repo)).toBeNull();
+ expect(hasCompletedMapBaseline(repo), "the map baseline is saved").toBe(true);
+ expect(existsSync(mapResultCachePath(repo)), "the result is stored").toBe(true);
+ expect(r.outcome).toMatchObject({ ok: true, pid: process.pid });
+ expect(readMapRefreshOutcome(repo)).toEqual(r.outcome);
+ expect(mapLockHeld(repo), "the lock is let go").toBe(false);
+
+ expect((await child()).outcome, "a second run is a no-op").toBeNull();
+ expect(backend.mapRequests()).toBe(1);
+
+ // And the next unchanged `ix map` reuses it rather than asking.
+ await map();
+ expect(backend.mapRequests()).toBe(1);
+ });
+
+ it("refreshes a root named under another spelling of the same directory", async () => {
+ // Windows CI names the temp dir C:\Users\RUNNER~1\... (an 8.3 short name),
+ // while `ix map` stores the long, canonical root in its baselines. A
+ // junction (a symlink on POSIX) is the same mismatch on any platform.
+ await deferred();
+ const alias = join(home, "repo-alias");
+ symlinkSync(repo, alias, "junction");
+ expect(hasCompletedMapBaseline(alias), "an alias reads the same ingest baseline").toBe(false);
+
+ const outcome = await runBackgroundMapRefresh(alias);
+ expect(backend.mapRequests()).toBe(1);
+ expect(outcome?.ok).toBe(true);
+ expect(readMapStale(repo)).toBeNull();
+ expect(hasCompletedMapBaseline(repo)).toBe(true);
+ expect(hasCompletedMapBaseline(alias), "and the alias sees the map as complete").toBe(true);
+ });
+
+ it("does nothing while another process holds the map lock", async () => {
+ await deferred();
+ const marker = readMapStale(repo);
+ const holder = acquireMapLock(repo, "holder")!;
+ try {
+ expect((await child()).outcome).toBeNull();
+ } finally {
+ holder.release();
+ }
+ expect(backend.requests).toEqual([]);
+ expect(readMapStale(repo)).toEqual(marker);
+ expect(readMapRefreshOutcome(repo)).toBeNull();
+ });
+
+ for (const [what, setUp, reason] of [
+ ["a map whose outcome is not a completed one", (b: FakeBackend) => { b.mapOutcome = "partial"; }, /the map did not complete: outcome partial/],
+ ["an empty map", (b: FakeBackend) => { b.emptyMap = true; }, /the map did not complete/],
+ ] as const) {
+ it(`leaves the stored map, the baseline and the marker as they were after ${what}`, async () => {
+ await deferred();
+ const marker = readMapStale(repo)!;
+ const stored = readFileSync(mapResultCachePath(repo), "utf8");
+ setUp(backend);
+ process.exitCode = undefined;
+ const r = await child();
+ expect(r.out).toBe("");
+ expect(backend.mapRequests()).toBe(1);
+ expect(process.exitCode).toBeUndefined();
+ const kept = readMapStale(repo);
+ expect(kept, "the marker stays").not.toBeNull();
+ expect(kept?.since).toBe(marker.since);
+ expect(kept?.ingestRev).toBe(marker.ingestRev);
+ expect(readFileSync(mapResultCachePath(repo), "utf8"), "the last map is still stored").toBe(stored);
+ expect(hasCompletedMapBaseline(repo), "no completed map is claimed").toBe(false);
+ expect(r.outcome?.ok).toBe(false);
+ expect(r.outcome?.reason).toMatch(reason);
+ expect(readMapRefreshOutcome(repo)).toEqual(r.outcome);
+ });
+ }
+
+ it("records a failed request, never throws or sets an exit code, and keeps the marker", async () => {
+ await deferred();
+ const since = readMapStale(repo)!.since;
+ backend.mapStatus = 500;
+ process.exitCode = undefined;
+ const r = await child();
+ expect(process.exitCode).toBeUndefined();
+ expect(readMapStale(repo)?.since).toBe(since);
+ expect(r.outcome?.ok).toBe(false);
+ expect(r.outcome?.reason).toMatch(/^the map request failed: /);
+ expect(r.outcome?.reason, "one line").not.toContain("\n");
+ });
+
+ it("stops at its hard time limit, records why, and lets the lock go", async () => {
+ await deferred();
+ backend.mapDelayMs = 5_000;
+ process.exitCode = undefined;
+ const t0 = Date.now();
+ const r = await child({ timeoutMs: 300 });
+ expect(Date.now() - t0).toBeLessThan(3_000);
+ expect(r.outcome).toMatchObject({ ok: false, reason: "timed out after 0.3 s" });
+ expect(readMapStale(repo), "the marker stays").not.toBeNull();
+ expect(mapLockHeld(repo)).toBe(false);
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it("keeps a marker that was re-written while it mapped", async () => {
+ await deferred();
+ backend.onMap = () => markMapStale(repo, { since: Date.now() + 1, ingestRev: 999 });
+ const r = await child();
+ expect(backend.mapRequests()).toBe(1);
+ expect(readMapStale(repo)?.ingestRev, "a newer ingest's marker stays").toBe(999);
+ expect(r.outcome).toMatchObject({ ok: true, reason: expect.stringMatching(/files changed while it was refreshed/) });
+ });
+
+ it("runs a coalesced map's rerun request and re-marks the map stale", async () => {
+ await deferred();
+ const late = "export const late = 2;\n";
+ // An edit lands mid-refresh and its own `ix map` coalesces into the lock.
+ backend.onMap = () => {
+ writeFileSync(join(repo, "src", "m2.ts"), late, "utf8");
+ requestMapRerun(repo);
+ };
+ process.exitCode = undefined;
+ await child();
+ expect(backend.mapRequests(), "the refresh asked once").toBe(1);
+ expect(backend.hashes.get("src/m2.ts")?.hash, "the late edit reached the backend").toBe(hashOf(late));
+ expect(readMapStale(repo), "the edit's map is deferred in turn").not.toBeNull();
+ expect(takeMapRerun(repo), "and the request consumed").toBe(false);
+ expect(process.exitCode).toBeUndefined();
+ });
+ });
+});
+
+describe("mapRefreshInvocation", () => {
+ it("starts the same Node and CLI entry, detached, with no shell, no stdio and no window", async () => {
+ const inv = await mapRefreshInvocation("/w/repo", "/opt/ix/dist/cli/main.js", ["--inspect"]);
+ expect(inv.command).toBe(process.execPath);
+ expect(inv.args, "debugger flags are not cloned").toEqual(["/opt/ix/dist/cli/main.js", MAP_REFRESH_ARG, "/w/repo"]);
+ expect(inv.options).toMatchObject({ cwd: "/w/repo", detached: true, stdio: "ignore", windowsHide: true, shell: false });
+ });
+
+ it("keeps the source loader of a TypeScript entry", async () => {
+ const inv = await mapRefreshInvocation("/w/repo", "/src/cli/main.ts", ["--import", "tsx"]);
+ expect(inv.args).toEqual(["--import", "tsx", "/src/cli/main.ts", MAP_REFRESH_ARG, "/w/repo"]);
+ });
+});
+
+describe("refresh settings", () => {
+ it("mapRefreshDebounceMs defaults to 30 s, takes a plain number of ms, and 0 or empty for none", () => {
+ expect(mapRefreshDebounceMs(undefined)).toBe(30_000);
+ expect(mapRefreshDebounceMs("5000")).toBe(5_000);
+ expect(mapRefreshDebounceMs("0")).toBe(0);
+ expect(mapRefreshDebounceMs("")).toBe(0);
+ expect(mapRefreshDebounceMs("30s"), "not a number of ms keeps the default").toBe(30_000);
+ });
+
+ it("mapBackgroundRefreshEnabled is on unless set to 0", () => {
+ expect(mapBackgroundRefreshEnabled({})).toBe(true);
+ expect(mapBackgroundRefreshEnabled({ IX_MAP_BACKGROUND_REFRESH: "1" })).toBe(true);
+ expect(mapBackgroundRefreshEnabled({ IX_MAP_BACKGROUND_REFRESH: "0" })).toBe(false);
+ expect(mapBackgroundRefreshEnabled({ IX_MAP_BACKGROUND_REFRESH: " 0 " })).toBe(false);
+ });
+
+ it("mapBackgroundTimeoutMs defaults to 5 min and takes a plain positive number of ms", () => {
+ expect(mapBackgroundTimeoutMs(undefined)).toBe(300_000);
+ expect(mapBackgroundTimeoutMs("60000")).toBe(60_000);
+ expect(mapBackgroundTimeoutMs("0")).toBe(300_000);
+ expect(mapBackgroundTimeoutMs("5m")).toBe(300_000);
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/map-result-cache.test.ts b/ix-cli/src/cli/__tests__/map-result-cache.test.ts
index 6154bdcc..814fbf06 100644
--- a/ix-cli/src/cli/__tests__/map-result-cache.test.ts
+++ b/ix-cli/src/cli/__tests__/map-result-cache.test.ts
@@ -16,16 +16,20 @@ import {
clearMapBaseline,
ingestMtimeCachePath,
mapResultCachePath,
+ mapStalePath,
} from "../config.js";
import {
backendIdentity,
loadCachedMap,
+ loadLastMap,
resolveMapCacheSlot,
revisionToken,
saveCachedMap,
type MapCacheSlot,
} from "../map-result-cache.js";
import { acquireMapLock, lockPathForTest, requestMapRerun, takeMapRerun } from "../single-flight.js";
+import { readMapStale } from "../map-freshness.js";
+import { hasCompletedMapBaseline } from "../stale.js";
import { createHash } from "node:crypto";
/**
@@ -56,6 +60,8 @@ class FakeBackend {
onCommit: (() => void) | undefined;
/** Answer every commit with a 500, as a backend that is down would. */
failCommits = false;
+ /** Answer a commit carrying a patch for one of these uris with a 500: a partial failure. */
+ readonly failUris = new Set<string>();
readonly hashes = new Map<string, { workspaceId: string | null; uri: string; hash: string }>();
private readonly patches = new Map<string, unknown[]>();
private server: Server | undefined;
@@ -104,6 +110,9 @@ class FakeBackend {
const parsed = JSON.parse(body) as { patches?: SentPatch[] };
patches = parsed.patches ?? [parsed as SentPatch];
} catch { /* a body we cannot read is still a request */ }
+ if (patches.some(p => p.source?.uri && this.failUris.has(p.source.uri))) {
+ return send(500, { error: "write refused" });
+ }
if (!this.frozenRevision) this.rev += patches.length || 1;
for (const { patchId, source, intent, ops } of patches) {
if (patchId) this.patches.set(patchId, ops ?? []);
@@ -233,6 +242,7 @@ describe("ix map reuses an unchanged map", () => {
for (const k of [
"HOME", "USERPROFILE", "IX_HOME", "IX_ENDPOINT", "IX_LOCK_DIR", "IX_AUTO_MAP",
"IX_MAP_FULL_INGEST", "IX_MAP_DEADLINE_MS", "IX_STITCH_COOLDOWN_MS", "IX_STITCH_WAIT_MS",
+ "IX_MAP_EAGER", "IX_MAP_REFRESH_DEBOUNCE_MS",
]) {
saved[k] = process.env[k];
delete process.env[k];
@@ -344,32 +354,254 @@ describe("ix map reuses an unchanged map", () => {
expect(line(fresh.stderr)).toBe("map: 4 files · 1s/0ss/1m regions");
});
- it("asks again when a file changed", async () => {
- await map("--format", "json");
- writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");
- const before = backend.mapRequests();
- const after = await map("--format", "json");
- expect(backend.mapRequests()).toBe(before + 1);
- expect(JSON.parse(after.stdout).file_count).toBe(5);
- });
+ describe("an explicit `ix map` computes a stale map (CL-13)", () => {
+ // No IX_AUTO_MAP: a person or agent running the command, who wants the
+ // map now. Only the hooks' automatic runs defer.
+ const autoMap = async (...args: string[]) => {
+ process.env.IX_AUTO_MAP = "1";
+ try { return await map(...args); } finally { delete process.env.IX_AUTO_MAP; }
+ };
- it("asks again when an ingest wrote to the graph, even if the revision did not move", async () => {
- await map("--format", "json");
- backend.frozenRevision = true;
- writeFileSync(join(repo, "src", "m1.ts"), "export function f1(): number { return 100; }\n", "utf8");
- const before = backend.mapRequests();
- await map("--format", "json");
- expect(backend.mapRequests()).toBe(before + 1);
+ it("computes after an incremental edit, as before CL-13", async () => {
+ await map("--format", "json");
+ writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");
+ const before = backend.mapRequests();
+ const after = JSON.parse((await map("--format", "json")).stdout);
+ expect(backend.mapRequests()).toBe(before + 1);
+ expect(after.map_stale).toBe(false);
+ expect(after.regions_as_of).toBeNull();
+ expect(after.file_count).toBe(5);
+ expect(readMapStale(repo)).toBeNull();
+ expect(hasCompletedMapBaseline(repo)).toBe(true);
+ });
+
+ it("recomputes on a no-change run after an automatic map deferred, returns fresh counts, and clears the marker", async () => {
+ const first = JSON.parse((await map("--format", "json")).stdout);
+ writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");
+ const deferred = JSON.parse((await autoMap("--format", "json")).stdout);
+ expect(deferred.map_stale, "the hook's run deferred").toBe(true);
+ expect(deferred.file_count).toBe(first.file_count);
+ expect(readMapStale(repo)).not.toBeNull();
+
+ const before = backend.mapRequests();
+ const explicit = JSON.parse((await map("--format", "json")).stdout);
+ expect(backend.mapRequests(), "nothing changed, but the map was stale").toBe(before + 1);
+ expect(explicit.map_stale).toBe(false);
+ expect(explicit.regions_as_of).toBeNull();
+ expect(explicit.file_count, "this ingest's count, not the last map's").toBe(5);
+ expect(explicit.map_rev).toBeGreaterThan(first.map_rev);
+ expect(readMapStale(repo), "the marker is cleared").toBeNull();
+ expect(hasCompletedMapBaseline(repo)).toBe(true);
+
+ // Fresh now: the next run is the ordinary no-change reuse.
+ const again = backend.mapRequests();
+ await map("--format", "json");
+ expect(backend.mapRequests()).toBe(again);
+ });
+
+ it("computes under --silent too: agents run `ix map --silent` to refresh", async () => {
+ await map("--silent");
+ writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");
+ const before = backend.mapRequests();
+ const run = await map("--silent");
+ expect(backend.mapRequests()).toBe(before + 1);
+ expect(run.stderr).not.toContain("map=stale");
+ expect(readMapStale(repo)).toBeNull();
+ });
});
- it("asks again when a file was deleted, even if the revision did not move", async () => {
- await map("--format", "json");
- backend.frozenRevision = true;
- unlinkSync(join(repo, "src", "m3.ts"));
- const before = backend.mapRequests();
- const after = await map("--format", "json");
- expect(backend.mapRequests()).toBe(before + 1);
- expect(JSON.parse(after.stdout).file_count).toBe(3);
+ describe("an automatic map defers after an incremental edit (CL-13)", () => {
+ const line = (s: string) => s.split("\n").find(l => l.startsWith("map: "))?.replace(/ · \d+ms/, "");
+ // IX_AUTO_MAP=1 is what the editor/agent hooks and `ix watch` set; the
+ // outer afterEach restores it.
+ beforeEach(() => { process.env.IX_AUTO_MAP = "1"; });
+
+ it("defers the map after an incremental edit", async () => {
+ const first = JSON.parse((await map("--format", "json")).stdout);
+ expect(first.map_stale).toBe(false);
+ writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");
+ const before = backend.mapRequests();
+ const after = JSON.parse((await map("--format", "json")).stdout);
+ expect(backend.mapRequests(), "no map request after an edit").toBe(before);
+ expect(after.map_stale).toBe(true);
+ // Everything is the previous map's, not this ingest's, and says so.
+ expect(after.file_count).toBe(first.file_count);
+ expect(after.map_rev).toBe(first.map_rev);
+ expect(after.regions).toEqual(first.regions);
+ expect(after.region_count).toBe(first.region_count);
+ expect(after.regions_as_of).toEqual({ map_rev: first.map_rev, file_count: first.file_count });
+ expect(first.regions_as_of, "null, but present, when fresh").toBeNull();
+ expect(existsSync(mapStalePath(repo)), "the marker is written").toBe(true);
+ // The edit itself reached the graph.
+ expect([...backend.hashes.values()].some(r => r.uri === "src/m9.ts")).toBe(true);
+ // The completion marker does not claim the old map for the new revision.
+ expect(hasCompletedMapBaseline(repo)).toBe(false);
+ });
+
+ it("defers when an ingest wrote to the graph, even if the revision did not move", async () => {
+ await map("--format", "json");
+ backend.frozenRevision = true;
+ writeFileSync(join(repo, "src", "m1.ts"), "export function f1(): number { return 100; }\n", "utf8");
+ const before = backend.mapRequests();
+ const after = JSON.parse((await map("--format", "json")).stdout);
+ expect(backend.mapRequests()).toBe(before);
+ expect(after.map_stale).toBe(true);
+ });
+
+ it("defers when a file was deleted, even if the revision did not move", async () => {
+ await map("--format", "json");
+ backend.frozenRevision = true;
+ unlinkSync(join(repo, "src", "m3.ts"));
+ const before = backend.mapRequests();
+ const after = JSON.parse((await map("--format", "json")).stdout);
+ expect(backend.mapRequests()).toBe(before);
+ expect(after.map_stale).toBe(true);
+ expect(after.file_count, "the previous map's count, until a refresh").toBe(4);
+ expect(after.regions_as_of, "named as the previous map's").toEqual({ map_rev: expect.any(Number), file_count: 4 });
+ });
+
+ it("always computes the first map", async () => {
+ const first = JSON.parse((await map("--format", "json")).stdout);
+ expect(backend.mapRequests()).toBe(1);
+ expect(first.map_stale).toBe(false);
+ expect(existsSync(mapStalePath(repo))).toBe(false);
+ });
+
+ it("computes under --remap and clears the marker", async () => {
+ await map("--format", "json");
+ writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");
+ await map("--format", "json");
+ expect(readMapStale(repo)).not.toBeNull();
+ const before = backend.mapRequests();
+ const remapped = JSON.parse((await map("--format", "json", "--remap")).stdout);
+ expect(backend.mapRequests()).toBe(before + 1);
+ expect(remapped.map_stale).toBe(false);
+ expect(remapped.file_count).toBe(5);
+ expect(readMapStale(repo)).toBeNull();
+ expect(hasCompletedMapBaseline(repo)).toBe(true);
+ });
+
+ it("computes under --full", async () => {
+ await map("--format", "json");
+ writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");
+ const before = backend.mapRequests();
+ const full = JSON.parse((await map("--format", "json", "--full")).stdout);
+ expect(backend.mapRequests()).toBe(before + 1);
+ expect(full.map_stale).toBe(false);
+ expect(readMapStale(repo)).toBeNull();
+ });
+
+ it("computes under IX_MAP_EAGER=1, as before", async () => {
+ process.env.IX_MAP_EAGER = "1";
+ await map("--format", "json");
+ writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");
+ const before = backend.mapRequests();
+ const after = JSON.parse((await map("--format", "json")).stdout);
+ expect(backend.mapRequests()).toBe(before + 1);
+ expect(after.file_count).toBe(5);
+ expect(after.map_stale).toBe(false);
+ });
+
+ it("stays deferred on a no-change automatic run while the marker is set", async () => {
+ await map("--format", "json");
+ writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");
+ await map("--format", "json");
+ const marker = readMapStale(repo);
+ const before = backend.mapRequests();
+ const again = JSON.parse((await map("--format", "json")).stdout);
+ expect(backend.mapRequests(), "no request for an unchanged, already stale map").toBe(before);
+ expect(again.map_stale).toBe(true);
+ expect(readMapStale(repo), "the marker it found is kept as it was").toEqual(marker);
+ });
+
+ it("computes when there is no stored map to show, or only another request's", async () => {
+ await map("--format", "json");
+ rmSync(mapResultCachePath(repo), { force: true });
+ writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");
+ let before = backend.mapRequests();
+ await map("--format", "json");
+ expect(backend.mapRequests(), "nothing stored").toBe(before + 1);
+
+ const stored = JSON.parse(readFileSync(mapResultCachePath(repo), "utf8"));
+ writeFileSync(mapResultCachePath(repo), JSON.stringify({ ...stored, key: "another request" }));
+ writeFileSync(join(repo, "src", "m8.ts"), "export const eight = 8;\n", "utf8");
+ before = backend.mapRequests();
+ const after = JSON.parse((await map("--format", "json")).stdout);
+ expect(backend.mapRequests(), "a foreign stored map").toBe(before + 1);
+ expect(after.map_stale).toBe(false);
+ expect(loadLastMap(repo, "another request")).toBeUndefined();
+ });
+
+ it("computes after an ingest with commit errors", async () => {
+ await map("--format", "json");
+ writeFileSync(join(repo, "src", "m8.ts"), "export const eight = 8;\n", "utf8");
+ writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");
+ // One of the two lands, the other is refused: a partial failure, which
+ // exits 1 but still maps.
+ backend.failUris.add("src/m9.ts");
+ const before = backend.mapRequests();
+ await runMap();
+ expect(process.exitCode, "the partial commit failure is reported").toBe(1);
+ expect(backend.mapRequests(), "a run with errors is not deferred").toBe(before + 1);
+ expect(readMapStale(repo)).toBeNull();
+ });
+
+ it("neither maps nor defers after an ingest that failed outright", async () => {
+ await map("--format", "json");
+ writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");
+ backend.failCommits = true;
+ const before = backend.mapRequests();
+ await runMap();
+ expect(process.exitCode).toBe(1);
+ expect(backend.mapRequests()).toBe(before);
+ expect(readMapStale(repo)).toBeNull();
+ });
+
+ it("says map=stale on the --silent line, and only then", async () => {
+ const clean = await map("--silent");
+ expect(line(clean.stderr)).toBe("map: 4 files · 1s/0ss/1m regions");
+ writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");
+ const deferred = await map("--silent");
+ expect(line(deferred.stderr)).toBe("map: 4 files · 1s/0ss/1m regions · map=stale");
+ });
+
+ it("says map_stale=true in llm only when stale", async () => {
+ const clean = await map("--format", "llm");
+ expect(clean.stdout).not.toContain("map_stale");
+ writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");
+ const deferred = await map("--format", "llm");
+ const record = deferred.stdout.split("\n")[0];
+ expect(record).toMatch(/^map .*map_stale=true/);
+ expect(record).toMatch(/\bregions_as_of_rev=\d+\b/);
+ expect(record).toMatch(/\bregions_as_of_files=4\b/);
+ expect(clean.stdout).not.toContain("regions_as_of");
+ // Its own record, straight after the `map` record, not just a field on it.
+ expect(deferred.stdout.split("\n")[1]).toMatch(/^diagnostic code=map_stale message="Stale map: not recomputed after this edit\. Every count and region here is from the last map \(map rev \d+, 4 files\)\. Run ix map --remap/);
+ expect(clean.stdout).not.toContain("diagnostic");
+ });
+
+ it("opens a stale text map with a warning on stdout that says how to refresh", async () => {
+ await map();
+ writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");
+ const deferred = await map();
+ const first = deferred.stdout.split("\n").find(l => l.trim() !== "") ?? "";
+ expect(first, "the first thing printed").toMatch(/Warning\s+Stale map: not recomputed after this edit/);
+ expect(first).toContain("ix map --remap");
+ expect(first, "names the map the regions are from").toMatch(/last map \(map rev \d+, 4 files\)/);
+ expect(deferred.stderr).not.toContain("Mapped in");
+ });
+
+ it("marks the map stale when a coalesced map's rerun changed files", async () => {
+ await map("--silent");
+ writeFileSync(join(repo, "src", "m1.ts"), "export const changed = 1;\n", "utf8");
+ backend.onCommit = () => {
+ writeFileSync(join(repo, "src", "m2.ts"), "export const late = 2;\n", "utf8");
+ requestMapRerun(repo);
+ };
+ await map("--silent");
+ const marker = readMapStale(repo);
+ expect(marker, "the rerun's ingest left the map stale, and says so").not.toBeNull();
+ });
});
it("asks again when another client moved the revision", async () => {
@@ -475,6 +707,62 @@ describe("ingestFiles invalidates the cached map", () => {
}
};
+ describe("reports which runs were an ordinary incremental update", () => {
+ const ingestWith = async (extra: { force?: boolean } = {}) => {
+ const write = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
+ try {
+ return await ingestFiles(repo, { format: "json", suppressOutput: true, printSummary: false, mapMode: true, ...extra });
+ } finally {
+ write.mockRestore();
+ }
+ };
+
+ it("is false for the first ingest and for one that changed nothing", async () => {
+ expect((await ingest()).incremental).toBe(false);
+ expect((await ingest()).incremental).toBe(false);
+ });
+
+ it("is true for a baseline run that changed or deleted a file", async () => {
+ await ingest();
+ writeFileSync(join(repo, "src", "m1.ts"), "export const v1 = 100;\n", "utf8");
+ expect((await ingest()).incremental).toBe(true);
+ unlinkSync(join(repo, "src", "m2.ts"));
+ expect((await ingest()).incremental).toBe(true);
+ });
+
+ it("is false under --force", async () => {
+ await ingest();
+ writeFileSync(join(repo, "src", "m1.ts"), "export const v1 = 100;\n", "utf8");
+ expect((await ingestWith({ force: true })).incremental).toBe(false);
+ });
+
+ it("is false when the DB-reset guard fires", async () => {
+ await ingest();
+ backend.hashes.clear();
+ writeFileSync(join(repo, "src", "m1.ts"), "export const v1 = 100;\n", "utf8");
+ expect((await ingest()).incremental).toBe(false);
+ });
+
+ it("is false for an extractor rebuild", async () => {
+ await ingest();
+ const baseline = JSON.parse(readFileSync(ingestMtimeCachePath(repo), "utf8"));
+ writeFileSync(ingestMtimeCachePath(repo), JSON.stringify({ ...baseline, extractor: "tree-sitter/0.1" }));
+ writeFileSync(join(repo, "src", "m1.ts"), "export const v1 = 100;\n", "utf8");
+ expect((await ingest()).incremental).toBe(false);
+ });
+
+ it("is false for a run with commit errors", async () => {
+ await ingest();
+ writeFileSync(join(repo, "src", "m0.ts"), "export const v0 = 100;\n", "utf8");
+ writeFileSync(join(repo, "src", "m1.ts"), "export const v1 = 100;\n", "utf8");
+ backend.failUris.add("src/m1.ts");
+ const summary = await ingest();
+ expect(summary.commitErrors).toBeGreaterThan(0);
+ expect(summary.incremental).toBe(false);
+ process.exitCode = undefined;
+ });
+ });
+
it("reports an ingest that wrote nothing as unchanged, and one that wrote as changed", async () => {
expect((await ingest()).graphUnchanged).toBe(false);
expect((await ingest()).graphUnchanged).toBe(true);
diff --git a/ix-cli/src/cli/__tests__/region-readers-refresh.test.ts b/ix-cli/src/cli/__tests__/region-readers-refresh.test.ts
new file mode 100644
index 00000000..d633fcfb
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/region-readers-refresh.test.ts
@@ -0,0 +1,169 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Command } from "commander";
+
+/**
+ * CL-13: `ix map` may defer the map after an edit, so every command that reads
+ * regions calls `ensureFreshMap` first, which starts a background refresh and
+ * never maps inline. These run each reader against a stub client and check
+ * three things: it is asked for exactly once, before the first region read,
+ * and a refresh that cannot start changes neither the output nor the exit
+ * code.
+ */
+
+// The suite runs from a checkout no workspace covers; it is about ordering,
+// not scoping, so the directory counts as mapped.
+vi.mock("../bootstrap.js", async (orig) => ({
+ ...(await orig<typeof import("../bootstrap.js")>()),
+ resolveWorkspaceId: () => "ws-test",
+}));
+
+vi.mock("../config.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../config.js")>(),
+ readStitchScope: () => ({ systemId: null }),
+ writeStitchScope: vi.fn(),
+}));
+
+const { events, refreshImpl } = vi.hoisted(() => ({
+ events: [] as string[],
+ refreshImpl: { current: async (): Promise<unknown> => undefined },
+}));
+
+vi.mock("../map-freshness.js", async (orig) => ({
+ ...(await orig<typeof import("../map-freshness.js")>()),
+ ensureFreshMap: vi.fn(async () => {
+ events.push("refresh");
+ await refreshImpl.current();
+ }),
+}));
+
+vi.mock("../hierarchy.js", async (orig) => {
+ const actual = await orig<typeof import("../hierarchy.js")>();
+ return {
+ ...actual,
+ getSystemPath: async () => { events.push("region-read"); return []; },
+ getEffectiveSystemPath: async () => { events.push("region-read"); return []; },
+ bucketByHierarchy: async () => { events.push("region-read"); return []; },
+ };
+});
+
+const NODE = {
+ id: "node-1", kind: "function", name: "Target",
+ provenance: { sourceUri: "src/a.ts" }, attrs: { line_start: 1, line_end: 3 },
+};
+
+/** A client that answers anything; region-shaped reads are logged. */
+vi.mock("../../client/api.js", () => {
+ const regionReads = new Set(["getSubsystemMap", "listSubsystems", "subsystemScores", "subsystems"]);
+ const answers: Record<string, (...a: unknown[]) => unknown> = {
+ search: () => [NODE],
+ entity: () => ({ node: NODE, edges: [], claims: [], decisions: [] }),
+ workspaceSystem: () => ({ systemId: null }),
+ stats: () => ({ nodes: { total: 10, byKind: [] }, edges: { total: 10, byPredicate: [] } }),
+ currentRevision: () => 1,
+ health: () => ({ status: "ok" }),
+ getSubsystemMap: () => ({ file_count: 0, region_count: 0, levels: 0, map_rev: 1, regions: [], hierarchy: [] }),
+ };
+ class IxClient {
+ endpoint = "http://127.0.0.1:1";
+ constructor() {
+ return new Proxy(this, {
+ get(target, prop) {
+ if (prop in target) return (target as any)[prop];
+ if (typeof prop !== "string" || prop === "then") return undefined;
+ return async (...args: unknown[]) => {
+ if (regionReads.has(prop)) events.push("region-read");
+ const answer = answers[prop];
+ return answer ? answer(...args) : { nodes: [], edges: [], results: [] };
+ };
+ },
+ });
+ }
+ }
+ return { IxClient, LocalTokenRequiredError: class extends Error {} };
+});
+
+type Register = (program: Command) => void;
+
+const READERS: ReadonlyArray<readonly [string, string[], () => Promise<Register>]> = [
+ ["overview", ["overview", "Target"], async () => (await import("../commands/overview.js")).registerOverviewCommand],
+ ["impact", ["impact", "Target"], async () => (await import("../commands/impact.js")).registerImpactCommand],
+ ["locate", ["locate", "Target"], async () => (await import("../commands/locate.js")).registerLocateCommand],
+ ["subsystems", ["subsystems"], async () => (await import("../commands/subsystems.js")).registerSubsystemsCommand],
+ ["explain", ["explain", "Target"], async () => (await import("../commands/explain.js")).registerExplainCommand],
+];
+
+async function run(register: Register, args: string[]): Promise<string> {
+ const program = new Command().name("ix").exitOverride();
+ register(program);
+ const out: string[] = [];
+ const log = vi.spyOn(console, "log").mockImplementation((...parts) => { out.push(parts.join(" ")); });
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ const write = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
+ try {
+ await program.parseAsync([...args, "--format", "json"], { from: "user" });
+ } finally {
+ log.mockRestore();
+ error.mockRestore();
+ write.mockRestore();
+ }
+ return out.join("\n");
+}
+
+describe.each(READERS)("ix %s refreshes a deferred map first", (_name, args, load) => {
+ let home = "";
+ const saved: Record<string, string | undefined> = {};
+
+ beforeEach(() => {
+ events.length = 0;
+ refreshImpl.current = async () => undefined;
+ process.exitCode = undefined;
+ home = mkdtempSync(join(tmpdir(), "ix-readers-refresh-"));
+ for (const k of ["IX_HOME", "IX_GRAPH_HEALTH", "IX_MAP_BACKGROUND_REFRESH", "IX_LOCK_DIR"]) saved[k] = process.env[k];
+ process.env.IX_LOCK_DIR = join(home, "locks");
+ process.env.IX_HOME = home;
+ process.env.IX_GRAPH_HEALTH = "0";
+ });
+
+ afterEach(() => {
+ process.exitCode = undefined;
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ it("asks once, before the first region read", async () => {
+ await run(await load(), args);
+ expect(events.filter(e => e === "refresh")).toHaveLength(1);
+ expect(events.indexOf("refresh")).toBe(0);
+ expect(events, "the command did read regions").toContain("region-read");
+ });
+
+ it("answers the same, with the same exit code, when the refresh fails inside", async () => {
+ const register = await load();
+ const fine = await run(register, args);
+ const fineExit = process.exitCode;
+ expect(fine.length, "the reader printed its answer").toBeGreaterThan(0);
+
+ // The real thing, made to fail where it starts the background refresh:
+ // whatever goes wrong there, the reader must not see it.
+ const real = await vi.importActual<typeof import("../map-freshness.js")>("../map-freshness.js");
+ real.markMapStale(join(home, "repo"), { ingestRev: 1 });
+ let spawnAsked = 0;
+ process.env.IX_MAP_BACKGROUND_REFRESH = "1";
+ refreshImpl.current = () => real.ensureFreshMap({
+ root: join(home, "repo"),
+ spawn: () => { spawnAsked++; throw new Error("spawn EAGAIN"); },
+ });
+ const failed = await run(register, args);
+ expect(spawnAsked, "the reader got as far as starting the refresh").toBe(1);
+ expect(failed).toBe(fine);
+ expect(process.exitCode).toBe(fineExit);
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/stale-workspace.test.ts b/ix-cli/src/cli/__tests__/stale-workspace.test.ts
index d7d97342..e3f7000f 100644
--- a/ix-cli/src/cli/__tests__/stale-workspace.test.ts
+++ b/ix-cli/src/cli/__tests__/stale-workspace.test.ts
@@ -10,6 +10,7 @@ import { clearIngestMtimeCache, clearMapBaseline, ingestMtimeCachePath, saveConf
import { loadIngestBaseline } from "../ingest-baseline.js";
import { saveMapBaseline } from "../map-baseline.js";
import { persistIngestBaselineIfClean } from "../commands/ingest.js";
+import { markMapStale, readMapStale } from "../map-freshness.js";
import {
createStaleProbe,
detectStaleFiles,
@@ -73,6 +74,8 @@ describe("workspace-scoped staleness", () => {
expect(beforeB).toEqual({
graphCompleted: true,
mapCompleted: false,
+ mapStale: false,
+ mapRefreshError: null,
lastIngestAt: ingestedA.toISOString(),
currentRev: 11,
staleFiles: 1,
@@ -138,6 +141,8 @@ describe("workspace-scoped staleness", () => {
expect(detectStaleFiles(root)).toEqual({
graphCompleted: false,
mapCompleted: false,
+ mapStale: false,
+ mapRefreshError: null,
lastIngestAt: null,
currentRev: 0,
staleFiles: 0,
@@ -181,6 +186,44 @@ describe("workspace-scoped staleness", () => {
});
});
+ it("reports a map deferred after an edit as stale, without calling it completed", () => {
+ const root = path.join(home, "deferred");
+ const filePath = writeSource(root, "deferred.js", "export const value = 1;\n");
+ persistIngestBaselineIfClean(
+ root,
+ new Map([[filePath, fs.statSync(filePath).mtimeMs]]),
+ 7,
+ 0,
+ 0,
+ new Date("2026-08-24T12:00:00.000Z"),
+ );
+ expect(saveMapBaseline(root, 6)).toBe(true);
+ expect(detectStaleFiles(root)).toMatchObject({ mapCompleted: false, mapStale: false });
+
+ markMapStale(root);
+ expect(readMapStale(root)?.ingestRev).toBe(7);
+ // mapCompleted keeps its strict meaning; mapStale says why it is false.
+ expect(detectStaleFiles(root)).toMatchObject({ mapCompleted: false, mapStale: true });
+ });
+
+ it("drops the stale marker with the map baseline and with the ingest baseline", () => {
+ const root = path.join(home, "marker-cleared");
+ markMapStale(root, { ingestRev: 3 });
+ expect(readMapStale(root)).not.toBeNull();
+ clearMapBaseline(root);
+ expect(readMapStale(root)).toBeNull();
+
+ markMapStale(root, { ingestRev: 3 });
+ clearIngestMtimeCache(root);
+ expect(readMapStale(root)).toBeNull();
+ });
+
+ it("reads no stale map for a workspace with no baseline, marker or not", () => {
+ const root = path.join(home, "never-ingested");
+ markMapStale(root, { ingestRev: null });
+ expect(detectStaleFiles(root).mapStale).toBe(false);
+ });
+
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");
@@ -201,6 +244,8 @@ describe("workspace-scoped staleness", () => {
expect(detectStaleFiles(root)).toEqual({
graphCompleted: true,
mapCompleted: false,
+ mapStale: false,
+ mapRefreshError: null,
lastIngestAt: "2026-08-24T12:00:00.000Z",
currentRev: 26,
staleFiles: 0,
@@ -275,6 +320,8 @@ describe("workspace-scoped staleness", () => {
expect(detectStaleFiles(root)).toEqual({
graphCompleted: true,
mapCompleted: false,
+ mapStale: false,
+ mapRefreshError: null,
lastIngestAt: ingestedAt.toISOString(),
currentRev: 14,
staleFiles: 1,
diff --git a/ix-cli/src/cli/__tests__/status-doctor-honest.test.ts b/ix-cli/src/cli/__tests__/status-doctor-honest.test.ts
index c978cfc4..6f8dc184 100644
--- a/ix-cli/src/cli/__tests__/status-doctor-honest.test.ts
+++ b/ix-cli/src/cli/__tests__/status-doctor-honest.test.ts
@@ -122,10 +122,18 @@ describe("ix status", () => {
beforeEach(() => { lastIngestAt = null; });
async function status(...args: string[]): Promise<string> {
+ return statusWith({}, ...args);
+ }
+
+ async function statusWith(
+ info: { mapCompleted?: boolean; mapStale?: boolean; mapRefreshError?: string | null },
+ ...args: string[]
+ ): Promise<string> {
vi.doMock("../stale.js", async (orig) => ({
...(await orig<typeof import("../stale.js")>()),
detectStaleFiles: () => ({
- graphCompleted: true, mapCompleted: true, currentRev: 7, lastIngestAt,
+ graphCompleted: true, mapCompleted: info.mapCompleted ?? true, mapStale: info.mapStale ?? false, mapRefreshError: info.mapRefreshError ?? null,
+ currentRev: 7, lastIngestAt,
staleFiles: 0, sampleChangedFiles: [], replayedFiles: [], parseTimeouts: [],
}),
}));
@@ -160,6 +168,58 @@ describe("ix status", () => {
expect(llm).toMatch(/^graph status=empty reason=no_nodes/m);
});
+ it("reports a map deferred after an edit as stale, in every format (CL-13)", async () => {
+ registerRepo();
+ stats = { nodes: { total: 10 }, edges: { total: 10 } };
+ const stale = { mapCompleted: false, mapStale: true };
+ const json = JSON.parse(await statusWith(stale, "--format", "json"));
+ expect(json.mapCompleted).toBe(false);
+ expect(json.mapStale).toBe(true);
+
+ out.length = 0;
+ const llm = await statusWith(stale, "--format", "llm");
+ expect(llm).toMatch(/^status .*map_complete=false.*map_stale=true/m);
+
+ out.length = 0;
+ const text = await statusWith(stale);
+ expect(text).toMatch(/Map:\s+stale/);
+ expect(text).toMatch(/ix map --remap/);
+ expect(text).not.toMatch(/No completed architecture map/);
+ });
+
+ it("reports why the last background map refresh failed, in every format", async () => {
+ registerRepo();
+ stats = { nodes: { total: 10 }, edges: { total: 10 } };
+ const failed = { mapCompleted: false, mapStale: true, mapRefreshError: "timed out after 300 s" };
+ const json = JSON.parse(await statusWith(failed, "--format", "json"));
+ expect(json.mapRefreshError).toBe("timed out after 300 s");
+
+ out.length = 0;
+ const llm = await statusWith(failed, "--format", "llm");
+ expect(llm).toMatch(/map_stale=true map_refresh_error="timed out after 300 s"/);
+
+ out.length = 0;
+ const text = await statusWith(failed);
+ expect(text).toMatch(/last background map refresh failed: timed out after 300 s/);
+ expect(text).toMatch(/ix map --remap/);
+ });
+
+ it("keeps the incomplete-map warning when the map is not merely stale", async () => {
+ registerRepo();
+ stats = { nodes: { total: 10 }, edges: { total: 10 } };
+ const json = JSON.parse(await statusWith({ mapCompleted: false }, "--format", "json"));
+ expect(json.mapStale).toBe(false);
+
+ out.length = 0;
+ const llm = await statusWith({ mapCompleted: false }, "--format", "llm");
+ expect(llm).not.toMatch(/map_stale/);
+
+ out.length = 0;
+ const text = await statusWith({ mapCompleted: false });
+ expect(text).toMatch(/No completed architecture map/);
+ expect(text).not.toMatch(/Map:\s+stale/);
+ });
+
it("shows the last ix verify, and warns when it found divergence", async () => {
registerRepo();
stats = HOLLOW;
@@ -315,6 +375,78 @@ describe("doctor checks", () => {
expect(assessConfigFile("c.yaml", () => "- a\n- b\n")).toMatchObject({ ok: false });
});
+ it("Completed map: a map deferred after an edit warns, an incomplete one still fails (CL-13)", async () => {
+ const { assessMapCompletion } = await import("../commands/doctor.js");
+ const { persistIngestBaselineIfClean } = await import("../commands/ingest.js");
+ const { saveMapBaseline } = await import("../map-baseline.js");
+ const { markMapStale } = await import("../map-freshness.js");
+ const file = join(repo, "a.ts");
+ writeFileSync(file, "export const a = 1;\n");
+ const local = async () => false;
+
+ expect(await assessMapCompletion(repo, local)).toMatchObject({ ok: false });
+ expect((await assessMapCompletion(repo, local)).warn).toBeUndefined();
+
+ persistIngestBaselineIfClean(repo, new Map([[file, 1]]), 5, 0, 0, new Date());
+ expect(saveMapBaseline(repo, 5)).toBe(true);
+ expect(await assessMapCompletion(repo, local)).toMatchObject({ ok: true });
+
+ // An edit: the source moves on to revision 6 and `ix map` defers the map.
+ persistIngestBaselineIfClean(repo, new Map([[file, 2]]), 6, 0, 0, new Date());
+ const incomplete = await assessMapCompletion(repo, local);
+ expect(incomplete).toMatchObject({ ok: false, detail: expect.stringMatching(/revision 6/) });
+ expect(incomplete.warn, "not merely stale: still a failure").toBeUndefined();
+
+ markMapStale(repo);
+ expect(await assessMapCompletion(repo, local))
+ .toEqual({ ok: false, warn: true, detail: expect.stringMatching(/stale \(deferred after an edit\); a region view refreshes it in the background/) });
+
+ // A refresh was started for that deferral and has not cleared it yet:
+ // still the design working.
+ const { mapStalePath } = await import("../config.js");
+ writeFileSync(mapStalePath(repo), JSON.stringify({ since: 1, ingestRev: 6, lastAttemptAt: 2 }));
+ expect(await assessMapCompletion(repo, local)).toMatchObject({ ok: false, warn: true });
+ });
+
+ it("Completed map: a failed background refresh is a warning with its reason, not a failure", async () => {
+ const { assessMapCompletion } = await import("../commands/doctor.js");
+ const { persistIngestBaselineIfClean } = await import("../commands/ingest.js");
+ const { saveMapBaseline } = await import("../map-baseline.js");
+ const { markMapStale } = await import("../map-freshness.js");
+ const { mapRefreshOutcomePath } = await import("../config.js");
+ const file = join(repo, "a.ts");
+ writeFileSync(file, "export const a = 1;\n");
+ const local = async () => false;
+ persistIngestBaselineIfClean(repo, new Map([[file, 1]]), 5, 0, 0, new Date());
+ expect(saveMapBaseline(repo, 5)).toBe(true);
+ persistIngestBaselineIfClean(repo, new Map([[file, 2]]), 6, 0, 0, new Date());
+ markMapStale(repo);
+
+ // What `runBackgroundMapRefresh` records when the map outlives its limit.
+ writeFileSync(mapRefreshOutcomePath(repo), JSON.stringify({
+ startedAt: 1, finishedAt: 2, ok: false, reason: "timed out after 300 s", pid: 1,
+ }));
+ const failed = await assessMapCompletion(repo, local);
+ expect(failed).toEqual({
+ ok: false,
+ warn: true,
+ detail: "architecture map is stale; its last background refresh failed (timed out after 300 s) — run `ix map --remap`",
+ });
+ });
+
+ it("Completed map: a stale map with no map ever completed still fails", async () => {
+ const { assessMapCompletion } = await import("../commands/doctor.js");
+ const { persistIngestBaselineIfClean } = await import("../commands/ingest.js");
+ const { markMapStale } = await import("../map-freshness.js");
+ const file = join(repo, "a.ts");
+ writeFileSync(file, "export const a = 1;\n");
+ persistIngestBaselineIfClean(repo, new Map([[file, 1]]), 5, 0, 0, new Date());
+ markMapStale(repo);
+ const never = await assessMapCompletion(repo, async () => false);
+ expect(never).toMatchObject({ ok: false, detail: expect.stringMatching(/no architecture map has ever completed/) });
+ expect(never.warn).toBeUndefined();
+ });
+
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 () => ({
diff --git a/ix-cli/src/cli/__tests__/view-server.test.ts b/ix-cli/src/cli/__tests__/view-server.test.ts
index 1155accd..5a58ca21 100644
--- a/ix-cli/src/cli/__tests__/view-server.test.ts
+++ b/ix-cli/src/cli/__tests__/view-server.test.ts
@@ -75,7 +75,7 @@ describe("view server (/__ix/remap)", () => {
// behind whenever a run was interrupted before cleanup.
marker = join(distDir, "stub-ran.txt");
- // A stub `ix` CLI main: the server runs `node <MAP_MAIN> map <root> --silent`.
+ // A stub `ix` CLI main: the server runs `node <MAP_MAIN> map <root> --silent --remap`.
// STUB_MS holds it open so overlapping requests are observable; STUB_EXIT
// drives the failure path.
// `.cjs` for the same reason the server script is: this stub is CommonJS
@@ -239,9 +239,10 @@ describe("view server (/__ix/remap)", () => {
const res = await post("/__ix/remap", { host: `127.0.0.1:${port}` });
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ ok: true });
- // The recorded workspace root, never the server's own cwd, and --silent
- // because nothing reads the output.
- expect(runs()).toEqual([`map ${mapRoot} --silent`]);
+ // The recorded workspace root, never the server's own cwd, --silent
+ // because nothing reads the output, and --remap so an automatic map's
+ // deferral (CL-13) can never turn the Remap button into a no-op.
+ expect(runs()).toEqual([`map ${mapRoot} --silent --remap`]);
});
it("uses the argv CLI path outside the test-only MAP_MAIN override", async () => {
@@ -250,7 +251,7 @@ describe("view server (/__ix/remap)", () => {
resetRuns();
const res = await post("/__ix/remap", { host: `127.0.0.1:${port}` });
expect(res.status).toBe(200);
- expect(runs()).toEqual([`map ${mapRoot} --silent`]);
+ expect(runs()).toEqual([`map ${mapRoot} --silent --remap`]);
} finally {
await startServer({ STUB_EXIT: "0" });
}
diff --git a/ix-cli/src/cli/commands/doctor.ts b/ix-cli/src/cli/commands/doctor.ts
index a147871c..dc173c3a 100644
--- a/ix-cli/src/cli/commands/doctor.ts
+++ b/ix-cli/src/cli/commands/doctor.ts
@@ -40,6 +40,8 @@ import { backendCeiling, isNewer, readBackendHealth } from "./upgrade.js";
import { loadIngestBaseline } from "../ingest-baseline.js";
import { isCloudReady } from "../remote.js";
import { hasCompletedMapBaseline } from "../stale.js";
+import { readMapRefreshOutcome, readMapStale } from "../map-freshness.js";
+import { loadMapBaseline } from "../map-baseline.js";
import { printJson } from "../format.js";
import { runVerify, type VerifyReport } from "../verify.js";
import { healthFromError } from "../database-probe.js";
@@ -349,6 +351,68 @@ function workspaceOrNone(lookup: () => WorkspaceConfig | undefined): WorkspaceCo
}
}
+/**
+ * The "Completed map for this workspace" check, for one resolved root.
+ * Exported for tests.
+ */
+export async function assessMapCompletion(
+ root: string,
+ cloudReady: () => Promise<boolean> = isCloudReady,
+): Promise<CheckResult> {
+ const source = loadIngestBaseline(root);
+ if (!source) {
+ // No local baseline means one of: never mapped, an initial map
+ // that committed patches but never finished, or a workspace fed
+ // by the cloud runner — which writes none by design. Only the
+ // last is healthy, and only a registered runner makes it
+ // possible, so that is the one case this warns instead of fails.
+ const cloud = await cloudReady();
+ return cloud
+ ? { ok: false, warn: true, detail: "no local baseline — expected for a cloud-ingested workspace" }
+ : { ok: false, detail: "no completed map baseline — the graph may be partial. Run `ix map`." };
+ }
+ if (!hasCompletedMapBaseline(root)) {
+ // CL-13: an `ix map` after an edit defers the map, so the
+ // marker trails the source revision until a region view
+ // refreshes it. That is the design working, not a partial map,
+ // and failing here would make `ix doctor` exit 1 after every edit.
+ const stale = readMapStale(root);
+ if (stale !== null) {
+ // Deferred maps are only ever served from a map that completed once;
+ // without one there is nothing to be merely stale against.
+ if (loadMapBaseline(root) === null && loadMapBaseline(canonicalWorkspacePath(root)) === null) {
+ return {
+ ok: false,
+ detail: "no architecture map has ever completed for this workspace — run `ix map --remap`",
+ };
+ }
+ // A background refresh that failed is reported, not failed on: a
+ // map that takes longer than the refresh's limit, or a backend that was
+ // briefly down, must not keep `ix doctor` exiting 1 after every edit.
+ // The regions are the last completed map's, and `--remap` brings them
+ // up to date.
+ const last = readMapRefreshOutcome(root);
+ if (last?.ok === false) {
+ return {
+ ok: false,
+ warn: true,
+ detail: `architecture map is stale; its last background refresh failed (${last.reason ?? "no reason recorded"}) — run \`ix map --remap\``,
+ };
+ }
+ return {
+ ok: false,
+ warn: true,
+ detail: "architecture map is stale (deferred after an edit); a region view refreshes it in the background, or run `ix map --remap`",
+ };
+ }
+ return {
+ ok: false,
+ detail: `source graph at revision ${source.currentRev} has no completed architecture map — run \`ix map\``,
+ };
+ }
+ return { ok: true, detail: `recorded at revision ${source.currentRev}` };
+}
+
/** "ripgrep on PATH": `ix text` needs it; everything else works without it. */
export function checkRipgrep(run: () => string = () => execFileSync("rg", ["--version"], { encoding: "utf-8", timeout: 5000 })): CheckResult {
try {
@@ -597,26 +661,7 @@ export function registerDoctorCommand(program: Command): void {
try {
// Resolve once: both marker files are keyed by the exact root
// string, and `hasCompletedMapBaseline` resolves internally.
- const root = resolvePath(matchedWorkspace.root_path);
- const source = loadIngestBaseline(root);
- if (!source) {
- // No local baseline means one of: never mapped, an initial map
- // that committed patches but never finished, or a workspace fed
- // by the cloud runner — which writes none by design. Only the
- // last is healthy, and only a registered runner makes it
- // possible, so that is the one case this warns instead of fails.
- const cloud = await isCloudReady();
- return cloud
- ? { ok: false, warn: true, detail: "no local baseline — expected for a cloud-ingested workspace" }
- : { ok: false, detail: "no completed map baseline — the graph may be partial. Run `ix map`." };
- }
- if (!hasCompletedMapBaseline(root)) {
- return {
- ok: false,
- detail: `source graph at revision ${source.currentRev} has no completed architecture map — run \`ix map\``,
- };
- }
- return { ok: true, detail: `recorded at revision ${source.currentRev}` };
+ return await assessMapCompletion(resolvePath(matchedWorkspace.root_path));
} catch (e: any) {
return { ok: false, detail: e.message ?? "map completion check failed" };
}
diff --git a/ix-cli/src/cli/commands/explain.ts b/ix-cli/src/cli/commands/explain.ts
index 365ee52d..57bfae5f 100644
--- a/ix-cli/src/cli/commands/explain.ts
+++ b/ix-cli/src/cli/commands/explain.ts
@@ -14,6 +14,7 @@ import { renderExplainLlm, renderExplainRawLlm } from "../explain/llm.js";
import { printLlmLines } from "../llm.js";
import { parsePickOption } from "../options.js";
import { renderSection, renderWarning, renderNote } from "../ui.js";
+import { ensureFreshMap } from "../map-freshness.js";
import { forMcp, toolCall } from "../next-step.js";
import {
assessTargetStructure, checkGraphHealth, graphHealthJson, graphHealthProse, isUnhealthy, worseHealth,
@@ -40,6 +41,12 @@ export function registerExplainCommand(program: Command): void {
return;
}
+ // The facts below include the target's system > subsystem > module
+ // path, read from the map's regions; an `ix map` after an edit may have
+ // left the map for this read (CL-13). Never throws and never moves the
+ // exit code; with no deferred map it is one file check.
+ await ensureFreshMap();
+
// New pipeline: collect facts → infer role → infer importance → render.
// The workspace health check runs alongside: cached per backend
// revision, so on a warm cache it is one ~10 ms request in parallel.
diff --git a/ix-cli/src/cli/commands/impact.ts b/ix-cli/src/cli/commands/impact.ts
index 99e9802f..e24009d1 100644
--- a/ix-cli/src/cli/commands/impact.ts
+++ b/ix-cli/src/cli/commands/impact.ts
@@ -14,6 +14,7 @@ import { captureJson, lineSpan, printJson, relativePath, rowLocation, sliceEdgeR
import { forMcp, suggest, type Relation } from "../next-step.js";
import { llmLine, llmShortId } from "../llm.js";
import { parsePickOption } from "../options.js";
+import { ensureFreshMap } from "../map-freshness.js";
const CONTAINER_KINDS = new Set(["class", "module", "file", "object", "trait", "interface"]);
@@ -49,6 +50,10 @@ export function registerImpactCommand(program: Command): void {
if (opts.format === "text" && !set.all) printResolved(target);
+ // An `ix map` after an edit may have left the map for this read (CL-13).
+ // Never throws and never moves the exit code.
+ await ensureFreshMap();
+
// A hollowed graph reports "low risk, no dependents" for anything:
// the answer is only as good as the edges it counts. Said first, in
// every format, before the counts it undermines.
diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.ts
index 036cc1f0..bce9d307 100644
--- a/ix-cli/src/cli/commands/ingest.ts
+++ b/ix-cli/src/cli/commands/ingest.ts
@@ -1739,6 +1739,19 @@ export interface IngestFilesSummary {
* something must not claim the graph is where it was.
*/
graphUnchanged: boolean;
+ /**
+ * True only when this run was an ordinary incremental update of a graph
+ * whose baseline it trusted: a local baseline existed (Path A), nothing was
+ * forced or migrated, the DB-reset guard and an extractor rebuild did not
+ * fire, at least one file changed or was deleted, and nothing failed to
+ * parse or commit.
+ *
+ * `ix map` reads it to decide whether it may defer `/v1/map` to the next
+ * command that reads regions (CL-13). It errs towards false: a run that
+ * might have left the graph somewhere unexpected computes the map, so the
+ * completed-map diagnostics still see every run that had errors.
+ */
+ incremental: boolean;
/**
* Files tree-sitter parsed with ERROR or MISSING nodes. They are in the
* graph, but whatever sat in the broken region may not be. Not counted in
@@ -2507,6 +2520,8 @@ export async function ingestFiles(
let graphStartedEmpty: boolean | undefined;
let extractorRebuild = false;
let deletionsFound = false;
+ // Path A with a local baseline: the run updated a graph it already knew.
+ let baselineRun = false;
let stitchSent = false;
let filesSkipped = 0;
/**
@@ -4334,6 +4349,7 @@ export async function ingestFiles(
// calls as a whole-repository pass would.
const hasBaseline = previousBaseline !== null && mtimeCache.size > 0;
const incrementalRun = (hasBaseline || knownHashes.size > 0 || mtimeChangedPaths.length === 0) && !opts.force;
+ baselineRun = hasBaseline && incrementalRun;
if (incrementalRun) {
// Path A: has baseline or all mtime-clean → pre-scan to detect changes before loading modules.
// If nothing changed, module load is skipped entirely. A file with no
@@ -5226,6 +5242,14 @@ export async function ingestFiles(
parseErrors + crashedParses() === 0 &&
commitErrors === 0 &&
stitchErrors === 0,
+ incremental:
+ baselineRun &&
+ opts.force !== true &&
+ !workspaceMigrated &&
+ !dbResetDetected &&
+ !extractorRebuild &&
+ (filesChanged > 0 || deletionsFound) &&
+ parseErrors + crashedParses() + commitErrors === 0,
};
if (cutoffFired) {
// Gated on the cutoff having FIRED, not on what was left unsent. A patch
diff --git a/ix-cli/src/cli/commands/locate.ts b/ix-cli/src/cli/commands/locate.ts
index 534561d2..7e5e6cf3 100644
--- a/ix-cli/src/cli/commands/locate.ts
+++ b/ix-cli/src/cli/commands/locate.ts
@@ -20,6 +20,7 @@ import { getEffectiveSystemPath, hasMapData } from "../hierarchy.js";
import { humanizeLabel } from "../impact/risk-semantics.js";
import { renderSection, renderKeyValue, renderNote, renderWarning, renderBreadcrumb, reportAmbiguousTarget, reportResolutionNotices } from "../ui.js";
import { forMcp } from "../next-step.js";
+import { ensureFreshMap } from "../map-freshness.js";
const CONTAINER_KINDS = new Set(["class", "module", "file", "trait", "object", "interface"]);
const FILE_KINDS = new Set(["file"]);
@@ -63,7 +64,12 @@ Several symbols answer in one call, grouped per symbol (json: {targets: [...]}).
${EXIT_CODES_HELP}`)
.action(async (symbols: string[], opts: { kind?: string; path?: string; pick?: number; format: string }) => {
const client = createClient();
- await runPerTarget(symbols, opts.format, (symbol) => locateOne(client, symbol, opts));
+ // An `ix map` after an edit may have left the map for the system paths
+ // read below (CL-13). Checked once per call, on the first target that
+ // resolves, so several targets print at most one stale-map notice.
+ let mapChecked: Promise<unknown> | undefined;
+ const freshMap = (): Promise<unknown> => (mapChecked ??= ensureFreshMap());
+ await runPerTarget(symbols, opts.format, (symbol) => locateOne(client, symbol, opts, freshMap));
});
}
@@ -71,6 +77,7 @@ async function locateOne(
client: IxClient,
symbol: string,
opts: { kind?: string; path?: string; pick?: number; format: string },
+ freshMap: () => Promise<unknown>,
): Promise<void> {
const diagnostics: string[] = [];
@@ -120,6 +127,9 @@ async function locateOne(
const isContainer = CONTAINER_KINDS.has(target.kind);
const isFile = FILE_KINDS.has(target.kind);
+ // Never throws and never moves the exit code.
+ await freshMap();
+
// Parallel fetch: effective system path, parent container (for non-containers), entity details
const [systemPath, containsResult, details] = await Promise.all([
getEffectiveSystemPath(client, target.id),
diff --git a/ix-cli/src/cli/commands/map.ts b/ix-cli/src/cli/commands/map.ts
index 140dcf48..f63b883b 100644
--- a/ix-cli/src/cli/commands/map.ts
+++ b/ix-cli/src/cli/commands/map.ts
@@ -15,9 +15,12 @@ import { acquireMapLock, requestMapRerun, takeMapRerun } from "../single-flight.
import { canRenderProgress } from "../stderr.js";
import { loadIngestBaseline } from "../ingest-baseline.js";
import { saveMapBaseline } from "../map-baseline.js";
-import { loadCachedMap, resolveMapCacheSlot, saveCachedMap } from "../map-result-cache.js";
+import { loadCachedMap, loadLastMap, resolveMapCacheSlot, saveCachedMap } from "../map-result-cache.js";
+import { clearMapStale, markMapStale, readMapStale } from "../map-freshness.js";
import { resolveMapRoot } from "../map-root.js";
import { readBackendHealth } from "./upgrade.js";
+import { renderWarning } from "../ui.js";
+import type { IxClient } from "../../client/api.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
@@ -38,7 +41,7 @@ export function mapDeadlineMs(raw = process.env.IX_MAP_DEADLINE_MS): number | un
return budget;
}
-function mapDeadlineSignal(): AbortSignal | undefined {
+export function mapDeadlineSignal(): AbortSignal | undefined {
const budget = mapDeadlineMs();
return budget === undefined ? undefined : AbortSignal.timeout(budget);
}
@@ -74,6 +77,44 @@ export function applyRequestedMapCoalesceExitCode(
return true;
}
+/**
+ * Whether an automatic `ix map` (IX_AUTO_MAP=1) computes the map even after an
+ * incremental edit, as it did before CL-13. IX_MAP_EAGER=1 restores that for
+ * a hook that reads regions straight from `ix map` and cannot run a region
+ * view to refresh them. An `ix map` run by hand always computes.
+ */
+export function mapEager(raw = process.env.IX_MAP_EAGER): boolean {
+ return raw === "1";
+}
+
+/**
+ * The `/v1/map` request for `cwd`: workspace-scoped, or system-scoped when it
+ * is part of a multi-repo system. Shared by `ix map` and `ensureFreshMap`, so a
+ * lazily recomputed map asks for exactly what `ix map` would.
+ *
+ * A co-ingest system is found locally (`detectSystem`); a SEPARATELY-ingested
+ * repo that the stitcher joined into a system (Path-2 grouping, Ix#225 Half B)
+ * has no local marker, so its system_id is looked up from the backend, making
+ * `ix map <repo>` show the whole stitched system. That lookup is best-effort:
+ * an unanswered one leaves the map at workspace scope.
+ */
+export async function resolveMapScope(
+ client: Pick<IxClient, "workspaceSystem">,
+ cwd: string,
+ full: boolean | undefined,
+ systemId: string | undefined = detectSystem(cwd)?.systemId,
+): Promise<{ full?: boolean; workspaceId?: string; systemId?: string }> {
+ let effectiveSystemId = systemId;
+ if (!effectiveSystemId) {
+ const ws = resolveWorkspaceId(cwd);
+ if (ws) {
+ const looked = await client.workspaceSystem(ws).catch(() => ({ systemId: null }));
+ if (looked.systemId) effectiveSystemId = looked.systemId;
+ }
+ }
+ return { full, workspaceId: effectiveSystemId ? undefined : resolveWorkspaceId(cwd), systemId: effectiveSystemId };
+}
+
/** Watch opts into full patches; ordinary `ix map` keeps its topology-only ingest. */
export function mapModeForIngest(raw = process.env.IX_MAP_FULL_INGEST): boolean {
return raw !== "1";
@@ -302,15 +343,17 @@ function emitDroppedFileWarning(
/**
* The one stderr line `ix map --silent` prints. `too_large=N` appears only
- * when files were left out for size, so a repo without any keeps the line it
- * always had. Exported for tests.
+ * when files were left out for size, and `map=stale` only when the map was
+ * deferred after an edit (CL-13), both after every other token, so a repo
+ * without either keeps the line it always had. Exported for tests.
*/
export function silentSummaryLine(s: {
files: number; systems: number; subsystems: number; modules: number; mapMs: number;
- stitch: string; filesTooLarge?: number;
+ stitch: string; filesTooLarge?: number; mapStale?: boolean;
}): string {
const tooLarge = (s.filesTooLarge ?? 0) > 0 ? ` · too_large=${s.filesTooLarge}` : "";
- return `map: ${s.files} files · ${s.systems}s/${s.subsystems}ss/${s.modules}m regions · ${s.mapMs}ms${s.stitch}${tooLarge}\n`;
+ const stale = s.mapStale ? " · map=stale" : "";
+ return `map: ${s.files} files · ${s.systems}s/${s.subsystems}ss/${s.modules}m regions · ${s.mapMs}ms${s.stitch}${tooLarge}${stale}\n`;
}
/**
@@ -404,6 +447,7 @@ export function registerMapCommand(program: Command): void {
.option("--graph", "Render the hierarchy as a graph/tree view (default)")
.option("--list", "Render the ranked list view instead of the default graph/tree view")
.option("--full", "Force full local map, bypassing automatic safety limits (advanced/testing)")
+ .option("--remap", "Compute the map now, even from an automatic (hook) run that would defer it")
.option("--verbose", "Show raw confidence/crosscut scores and signals, plus per-file ingest diagnostics (including why a patch failed to commit)")
.option("--silent", "Suppress all output except a one-line summary (useful for LLM hooks)")
.addHelpText(
@@ -425,11 +469,21 @@ Advanced:
--silent Skip the full map rendering. Prints one summary line to stderr and
exits. Ideal for LLM hooks and automated workflows where the full
output would waste context tokens.
+ --remap Compute the map now, even from an automatic run. An \`ix map\`
+ you run computes the map (and clears a stale one). The automatic
+ \`ix map\` the editor/agent hooks run after an edit (they set
+ IX_AUTO_MAP=1) ingests it and defers the map itself: it prints the
+ last map's regions marked stale (map=stale), and the next region
+ view (overview, subsystems, locate, impact, explain, view) answers
+ from them and starts a background refresh. IX_MAP_EAGER=1 makes
+ automatic runs compute too, as before; IX_MAP_BACKGROUND_REFRESH=0
+ stops region views starting one.
Examples:
ix map .
ix map --format json
ix map --silent
+ ix map --remap
ix map --level 2
ix map --min-confidence 0.5
ix map --max-items 10
@@ -440,7 +494,7 @@ Examples:
ix map . --full
ix map . --full --verbose`
)
- .action(async (pathArg: string | undefined, opts: { format: string; level?: string; minConfidence: string; maxItems: string; allItems?: boolean; sort: string; graph?: boolean; list?: boolean; full?: boolean; verbose?: boolean; silent?: boolean }) => {
+ .action(async (pathArg: string | undefined, opts: { format: string; level?: string; minConfidence: string; maxItems: string; allItems?: boolean; sort: string; graph?: boolean; list?: boolean; full?: boolean; remap?: boolean; verbose?: boolean; silent?: boolean }) => {
const held: HeldMap = {};
try {
await runMapCommand(pathArg, opts, held);
@@ -450,6 +504,17 @@ Examples:
});
}
+/**
+ * What a deferred `ix map` (CL-13) adds to its output. `mapStale` says the
+ * map was not recomputed for this ingest; `regionsAsOf` names the last
+ * computed map that `file_count`, the regions, `region_count`, `levels`,
+ * `map_rev` and `outcome` all come from.
+ */
+export interface MapStaleState {
+ mapStale?: boolean;
+ regionsAsOf?: { map_rev: number; file_count: number };
+}
+
/** `ix map --format json`. Exported for tests. */
export function mapJsonPayload(
result: MapView,
@@ -458,6 +523,7 @@ export function mapJsonPayload(
IngestFilesSummary,
"parseErrors" | "commitErrors" | "stitchSkipped" | "stitchSkippedRule" | "filesTooLarge" | "filesTooLargePaths"
> | undefined,
+ state: MapStaleState = {},
): Record<string, unknown> {
return {
file_count: result.file_count,
@@ -465,6 +531,13 @@ export function mapJsonPayload(
levels: result.levels,
map_rev: result.map_rev,
outcome: result.outcome,
+ // CL-13. True when this run deferred the map after an edit: every field
+ // above and the regions below are the last computed map's, not this
+ // ingest's, until a region view or `ix map --remap` refreshes them.
+ // `regions_as_of` names that map ({map_rev, file_count}) and is null when
+ // the map is fresh. Both always present, like their siblings.
+ map_stale: state.mapStale === true,
+ regions_as_of: state.mapStale === true && state.regionsAsOf ? { ...state.regionsAsOf } : null,
// Always present so a consumer can branch on them without a key check.
// A dropped file is silent otherwise: the backend still answers with a
// completed outcome, so `outcome` alone cannot distinguish a whole map
@@ -505,6 +578,7 @@ export function renderMapLlm(
IngestFilesSummary,
"parseErrors" | "commitErrors" | "stitchSkipped" | "stitchSkippedRule" | "filesTooLarge" | "filesTooLargePaths"
>,
+ state: MapStaleState = {},
): void {
console.log(llmLine("map", [
["files", result.file_count],
@@ -512,6 +586,12 @@ export function renderMapLlm(
["levels", result.levels],
["rev", result.map_rev],
["outcome", result.outcome],
+ // CL-13: the map was deferred after an edit, so the record and the region
+ // rows are the last computed map's; regions_as_of_rev/_files name that
+ // map. Only when stale, per the zero-drop rule.
+ ["map_stale", state.mapStale ? true : undefined],
+ ["regions_as_of_rev", state.mapStale ? state.regionsAsOf?.map_rev : undefined],
+ ["regions_as_of_files", state.mapStale ? state.regionsAsOf?.file_count : undefined],
// The same signal the json payload carries as parse_errors/commit_errors.
// Agents are told to pass --format llm unconditionally, so leaving it out
// of this record hid the dropped files from the one consumer #554 is about.
@@ -528,6 +608,9 @@ export function renderMapLlm(
// are some; the `too_large` rows after this name up to 20 of them.
["files_too_large", ingest?.filesTooLarge ? ingest.filesTooLarge : undefined],
]));
+ // Its own record too, right after the `map` record: a reader skimming the
+ // records must not take the last map's counts for this edit's.
+ if (state.mapStale) console.log(llmLine("diagnostic", [["code", "map_stale"], ["message", mapStaleNotice(state)]]));
for (const path of ingest?.filesTooLarge ? ingest.filesTooLargePaths ?? [] : []) {
console.log(llmLine("too_large", [["path", path]]));
}
@@ -912,7 +995,7 @@ function formatRegionLine(region: MapRegion, verbose: boolean, depth = 0): strin
/** What a map that ran holds when it finishes: the workspace whose lock it took. */
interface HeldMap { root?: string; local?: boolean }
-async function runMapCommand(pathArg: string | undefined, opts: { format: string; level?: string; minConfidence: string; maxItems: string; allItems?: boolean; sort: string; graph?: boolean; list?: boolean; full?: boolean; verbose?: boolean; silent?: boolean }, held: HeldMap): Promise<void> {
+async function runMapCommand(pathArg: string | undefined, opts: { format: string; level?: string; minConfidence: string; maxItems: string; allItems?: boolean; sort: string; graph?: boolean; list?: boolean; full?: boolean; remap?: boolean; verbose?: boolean; silent?: boolean }, held: HeldMap): Promise<void> {
let cwd: string;
try {
cwd = resolveMapRoot(pathArg);
@@ -1069,30 +1152,44 @@ async function runMapCommand(pathArg: string | undefined, opts: { format: string
const mapBarWidth = 25;
const mapStart = performance.now();
- // Path-2 grouping (Ix#225 Half B): a co-ingest system is found by detectSystem
- // above; a SEPARATELY-ingested repo that the stitcher joined into a system has
- // no local marker, so look its system_id up from the backend and scope to it,
- // making `ix map <repo>` show the whole stitched system.
- let effectiveSystemId = systemId;
- if (!effectiveSystemId) {
- const ws = resolveWorkspaceId(cwd);
- if (ws) {
- // Best-effort, as before workspaceSystem started reporting failures:
- // an unanswered lookup leaves the map at workspace scope.
- const looked = await client.workspaceSystem(ws).catch(() => ({ systemId: null }));
- if (looked.systemId) effectiveSystemId = looked.systemId;
- }
- }
- const mapRequest = { full: opts.full, workspaceId: effectiveSystemId ? undefined : resolveWorkspaceId(cwd), systemId: effectiveSystemId };
+ // Scope: the co-ingest system found above, a stitched system the backend
+ // knows of, or the workspace (see `resolveMapScope`).
+ const mapRequest = await resolveMapScope(client, cwd, opts.full, systemId);
// Reuse the last response when this run's ingest wrote nothing and the
// backend's head revision has not moved since it was computed. Local
// only: a cloud ingest reports no summary, so it cannot vouch for that.
const cacheSlot = localIngest ? await resolveMapCacheSlot(client, mapRequest, () => readBackendHealth(client)) : undefined;
- const cached = cacheSlot && localIngest?.graphUnchanged ? loadCachedMap(cwd, cacheSlot) : undefined;
+
+ // CL-13: an automatic map (IX_AUTO_MAP=1: the editor/agent hooks and
+ // `ix watch`) leaves `/v1/map` after an incremental edit for the next
+ // command that reads regions (`ensureFreshMap`) and prints the last map's
+ // regions, marked stale. Those hooks read none of them, and the request was
+ // most of the run. An `ix map` a person or agent runs never defers: it is
+ // asked for because the map is wanted now, so it computes, and clears the
+ // marker, as before CL-13. Also not for the first map (nothing is stored),
+ // --full, --remap or IX_MAP_EAGER=1, a system scope (never stored), a cloud
+ // ingest, or an ingest that might have left the graph somewhere unexpected
+ // (`incremental` is false then). An automatic run that changed nothing
+ // while the map is already stale stays deferred: computing it there would
+ // only move the cost to the next hook.
+ const staleBefore = localIngest ? readMapStale(cwd) : null;
+ const deferAllowed = autoMap && !opts.full && !opts.remap && !mapEager() && !mapRequest.systemId;
+ const wantsDefer = deferAllowed && cacheSlot !== undefined && localIngest !== undefined
+ && (localIngest.incremental || (staleBefore !== null && localIngest.graphUnchanged));
+ const deferred = wantsDefer ? loadLastMap(cwd, cacheSlot!.key) : undefined;
+ // A stale map is never served from the no-change cache: its slot can still
+ // match after an edit that did not move the revision.
+ const cached = !deferred && staleBefore === null && cacheSlot && localIngest?.graphUnchanged
+ ? loadCachedMap(cwd, cacheSlot)
+ : undefined;
let result: MapView;
- if (cached) {
+ if (deferred) {
+ result = deferred;
+ // A new marker for a new edit; an unchanged run keeps the one it found.
+ if (localIngest?.incremental) markMapStale(cwd);
+ } else if (cached) {
result = cached;
} else {
// Same gate as the ingest bar: --silent and the machine formats were the
@@ -1117,23 +1214,41 @@ async function runMapCommand(pathArg: string | undefined, opts: { format: string
return;
}
if (mapInterval) { clearInterval(mapInterval); process.stderr.write('\r' + ' '.repeat(60) + '\r'); }
+ // Computed: whatever was deferred before is not any more.
+ clearMapStale(cwd);
}
const mapMs = Math.round(performance.now() - mapStart);
- const emptyMapError = invalidateBaselineForIncompleteCompletedMap(result, localIngest, cwd);
- if (emptyMapError) {
- emitError(emptyMapError);
- process.exitCode = 1;
- return;
- }
- // The cache holds the latest response the backend gave, or nothing: a
- // response that is not kept removes the one before it, so a later hit
- // can never be older than a miss in between.
- if (persistCompletedMapBaseline(result, cwd) && cacheSlot) {
- if (!cached) saveCachedMap(cwd, cacheSlot, result);
- } else {
- clearMapResultCache(cwd);
+ // A deferred map records nothing: its regions are the last map's, already
+ // recorded when it was computed, and the completed-map marker must not
+ // claim them for this ingest's revision. `ensureFreshMap` records the map
+ // it computes.
+ if (!deferred) {
+ const emptyMapError = invalidateBaselineForIncompleteCompletedMap(result, localIngest, cwd);
+ if (emptyMapError) {
+ emitError(emptyMapError);
+ process.exitCode = 1;
+ return;
+ }
+ // The cache holds the latest response the backend gave, or nothing: a
+ // response that is not kept removes the one before it, so a later hit
+ // can never be older than a miss in between.
+ if (persistCompletedMapBaseline(result, cwd) && cacheSlot) {
+ if (!cached) saveCachedMap(cwd, cacheSlot, result);
+ } else {
+ clearMapResultCache(cwd);
+ }
}
+ const mapStale = deferred !== undefined;
+ // A deferred map's counts and regions are the last map's. They keep their
+ // fields, so a consumer reading them still parses, and the map they come
+ // from is named beside them, so none can be taken for this ingest's. The
+ // file count stays the last map's too: the backend's count is not one the
+ // CLI can work out locally (it leaves out files the ingest discovered and
+ // sent), and a guess would match neither map.
+ const staleState: MapStaleState = mapStale
+ ? { mapStale, regionsAsOf: { map_rev: result.map_rev, file_count: result.file_count } }
+ : {};
// stderr, so it reaches a human on the text path and never contaminates
// the JSON/llm payload on stdout. The exit code deliberately stays 0:
@@ -1173,12 +1288,15 @@ async function runMapCommand(pathArg: string | undefined, opts: { format: string
: ` · stitch_skipped_rule=${rule}`;
process.stderr.write(silentSummaryLine({
files: result.file_count, systems, subsystems, modules, mapMs, stitch,
- filesTooLarge: localIngest?.filesTooLarge,
+ filesTooLarge: localIngest?.filesTooLarge, mapStale,
}));
return;
}
- if (!machineFormat) {
+ // A deferred map says so where its reader looks, not in a dim stderr
+ // aside: a text map opens with a warning on stdout, an llm map carries a
+ // `diagnostic code=map_stale` record (`renderMapLlm`).
+ if (!machineFormat && !mapStale) {
const mapSec = (mapMs / 1000).toFixed(1);
process.stderr.write(chalk.dim(` Mapped in ${mapSec}s\n`));
}
@@ -1194,27 +1312,42 @@ async function runMapCommand(pathArg: string | undefined, opts: { format: string
if (minConf > 0) regions = regions.filter(r => r.confidence >= minConf);
if (opts.format === "json") {
- printJson(mapJsonPayload(result, regions, localIngest));
+ printJson(mapJsonPayload(result, regions, localIngest, staleState));
return;
}
if (opts.format === "llm") {
- renderMapLlm(result, regions, localIngest);
+ renderMapLlm(result, regions, localIngest, staleState);
return;
}
+ if (staleState.mapStale) renderWarning(mapStaleNotice(staleState));
renderMapText(result, cwd, opts);
}
+/**
+ * The one sentence a deferred map's text and llm output lead with: the counts
+ * and regions are the last map's, which one, and how to get this edit's.
+ * Exported for tests.
+ */
+export function mapStaleNotice(state: MapStaleState): string {
+ const asOf = state.regionsAsOf
+ ? ` (map rev ${state.regionsAsOf.map_rev}, ${state.regionsAsOf.file_count} files)`
+ : "";
+ return `Stale map: not recomputed after this edit. Every count and region here is from the last map${asOf}. Run ix map --remap to recompute it now; region views refresh it in the background.`;
+}
+
/**
* One more ingest when a map that coalesced into this one asked for it (see
* `requestMapRerun`), before the lock is let go. One pass at most: under a
* stream of edits a rerun per request would never finish, and the next edit's
* own map picks up whatever arrives after it. Ingest only -- this run's output
- * has already been printed, and the hierarchy is refreshed by the next map.
+ * has already been printed. When the ingest changed the graph, the map is
+ * marked stale, so the next region view refreshes the hierarchy (CL-13);
+ * it used to be left stale with nothing to say so.
*/
-async function rerunIfRequested(root: string, local: boolean, opts: { silent?: boolean; format: string }): Promise<void> {
+export async function rerunIfRequested(root: string, local: boolean, opts: { silent?: boolean; format: string }): Promise<void> {
if (!local || !takeMapRerun(root)) return;
try {
- await ingestFiles(root, {
+ const summary = await ingestFiles(root, {
recursive: true,
format: "json",
printSummary: false,
@@ -1224,6 +1357,7 @@ async function rerunIfRequested(root: string, local: boolean, opts: { silent?: b
// run's may be all but spent.
deadlineSignal: mapDeadlineSignal(),
});
+ if (!summary.graphUnchanged) markMapStale(root);
} catch (err: any) {
if (opts.silent !== true && opts.format !== "json" && opts.format !== "llm") {
process.stderr.write(chalk.dim(` Re-run for a map that waited on this one failed: ${err?.message ?? err}\n`));
diff --git a/ix-cli/src/cli/commands/overview.ts b/ix-cli/src/cli/commands/overview.ts
index c1c1635f..d8d7d4f8 100644
--- a/ix-cli/src/cli/commands/overview.ts
+++ b/ix-cli/src/cli/commands/overview.ts
@@ -11,6 +11,7 @@ import { llmLine, type LlmValue } from "../llm.js";
import { parsePickOption } from "../options.js";
import { renderSection, renderKeyValue, renderNote, renderBreadcrumb } from "../ui.js";
import { forMcp } from "../next-step.js";
+import { ensureFreshMap } from "../map-freshness.js";
const CONTAINER_KINDS = new Set(["class", "module", "file", "trait", "object", "interface"]);
const STRUCTURAL_CONTAINER_KINDS = new Set(["class", "object", "trait", "interface"]);
@@ -64,6 +65,10 @@ Examples:
if (opts.format === "text") printResolved(target);
+ // An `ix map` after an edit may have left the map for this read (CL-13).
+ // Never throws and never moves the exit code.
+ await ensureFreshMap();
+
const isContainer = CONTAINER_KINDS.has(target.kind);
const isRegion = REGION_KINDS.has(target.kind);
diff --git a/ix-cli/src/cli/commands/status.ts b/ix-cli/src/cli/commands/status.ts
index 8965c2b7..45558932 100644
--- a/ix-cli/src/cli/commands/status.ts
+++ b/ix-cli/src/cli/commands/status.ts
@@ -26,6 +26,10 @@ import { loadVerifyRecord, verifyRecordOutdated, type VerifyRecord } from "../ve
interface StatusStaleInfo {
graphCompleted: boolean;
mapCompleted: boolean;
+ /** The map was deferred after an edit (CL-13); see `StaleInfo.mapStale`. */
+ mapStale?: boolean;
+ /** Why the last background map refresh failed, while the map is stale; see `StaleInfo.mapRefreshError`. */
+ mapRefreshError?: string | null;
currentRev: number;
lastIngestAt: string | null;
staleFiles: number;
@@ -64,6 +68,10 @@ export function renderStatusLlm(
["graph_health", graph ? graphHealthWord(graph) : null],
["graph_complete", staleInfo ? String(staleInfo.graphCompleted) : null],
["map_complete", staleInfo ? String(staleInfo.mapCompleted) : null],
+ // CL-13: why map_complete is false right after an edit. Only when true,
+ // per the zero-drop rule.
+ ["map_stale", staleInfo?.mapStale ? "true" : null],
+ ["map_refresh_error", staleInfo?.mapStale ? staleInfo.mapRefreshError ?? null : null],
["rev", staleInfo ? String(staleInfo.currentRev) : null],
["last_ingest_at", staleInfo?.lastIngestAt ?? null],
["stale_files", staleInfo ? String(staleInfo.staleFiles) : null],
@@ -161,6 +169,8 @@ export function registerStatusCommand(program: Command): void {
backend: health.status,
graphCompleted: staleInfo?.graphCompleted ?? null,
mapCompleted: staleInfo?.mapCompleted ?? null,
+ mapStale: staleInfo?.mapStale ?? false,
+ mapRefreshError: staleInfo?.mapStale ? staleInfo.mapRefreshError ?? null : null,
currentRev: staleInfo?.currentRev ?? null,
lastIngestAt: staleInfo?.lastIngestAt ?? null,
staleFiles: staleInfo?.staleFiles ?? 0,
@@ -212,7 +222,17 @@ export function registerStatusCommand(program: Command): void {
// will not bring these files in, a larger budget will.
renderWarning(describeStatusParseTimeouts(staleInfo.parseTimeouts));
}
- if (staleInfo.graphCompleted && !staleInfo.mapCompleted) {
+ if (staleInfo.graphCompleted && staleInfo.mapStale) {
+ // Deferred after an edit, not missing: the last map's regions
+ // stand until something reads them.
+ renderKeyValue("Map", "stale");
+ if (staleInfo.mapRefreshError) {
+ renderWarning(`The last background map refresh failed: ${staleInfo.mapRefreshError}`);
+ renderNote("run ix map --remap to recompute the map");
+ } else {
+ renderNote("a region view refreshes it in the background, or run ix map --remap");
+ }
+ } else 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.");
}
diff --git a/ix-cli/src/cli/commands/subsystems.ts b/ix-cli/src/cli/commands/subsystems.ts
index a57a1d15..5daa8e2a 100644
--- a/ix-cli/src/cli/commands/subsystems.ts
+++ b/ix-cli/src/cli/commands/subsystems.ts
@@ -11,6 +11,7 @@ import { llmLine, llmError, llmShortId } from "../llm.js";
import { parsePickOption } from "../options.js";
import { setOutcome } from "../outcome.js";
import { renderMapText, renderMapLlm, type MapRegion, type MapResult } from "./map.js";
+import { ensureFreshMap } from "../map-freshness.js";
import {
renderSubsystemExplanationJson,
renderSubsystemExplanationText,
@@ -162,6 +163,10 @@ Examples:
return;
}
+ // An `ix map` after an edit may have left the map for this read (CL-13).
+ // Never throws and never moves the exit code.
+ await ensureFreshMap();
+
if (opts.list) {
let result: SubsystemListResult;
try {
diff --git a/ix-cli/src/cli/commands/view.ts b/ix-cli/src/cli/commands/view.ts
index 81f50ea5..4d06fcbb 100644
--- a/ix-cli/src/cli/commands/view.ts
+++ b/ix-cli/src/cli/commands/view.ts
@@ -17,6 +17,7 @@ import { resolveWorkspaceId } from "../bootstrap.js";
import { findWorkspaceForCwd, getDefaultWorkspace, getLocalToken, loadWorkspaces } from "../config.js";
import { detectSystem } from "../system.js";
import { createClient } from "../../client/factory.js";
+import { ensureFreshMap } from "../map-freshness.js";
const IX_HOME = process.env.IX_HOME || join(homedir(), ".ix");
const PID_FILE = join(IX_HOME, "compass.pid");
@@ -524,10 +525,13 @@ const server = http.createServer((req, res) => {
return;
}
// --silent because nothing here reads stdout, and the default text render
- // is work done only to be thrown away. maxBuffer is raised anyway: the
+ // is work done only to be thrown away. --remap because this is the Remap
+ // button: it must recompute the map even when the server inherited
+ // IX_AUTO_MAP=1, under which a stale map would be served as is (CL-13).
+ // maxBuffer is raised anyway: the
// default 1 MiB makes Node SIGTERM the child mid-map, which surfaces as a
// 500 rather than as the truncation it is.
- const child = execFile(process.execPath, [MAP_MAIN, "map", MAP_ROOT, "--silent"], { cwd: MAP_ROOT, timeout: 1800000, maxBuffer: 64 * 1024 * 1024 }, (err, stdout, stderr) => {
+ const child = execFile(process.execPath, [MAP_MAIN, "map", MAP_ROOT, "--silent", "--remap"], { cwd: MAP_ROOT, timeout: 1800000, maxBuffer: 64 * 1024 * 1024 }, (err, stdout, stderr) => {
mapInFlight = null;
if (res.destroyed) return; // client disconnected while mapping
res.writeHead(err ? 500 : 200, { "Content-Type": "application/json" });
@@ -744,6 +748,11 @@ export function registerViewCommand(program: Command): void {
? `system "${systemId}"`
: (workspaceName ? `workspace "${workspaceName}"` : "all workspaces");
+ // An `ix map` after an edit may have left the map for whatever reads
+ // regions next (CL-13); the visualizer shows them. Not under --all,
+ // which has no one workspace to refresh. Never throws.
+ if (!opts.all) await ensureFreshMap(mapRoot ? { root: mapRoot } : {});
+
const existing = readAlivePid();
if (existing) {
console.log(`[ok] Visualizer is already running (PID ${existing})`);
diff --git a/ix-cli/src/cli/config.ts b/ix-cli/src/cli/config.ts
index 764d455c..48355d99 100644
--- a/ix-cli/src/cli/config.ts
+++ b/ix-cli/src/cli/config.ts
@@ -104,6 +104,27 @@ export function mapResultCachePath(projectRoot: string): string {
return join(ixHome(), `map_result_${key}.json`);
}
+/**
+ * Path to the "architecture map is stale" marker for one project root: an
+ * `ix map` after an incremental edit left its `/v1/map` request for the next
+ * command that reads regions (see `map-freshness.ts`). Cleared with the map
+ * baseline, since it describes the same hierarchy.
+ */
+export function mapStalePath(projectRoot: string): string {
+ const key = rootKey(projectRoot);
+ return join(ixHome(), `map_stale_${key}.json`);
+}
+
+/**
+ * Path to the outcome of the last background map refresh for one project
+ * root (see `map-freshness.ts`): when it ran and whether it completed, and
+ * why not. Read by `ix doctor` and `ix status`; cleared with the map baseline.
+ */
+export function mapRefreshOutcomePath(projectRoot: string): string {
+ const key = rootKey(projectRoot);
+ return join(ixHome(), `map_refresh_${key}.json`);
+}
+
/**
* Path to the cached answer to "is this workspace stitched into a System?".
*
@@ -163,11 +184,14 @@ export function clearMapResultCache(projectRoot: string): void {
/**
* Remove the architecture-map completion marker, and the cached map response
- * with it: whatever made the marker wrong makes the cached hierarchy wrong too.
- * Leaves the source ingest baseline alone. Best-effort.
+ * and the stale marker with it: whatever made the marker wrong makes the
+ * cached hierarchy wrong too, and a map that is no longer recorded is not
+ * merely deferred. Leaves the source ingest baseline alone. Best-effort.
*/
export function clearMapBaseline(projectRoot: string): void {
try { rmSync(mapBaselinePath(projectRoot), { force: true }); } catch { /* non-critical */ }
+ try { rmSync(mapStalePath(projectRoot), { force: true }); } catch { /* non-critical */ }
+ try { rmSync(mapRefreshOutcomePath(projectRoot), { force: true }); } catch { /* non-critical */ }
clearMapResultCache(projectRoot);
}
diff --git a/ix-cli/src/cli/main.ts b/ix-cli/src/cli/main.ts
index 48097ca6..d13a3ca5 100644
--- a/ix-cli/src/cli/main.ts
+++ b/ix-cli/src/cli/main.ts
@@ -53,7 +53,14 @@ try {
// loads the graph code itself only when there is an edit to report.
// `--help` still goes through the CLI, where the command is documented.
const args = process.argv.slice(2);
-if (args[0] === "hook" && args[1] === "claude-post-edit" && !args.some((a) => a === "-h" || a === "--help")) {
+// `ix __map-refresh <root>` is the detached background map refresh a region
+// view starts (`map-freshness.ts`); it is not a command anyone types, so it
+// skips the command tree too. It exits when done, whatever is left pending.
+if (args[0] === "__map-refresh" && args[1] !== undefined) {
+ const { runBackgroundMapRefresh } = await import("./map-freshness.js");
+ try { await runBackgroundMapRefresh(args[1]); } catch { /* recorded where it could be */ }
+ process.exit(0);
+} else if (args[0] === "hook" && args[1] === "claude-post-edit" && !args.some((a) => a === "-h" || a === "--help")) {
const { parseHookArgs, runHookProcess } = await import("./hook/entry.js");
await runHookProcess(parseHookArgs(args.slice(2)));
} else {
diff --git a/ix-cli/src/cli/map-freshness.ts b/ix-cli/src/cli/map-freshness.ts
new file mode 100644
index 00000000..8e6790a5
--- /dev/null
+++ b/ix-cli/src/cli/map-freshness.ts
@@ -0,0 +1,470 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { spawn, type SpawnOptions } from "node:child_process";
+import * as fs from "node:fs";
+import * as path from "node:path";
+import { fileURLToPath } from "node:url";
+import type { IxClient } from "../client/api.js";
+import { mapRefreshOutcomePath, mapStalePath } from "./config.js";
+import { loadIngestBaseline } from "./ingest-baseline.js";
+
+/**
+ * The architecture map left for later (CL-13).
+ *
+ * `ix map` runs after every agent turn and on every edit (the plugins' Stop
+ * and PostToolUse hooks). After an incremental ingest the `/v1/map` request is
+ * most of its cost -- 2.6-3.9 s on keras for a one-line edit -- and nothing on
+ * that path reads the regions it returns. So `ix map` skips the request,
+ * prints the regions of the last map, and writes this marker. The commands
+ * that read regions (`overview`, `subsystems`, `locate`, `impact`,
+ * `explain`, `view`) call `ensureFreshMap` first. It never maps inline: those
+ * readers run inside blocking agent hooks with ~10 s budgets, and `/v1/map`
+ * can take longer than that on a large repo. While the marker is set it
+ * answers from the last map, says so, and starts a detached background
+ * process (`runBackgroundMapRefresh`) that recomputes the map under the map
+ * lock and records how that went (`readMapRefreshOutcome`).
+ *
+ * The marker sits beside `map_result_*` in IX_HOME, keyed the same way, and is
+ * removed with the map baseline (`clearMapBaseline`), so reset and a forced
+ * re-ingest leave none behind.
+ */
+export interface MapStaleInfo {
+ /** When the map was deferred, epoch ms. */
+ since: number;
+ /** The ingest baseline's revision the deferral followed, or null when there was none. */
+ ingestRev: number | null;
+ /** When a refresh was last attempted, epoch ms; the debounce runs from here. */
+ lastAttemptAt?: number;
+}
+
+const isFiniteNumber = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
+
+/** The marker for `projectRoot`, or null when there is none. A malformed file reads as none. */
+export function readMapStale(projectRoot: string): MapStaleInfo | null {
+ try {
+ const data = JSON.parse(fs.readFileSync(mapStalePath(projectRoot), "utf-8")) as Record<string, unknown> | null;
+ if (data === null || typeof data !== "object") return null;
+ if (!isFiniteNumber(data.since)) return null;
+ if (data.ingestRev !== null && !isFiniteNumber(data.ingestRev)) return null;
+ if (data.lastAttemptAt !== undefined && !isFiniteNumber(data.lastAttemptAt)) return null;
+ const info: MapStaleInfo = { since: data.since, ingestRev: data.ingestRev as number | null };
+ if (data.lastAttemptAt !== undefined) info.lastAttemptAt = data.lastAttemptAt;
+ return info;
+ } catch {
+ return null;
+ }
+}
+
+function writeMapStale(projectRoot: string, info: MapStaleInfo): void {
+ const target = mapStalePath(projectRoot);
+ const tmp = `${target}.${process.pid}.tmp`;
+ try {
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ // Via a temp file and rename, so a reader never sees half a file.
+ fs.writeFileSync(tmp, JSON.stringify(info));
+ fs.renameSync(tmp, target);
+ } catch {
+ try { fs.rmSync(tmp, { force: true }); } catch { /* non-critical */ }
+ }
+}
+
+/**
+ * Record that the map for `projectRoot` was deferred after an ingest. A new
+ * marker each time, with no `lastAttemptAt`: a later edit's refresh has not
+ * been tried yet, so the debounce does not hold it back. Best-effort.
+ */
+export function markMapStale(projectRoot: string, info: Partial<Pick<MapStaleInfo, "since" | "ingestRev">> = {}): void {
+ writeMapStale(projectRoot, {
+ since: info.since ?? Date.now(),
+ ingestRev: info.ingestRev !== undefined ? info.ingestRev : (loadIngestBaseline(projectRoot)?.currentRev ?? null),
+ });
+}
+
+/** Remove the marker: the map was computed. Best-effort. */
+export function clearMapStale(projectRoot: string): void {
+ try { fs.rmSync(mapStalePath(projectRoot), { force: true }); } catch { /* non-critical */ }
+}
+
+/**
+ * Remove the marker only if it is still the one `seen` describes. A marker
+ * re-written while a refresh was running belongs to an ingest that refresh
+ * may not have mapped, and must stay.
+ */
+function clearMapStaleIfUnchanged(projectRoot: string, seen: MapStaleInfo): void {
+ const current = readMapStale(projectRoot);
+ if (current === null) return;
+ if (current.since !== seen.since || current.ingestRev !== seen.ingestRev) return;
+ clearMapStale(projectRoot);
+}
+
+const DEFAULT_REFRESH_DEBOUNCE_MS = 30_000;
+
+/**
+ * How long after an attempted refresh another may start, in ms; 0 = no
+ * debounce. Matched, not parsed, as the other IX_*_MS settings are: a value
+ * that is not a plain number of ms keeps the default.
+ */
+export function mapRefreshDebounceMs(raw = process.env.IX_MAP_REFRESH_DEBOUNCE_MS): number {
+ if (raw === undefined) return DEFAULT_REFRESH_DEBOUNCE_MS;
+ const trimmed = raw.trim();
+ if (trimmed === "") return 0;
+ if (!/^\d+$/.test(trimmed)) return DEFAULT_REFRESH_DEBOUNCE_MS;
+ return Number.parseInt(trimmed, 10);
+}
+
+export interface EnsureFreshMapOptions {
+ /** The workspace root; defaults to the root a bare `ix map` would map. */
+ root?: string;
+ /** For tests: the clock. */
+ now?: () => number;
+ /** For tests: what starts the background refresh. Defaults to `spawnMapRefresh`. */
+ spawn?: (root: string) => void | Promise<void>;
+}
+
+/**
+ * Whether a reader may start a background refresh. IX_MAP_BACKGROUND_REFRESH=0
+ * turns it off: readers then answer from the last map, say it is stale, and
+ * leave the refresh to `ix map --remap`. They never map inline either way.
+ */
+export function mapBackgroundRefreshEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
+ const raw = env.IX_MAP_BACKGROUND_REFRESH;
+ return raw === undefined || raw.trim() !== "0";
+}
+
+const DEFAULT_BACKGROUND_TIMEOUT_MS = 5 * 60 * 1000;
+
+/**
+ * The background refresh's hard wall-clock limit, in ms: well above any hook's
+ * budget, so a slow map gets to finish, and finite, so a wedged one cannot hold
+ * the map lock forever. IX_MAP_BACKGROUND_TIMEOUT_MS, a plain number of ms > 0;
+ * anything else keeps the 5 min default.
+ */
+export function mapBackgroundTimeoutMs(raw = process.env.IX_MAP_BACKGROUND_TIMEOUT_MS): number {
+ if (raw === undefined || !/^\d+$/.test(raw.trim())) return DEFAULT_BACKGROUND_TIMEOUT_MS;
+ const n = Number.parseInt(raw.trim(), 10);
+ return n > 0 ? n : DEFAULT_BACKGROUND_TIMEOUT_MS;
+}
+
+/** The first argument that makes the CLI entry run a background refresh (see `main.ts`). */
+export const MAP_REFRESH_ARG = "__map-refresh";
+
+/** The CLI entry beside this module: `main.js` when built, `main.ts` under tsx. */
+function cliEntryPath(): string {
+ const self = fileURLToPath(import.meta.url);
+ return path.join(path.dirname(self), `main${path.extname(self)}`);
+}
+
+/**
+ * How the background refresh for `root` is started: the same Node and CLI
+ * entry as this process (with its source loaders, under tsx), no shell, no
+ * inherited stdio -- a hook that waits for its child's pipes to close must not
+ * wait for this one -- detached into its own process group, and with no
+ * console window on Windows. Exported for tests.
+ */
+export async function mapRefreshInvocation(
+ root: string,
+ entry = cliEntryPath(),
+ execArgv = process.execArgv,
+): Promise<{ command: string; args: string[]; options: SpawnOptions }> {
+ const { childCliArgs } = await import("./commands/watch.js");
+ return {
+ command: process.execPath,
+ args: childCliArgs(entry, [MAP_REFRESH_ARG, root], execArgv),
+ options: { cwd: root, detached: true, stdio: "ignore", windowsHide: true, shell: false },
+ };
+}
+
+/** Start the background refresh for `root` (`mapRefreshInvocation`) and return at once. */
+export async function spawnMapRefresh(root: string): Promise<void> {
+ const { command, args, options } = await mapRefreshInvocation(root);
+ const child = spawn(command, args, options);
+ // A child that fails to start reports it asynchronously; the reader has
+ // answered by then, and the marker and debounce stand.
+ child.on("error", () => { /* non-critical */ });
+ // Not waited for: this process exits on its own schedule.
+ child.unref();
+}
+
+/**
+ * Bring the architecture map up to date after an `ix map` deferred it --
+ * in the background, never here.
+ *
+ * Called by the commands that read regions, before their first read. Without
+ * a marker it returns at once, with no network call. With one it does not
+ * wait for a map: the command answers from the stored regions and, unless one
+ * of these holds, a detached `runBackgroundMapRefresh` is started for the
+ * workspace:
+ *
+ * - IX_MAP_BACKGROUND_REFRESH=0;
+ * - debounced: a refresh was started less than `IX_MAP_REFRESH_DEBOUNCE_MS`
+ * (default 30 s) ago, so a backend that cannot map is not asked by every read;
+ * - another process holds the map lock (an `ix map`, or a refresh already
+ * running);
+ * - a cloud-ingested workspace (which never writes the marker anyway).
+ *
+ * It never throws, never touches the exit code and prints nothing on stdout.
+ * While the map is stale it says so in one line on stderr, so the reader's
+ * answer is never silently older than the code. Resolves to true when the
+ * map is stale.
+ */
+export async function ensureFreshMap(opts: EnsureFreshMapOptions = {}): Promise<boolean> {
+ let why: string | undefined;
+ try {
+ why = await scheduleRefresh(opts);
+ } catch {
+ // Never the reader's problem: it answers from the regions it has.
+ why = "its refresh failed";
+ }
+ if (why === undefined) return false;
+ try {
+ process.stderr.write(`ix: architecture map is stale (${why}); regions shown may predate recent edits. Run ix map --remap to refresh.\n`);
+ } catch { /* non-critical */ }
+ return true;
+}
+
+/** The root a reader's refresh is for, canonical; undefined when there is none. */
+async function readerRoot(given: string | undefined): Promise<string | undefined> {
+ // The reader's workspace (what its entity lookup queries), not the
+ // write-command routing of `resolveMapRoot`: a pinned workspace B read from
+ // an unrelated repo A must refresh B's map, not look at A's marker.
+ //
+ // Canonical, as `ix map` spells it, whoever names it: the marker's path is
+ // keyed on the canonical root, but the ingest and map baselines also store
+ // the root and match it as a string. A root given under another spelling --
+ // a symlink, macOS's /tmp, a Windows 8.3 name like RUNNER~1 -- found the
+ // marker but no baseline, so every refresh failed and the marker stayed.
+ if (given !== undefined) {
+ const { canonicalWorkspacePath } = await import("./config.js");
+ return canonicalWorkspacePath(given);
+ }
+ const { canonicalMapRoot } = await import("./map-root.js");
+ const { resolveWorkspaceRoot } = await import("./config.js");
+ try { return canonicalMapRoot(resolveWorkspaceRoot()); } catch { return undefined; }
+}
+
+/** Why the map is stale after scheduling, or undefined when it is fresh. */
+async function scheduleRefresh(opts: EnsureFreshMapOptions): Promise<string | undefined> {
+ const root = await readerRoot(opts.root);
+ if (root === undefined) return undefined;
+ const marker = readMapStale(root);
+ if (marker === null) return undefined;
+
+ const { isCloudReady } = await import("./remote.js");
+ if (await isCloudReady()) return undefined;
+
+ if (!mapBackgroundRefreshEnabled()) return "background refresh is off";
+
+ const now = opts.now ?? Date.now;
+ const debounce = mapRefreshDebounceMs();
+ // From the later of the last start and the last failed finish: a refresh
+ // that ran into its time limit is not followed by another straight away.
+ const debounced = (m: MapStaleInfo): boolean => {
+ if (debounce <= 0) return false;
+ const last = readMapRefreshOutcome(root);
+ const failedAt = last?.ok === false ? last.finishedAt : undefined;
+ const from = Math.max(m.lastAttemptAt ?? -Infinity, failedAt ?? -Infinity);
+ return Number.isFinite(from) && now() - from < debounce;
+ };
+ const debouncedWhy = (): string => {
+ const last = readMapRefreshOutcome(root);
+ return last?.ok === false ? "its last background refresh failed" : "a refresh was tried moments ago";
+ };
+ if (debounced(marker)) return debouncedWhy();
+
+ // Taken only to decide and record the attempt, then let go for the child:
+ // two readers at once start one refresh, not two.
+ const { acquireMapLock } = await import("./single-flight.js");
+ const lock = acquireMapLock(root, `ix map refresh scheduler ${root}`);
+ // Another `ix map` holds it: a running refresh, or an incremental `ix map`
+ // that defers the map and only writes the marker. Either way, not now.
+ if (!lock) return "another ix map is running";
+ try {
+ const current = readMapStale(root);
+ if (current === null) return undefined;
+ if (debounced(current)) return debouncedWhy();
+ // Recorded before the child starts, so the readers that follow it
+ // inside the debounce window do not start another.
+ writeMapStale(root, { ...current, lastAttemptAt: now() });
+ } finally {
+ lock.release();
+ }
+ try {
+ await (opts.spawn ?? spawnMapRefresh)(root);
+ } catch {
+ return "its refresh could not start";
+ }
+ return "refreshing in background";
+}
+
+/** What the last background refresh for a root did. */
+export interface MapRefreshOutcome {
+ /** When it started, epoch ms. */
+ startedAt: number;
+ /** When it finished, epoch ms; absent while it runs. */
+ finishedAt?: number;
+ /** True when it recorded a completed map; absent while it runs. */
+ ok?: boolean;
+ /** Why it did not complete, or what it left behind; one line. */
+ reason?: string;
+ /** The process that ran it. */
+ pid: number;
+}
+
+/** The last background refresh's outcome for `projectRoot`, or null. A malformed file reads as none. */
+export function readMapRefreshOutcome(projectRoot: string): MapRefreshOutcome | null {
+ try {
+ const data = JSON.parse(fs.readFileSync(mapRefreshOutcomePath(projectRoot), "utf-8")) as Record<string, unknown> | null;
+ if (data === null || typeof data !== "object") return null;
+ if (!isFiniteNumber(data.startedAt) || !isFiniteNumber(data.pid)) return null;
+ const out: MapRefreshOutcome = { startedAt: data.startedAt, pid: data.pid };
+ if (isFiniteNumber(data.finishedAt)) out.finishedAt = data.finishedAt;
+ if (typeof data.ok === "boolean") out.ok = data.ok;
+ if (typeof data.reason === "string") out.reason = data.reason;
+ return out;
+ } catch {
+ return null;
+ }
+}
+
+function writeMapRefreshOutcome(projectRoot: string, outcome: MapRefreshOutcome): void {
+ const target = mapRefreshOutcomePath(projectRoot);
+ const tmp = `${target}.${process.pid}.tmp`;
+ try {
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(tmp, JSON.stringify(outcome));
+ fs.renameSync(tmp, target);
+ } catch {
+ try { fs.rmSync(tmp, { force: true }); } catch { /* non-critical */ }
+ }
+}
+
+/** An error's message on one short line, for the outcome file. */
+function oneLine(e: unknown): string {
+ const text = String((e as { message?: unknown })?.message ?? e).replace(/\s+/g, " ").trim();
+ return text.length > 200 ? `${text.slice(0, 197)}...` : text;
+}
+
+export interface BackgroundMapRefreshOptions {
+ /** For tests: the client to refresh through. */
+ client?: IxClient;
+ /** For tests: the clock. */
+ now?: () => number;
+ /** The hard limit, in ms; defaults to `mapBackgroundTimeoutMs()`. */
+ timeoutMs?: number;
+}
+
+/**
+ * The background refresh: what `ix __map-refresh <root>` runs, in the detached
+ * process `ensureFreshMap` starts.
+ *
+ * Under the map lock -- the same one `ix map` takes, so it never runs beside
+ * one -- and only while the marker is set, it maps exactly as `ix map` would,
+ * records the result as `ix map` does, and removes the marker if no newer edit
+ * re-wrote it meanwhile. A refresh that does not succeed -- a failed request,
+ * a response that is not a completed map, or the hard time limit -- leaves the
+ * stored regions, the map baseline and the marker as they were.
+ *
+ * An `ix map` that coalesced into it asked for one more ingest
+ * (`requestMapRerun`); that is run after the map, and re-marks the map stale
+ * when it changed files.
+ *
+ * Whatever happens is written where `ix doctor` and `ix status` read it
+ * (`readMapRefreshOutcome`). Resolves to that outcome, or null when it did
+ * nothing: another process held the lock, or the map was already fresh.
+ */
+export async function runBackgroundMapRefresh(
+ rootArg: string,
+ opts: BackgroundMapRefreshOptions = {},
+): Promise<MapRefreshOutcome | null> {
+ const { canonicalWorkspacePath } = await import("./config.js");
+ const root = canonicalWorkspacePath(rootArg);
+ const now = opts.now ?? Date.now;
+ if (readMapStale(root) === null) return null;
+
+ const { acquireMapLock } = await import("./single-flight.js");
+ const lock = acquireMapLock(root, `ix map background refresh ${root}`);
+ if (!lock) return null;
+ try {
+ const current = readMapStale(root);
+ if (current === null) return null;
+ const startedAt = now();
+ writeMapStale(root, { ...current, lastAttemptAt: startedAt });
+ writeMapRefreshOutcome(root, { startedAt, pid: process.pid });
+
+ // The limit both aborts the requests in flight and, for whatever does
+ // not listen to that, stops waiting; either way it is reported as such.
+ const timeoutMs = opts.timeoutMs ?? mapBackgroundTimeoutMs();
+ const timedOutReason = `timed out after ${timeoutMs / 1000} s`;
+ const deadline = AbortSignal.timeout(timeoutMs);
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const timedOut = new Promise<{ ok: false; reason: string }>(resolve => {
+ timer = setTimeout(() => resolve({ ok: false, reason: timedOutReason }), timeoutMs);
+ timer.unref?.();
+ });
+ let result: { ok: boolean; reason?: string };
+ try {
+ result = await Promise.race([refreshUnderLock(root, current, deadline, opts.client), timedOut]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+ if (!result.ok && deadline.aborted) result = { ok: false, reason: timedOutReason };
+ const outcome: MapRefreshOutcome = { startedAt, finishedAt: now(), ok: result.ok, pid: process.pid };
+ if (result.reason !== undefined) outcome.reason = result.reason;
+ writeMapRefreshOutcome(root, outcome);
+ return outcome;
+ } finally {
+ lock.release();
+ }
+}
+
+/** The map request and what follows it, under the lock `runBackgroundMapRefresh` holds. */
+async function refreshUnderLock(
+ root: string,
+ seen: MapStaleInfo,
+ deadline: AbortSignal,
+ injected: IxClient | undefined,
+): Promise<{ ok: boolean; reason?: string }> {
+ // Loaded here, not at the top: `commands/map.ts` imports this module, and
+ // a reader with no marker never needs any of it.
+ const map = await import("./commands/map.js");
+ const { createClient } = await import("../client/factory.js");
+ const { resolveMapCacheSlot, saveCachedMap } = await import("./map-result-cache.js");
+ const { clearMapResultCache } = await import("./config.js");
+ const { readBackendHealth } = await import("./commands/upgrade.js");
+
+ let failure: string | undefined;
+ try {
+ const own = map.mapDeadlineSignal();
+ const client = injected ?? createClient({ deadlineSignal: own ? AbortSignal.any([own, deadline]) : deadline, longRunning: true });
+ const request = await map.resolveMapScope(client, root, false);
+ const slot = await resolveMapCacheSlot(client, request, () => readBackendHealth(client));
+ const result = await client.map(request) as import("./commands/map.js").MapResult;
+
+ // Only a completed, non-empty map is recorded. The empty and regionless
+ // diagnoses of `ix map` need the ingest's counts, which a refresh has
+ // none of, so they do not run here.
+ if (map.persistCompletedMapBaseline(result, root)) {
+ // The last map stored is this one, or none: one keyed to another
+ // request must not outlive the map that replaced it.
+ if (slot) saveCachedMap(root, slot, result);
+ else clearMapResultCache(root);
+ clearMapStaleIfUnchanged(root, seen);
+ } else {
+ failure = `the map did not complete: outcome ${String(result?.outcome)}, ${String(result?.file_count)} files`;
+ }
+ } catch (e) {
+ failure = `the map request failed: ${oneLine(e)}`;
+ }
+ // An `ix map` that coalesced into this refresh asked for one more ingest
+ // and has already exited: run it, as the lock holder of `ix map` would, so
+ // that edit is not lost -- whether or not the map above succeeded. It
+ // re-marks the map stale if it changed files.
+ const exitCode = process.exitCode;
+ try { await map.rerunIfRequested(root, true, { silent: true, format: "json" }); }
+ catch { /* rerunIfRequested reports its own failures */ }
+ finally { process.exitCode = exitCode; }
+
+ if (failure !== undefined) return { ok: false, reason: failure };
+ if (readMapStale(root) !== null) return { ok: true, reason: "files changed while it was refreshed; the map is stale again" };
+ return { ok: true };
+}
diff --git a/ix-cli/src/cli/map-result-cache.ts b/ix-cli/src/cli/map-result-cache.ts
index c0b52dc1..937ce916 100644
--- a/ix-cli/src/cli/map-result-cache.ts
+++ b/ix-cli/src/cli/map-result-cache.ts
@@ -30,6 +30,15 @@ import { isRev } from "./ingest-baseline.js";
* workspace whose data was deleted without a commit, which the ingest's
* DB-reset guard catches.
*
+ * The revision is the backend's GLOBAL head because that is the only one it
+ * serves (`/v1/revisions/current`; see docs/api/openapi.yaml). A write in any
+ * workspace therefore invalidates every workspace's slot. Once the backend
+ * serves a workspace-local revision (audit F-18), the slot should key on that
+ * instead; until then no client code asks for one.
+ *
+ * After an incremental edit, `ix map` does not ask at all: it defers the map
+ * and prints the last stored response (`loadLastMap`, `map-freshness.ts`).
+ *
* Only a workspace-scoped map is cached. A system-scoped one can change
* without a commit: the stitcher writes cross-repo edges and stamps system
* ids directly. So does the unscoped global map, which persists regions as a
@@ -191,3 +200,20 @@ export function saveCachedMap(projectRoot: string, slot: MapCacheSlot, result: C
try { fs.rmSync(tmp, { force: true }); } catch { /* non-critical */ }
}
}
+
+/**
+ * The last response stored for this root and request key, whatever revision
+ * it was computed at -- what a deferred `ix map` prints (CL-13). Deliberately
+ * blind to the revision: the caller has just ingested an edit and knows the
+ * regions are behind, and marks them so. Used only on that deferral path;
+ * everything else reads `loadCachedMap`.
+ */
+export function loadLastMap(projectRoot: string, key: string): CachedMapResponse | undefined {
+ try {
+ const data = JSON.parse(fs.readFileSync(mapResultCachePath(projectRoot), "utf-8")) as Partial<SerializedMapCache>;
+ if (data.root !== projectRoot || data.key !== key) return undefined;
+ return isCachedMapResponse(data.result) ? data.result : undefined;
+ } catch {
+ return undefined;
+ }
+}
diff --git a/ix-cli/src/cli/single-flight.ts b/ix-cli/src/cli/single-flight.ts
index aa0f257a..8e0df94a 100644
--- a/ix-cli/src/cli/single-flight.ts
+++ b/ix-cli/src/cli/single-flight.ts
@@ -148,6 +148,18 @@ export function acquireMapLock(workspaceRoot: string, label: string): LockHandle
return acquireLockAt(lockPathFor(workspaceRoot), label);
}
+/**
+ * Whether a live process holds the map lock for `workspaceRoot`, without
+ * taking it. A lock whose holder is gone (see `isStale`) reads as free. For a
+ * caller that only decides whether to start work that will take the lock
+ * itself; the answer can change the moment it is read.
+ */
+export function mapLockHeld(workspaceRoot: string): boolean {
+ const path = lockPathFor(workspaceRoot);
+ try { statSync(path); } catch { return false; }
+ return !isStale(readMeta(path), path);
+}
+
/**
* Acquire the lock stored at `path`, with the same semantics as
* [[acquireMapLock]]: a LockHandle on success, null when a live holder owns it.
diff --git a/ix-cli/src/cli/stale.ts b/ix-cli/src/cli/stale.ts
index 3422dd16..009c1475 100644
--- a/ix-cli/src/cli/stale.ts
+++ b/ix-cli/src/cli/stale.ts
@@ -2,14 +2,27 @@
import * as fs from "node:fs";
import * as path from "node:path";
-import { resolveWorkspaceRoot } from "./config.js";
-import { loadIngestBaseline } from "./ingest-baseline.js";
+import { canonicalWorkspacePath, resolveWorkspaceRoot } from "./config.js";
+import { loadIngestBaseline, type IngestBaseline } from "./ingest-baseline.js";
import { hasCompletedMapFor } from "./map-baseline.js";
+import { readMapRefreshOutcome, readMapStale } from "./map-freshness.js";
import { canonicalizeDiscoveredFilePath, discoverSourceFiles } from "./file-discovery.js";
export interface StaleInfo {
graphCompleted: boolean;
mapCompleted: boolean;
+ /**
+ * The last `ix map` deferred the map after an edit (CL-13): regions are the
+ * last computed map's until a region view or `ix map --remap` refreshes
+ * them. `mapCompleted` keeps its strict meaning and reads false meanwhile;
+ * this says why.
+ */
+ mapStale: boolean;
+ /**
+ * While `mapStale`: why the last background refresh failed, when it did
+ * (`readMapRefreshOutcome`); null otherwise.
+ */
+ mapRefreshError: string | null;
lastIngestAt: string | null;
currentRev: number;
staleFiles: number;
@@ -87,6 +100,8 @@ export function detectStaleFiles(
return {
graphCompleted: false,
mapCompleted: false,
+ mapStale: false,
+ mapRefreshError: null,
lastIngestAt: null,
currentRev: 0,
staleFiles: 0,
@@ -153,9 +168,14 @@ export function detectStaleFiles(
}
}
+ const mapStale = readMapStale(workspaceRoot) !== null;
+ const lastRefresh = mapStale ? readMapRefreshOutcome(workspaceRoot) : null;
+ const mapRefreshError = lastRefresh?.ok === false ? (lastRefresh.reason ?? "no reason recorded") : null;
return {
graphCompleted: true,
mapCompleted: hasCompletedMapFor(workspaceRoot, baseline),
+ mapStale,
+ mapRefreshError,
lastIngestAt: baseline.lastIngestAt,
currentRev: baseline.currentRev,
staleFiles: changedFiles.length,
@@ -165,6 +185,23 @@ export function detectStaleFiles(
};
}
+/**
+ * The ingest baseline for `root`, and the spelling of the root it is stored
+ * under. The baselines match their root as a string. `ix map` stores the
+ * canonical root, so a symlinked or 8.3-named spelling of it (RUNNER~1 on
+ * Windows) read as never mapped; a root stored as given (`ix ingest` of a path
+ * spelled that way) is still found under its own spelling first.
+ */
+function loadBaselineUnderEitherSpelling(root: string): { root: string; baseline: IngestBaseline } | null {
+ const resolved = path.resolve(root);
+ const asGiven = loadIngestBaseline(resolved);
+ if (asGiven) return { root: resolved, baseline: asGiven };
+ const canonical = canonicalWorkspacePath(resolved);
+ if (canonical === resolved) return null;
+ const baseline = loadIngestBaseline(canonical);
+ return baseline ? { root: canonical, baseline } : null;
+}
+
/**
* Whether the active workspace has a completed map baseline.
*
@@ -175,9 +212,8 @@ export function detectStaleFiles(
*/
export function hasCompletedMapBaseline(root?: string): boolean {
try {
- const workspaceRoot = path.resolve(root ?? resolveWorkspaceRoot());
- const baseline = loadIngestBaseline(workspaceRoot);
- return baseline !== null && hasCompletedMapFor(workspaceRoot, baseline);
+ const found = loadBaselineUnderEitherSpelling(root ?? resolveWorkspaceRoot());
+ return found !== null && hasCompletedMapFor(found.root, found.baseline);
} catch {
return false;
}
@@ -186,7 +222,7 @@ export function hasCompletedMapBaseline(root?: string): boolean {
/** Whether source ingestion completed cleanly for the active workspace. */
export function hasCompletedSourceGraphBaseline(root?: string): boolean {
try {
- return loadIngestBaseline(path.resolve(root ?? resolveWorkspaceRoot())) !== null;
+ return loadBaselineUnderEitherSpelling(root ?? resolveWorkspaceRoot()) !== null;
} catch {
return false;
}
diff --git a/ix-cli/vitest.setup.ts b/ix-cli/vitest.setup.ts
index 7c4eeee8..57c55265 100644
--- a/ix-cli/vitest.setup.ts
+++ b/ix-cli/vitest.setup.ts
@@ -16,6 +16,12 @@
// under the default forks pool, so no file can leak an IX_HOME to the next.
delete process.env.IX_HOME;
+// No test may start a real background map refresh (a detached `ix
+// __map-refresh` process that outlives the test). Region views start one
+// whenever a deferred map is stale; with this they only say so. The tests of
+// that path turn it back on and inject the spawner.
+process.env.IX_MAP_BACKGROUND_REFRESH = "0";
+
// A target that resolves to nothing runs one bounded `rg` over the workspace to
// say why (`cli/miss-reason.ts`). Under test the "workspace" is this checkout,
// whose sources and fixtures mention every name a test misses on, so the
diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.md
index eaa72c0a..302ae394 100644
--- a/skills/ix/references/flags.md
+++ b/skills/ix/references/flags.md
@@ -585,6 +585,7 @@ Map the architectural hierarchy of a codebase.
| `--graph` | — | off | Render the hierarchy as a graph/tree view (default) |
| `--list` | — | off | Render the ranked list view instead of the default graph/tree view |
| `--full` | — | off | Force full local map, bypassing automatic safety limits (advanced/testing) |
+| `--remap` | — | off | Compute the map now, even from an automatic (hook) run that would defer it |
| `--verbose` | — | off | Show raw confidence/crosscut scores and signals, plus per-file ingest diagnostics (including why a patch failed to commit) |
| `--silent` | — | off | Suppress all output except a one-line summary (useful for LLM hooks) |