Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
feat(cli): region readers report a stale map in json and llm output (#880)
Ian Hocke31c087e8d9d
diff --git a/docs/llm-format.md b/docs/llm-format.mdindex 0da0f5f7..6b6a36c9 100644--- a/docs/llm-format.md+++ b/docs/llm-format.md@@ -437,6 +437,18 @@ views starting a refresh. `--format json` carries `map_stale` on every map (`fal`regions_as_of` (`{map_rev, file_count}` of the last map, `null` whenfresh); `ix map --silent` ends its line with `· map=stale`.+The region views say it in their machine output too, not only on stderr.+While the map is stale, `overview`, `subsystems`, `locate`, `impact` and+`explain` print one `diagnostic code=map_stale` record, worded as `ix map`'s,+with their answer (just before its first record), and their `--format json`+object gains `map_stale: true` and, when the deferring `ix map` recorded which+map it was, `regions_as_of` (`{map_rev, file_count}`, as above) at its top+level. A fresh map adds neither key and no record. An error answer carries+neither: it is its own answer, and a caller takes a leading `error` record as+the command failing. `ix locate` with several targets prints the record once+per call and puts the keys on each answered target's object; `ix impact --all`+puts them on the grouping object. Text output only has the stderr line.+`ix stats`:```diff --git a/ix-cli/src/cli/__tests__/map-freshness.test.ts b/ix-cli/src/cli/__tests__/map-freshness.test.tsindex adb87184..72ec75c9 100644--- a/ix-cli/src/cli/__tests__/map-freshness.test.ts+++ b/ix-cli/src/cli/__tests__/map-freshness.test.ts@@ -13,12 +13,15 @@ import { Command } from "commander";import { registerMapCommand } from "../commands/map.js";import { canonicalWorkspacePath, mapResultCachePath, mapStalePath } from "../config.js";import {+ clearMapStale,ensureFreshMap,+ ensureFreshMapState,MAP_REFRESH_ARG,mapBackgroundRefreshEnabled,mapBackgroundTimeoutMs,mapRefreshDebounceMs,mapRefreshInvocation,+ mapStaleJson,markMapStale,readMapRefreshOutcome,readMapStale,@@ -286,6 +289,50 @@ describe("map refresh", () => {});describe("ensureFreshMap (the reader)", () => {+ it("reports the map its regions are from, as the deferred ix map named it", async () => {+ await map();+ writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");+ process.env.IX_AUTO_MAP = "1";+ let shown: { map_stale: boolean; regions_as_of: { map_rev: number; file_count: number } | null };+ try {+ const r = await captured(async () => {+ const program = new Command();+ registerMapCommand(program);+ await program.parseAsync(["node", "ix", "map", repo, "--format", "json"]);+ });+ shown = JSON.parse(r.out);+ } finally {+ delete process.env.IX_AUTO_MAP;+ rmSync(lockPathForTest(repo), { force: true });+ }+ expect(shown.map_stale, "the edit's map was deferred").toBe(true);+ expect(shown.regions_as_of).not.toBeNull();+ expect(readMapStale(repo)?.regionsAsOf, "the marker names the same map").toEqual(shown.regions_as_of);++ const r = await captured(() => ensureFreshMapState({ root: repo, spawn: () => {} }));+ expect(r.value).toEqual({ mapStale: true, regionsAsOf: shown.regions_as_of });+ expect(mapStaleJson(r.value)).toEqual({ map_stale: true, regions_as_of: shown.regions_as_of });+ expect(r.out, "nothing on stdout").toBe("");+ expect(readMapStale(repo)?.regionsAsOf, "recording the attempt keeps it").toEqual(shown.regions_as_of);+ });++ it("keeps the map a standing marker names when re-marked, and forgets it once the map is computed", () => {+ markMapStale(repo, { ingestRev: 1, regionsAsOf: { map_rev: 4, file_count: 3 } });+ markMapStale(repo, { ingestRev: 2 });+ expect(readMapStale(repo)?.regionsAsOf).toEqual({ map_rev: 4, file_count: 3 });+ clearMapStale(repo);+ markMapStale(repo, { ingestRev: 3 });+ expect(readMapStale(repo)).not.toBeNull();+ expect(readMapStale(repo)?.regionsAsOf).toBeUndefined();+ });++ it("says nothing in the json fields when the map is fresh", async () => {+ await map();+ const r = await captured(() => ensureFreshMapState({ root: repo, spawn: () => {} }));+ expect(r.value).toEqual({});+ expect(mapStaleJson(r.value)).toEqual({});+ });+it("makes no request and starts nothing without a marker", async () => {await map();backend.requests.length = 0;diff --git a/ix-cli/src/cli/__tests__/region-readers-refresh.test.ts b/ix-cli/src/cli/__tests__/region-readers-refresh.test.tsindex d633fcfb..566b626e 100644--- a/ix-cli/src/cli/__tests__/region-readers-refresh.test.ts+++ b/ix-cli/src/cli/__tests__/region-readers-refresh.test.ts@@ -8,11 +8,12 @@ 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.+ * regions calls `ensureFreshMapState` (`ensureFreshMap`, with what its output+ * says about it) 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 answer nor the exit code -- the json+ * only says the map is stale (region-readers-stale-output.test.ts).*/// The suite runs from a checkout no workspace covers; it is about ordering,@@ -30,14 +31,14 @@ vi.mock("../config.js", async (importOriginal) => ({const { events, refreshImpl } = vi.hoisted(() => ({events: [] as string[],- refreshImpl: { current: async (): Promise<unknown> => undefined },+ refreshImpl: { current: async (): Promise<unknown> => ({}) },}));vi.mock("../map-freshness.js", async (orig) => ({...(await orig<typeof import("../map-freshness.js")>()),- ensureFreshMap: vi.fn(async () => {+ ensureFreshMapState: vi.fn(async () => {events.push("refresh");- await refreshImpl.current();+ return await refreshImpl.current();}),}));@@ -120,7 +121,7 @@ describe.each(READERS)("ix %s refreshes a deferred map first", (_name, args, loabeforeEach(() => {events.length = 0;- refreshImpl.current = async () => undefined;+ refreshImpl.current = async () => ({});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];@@ -157,13 +158,15 @@ describe.each(READERS)("ix %s refreshes a deferred map first", (_name, args, loareal.markMapStale(join(home, "repo"), { ingestRev: 1 });let spawnAsked = 0;process.env.IX_MAP_BACKGROUND_REFRESH = "1";- refreshImpl.current = () => real.ensureFreshMap({+ refreshImpl.current = () => real.ensureFreshMapState({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);+ const { map_stale: mapStale, ...answer } = JSON.parse(failed);+ expect(mapStale, "the json says the map is stale").toBe(true);+ expect(answer).toEqual(JSON.parse(fine));expect(process.exitCode).toBe(fineExit);});});diff --git a/ix-cli/src/cli/__tests__/region-readers-stale-output.test.ts b/ix-cli/src/cli/__tests__/region-readers-stale-output.test.tsnew file mode 100644index 00000000..b6a08976--- /dev/null+++ b/ix-cli/src/cli/__tests__/region-readers-stale-output.test.ts@@ -0,0 +1,226 @@+// 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: a region reader that finds the map deferred answers from the last+ * map. Its stderr says so; these check that its machine output does too --+ * `map_stale` (and `regions_as_of` when the marker knows it) at the top of+ * the json payload, one `diagnostic code=map_stale` record in llm, worded as+ * `ix map` words it -- and that a fresh map, the text output and the exit+ * code are left as they were.+ */++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(),+}));++vi.mock("../hierarchy.js", async (orig) => ({+ ...(await orig<typeof import("../hierarchy.js")>()),+ getSystemPath: async () => [],+ getEffectiveSystemPath: async () => [],+ bucketByHierarchy: async () => [],+}));++const { failing } = vi.hoisted(() => ({ failing: new Set<string>() }));++const NODE = {+ id: "node-1", kind: "function", name: "Target",+ provenance: { sourceUri: "src/a.ts" }, attrs: { line_start: 1, line_end: 3 },+};++vi.mock("../../client/api.js", () => {+ 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 (failing.has(prop)) throw new Error("backend went away");+ 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],+ ["subsystems --list", ["subsystems", "--list"], async () => (await import("../commands/subsystems.js")).registerSubsystemsCommand],+ ["explain", ["explain", "Target"], async () => (await import("../commands/explain.js")).registerExplainCommand],+];++async function run(register: Register, args: string[], format: string): Promise<{ out: string; exitCode: unknown }> {+ 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);+ process.exitCode = undefined;+ try {+ await program.parseAsync([...args, "--format", format], { from: "user" });+ } catch {+ // A backend failure the CLI's top-level handler would report.+ } finally {+ log.mockRestore();+ error.mockRestore();+ write.mockRestore();+ }+ const exitCode = process.exitCode;+ process.exitCode = undefined;+ return { out: out.join("\n"), exitCode };+}++const AS_OF = { map_rev: 7, file_count: 42 };++let home = "";+const saved: Record<string, string | undefined> = {};++beforeEach(() => {+ failing.clear();+ home = mkdtempSync(join(tmpdir(), "ix-readers-stale-"));+ 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";+ // Stale, and nothing started in the background: the reader answers from+ // the last map and says why.+ process.env.IX_MAP_BACKGROUND_REFRESH = "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 });+});++/** The root a reader with no `root` option checks, so the marker is the one it reads. */+async function readerRoot(): Promise<string> {+ const { canonicalMapRoot } = await import("../map-root.js");+ const { resolveWorkspaceRoot } = await import("../config.js");+ return canonicalMapRoot(resolveWorkspaceRoot());+}++async function markStale(regionsAsOf?: { map_rev: number; file_count: number }): Promise<void> {+ const { markMapStale } = await import("../map-freshness.js");+ markMapStale(await readerRoot(), { ingestRev: 3, ...(regionsAsOf ? { regionsAsOf } : {}) });+}++async function expectedDiagnostic(regionsAsOf?: { map_rev: number; file_count: number }): Promise<string> {+ const { llmLine } = await import("../llm.js");+ const { mapStaleNotice } = await import("../commands/map.js");+ return llmLine("diagnostic", [["code", "map_stale"], ["message", mapStaleNotice({ mapStale: true, regionsAsOf })]]);+}++const staleDiagnostics = (out: string): string[] => out.split("\n").filter((l) => /^diagnostic code=map_stale\b/.test(l));++describe.each(READERS)("ix %s says in its machine output when the map is stale", (_name, args, load) => {+ it("json: no map_stale or regions_as_of while the map is fresh", async () => {+ const { out } = await run(await load(), args, "json");+ const payload = JSON.parse(out);+ expect(payload).not.toHaveProperty("map_stale");+ expect(payload).not.toHaveProperty("regions_as_of");+ });++ it("json: map_stale and regions_as_of at the top level while it is stale", async () => {+ const register = await load();+ const fresh = JSON.parse((await run(register, args, "json")).out);+ await markStale(AS_OF);+ const stale = JSON.parse((await run(register, args, "json")).out);+ expect(stale.map_stale).toBe(true);+ expect(stale.regions_as_of).toEqual(AS_OF);+ // Only added: everything else reads as before.+ const { map_stale: _s, regions_as_of: _r, ...rest } = stale;+ expect(rest).toEqual(fresh);+ });++ it("json: map_stale without regions_as_of when the marker does not name the map", async () => {+ await markStale();+ const stale = JSON.parse((await run(await load(), args, "json")).out);+ expect(stale.map_stale).toBe(true);+ expect(stale).not.toHaveProperty("regions_as_of");+ });++ it("llm: one diagnostic code=map_stale record worded as ix map words it; none when fresh", async () => {+ const register = await load();+ const fresh = await run(register, args, "llm");+ expect(staleDiagnostics(fresh.out)).toEqual([]);+ await markStale(AS_OF);+ const stale = await run(register, args, "llm");+ expect(staleDiagnostics(stale.out)).toEqual([await expectedDiagnostic(AS_OF)]);+ // The rest of the records are the fresh run's.+ expect(stale.out.split("\n").filter((l) => !/^diagnostic code=map_stale\b/.test(l))).toEqual(fresh.out.split("\n"));+ expect(stale.exitCode).toBe(fresh.exitCode);+ });++ it("llm: no map_stale record ahead of a failure, so a leading error record stays leading", async () => {+ await markStale(AS_OF);+ for (const m of ["entity", "expand", "listSubsystems", "getSubsystemMap"]) failing.add(m);+ const { out } = await run(await load(), args, "llm");+ expect(staleDiagnostics(out)).toEqual([]);+ if (out !== "") expect(out).toMatch(/^error code=/);+ });++ it("text: stdout and the exit code are unchanged", async () => {+ const register = await load();+ const fresh = await run(register, args, "text");+ await markStale(AS_OF);+ const stale = await run(register, args, "text");+ expect(stale.out).toBe(fresh.out);+ expect(stale.exitCode).toBe(fresh.exitCode);+ });+});++describe("ix locate with several targets", () => {+ const load = async () => (await import("../commands/locate.js")).registerLocateCommand;++ it("llm: one diagnostic for the whole call", async () => {+ await markStale(AS_OF);+ const { out } = await run(await load(), ["locate", "Target", "Target"], "llm");+ expect(staleDiagnostics(out)).toEqual([await expectedDiagnostic(AS_OF)]);+ });++ it("json: each answered target carries the flag", async () => {+ await markStale(AS_OF);+ const payload = JSON.parse((await run(await load(), ["locate", "Target", "Target"], "json")).out);+ expect(payload.targets).toHaveLength(2);+ for (const t of payload.targets) {+ expect(t.map_stale).toBe(true);+ expect(t.regions_as_of).toEqual(AS_OF);+ }+ });+});diff --git a/ix-cli/src/cli/commands/explain.ts b/ix-cli/src/cli/commands/explain.tsindex 57bfae5f..5de28870 100644--- a/ix-cli/src/cli/commands/explain.ts+++ b/ix-cli/src/cli/commands/explain.ts@@ -14,7 +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 { ensureFreshMapState, mapStaleJson, mapStaleLlm } from "../map-freshness.js";import { forMcp, toolCall } from "../next-step.js";import {assessTargetStructure, checkGraphHealth, graphHealthJson, graphHealthProse, isUnhealthy, worseHealth,@@ -44,8 +44,9 @@ export function registerExplainCommand(program: Command): void {// 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();+ // exit code; with no deferred map it is one file check. The json and+ // llm output say when it is stale.+ const mapState = await ensureFreshMapState();// New pipeline: collect facts → infer role → infer importance → render.// The workspace health check runs alongside: cached per backend@@ -73,7 +74,7 @@ export function registerExplainCommand(program: Command): void {}if (opts.format === "llm") {- printLlmLines(renderExplainLlm(facts, role, importance, rendered, health));+ printLlmLines([...mapStaleLlm(mapState), ...renderExplainLlm(facts, role, importance, rendered, health)]);} else if (opts.format === "json") {const output: any = {resolvedTarget: { kind: target.kind, name: target.name },@@ -81,6 +82,7 @@ export function registerExplainCommand(program: Command): void {role,importance,rendered,+ ...mapStaleJson(mapState),};if (degraded) {output.graph = graphHealthJson(health);diff --git a/ix-cli/src/cli/commands/impact.ts b/ix-cli/src/cli/commands/impact.tsindex e24009d1..f0495136 100644--- a/ix-cli/src/cli/commands/impact.ts+++ b/ix-cli/src/cli/commands/impact.ts@@ -14,7 +14,7 @@ import { captureJson, lineSpan, printJson, relativePath, rowLocation, sliceEdgeRimport { 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";+import { ensureFreshMapState, mapStaleJson, mapStaleLlm, type MapStaleState } from "../map-freshness.js";const CONTAINER_KINDS = new Set(["class", "module", "file", "object", "trait", "interface"]);@@ -51,8 +51,9 @@ 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();+ // Never throws and never moves the exit code. The json and llm output+ // say when it is stale: the region buckets below come from the map.+ const mapState = await ensureFreshMapState();// A hollowed graph reports "low risk, no dependents" for anything:// the answer is only as good as the edges it counts. Said first, in@@ -62,11 +63,13 @@ export function registerImpactCommand(program: Command): void {if (graph && opts.format === "llm") console.log(llmLine("graph", graphHealthLlmFields(health)));if (graph && opts.format === "text") renderWarning(graphHealthProse(health));+ // `--all` says it once, with the header grouping the candidates.+ const ownState = set.all ? {} : mapState;const analyse = (entity: ResolvedEntity) => CONTAINER_KINDS.has(entity.kind)- ? containerImpact(client, entity, limit, depth, opts.format, graph)- : leafImpact(client, entity, depth, limit, opts.format, graph);+ ? containerImpact(client, entity, limit, depth, opts.format, graph, ownState)+ : leafImpact(client, entity, depth, limit, opts.format, graph, ownState);- if (set.all) await impactOfAll(symbol, set, opts.format, analyse);+ if (set.all) await impactOfAll(symbol, set, opts.format, analyse, mapState);else await analyse(target);});@@ -86,6 +89,7 @@ async function impactOfAll(set: TargetSet,format: string,analyse: (entity: ResolvedEntity) => Promise<void>,+ mapState: MapStaleState = {},): Promise<void> {// `n` is the candidate's `--pick` number (resolve.ts candidateSet).const candidates = set.entities.map((e, i) => ({ n: e.n ?? i + 1, id: e.id, name: e.name, kind: e.kind, path: relativePath(e.path) ?? e.path }));@@ -105,6 +109,7 @@ async function impactOfAll(candidates,results,...(truncation ? { diagnostics: [{ code: "candidates_truncated", message: truncation }] } : {}),+ ...mapStaleJson(mapState),});return;}@@ -112,6 +117,7 @@ async function impactOfAll(if (format === "llm") {console.log(llmLine("impact_all", [["target", symbol], ["candidates", candidates.length], ["total", total]]));if (truncation) console.log(llmLine("diagnostic", [["code", "candidates_truncated"], ["message", truncation]]));+ for (const line of mapStaleLlm(mapState)) console.log(line);} else if (truncation) {renderWarning(truncation);}@@ -356,6 +362,7 @@ async function containerImpact(depth: number,format: string,graph?: Record<string, unknown>,+ mapState: MapStaleState = {},): Promise<void> {const isJson = format === "json";const diagnostics: string[] = [];@@ -465,6 +472,7 @@ async function containerImpact(stripNulls({resolvedTarget: { kind: target.kind, name: target.name },graph,+ ...mapStaleJson(mapState),depth,systemPath: systemPathMapped.length > 0 ? systemPathMapped : undefined,riskSummary: risk.riskSummary,@@ -494,6 +502,8 @@ async function containerImpact();} else if (format === "llm") {const lines = [+ // With the answer, not before it (mapStaleLlm).+ ...mapStaleLlm(mapState),...impactHeaderLlm(target, risk, systemPathMapped),llmLine("counts", [["members", members.length],@@ -582,6 +592,7 @@ async function leafImpact(limit: number,format: string,graph?: Record<string, unknown>,+ mapState: MapStaleState = {},): Promise<void> {const isJson = format === "json";const [callersResult, calleesResult, systemPath, decisionsResult, tasksResult, bugsResult] = await Promise.all([@@ -641,6 +652,7 @@ async function leafImpact(stripNulls({resolvedTarget: { kind: target.kind, name: target.name },graph,+ ...mapStaleJson(mapState),depth,systemPath: systemPathMapped.length > 0 ? systemPathMapped : undefined,riskSummary: risk.riskSummary,@@ -676,6 +688,8 @@ async function leafImpact(const callerSlice = sliceEdgeResults(callersResult.nodes, limit);const calleeSlice = sliceEdgeResults(calleesResult.nodes, limit);const lines = [+ // With the answer, not before it (mapStaleLlm).+ ...mapStaleLlm(mapState),...impactHeaderLlm(target, risk, systemPathMapped),llmLine("counts", [["callers", callerSlice.total],diff --git a/ix-cli/src/cli/commands/locate.ts b/ix-cli/src/cli/commands/locate.tsindex 7e5e6cf3..815a8dbe 100644--- a/ix-cli/src/cli/commands/locate.ts+++ b/ix-cli/src/cli/commands/locate.ts@@ -20,7 +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";+import { ensureFreshMapState, mapStaleJson, mapStaleLlm, type MapStaleState } from "../map-freshness.js";const CONTAINER_KINDS = new Set(["class", "module", "file", "trait", "object", "interface"]);const FILE_KINDS = new Set(["file"]);@@ -36,6 +36,9 @@ interface LocateOutput {systemPath: Array<{ name: string; kind: string }> | null;hasMapData?: boolean;stale?: boolean;+ /** The map is deferred (CL-13): the system path is the last map's. */+ map_stale?: true;+ regions_as_of?: { map_rev: number; file_count: number };diagnostics: string[];/** A miss: the `unresolved_target` record fields every graph command's miss carries. */error?: "unresolved_target";@@ -66,10 +69,19 @@ ${EXIT_CODES_HELP}`)const client = createClient();// 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));+ // resolves, so several targets print at most one stale-map notice --+ // and, in llm, one `diagnostic code=map_stale` record. In json each+ // answered target carries `map_stale`.+ let mapChecked: Promise<MapStaleState> | undefined;+ const freshMap = (): Promise<MapStaleState> => (mapChecked ??= ensureFreshMapState());+ let staleSaid = false;+ const staleLlmOnce = (state: MapStaleState): string[] => {+ if (staleSaid) return [];+ const lines = mapStaleLlm(state);+ staleSaid = lines.length > 0;+ return lines;+ };+ await runPerTarget(symbols, opts.format, (symbol) => locateOne(client, symbol, opts, freshMap, staleLlmOnce));});}@@ -77,7 +89,8 @@ async function locateOne(client: IxClient,symbol: string,opts: { kind?: string; path?: string; pick?: number; format: string },- freshMap: () => Promise<unknown>,+ freshMap: () => Promise<MapStaleState>,+ staleLlmOnce: (state: MapStaleState) => string[],): Promise<void> {const diagnostics: string[] = [];@@ -128,7 +141,7 @@ async function locateOne(const isFile = FILE_KINDS.has(target.kind);// Never throws and never moves the exit code.- await freshMap();+ const mapState = await freshMap();// Parallel fetch: effective system path, parent container (for non-containers), entity detailsconst [systemPath, containsResult, details] = await Promise.all([@@ -204,6 +217,10 @@ async function locateOne(if (stale) {output.stale = true;}+ // Only json reads these. llm has its own record, once per call, with the+ // answer and not before it (mapStaleLlm).+ if (opts.format === "json") Object.assign(output, mapStaleJson(mapState));+ if (opts.format === "llm") for (const line of staleLlmOnce(mapState)) console.log(line);outputLocate(output, symbol, opts.format);}diff --git a/ix-cli/src/cli/commands/map.ts b/ix-cli/src/cli/commands/map.tsindex f63b883b..8a9421c8 100644--- a/ix-cli/src/cli/commands/map.ts+++ b/ix-cli/src/cli/commands/map.ts@@ -16,7 +16,7 @@ import { canRenderProgress } from "../stderr.js";import { loadIngestBaseline } from "../ingest-baseline.js";import { saveMapBaseline } from "../map-baseline.js";import { loadCachedMap, loadLastMap, resolveMapCacheSlot, saveCachedMap } from "../map-result-cache.js";-import { clearMapStale, markMapStale, readMapStale } from "../map-freshness.js";+import { clearMapStale, markMapStale, mapStaleNotice, readMapStale, type MapStaleState } from "../map-freshness.js";import { resolveMapRoot } from "../map-root.js";import { readBackendHealth } from "./upgrade.js";import { renderWarning } from "../ui.js";@@ -508,12 +508,10 @@ 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.+ * `map_rev` and `outcome` all come from. Shared with the region readers, in+ * `map-freshness.ts`, with `mapStaleNotice`; both still exported from here.*/-export interface MapStaleState {- mapStale?: boolean;- regionsAsOf?: { map_rev: number; file_count: number };-}+export { mapStaleNotice, type MapStaleState };/** `ix map --format json`. Exported for tests. */export function mapJsonPayload(@@ -1188,7 +1186,11 @@ async function runMapCommand(pathArg: string | undefined, opts: { format: stringif (deferred) {result = deferred;// A new marker for a new edit; an unchanged run keeps the one it found.- if (localIngest?.incremental) markMapStale(cwd);+ // It names the map these regions are from, for the readers'+ // `regions_as_of`.+ if (localIngest?.incremental) {+ markMapStale(cwd, { regionsAsOf: { map_rev: deferred.map_rev, file_count: deferred.file_count } });+ }} else if (cached) {result = cached;} else {@@ -1323,18 +1325,6 @@ async function runMapCommand(pathArg: string | undefined, opts: { format: stringrenderMapText(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 adiff --git a/ix-cli/src/cli/commands/overview.ts b/ix-cli/src/cli/commands/overview.tsindex d8d7d4f8..9e749e6e 100644--- a/ix-cli/src/cli/commands/overview.ts+++ b/ix-cli/src/cli/commands/overview.ts@@ -11,7 +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";+import { ensureFreshMapState, mapStaleJson, mapStaleLlm, type MapStaleState } 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"]);@@ -66,16 +66,17 @@ 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();+ // Never throws and never moves the exit code. The json and llm answers+ // say so too: the system path below comes from the map's regions.+ const mapState = await ensureFreshMapState();const isContainer = CONTAINER_KINDS.has(target.kind);const isRegion = REGION_KINDS.has(target.kind);if (isContainer || isRegion) {- await overviewContainer(client, target, opts.format);+ await overviewContainer(client, target, opts.format, mapState);} else {- await overviewLeaf(client, target, opts.format);+ await overviewLeaf(client, target, opts.format, mapState);}});}@@ -139,7 +140,8 @@ function siblingKindLabel(kind: string): string {async function overviewContainer(client: IxClient,target: { id: string; kind: string; name: string; resolutionMode: string },- format: string+ format: string,+ mapState: MapStaleState = {},): Promise<void> {const diagnostics: string[] = [];const isRegion = REGION_KINDS.has(target.kind);@@ -199,11 +201,13 @@ async function overviewContainer(};if (format === "json") {- printJson(result);+ printJson({ ...result, ...mapStaleJson(mapState) });return;}if (format === "llm") {+ // With the answer, not before it (mapStaleLlm).+ for (const line of mapStaleLlm(mapState)) console.log(line);for (const line of overviewContainerLlm({ target, displayPath, systemPath: systemPathMapped, hasMap, childrenByKind, keyItems, diagnostics })) {console.log(line);}@@ -235,7 +239,8 @@ async function overviewContainer(async function overviewLeaf(client: IxClient,target: { id: string; kind: string; name: string; resolutionMode: string },- format: string+ format: string,+ mapState: MapStaleState = {},): Promise<void> {const diagnostics: string[] = [];@@ -335,11 +340,13 @@ async function overviewLeaf(};if (format === "json") {- printJson(result);+ printJson({ ...result, ...mapStaleJson(mapState) });return;}if (format === "llm") {+ // With the answer, not before it (mapStaleLlm).+ for (const line of mapStaleLlm(mapState)) console.log(line);for (const line of overviewLeafLlm({ target, displayPath, containedIn, systemPath: systemPathMapped, hasMap, siblingsByKind, keySiblings, diagnostics })) {console.log(line);}diff --git a/ix-cli/src/cli/commands/subsystems.ts b/ix-cli/src/cli/commands/subsystems.tsindex 5daa8e2a..e601b39d 100644--- a/ix-cli/src/cli/commands/subsystems.ts+++ b/ix-cli/src/cli/commands/subsystems.ts@@ -11,7 +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 { ensureFreshMapState, mapStaleJson, mapStaleLlm } from "../map-freshness.js";import {renderSubsystemExplanationJson,renderSubsystemExplanationText,@@ -164,8 +164,12 @@ Examples:}// 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();+ // Never throws and never moves the exit code. The json and llm answers+ // below say when it is stale; an error is its own answer.+ const mapState = await ensureFreshMapState();+ const mapStale = mapStaleJson(mapState);+ // With the answer, not before it (mapStaleLlm).+ const sayStaleLlm = (): void => { for (const line of mapStaleLlm(mapState)) console.log(line); };if (opts.list) {let result: SubsystemListResult;@@ -191,6 +195,7 @@ Examples:: scores;if (opts.format === "llm") {+ sayStaleLlm();console.log(llmLine("subsystems", [["count", filtered.length]]));for (const s of filtered) console.log(renderSubsystemScoreLlm(s));return;@@ -198,7 +203,7 @@ Examples:if (opts.format === "json") {if (opts.detailed) {- printJson(buildDetailedListPayload(filtered, result.pagination));+ printJson({ ...buildDetailedListPayload(filtered, result.pagination), ...mapStale });} else {const compact = filtered.map(s => ({name: s.name,@@ -208,10 +213,11 @@ Examples:chunks_per_file: roundFloat(s.chunk_density),smell_files: s.smell_files,}));- printJson({ scores: compact });+ printJson({ scores: compact, ...mapStale });}return;}+ // `--detailed` without `--format json`: a text-format run, left as it was.if (opts.detailed) {printJson(buildDetailedListPayload(filtered, result.pagination));return;@@ -262,20 +268,22 @@ Examples:const score = (scoreResult.scores ?? []).find((candidate) => candidate.region_id === result.target.id) ?? null;if (opts.format === "json") {- printJson(renderSubsystemExplanationJson(result, score));+ printJson({ ...renderSubsystemExplanationJson(result, score), ...mapStale });return;}+ if (opts.format === "llm") sayStaleLlm();console.log(renderSubsystemExplanationText(result, score));return;}if (opts.format === "json") {- printJson(compactMapResult(result));+ printJson({ ...compactMapResult(result), ...mapStale });return;}if (opts.format === "llm") {+ sayStaleLlm();if (isScopedSubsystemResult(result)) {for (const line of renderScopedSubsystemLlm(result)) console.log(line);} else {diff --git a/ix-cli/src/cli/map-freshness.ts b/ix-cli/src/cli/map-freshness.tsindex 8e6790a5..9f241814 100644--- a/ix-cli/src/cli/map-freshness.ts+++ b/ix-cli/src/cli/map-freshness.ts@@ -7,6 +7,7 @@ import { fileURLToPath } from "node:url";import type { IxClient } from "../client/api.js";import { mapRefreshOutcomePath, mapStalePath } from "./config.js";import { loadIngestBaseline } from "./ingest-baseline.js";+import { llmLine } from "./llm.js";/*** The architecture map left for later (CL-13).@@ -35,6 +36,12 @@ export interface MapStaleInfo {ingestRev: number | null;/** When a refresh was last attempted, epoch ms; the debounce runs from here. */lastAttemptAt?: number;+ /**+ * The last computed map the stored regions come from, when the deferring+ * `ix map` knew it; what readers report as `regions_as_of`. Absent on a+ * marker an older CLI wrote.+ */+ regionsAsOf?: { map_rev: number; file_count: number };}const isFiniteNumber = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);@@ -49,6 +56,11 @@ export function readMapStale(projectRoot: string): MapStaleInfo | 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;+ // Only an extra: one that does not parse leaves the marker standing.+ const asOf = data.regionsAsOf as Record<string, unknown> | null | undefined;+ if (asOf && typeof asOf === "object" && isFiniteNumber(asOf.map_rev) && isFiniteNumber(asOf.file_count)) {+ info.regionsAsOf = { map_rev: asOf.map_rev, file_count: asOf.file_count };+ }return info;} catch {return null;@@ -72,12 +84,22 @@ function writeMapStale(projectRoot: string, info: MapStaleInfo): void {* 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.+ *+ * `regionsAsOf` names the last computed map. When not given, the one a marker+ * already standing named is kept: no map was computed in between, or that+ * marker would have been removed.*/-export function markMapStale(projectRoot: string, info: Partial<Pick<MapStaleInfo, "since" | "ingestRev">> = {}): void {- writeMapStale(projectRoot, {+export function markMapStale(+ projectRoot: string,+ info: Partial<Pick<MapStaleInfo, "since" | "ingestRev" | "regionsAsOf">> = {},+): void {+ const next: MapStaleInfo = {since: info.since ?? Date.now(),ingestRev: info.ingestRev !== undefined ? info.ingestRev : (loadIngestBaseline(projectRoot)?.currentRev ?? null),- });+ };+ const regionsAsOf = info.regionsAsOf ?? readMapStale(projectRoot)?.regionsAsOf;+ if (regionsAsOf) next.regionsAsOf = { map_rev: regionsAsOf.map_rev, file_count: regionsAsOf.file_count };+ writeMapStale(projectRoot, next);}/** Remove the marker: the map was computed. Best-effort. */@@ -205,21 +227,79 @@ export async function spawnMapRefresh(root: string): Promise<void> {* 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.+ * map is stale; `ensureFreshMapState` says the same in the form a reader's+ * machine output carries (`mapStaleJson`, `mapStaleLlm`).*/export async function ensureFreshMap(opts: EnsureFreshMapOptions = {}): Promise<boolean> {- let why: string | undefined;+ return (await ensureFreshMapState(opts)).mapStale === true;+}++/**+ * `ensureFreshMap`, resolving to what the reader's json and llm output say+ * about it: `{}` when the map is fresh; `mapStale` and, when the marker names+ * it, the last computed map (`regionsAsOf`) when it is stale. Read from the+ * marker `ensureFreshMap` reads anyway, so no extra file or request.+ */+export async function ensureFreshMapState(opts: EnsureFreshMapOptions = {}): Promise<MapStaleState> {+ let scheduled: { why: string; marker: MapStaleInfo | null } | undefined;try {- why = await scheduleRefresh(opts);+ scheduled = await scheduleRefresh(opts);} catch {// Never the reader's problem: it answers from the regions it has.- why = "its refresh failed";+ scheduled = { why: "its refresh failed", marker: null };}- if (why === undefined) return false;+ if (scheduled === undefined) return {};try {- process.stderr.write(`ix: architecture map is stale (${why}); regions shown may predate recent edits. Run ix map --remap to refresh.\n`);+ process.stderr.write(`ix: architecture map is stale (${scheduled.why}); regions shown may predate recent edits. Run ix map --remap to refresh.\n`);} catch { /* non-critical */ }- return true;+ const asOf = scheduled.marker?.regionsAsOf;+ return asOf ? { mapStale: true, regionsAsOf: { ...asOf } } : { mapStale: true };+}++/**+ * What a deferred map (CL-13) adds to the output of the command that shows+ * it. `mapStale` says the map was not recomputed after the last ingest;+ * `regionsAsOf` names the last computed map the regions come from.+ */+export interface MapStaleState {+ mapStale?: boolean;+ regionsAsOf?: { map_rev: number; file_count: number };+}++/**+ * 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.+ * `ix map` and every region reader use it, so they say it the same way.+ */+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.`;+}++/**+ * A region reader's json fields for `state`, spread into the top level of its+ * payload: `map_stale: true` and, when known, `regions_as_of` (`{map_rev,+ * file_count}`, as `ix map --format json` has it). Nothing when the map is+ * fresh, so a fresh answer reads exactly as before.+ */+export function mapStaleJson(state: MapStaleState): { map_stale?: true; regions_as_of?: { map_rev: number; file_count: number } } {+ if (state.mapStale !== true) return {};+ return state.regionsAsOf+ ? { map_stale: true, regions_as_of: { ...state.regionsAsOf } }+ : { map_stale: true };+}++/**+ * A region reader's llm records for `state`: the one `diagnostic+ * code=map_stale` record `ix map` prints (`renderMapLlm`), or none when the+ * map is fresh. Printed with the answer, never ahead of an `error` record: a+ * caller takes a leading `error code=` as the command failing (mcp/server.ts).+ */+export function mapStaleLlm(state: MapStaleState): string[] {+ if (state.mapStale !== true) return [];+ return [llmLine("diagnostic", [["code", "map_stale"], ["message", mapStaleNotice(state)]])];}/** The root a reader's refresh is for, canonical; undefined when there is none. */@@ -242,8 +322,11 @@ async function readerRoot(given: string | undefined): Promise<string | undefinedtry { 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> {+/**+ * Why the map is stale after scheduling, and the marker that says so, or+ * undefined when it is fresh.+ */+async function scheduleRefresh(opts: EnsureFreshMapOptions): Promise<{ why: string; marker: MapStaleInfo } | undefined> {const root = await readerRoot(opts.root);if (root === undefined) return undefined;const marker = readMapStale(root);@@ -252,7 +335,7 @@ async function scheduleRefresh(opts: EnsureFreshMapOptions): Promise<string | unconst { isCloudReady } = await import("./remote.js");if (await isCloudReady()) return undefined;- if (!mapBackgroundRefreshEnabled()) return "background refresh is off";+ if (!mapBackgroundRefreshEnabled()) return { why: "background refresh is off", marker };const now = opts.now ?? Date.now;const debounce = mapRefreshDebounceMs();@@ -265,11 +348,11 @@ async function scheduleRefresh(opts: EnsureFreshMapOptions): Promise<string | unconst from = Math.max(m.lastAttemptAt ?? -Infinity, failedAt ?? -Infinity);return Number.isFinite(from) && now() - from < debounce;};- const debouncedWhy = (): string => {+ const debouncedWhy = (m: MapStaleInfo): { why: string; marker: MapStaleInfo } => {const last = readMapRefreshOutcome(root);- return last?.ok === false ? "its last background refresh failed" : "a refresh was tried moments ago";+ return { why: last?.ok === false ? "its last background refresh failed" : "a refresh was tried moments ago", marker: m };};- if (debounced(marker)) return debouncedWhy();+ if (debounced(marker)) return debouncedWhy(marker);// Taken only to decide and record the attempt, then let go for the child:// two readers at once start one refresh, not two.@@ -277,11 +360,12 @@ async function scheduleRefresh(opts: EnsureFreshMapOptions): Promise<string | unconst 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";+ if (!lock) return { why: "another ix map is running", marker };+ let current: MapStaleInfo | null;try {- const current = readMapStale(root);+ current = readMapStale(root);if (current === null) return undefined;- if (debounced(current)) return debouncedWhy();+ if (debounced(current)) return debouncedWhy(current);// Recorded before the child starts, so the readers that follow it// inside the debounce window do not start another.writeMapStale(root, { ...current, lastAttemptAt: now() });@@ -291,9 +375,9 @@ async function scheduleRefresh(opts: EnsureFreshMapOptions): Promise<string | untry {await (opts.spawn ?? spawnMapRefresh)(root);} catch {- return "its refresh could not start";+ return { why: "its refresh could not start", marker: current };}- return "refreshing in background";+ return { why: "refreshing in background", marker: current };}/** What the last background refresh for a root did. */diff --git a/skills/ix/references/output-formats.md b/skills/ix/references/output-formats.mdindex 69f0f02b..20f76f0e 100644--- a/skills/ix/references/output-formats.md+++ b/skills/ix/references/output-formats.md@@ -29,6 +29,13 @@ Ids appear only where two rows would otherwise read the same (same name, kindand path); pass one back as the symbol to pick that row. `--fields id` printsthem everywhere.+A `diagnostic code=map_stale` record (json: `map_stale: true`, with+`regions_as_of: {map_rev, file_count}` when known) on `ix overview`,+`subsystems`, `locate`, `impact`, `explain` or `map` means the architecture+map was not recomputed after the latest edits: system paths and regions are+the last map's. The answer is still usable; run `ix map --remap` when the+hierarchy itself matters. A fresh map adds neither.+### Setting it onceResolution is: the flag, then `IX_FORMAT`, then `format` in `~/.ix/config.yaml`