Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix(map): reject empty hierarchy after ingest (#509)

Hiro-Chiba6c7414e454b3
diff --git a/ix-cli/src/cli/__tests__/map-auto-skip.test.ts b/ix-cli/src/cli/__tests__/map-auto-skip.test.ts
index 4ef148db..e567221e 100644
--- a/ix-cli/src/cli/__tests__/map-auto-skip.test.ts
+++ b/ix-cli/src/cli/__tests__/map-auto-skip.test.ts
@@ -6,6 +6,8 @@ import { Command } from 'commander';
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
applyRequestedMapCoalesceExitCode,
+ describeEmptyCompletedMap,
+ invalidateBaselineForEmptyCompletedMap,
mapModeForIngest,
registerMapCommand,
requestedMapCoalesceExitCode,
@@ -93,3 +95,116 @@ describe('mapModeForIngest', () => {
expect(mapModeForIngest('1')).toBe(false);
});
});
+
+describe('describeEmptyCompletedMap', () => {
+ const emptyResult = {
+ file_count: 0,
+ region_count: 0,
+ regions: [],
+ outcome: 'full_local_completed',
+ };
+
+ it('rejects a completed empty map after a clean ingest committed source patches', () => {
+ const message = describeEmptyCompletedMap(emptyResult, {
+ filesDiscovered: 260,
+ patchesApplied: 260,
+ parseErrors: 0,
+ commitErrors: 0,
+ });
+
+ expect(message).toContain('mapped 0 files after local ingest found 260 supported source files');
+ expect(message).toContain('(260 patches committed)');
+ expect(message).toContain('no architecture hierarchy was created');
+ expect(message).toContain("the next 'ix map' re-parses every file");
+ });
+
+ it('does not reject an actually empty workspace', () => {
+ expect(describeEmptyCompletedMap(emptyResult, {
+ filesDiscovered: 0,
+ patchesApplied: 0,
+ parseErrors: 0,
+ commitErrors: 0,
+ })).toBeUndefined();
+ });
+
+ it('does not mask an ingest failure with a map-language diagnosis', () => {
+ expect(describeEmptyCompletedMap(emptyResult, {
+ filesDiscovered: 12,
+ patchesApplied: 12,
+ parseErrors: 1,
+ commitErrors: 0,
+ })).toBeUndefined();
+ expect(describeEmptyCompletedMap(emptyResult, {
+ filesDiscovered: 12,
+ patchesApplied: 12,
+ parseErrors: 0,
+ commitErrors: 1,
+ })).toBeUndefined();
+ });
+
+ it('ignores an outcome the backend does not actually send', () => {
+ // 'ok' was in the completed set but is not one of the six MapOutcome
+ // labels, so it only ever looked like coverage.
+ expect(describeEmptyCompletedMap({ ...emptyResult, outcome: 'ok' }, {
+ filesDiscovered: 260,
+ patchesApplied: 260,
+ parseErrors: 0,
+ commitErrors: 0,
+ })).toBeUndefined();
+ });
+
+ it('leaves guardrail refusals alone, which carry no regions by design', () => {
+ for (const outcome of ['local_map_too_large', 'local_map_not_recommended']) {
+ expect(describeEmptyCompletedMap({ ...emptyResult, outcome }, {
+ filesDiscovered: 260,
+ patchesApplied: 260,
+ parseErrors: 0,
+ commitErrors: 0,
+ })).toBeUndefined();
+ }
+ });
+
+ it('requires both an explicitly completed outcome and an entirely empty response', () => {
+ expect(describeEmptyCompletedMap({ ...emptyResult, outcome: 'local_map_not_recommended' }, {
+ filesDiscovered: 12,
+ patchesApplied: 12,
+ parseErrors: 0,
+ commitErrors: 0,
+ })).toBeUndefined();
+ expect(describeEmptyCompletedMap({ ...emptyResult, file_count: 12 }, {
+ filesDiscovered: 12,
+ patchesApplied: 12,
+ parseErrors: 0,
+ commitErrors: 0,
+ })).toBeUndefined();
+ expect(describeEmptyCompletedMap({ ...emptyResult, region_count: 1 }, {
+ filesDiscovered: 12,
+ patchesApplied: 12,
+ parseErrors: 0,
+ commitErrors: 0,
+ })).toBeUndefined();
+ });
+
+ it('invalidates the current workspace baseline, including on an unchanged retry', () => {
+ const invalidate = vi.fn();
+ const message = invalidateBaselineForEmptyCompletedMap(emptyResult, {
+ filesDiscovered: 260,
+ patchesApplied: 0,
+ parseErrors: 0,
+ commitErrors: 0,
+ }, '/workspace/account', invalidate);
+
+ expect(message).toContain('(0 patches committed)');
+ expect(invalidate).toHaveBeenCalledOnce();
+ expect(invalidate).toHaveBeenCalledWith('/workspace/account');
+ });
+
+ it('rejects an empty cached map when coupling is reported unchanged', () => {
+ expect(describeEmptyCompletedMap({ ...emptyResult, outcome: 'coupling_unchanged' }, {
+ filesDiscovered: 260,
+ patchesApplied: 0,
+ parseErrors: 0,
+ commitErrors: 0,
+ })).toBeDefined();
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/stale-workspace.test.ts b/ix-cli/src/cli/__tests__/stale-workspace.test.ts
index 44d32cf2..d75a5402 100644
--- a/ix-cli/src/cli/__tests__/stale-workspace.test.ts
+++ b/ix-cli/src/cli/__tests__/stale-workspace.test.ts
@@ -3,7 +3,7 @@ import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
-import { ingestMtimeCachePath, saveConfig } from "../config.js";
+import { clearIngestMtimeCache, ingestMtimeCachePath, saveConfig } from "../config.js";
import { loadIngestBaseline } from "../ingest-baseline.js";
import { persistIngestBaselineIfClean } from "../commands/ingest.js";
import { detectStaleFiles, isFileStale } from "../stale.js";
@@ -119,6 +119,31 @@ describe("workspace-scoped staleness", () => {
});
});
+ it("returns the unmapped state after an empty completed map invalidates a prior baseline", () => {
+ const root = path.join(home, "empty-completed-map");
+ const filePath = writeSource(root, "index.php", "<?php function value() { return 1; }\n");
+ persistIngestBaselineIfClean(
+ root,
+ new Map([[filePath, fs.statSync(filePath).mtimeMs]]),
+ 26,
+ 0,
+ 0,
+ new Date("2026-08-24T12:00:00.000Z"),
+ );
+ expect(detectStaleFiles(root).mapCompleted).toBe(true);
+
+ clearIngestMtimeCache(root);
+
+ expect(loadIngestBaseline(root)).toBeNull();
+ expect(detectStaleFiles(root)).toEqual({
+ mapCompleted: false,
+ lastIngestAt: null,
+ currentRev: 0,
+ staleFiles: 0,
+ sampleChangedFiles: [],
+ });
+ });
+
it("reports a mapped file that was deleted after ingest", async () => {
const root = path.join(home, "deleted-file");
const filePath = writeSource(root, "deleted.js", "export const value = 1;\n");
diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.ts
index 8214d286..2549e3b1 100644
--- a/ix-cli/src/cli/commands/ingest.ts
+++ b/ix-cli/src/cli/commands/ingest.ts
@@ -703,6 +703,14 @@ export type CommitOutcome =
| { kind: "warn"; message: string }
| { kind: "fatal"; message: string };
+/** Minimal local-ingest facts needed by commands that continue after ingestion. */
+export interface IngestFilesSummary {
+ filesDiscovered: number;
+ patchesApplied: number;
+ parseErrors: number;
+ commitErrors: number;
+}
+
/**
* Decide how loudly a run should complain about patches that failed to commit.
*
@@ -794,7 +802,7 @@ export function ingestCompletedCleanly(parseErrors: number, commitErrors: number
export async function ingestFiles(
path: string,
opts: { recursive?: boolean; force?: boolean; format: string; root?: string; debug?: boolean; printSummary?: boolean; suppressOutput?: boolean; lang?: string; mapMode?: boolean; deadlineSignal?: AbortSignal }
-): Promise<void> {
+): Promise<IngestFilesSummary> {
const debug = opts.debug || process.env.IX_DEBUG === '1';
const mapMode = opts.mapMode === true;
const trueStart = performance.now();
@@ -2059,6 +2067,12 @@ export async function ingestFiles(
opts.mapMode === true ? "--verbose" : "--debug",
opts.deadlineSignal?.aborted === true
);
+ const summary: IngestFilesSummary = {
+ filesDiscovered,
+ patchesApplied,
+ parseErrors,
+ commitErrors,
+ };
if (commitReport.kind === "warn") {
process.stderr.write(` ${commitReport.message}\n`);
// Non-zero even though we do not throw. A partial failure still means the
@@ -2072,7 +2086,7 @@ export async function ingestFiles(
if (opts.suppressOutput === true) {
if (commitReport.kind === "fatal") throw new Error(commitReport.message);
- return;
+ return summary;
}
if (opts.format === 'json') {
@@ -2173,6 +2187,7 @@ export async function ingestFiles(
// where main emitted a valid document carrying patchesApplied: 0. The
// suppressOutput path above throws earlier because it has no report to emit.
if (commitReport.kind === "fatal") throw new Error(commitReport.message);
+ return summary;
}
// ---------------------------------------------------------------------------
diff --git a/ix-cli/src/cli/commands/map.ts b/ix-cli/src/cli/commands/map.ts
index b3662ebc..c5ad8c8d 100644
--- a/ix-cli/src/cli/commands/map.ts
+++ b/ix-cli/src/cli/commands/map.ts
@@ -2,12 +2,12 @@ import { resolve } from "node:path";
import { type Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
-import { getEndpoint } from "../config.js";
+import { clearIngestMtimeCache, getEndpoint } from "../config.js";
import { roundFloat } from "../format.js";
import { llmLine, llmError } from "../llm.js";
import { bootstrap, resolveWorkspaceId } from "../bootstrap.js";
import { formatFetchError } from "../errors.js";
-import { ingestFiles } from "./ingest.js";
+import { ingestFiles, type IngestFilesSummary } from "./ingest.js";
import { detectSystem } from "../system.js";
import { getRemoteRunner, isCloudReady } from "../remote.js";
import { acquireMapLock } from "../single-flight.js";
@@ -121,6 +121,70 @@ export interface MapResult {
persistence?: MapPersistence;
}
+/**
+ * The backend's MapOutcome labels that mean "a map was produced" (MapTypes.scala).
+ *
+ * The other two it can send — `local_map_too_large` and `local_map_not_recommended`
+ * — are guardrail refusals that legitimately carry no regions, so they are left
+ * out: an empty response is the expected shape there, not a contradiction.
+ *
+ * `coupling_unchanged` belongs in this set even though it sounds like a skip.
+ * The backend answers it with the cached map from the last build's revision
+ * (`map.copy(outcome = CouplingUnchanged)`), not an empty delta — so an empty
+ * one is a real empty hierarchy being served from cache, which is exactly the
+ * state worth catching on a retry.
+ */
+const COMPLETED_MAP_OUTCOMES = new Set([
+ "full_local_completed",
+ "fast_local_completed",
+ "incremental_completed",
+ "coupling_unchanged",
+]);
+
+/**
+ * A completed map cannot legitimately contain no files immediately after a
+ * clean ingest found supported source files. Treat that contradiction as a
+ * failure instead of telling hooks and agents that an empty hierarchy is
+ * current.
+ */
+export function describeEmptyCompletedMap(
+ result: Pick<MapResult, "file_count" | "region_count" | "regions" | "outcome">,
+ ingest: Pick<IngestFilesSummary, "filesDiscovered" | "patchesApplied" | "parseErrors" | "commitErrors"> | undefined,
+): string | undefined {
+ if (!ingest || ingest.filesDiscovered <= 0 || ingest.parseErrors > 0 || ingest.commitErrors > 0) {
+ return undefined;
+ }
+ if (!result.outcome || !COMPLETED_MAP_OUTCOMES.has(result.outcome)) return undefined;
+ if (result.file_count !== 0 || result.region_count !== 0 || result.regions.length !== 0) return undefined;
+
+ const sourceFiles = ingest.filesDiscovered;
+ const patches = ingest.patchesApplied;
+ return `Backend reported ${result.outcome}, but mapped 0 files after local ingest found ${sourceFiles} supported source ${sourceFiles === 1 ? "file" : "files"} (${patches} ${patches === 1 ? "patch" : "patches"} committed). The source graph was ingested, but no architecture hierarchy was created. The active backend may not map this source language yet. The ingest cache has been cleared, so the next 'ix map' re-parses every file.`;
+}
+
+/**
+ * An empty completed map invalidates the local completion baseline. Keeping it
+ * would make `ix status` report mapCompleted=true for a hierarchy that does not
+ * exist. The next run may hash-skip unchanged files, so detection is based on
+ * discovered supported sources rather than only newly committed patches.
+ */
+/**
+ * Clearing the mtime cache is what invalidates the baseline — the baseline is
+ * stored in it — and it costs a full re-parse on the next run. That is the
+ * intended trade: a workspace whose hierarchy does not exist should not also be
+ * carrying a completion record that makes `ix status` claim it does.
+ */
+export function invalidateBaselineForEmptyCompletedMap(
+ result: Pick<MapResult, "file_count" | "region_count" | "regions" | "outcome">,
+ ingest: Pick<IngestFilesSummary, "filesDiscovered" | "patchesApplied" | "parseErrors" | "commitErrors"> | undefined,
+ projectRoot: string,
+ invalidate: (root: string) => void = clearIngestMtimeCache,
+): string | undefined {
+ const message = describeEmptyCompletedMap(result, ingest);
+ if (message) invalidate(projectRoot);
+ return message;
+}
+
type MapSortMode = "importance" | "confidence" | "size" | "alpha";
export interface MapTextRenderOptions {
level?: string;
@@ -254,6 +318,7 @@ Examples:
// The local backend bootstrap below only runs on the local path —
// cloud ingestion doesn't require a local Ix backend.
const ingestStart = performance.now();
+ let localIngest: IngestFilesSummary | undefined;
if (cloudReady) {
const runner = getRemoteRunner()!; // isCloudReady guarantees non-null
try {
@@ -276,7 +341,7 @@ Examples:
return;
}
try {
- await ingestFiles(cwd, {
+ localIngest = await ingestFiles(cwd, {
recursive: true,
format: (machineFormat || silent) ? "json" : "text",
printSummary: false,
@@ -338,6 +403,13 @@ Examples:
if (mapInterval) { clearInterval(mapInterval); process.stderr.write('\r' + ' '.repeat(60) + '\r'); }
const mapMs = Math.round(performance.now() - mapStart);
+ const emptyMapError = invalidateBaselineForEmptyCompletedMap(result, localIngest, cwd);
+ if (emptyMapError) {
+ emitError(emptyMapError);
+ process.exitCode = 1;
+ return;
+ }
+
if (silent) {
const systems = result.regions.filter(r => r.label_kind === "system").length;
const subsystems = result.regions.filter(r => r.label_kind === "subsystem").length;