From a97b713f740932339a5f1036ad2213168c421270 Mon Sep 17 00:00:00 2001
From: pablodiazjorge <102741971+pablodiazjorge@users.noreply.github.com>
Date: Mon, 12 Oct 2026 21:13:35 +0200
Subject: [PATCH 01/54] test(mcp): fix three MCP boundary suites on native
Windows (#2312)
* test(mcp): fix three MCP boundary suites on native Windows
* test(mcp): report unavailable root symlink coverage as a skip
---------
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
---
tests/boundary/mcp/dylibResolutionMcp.test.ts | 101 +++++++++---------
tests/boundary/mcp/electronMcp.test.ts | 17 +--
.../mcp/toolErrorSchemaDelivery.test.ts | 4 +-
3 files changed, 67 insertions(+), 55 deletions(-)
diff --git a/tests/boundary/mcp/dylibResolutionMcp.test.ts b/tests/boundary/mcp/dylibResolutionMcp.test.ts
index 4040935ae..d97961a73 100644
--- a/tests/boundary/mcp/dylibResolutionMcp.test.ts
+++ b/tests/boundary/mcp/dylibResolutionMcp.test.ts
@@ -247,7 +247,7 @@ it("traces a standalone Mach-O file whose name ends in .app", async () => {
});
});
-it.skipIf(process.getuid?.() === 0)(
+it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"keeps a permission denied while canonicalizing the opened bundle",
async () => {
const parent = await createTestTempDirectory("rea-dylib-mcp-revoked-");
@@ -451,52 +451,57 @@ it.each([
},
);
-it("reports caller-selected roots that cannot be traced as invalid input", async () => {
- const app = join(
- await createTestTempDirectory("rea-dylib-roots-"),
- "Fixture.app",
- );
- await mkdir(join(app, "Contents/MacOS"), { recursive: true });
- await writeFile(
- join(app, "Contents/Info.plist"),
- "CFBundleExecutableApp",
- );
- await writeFile(
- join(app, "Contents/MacOS/App"),
- machoImage({ commands: [buildVersionCommand(1)] }),
- );
- await symlink("/bin/ls", join(app, "Contents/MacOS/outside"));
- await withClient(async (client) => {
- const opened = await client.callTool({
- name: "open_binary",
- arguments: { path: app },
- });
- expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
- for (const [root, message] of [
- ["Contents/MacOS/Missing", "is not a regular file"],
- ["Contents/MacOS", "is not a regular file"],
- ["Contents/Info.plist", "is not a Mach-O image"],
- ["Contents/MacOS/outside", "resolves outside the analyzed root"],
- ] as const) {
- const called = await client.callTool({
- name: "trace_dylib_resolution",
- arguments: { roots: ["Contents/MacOS/App", root] },
- });
- expect(called.isError, root).toBe(true);
- expect(parseMcpToolError(called), root).toMatchObject({
- error: {
- code: "invalid_request",
- details: {
- issues: [
- {
- path: ["roots", 1],
- reason: "invalid_value",
- message: expect.stringContaining(`Root ${root} ${message}`),
- },
- ],
+for (const [root, message] of [
+ ["Contents/MacOS/Missing", "is not a regular file"],
+ ["Contents/MacOS", "is not a regular file"],
+ ["Contents/Info.plist", "is not a Mach-O image"],
+ ["Contents/MacOS/outside", "resolves outside the analyzed root"],
+] as const) {
+ const needsFileSymlink = root === "Contents/MacOS/outside";
+ // File symlinks on Windows need Developer Mode or an elevated token.
+ it.skipIf(process.platform === "win32" && needsFileSymlink)(
+ `reports caller-selected root ${root} as invalid input`,
+ async () => {
+ const app = join(
+ await createTestTempDirectory("rea-dylib-roots-"),
+ "Fixture.app",
+ );
+ await mkdir(join(app, "Contents/MacOS"), { recursive: true });
+ await writeFile(
+ join(app, "Contents/Info.plist"),
+ "CFBundleExecutableApp",
+ );
+ await writeFile(
+ join(app, "Contents/MacOS/App"),
+ machoImage({ commands: [buildVersionCommand(1)] }),
+ );
+ if (needsFileSymlink) await symlink("/bin/ls", join(app, root));
+ await withClient(async (client) => {
+ const opened = await client.callTool({
+ name: "open_binary",
+ arguments: { path: app },
+ });
+ expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
+ const called = await client.callTool({
+ name: "trace_dylib_resolution",
+ arguments: { roots: ["Contents/MacOS/App", root] },
+ });
+ expect(called.isError, root).toBe(true);
+ expect(parseMcpToolError(called), root).toMatchObject({
+ error: {
+ code: "invalid_request",
+ details: {
+ issues: [
+ {
+ path: ["roots", 1],
+ reason: "invalid_value",
+ message: expect.stringContaining(`Root ${root} ${message}`),
+ },
+ ],
+ },
},
- },
+ });
});
- }
- });
-});
+ },
+ );
+}
diff --git a/tests/boundary/mcp/electronMcp.test.ts b/tests/boundary/mcp/electronMcp.test.ts
index 3fe41b1ca..fef9839aa 100644
--- a/tests/boundary/mcp/electronMcp.test.ts
+++ b/tests/boundary/mcp/electronMcp.test.ts
@@ -1,7 +1,7 @@
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok as resultOk } from "../../../src/domain/result.js";
import { rm, symlink, writeFile } from "node:fs/promises";
-import { join } from "node:path";
+import { basename, join } from "node:path";
import { pathToFileURL } from "node:url";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
@@ -248,12 +248,12 @@ it("exposes endpoint-scoped Electron discovery and inspection as Evidence", asyn
expect(inspected.isError).not.toBe(true);
expect(inspected.structuredContent).toMatchObject({
normalized_result: {
- target: { file_path: expect.stringMatching(/\/index\.html$/u) },
+ target: { file_path: expect.stringMatching(/[\\/]index\.html$/u) },
scripts: {
items: [
expect.objectContaining({
frame_id: "frame-main",
- file_path: expect.stringMatching(/\/app\.js$/u),
+ file_path: expect.stringMatching(/[\\/]app\.js$/u),
cdp_hash: null,
length: null,
is_module: null,
@@ -264,7 +264,7 @@ it("exposes endpoint-scoped Electron discovery and inspection as Evidence", asyn
expect.objectContaining({
target_id: "electron-worker",
opener_target_id: "electron-page",
- file_path: expect.stringMatching(/\/worker\.js$/u),
+ file_path: expect.stringMatching(/[\\/]worker\.js$/u),
}),
],
},
@@ -276,8 +276,13 @@ it("runs active Electron scenarios with selected paths and inferred working dire
temporary.push(root);
const applicationPath = join(root, "main.js");
await writeFile(applicationPath, "module.exports = {};\n");
- const aliasedRoot = join(root, "..", `${root.split("/").at(-1)}-alias`);
- await symlink(root, aliasedRoot, "dir");
+ const aliasedRoot = join(root, "..", `${basename(root)}-alias`);
+ // A junction needs no symlink privilege on Windows.
+ await symlink(
+ root,
+ aliasedRoot,
+ process.platform === "win32" ? "junction" : "dir",
+ );
temporary.push(aliasedRoot);
const workingDirectory = await createTestTempDirectory(
"rea-electron-working-directory-",
diff --git a/tests/boundary/mcp/toolErrorSchemaDelivery.test.ts b/tests/boundary/mcp/toolErrorSchemaDelivery.test.ts
index af1952d8f..f35696d01 100644
--- a/tests/boundary/mcp/toolErrorSchemaDelivery.test.ts
+++ b/tests/boundary/mcp/toolErrorSchemaDelivery.test.ts
@@ -33,7 +33,9 @@ it("delivers typed tool failures without violating the advertised success schema
const diagnostic = parseMcpToolError(reply);
expect(diagnostic.error.message, request.name).not.toBe("");
if ("path" in request.arguments || "input_path" in request.arguments)
- expect(JSON.stringify(diagnostic), request.name).toContain(missing);
+ expect(JSON.stringify(diagnostic), request.name).toContain(
+ JSON.stringify(missing).slice(1, -1),
+ );
if (reply.structuredContent !== undefined) {
const validate = new Ajv2020({
strict: false,
From b123b2e51cc7d6d2157525664be2df88fb1ba3bd Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Tue, 13 Oct 2026 03:22:38 +0800
Subject: [PATCH 02/54] perf(evidence): authenticate and seal imported bundles
in one pass
Reuse the immutable domain parser at the file boundary instead of rebuilding and revalidating an already authenticated bundle. Existing filesystem and integrity regressions pass (27 tests); a 4 MiB parsing probe preserves immutable output and reduces repeated validation work.
---
src/application/EvidenceBundleFiles.ts | 12 ++----------
1 file changed, 2 insertions(+), 10 deletions(-)
diff --git a/src/application/EvidenceBundleFiles.ts b/src/application/EvidenceBundleFiles.ts
index 83f2f65d9..ecca7ab1e 100644
--- a/src/application/EvidenceBundleFiles.ts
+++ b/src/application/EvidenceBundleFiles.ts
@@ -1,9 +1,9 @@
import { resolve } from "node:path";
import {
- createImmutableEvidenceBundle,
describeEvidenceBundleFailure,
describeValidationFailure,
+ parseImmutableEvidenceBundle,
parseEvidenceBundle,
type EvidenceBundle,
} from "../domain/evidenceBundle.js";
@@ -49,15 +49,7 @@ export const readImmutableEvidenceBundle = (
signal?: AbortSignal,
resources?: ArtifactResourceScope,
): Promise> =>
- readBundle(
- path,
- (input) => {
- const bundle = parseEvidenceBundle(input);
- return createImmutableEvidenceBundle(bundle.records, bundle.unknowns);
- },
- signal,
- resources,
- );
+ readBundle(path, parseImmutableEvidenceBundle, signal, resources);
const readBundle = async (
path: string,
From cecc6ecbffe84689a173d1634f342e046b0c8ceb Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Tue, 13 Oct 2026 03:22:46 +0800
Subject: [PATCH 03/54] fix(process): preserve invalid runtime path selections
as input errors
Classify unresolvable and unusable executable or working-directory selections before launch, retaining field paths, attempted candidates and OS diagnostics. Preserve tagged analysis errors through capture lifecycle handling. Replace duplicate missing-path source assertions with public CLI/MCP regression coverage and retain distinct permission, file-kind and PATH checks.
---
src/process/capture/ProcessHarness.ts | 6 +-
.../ProcessScenarioRuntimeValidation.test.ts | 115 ++++++++++++++++--
.../ProcessScenarioRuntimeValidation.ts | 43 ++++---
.../tools/localToolContracts.test.ts | 100 +++++++++++++--
4 files changed, 220 insertions(+), 44 deletions(-)
diff --git a/src/process/capture/ProcessHarness.ts b/src/process/capture/ProcessHarness.ts
index 352b13ba9..1033e68cd 100644
--- a/src/process/capture/ProcessHarness.ts
+++ b/src/process/capture/ProcessHarness.ts
@@ -5,7 +5,7 @@ import type { ProcessScenario } from "../../domain/process/processScenario.js";
import { parseProcessCapture } from "../../domain/process/processCaptureParsing.js";
import { err, ok, type Result } from "../../domain/result.js";
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
-import type { AnalysisError } from "../../domain/analysisErrorBase.js";
+import { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
describeProcessCaptureExecutionFailure,
ProcessCaptureError,
@@ -864,7 +864,7 @@ export const captureProcessScenario = async (
const executionFailureReason =
describeProcessCaptureExecutionFailure(cause);
return err(
- failure instanceof ProcessCaptureError
+ failure instanceof AnalysisError
? failure
: new ProcessCaptureError("process capture failed", {
cause,
@@ -882,7 +882,7 @@ export const captureProcessScenario = async (
const failure = normalizeCaptureFailure(cause, signal);
const executionFailure = describeProcessCaptureExecutionFailure(cause);
return err(
- failure instanceof ProcessCaptureError
+ failure instanceof AnalysisError
? failure
: new ProcessCaptureError("process capture lifecycle failed", {
cause,
diff --git a/src/process/capture/ProcessScenarioRuntimeValidation.test.ts b/src/process/capture/ProcessScenarioRuntimeValidation.test.ts
index fcf23e6ef..1277b753f 100644
--- a/src/process/capture/ProcessScenarioRuntimeValidation.test.ts
+++ b/src/process/capture/ProcessScenarioRuntimeValidation.test.ts
@@ -10,6 +10,8 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, it } from "vitest";
+import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
+import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import {
resolveExecutable,
resolveProcessScenarioRuntimePaths,
@@ -51,7 +53,12 @@ it("resolves a Windows executable through the canonical PATH spelling", async ()
);
expect(resolved.executable).toBe(candidate);
} catch (cause: unknown) {
- const message = cause instanceof Error ? cause.message : String(cause);
+ const message =
+ cause instanceof AnalysisInputError
+ ? (cause.issues[0]?.message ?? cause.message)
+ : cause instanceof Error
+ ? cause.message
+ : String(cause);
expect(message).toContain(candidate);
expect(message).not.toContain(ambient);
}
@@ -60,14 +67,100 @@ it("resolves a Windows executable through the canonical PATH spelling", async ()
}
});
-it("retains the selected missing working directory and OS reason", async () => {
- const selected = join(tmpdir(), "rea-process-missing-cwd-unique");
- const scenario = parseProcessScenario({
- executable: process.execPath,
- working_directory: selected,
- });
-
- await expect(resolveProcessScenarioRuntimePaths(scenario)).rejects.toThrow(
- `working directory could not be resolved: ${selected} (ENOENT)`,
- );
+it("reports a working-directory file as invalid input", async () => {
+ const root = await mkdtemp(join(tmpdir(), "rea-process-invalid-cwd-"));
+ const selectedFile = join(root, "selected-file");
+ await writeFile(selectedFile, "not a directory");
+ try {
+ const failure = await runtimePathFailure({
+ executable: process.execPath,
+ working_directory: selectedFile,
+ });
+ expect(projectAnalysisError(failure)).toMatchObject({
+ code: "invalid_request",
+ details: {
+ operation: "capture_process_scenario",
+ issues: [
+ {
+ path: ["working_directory"],
+ reason: "invalid_value",
+ message: `working directory is not a directory: ${selectedFile}`,
+ },
+ ],
+ },
+ });
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
});
+
+it("reports an executable directory as invalid input", async () => {
+ const root = await mkdtemp(
+ join(tmpdir(), "rea-process-executable-directory-"),
+ );
+ const directory = join(root, "tool-directory");
+ try {
+ await mkdir(directory);
+ const directoryFailure = await runtimePathFailure({
+ executable: directory,
+ working_directory: root,
+ });
+ expect(projectAnalysisError(directoryFailure)).toMatchObject({
+ code: "invalid_request",
+ details: {
+ issues: [
+ {
+ path: ["executable"],
+ message: `executable could not be resolved: ${directory}; checked ${directory} (not a regular file)`,
+ },
+ ],
+ },
+ });
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+it.skipIf(process.platform === "win32")(
+ "reports a non-executable regular file as invalid input",
+ async () => {
+ const root = await mkdtemp(join(tmpdir(), "rea-process-non-executable-"));
+ const selected = join(root, "not-executable");
+ try {
+ await writeFile(selected, "not executable");
+ await chmod(selected, 0o644);
+ const failure = await runtimePathFailure({
+ executable: selected,
+ working_directory: root,
+ });
+ expect(projectAnalysisError(failure)).toMatchObject({
+ code: "invalid_request",
+ details: {
+ issues: [
+ {
+ path: ["executable"],
+ message: `executable could not be resolved: ${selected}; checked ${selected} (EACCES)`,
+ },
+ ],
+ },
+ });
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+);
+
+const runtimePathFailure = async (
+ scenario: Parameters[0],
+): Promise => {
+ let failure: unknown;
+ try {
+ await resolveProcessScenarioRuntimePaths(parseProcessScenario(scenario));
+ } catch (cause: unknown) {
+ failure = cause;
+ }
+ expect(failure).toBeInstanceOf(AnalysisInputError);
+ if (!(failure instanceof AnalysisInputError))
+ throw new Error("Selected runtime path should be invalid input");
+ return failure;
+};
diff --git a/src/process/capture/ProcessScenarioRuntimeValidation.ts b/src/process/capture/ProcessScenarioRuntimeValidation.ts
index 5196005b2..1ac9d2228 100644
--- a/src/process/capture/ProcessScenarioRuntimeValidation.ts
+++ b/src/process/capture/ProcessScenarioRuntimeValidation.ts
@@ -1,13 +1,11 @@
-import { access, realpath, stat } from "node:fs/promises";
import { constants as fsConstants } from "node:fs";
+import { access, realpath, stat } from "node:fs/promises";
import { delimiter, isAbsolute, join, resolve } from "node:path";
import type { ProcessScenario } from "../../domain/process/processScenario.js";
+import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import { snapshotEnvironment } from "../snapshotEnvironment.js";
-import {
- ProcessCaptureError,
- processCaptureCancelled,
-} from "./ProcessCaptureError.js";
+import { processCaptureCancelled } from "./ProcessCaptureError.js";
/** Resolve caller-selected executable and observation paths for this execution. */
export const resolveProcessScenarioRuntimePaths = async (
@@ -20,22 +18,25 @@ export const resolveProcessScenarioRuntimePaths = async (
try {
workingDirectory = await realpath(selectedWorkingDirectory);
} catch (cause: unknown) {
- throw new ProcessCaptureError(
+ throw invalidScenarioPath(
+ "working_directory",
`working directory could not be resolved: ${selectedWorkingDirectory}${osFailure(cause)}`,
- { cause },
+ cause,
);
}
let workingDirectoryStat;
try {
workingDirectoryStat = await stat(workingDirectory);
} catch (cause: unknown) {
- throw new ProcessCaptureError(
+ throw invalidScenarioPath(
+ "working_directory",
`working directory could not be inspected: ${workingDirectory}${osFailure(cause)}`,
- { cause },
+ cause,
);
}
if (!workingDirectoryStat.isDirectory())
- throw new ProcessCaptureError(
+ throw invalidScenarioPath(
+ "working_directory",
`working directory is not a directory: ${workingDirectory}`,
);
const executable = await resolveExecutable(
@@ -80,19 +81,27 @@ export const resolveExecutable = async (
if ((await stat(candidate)).isFile()) return candidate;
failures.push(`${candidate} (not a regular file)`);
} catch (cause: unknown) {
- const code = osErrorCode(cause);
- if (code !== "ENOENT" && code !== "ENOTDIR")
- failures.push(`${candidate}${osFailure(cause)}`);
+ failures.push(`${candidate}${osFailure(cause)}`);
continue;
}
}
- throw new ProcessCaptureError(
- failures.length === 0
- ? `executable could not be resolved: ${command}`
- : `executable could not be resolved: ${command}; checked ${failures.join("; ")}`,
+ throw invalidScenarioPath(
+ "executable",
+ `executable could not be resolved: ${command}; checked ${failures.join("; ")}`,
);
};
+const invalidScenarioPath = (
+ field: "executable" | "working_directory",
+ message: string,
+ cause?: unknown,
+): AnalysisInputError =>
+ new AnalysisInputError(
+ "capture_process_scenario",
+ cause === undefined ? undefined : { cause },
+ [{ path: [field], reason: "invalid_value", message }],
+ );
+
const osErrorCode = (cause: unknown): string | undefined =>
typeof cause === "object" &&
cause !== null &&
diff --git a/tests/acceptance/tools/localToolContracts.test.ts b/tests/acceptance/tools/localToolContracts.test.ts
index dfd38344b..7b911bd27 100644
--- a/tests/acceptance/tools/localToolContracts.test.ts
+++ b/tests/acceptance/tools/localToolContracts.test.ts
@@ -19,6 +19,25 @@ const electron = {
executable_path: "/tmp/Electron",
application_path: "/tmp/main.js",
};
+
+const runCliExpectingInputError = async (
+ scenarioPath: string,
+): Promise => {
+ const failure = await execute(process.execPath, [
+ cli,
+ "capture-process",
+ scenarioPath,
+ "--json",
+ ]).then(
+ () => undefined,
+ (cause: unknown) => cause,
+ );
+ expect(failure).toMatchObject({ code: 1 });
+ if (!(failure instanceof Error) || !("stdout" in failure))
+ throw new Error("Expected the CLI to report an input error on stdout");
+ return JSON.parse(String(failure.stdout)) as unknown;
+};
+
const pathRequests: readonly [string, Record][] = [
["open_binary", { path: nul }],
["open_binary", { path: process.execPath, snapshot_path: nul }],
@@ -235,25 +254,80 @@ captureTest(
});
expect(parseMcpToolError(failed)).toMatchObject({
error: {
- code: "process_capture_failed",
- message: expect.stringContaining(missing),
- details: { execution_failure: expect.stringContaining(missing) },
+ code: "invalid_request",
+ details: {
+ operation: "capture_process_scenario",
+ issues: [
+ {
+ path: ["executable"],
+ message: expect.stringContaining(`${missing} (ENOENT)`),
+ },
+ ],
+ },
},
});
await writeFile(
join(root, "scenario.json"),
JSON.stringify({ executable: missing }),
);
- await expect(
- execute(process.execPath, [
- cli,
- "capture-process",
- join(root, "scenario.json"),
- "--json",
- ]),
- ).rejects.toMatchObject({
- code: 1,
- stdout: expect.stringContaining(missing),
+ const executableCliFailure = await runCliExpectingInputError(
+ join(root, "scenario.json"),
+ );
+ expect(executableCliFailure).toMatchObject({
+ code: "invalid_request",
+ details: {
+ operation: "capture_process_scenario",
+ issues: [
+ {
+ path: ["executable"],
+ message: expect.stringContaining(`${missing} (ENOENT)`),
+ },
+ ],
+ },
+ });
+
+ const missingWorkingDirectory = join(root, "missing-working-directory");
+ const cwdFailure = await call("capture_process_scenario", {
+ executable: process.execPath,
+ working_directory: missingWorkingDirectory,
+ });
+ expect(parseMcpToolError(cwdFailure)).toMatchObject({
+ error: {
+ code: "invalid_request",
+ details: {
+ operation: "capture_process_scenario",
+ issues: [
+ {
+ path: ["working_directory"],
+ message: expect.stringContaining(
+ `${missingWorkingDirectory} (ENOENT)`,
+ ),
+ },
+ ],
+ },
+ },
+ });
+ const cwdScenario = join(root, "missing-working-directory.json");
+ await writeFile(
+ cwdScenario,
+ JSON.stringify({
+ executable: process.execPath,
+ working_directory: missingWorkingDirectory,
+ }),
+ );
+ expect(await runCliExpectingInputError(cwdScenario)).toMatchObject({
+ code: "invalid_request",
+ details: {
+ operation: "capture_process_scenario",
+ issues: [
+ {
+ path: ["working_directory"],
+ message: expect.stringContaining(
+ `${missingWorkingDirectory} (ENOENT)`,
+ ),
+ },
+ ],
+ },
});
},
60_000,
From 23971376158e7815edcbe6c04a8df7c9504650dc Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Tue, 13 Oct 2026 03:22:53 +0800
Subject: [PATCH 04/54] fix(setup): honor config roots and display terminal
dry-run plans
Normalize empty XDG config homes once for configuration writers and registration readers. Render the resolved plan for terminal dry runs while preserving structured output. Cover registration placement and a real PTY dry run, including absence of configuration writes.
---
src/application/SupportedClients.ts | 20 +++----
src/cli/interactiveSetup.ts | 7 +++
src/cli/setupCommands.ts | 6 ++
tests/boundary/cli/cliSetup.test.ts | 58 ++++++++++++++++++-
.../clientConfigurationDialects.test.ts | 16 +++++
5 files changed, 95 insertions(+), 12 deletions(-)
diff --git a/src/application/SupportedClients.ts b/src/application/SupportedClients.ts
index 18c3480d9..488dda49d 100644
--- a/src/application/SupportedClients.ts
+++ b/src/application/SupportedClients.ts
@@ -75,6 +75,10 @@ interface ClientDefinition {
) => NonNullable;
}
+/** XDG treats an empty config-home value as unset. */
+const xdgConfigHome = ({ home, env }: ClientPathContext): string =>
+ env.XDG_CONFIG_HOME || join(home, ".config");
+
const vscodeUserDirectory = ({
home,
platform,
@@ -88,7 +92,7 @@ const vscodeUserDirectory = ({
);
if (platform === "darwin")
return join(home, "Library", "Application Support", "Code", "User");
- return join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "Code", "User");
+ return join(xdgConfigHome({ home, platform, env }), "Code", "User");
};
const traeUserDirectory = ({
@@ -104,7 +108,7 @@ const traeUserDirectory = ({
);
if (platform === "darwin")
return join(home, "Library", "Application Support", "Trae", "User");
- return join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "Trae", "User");
+ return join(xdgConfigHome({ home, platform, env }), "Trae", "User");
};
const claudeDesktopDirectory = ({
@@ -115,7 +119,7 @@ const claudeDesktopDirectory = ({
if (platform === "win32")
return join(env.APPDATA ?? join(home, "AppData", "Roaming"), "Claude");
if (platform === "linux")
- return join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "Claude");
+ return join(xdgConfigHome({ home, platform, env }), "Claude");
return join(home, "Library", "Application Support", "Claude");
};
@@ -268,19 +272,13 @@ const openCodeOverrideDirectory = (
const opencodeDirectory = (context: ClientPathContext): string =>
openCodeOverrideDirectory(context.env) ??
- join(
- context.env.XDG_CONFIG_HOME ?? join(context.home, ".config"),
- "opencode",
- );
+ join(xdgConfigHome(context), "opencode");
/** OpenCode loads global JSON before JSONC, then explicit file and directory overrides. */
const openCodeConfigurationPaths = (
context: ClientPathContext,
): readonly string[] => {
- const directory = join(
- context.env.XDG_CONFIG_HOME ?? join(context.home, ".config"),
- "opencode",
- );
+ const directory = join(xdgConfigHome(context), "opencode");
const overrideDirectory = openCodeOverrideDirectory(context.env);
const paths = [
join(directory, "config.json"),
diff --git a/src/cli/interactiveSetup.ts b/src/cli/interactiveSetup.ts
index 9fcdf3d18..6d19ae6eb 100644
--- a/src/cli/interactiveSetup.ts
+++ b/src/cli/interactiveSetup.ts
@@ -82,6 +82,13 @@ export const renderSetupProgress = (event: SetupProgressEvent): void => {
writeLine(`${symbol} ${event.label}${suffix}`);
};
+/** Show the resolved dry-run plan to a human at an interactive terminal. */
+export const renderSetupDryRun = (actions: readonly SetupAction[]): void => {
+ intro("REA setup plan", promptStreams);
+ renderPreflight(actions);
+ outro("Dry run complete. No changes were made.", promptStreams);
+};
+
/** Finish an interactive setup journey without exposing the full doctor catalog. */
export const renderInteractiveSetupResult = (
result: SetupResult,
diff --git a/src/cli/setupCommands.ts b/src/cli/setupCommands.ts
index 15caac321..483de20cb 100644
--- a/src/cli/setupCommands.ts
+++ b/src/cli/setupCommands.ts
@@ -11,6 +11,7 @@ import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
import { isUpdateFailure } from "../application/UpdateFailure.js";
import {
confirmInteractiveSetup,
+ renderSetupDryRun,
renderInteractiveSetupResult,
renderSetupProgress,
} from "./interactiveSetup.js";
@@ -225,6 +226,8 @@ const runSetupCommand = async (
: undefined,
);
if (interactive) renderInteractiveSetupResult(result, environment);
+ else if (options.dryRun && !input.formatExplicit && hasInteractiveTerminal())
+ renderSetupDryRun(result.plannedActions);
return result;
};
@@ -282,6 +285,9 @@ const setupIsInteractive = (
!options.yes &&
!options.dryRun &&
!formatExplicit &&
+ hasInteractiveTerminal();
+
+const hasInteractiveTerminal = (): boolean =>
process.stdin.isTTY === true &&
process.stdout.isTTY === true &&
process.stderr.isTTY === true;
diff --git a/tests/boundary/cli/cliSetup.test.ts b/tests/boundary/cli/cliSetup.test.ts
index 742a3a6bc..38bc24bb3 100644
--- a/tests/boundary/cli/cliSetup.test.ts
+++ b/tests/boundary/cli/cliSetup.test.ts
@@ -1,5 +1,6 @@
import { execFile } from "node:child_process";
-import { rm } from "node:fs/promises";
+import { access, rm } from "node:fs/promises";
+import { join } from "node:path";
import { promisify } from "node:util";
import { spawn } from "@lydell/node-pty";
@@ -73,6 +74,61 @@ const clientStates = [
const agentActions = actions.filter(({ kind }) => kind !== "install_hopper");
+describe("TTY setup dry run", () => {
+ it("prints the plan and no-mutation notice for a TTY dry run", async () => {
+ const home = await createTestTempDirectory("rea-cli-setup-dry-run-");
+ const terminal = spawn(
+ process.execPath,
+ [
+ "scripts/rea.mjs",
+ "setup",
+ "--dry-run",
+ "--client",
+ "codex",
+ "--skill=false",
+ ],
+ {
+ cwd: process.cwd(),
+ env: {
+ ...process.env,
+ HOME: home,
+ USERPROFILE: home,
+ XDG_CONFIG_HOME: join(home, ".config"),
+ REA_LOG_LEVEL: "silent",
+ NO_COLOR: "1",
+ },
+ name: "xterm-256color",
+ cols: 120,
+ rows: 40,
+ },
+ );
+ let output = "";
+ terminal.onData((data) => {
+ output += data;
+ });
+ const exitCode = await new Promise((resolvePromise, reject) => {
+ const timeout = setTimeout(() => {
+ terminal.kill();
+ reject(new Error(`TTY dry run timed out after output:\n${output}`));
+ }, 15_000);
+ terminal.onExit(({ exitCode: code }) => {
+ clearTimeout(timeout);
+ resolvePromise(code);
+ });
+ });
+
+ expect(exitCode, output).toBe(0);
+ expect(output).toContain("CREATE Codex");
+ expect(output).toContain(join(home, ".codex/config.toml"));
+ expect(output).toContain("Dry run complete. No changes were made.");
+ await expect(
+ access(join(home, ".codex/config.toml")),
+ ).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ });
+});
+
describe("interactive setup journey", () => {
it("shows detected and absent clients without preselecting detected clients", async () => {
const result = await runJourney(
diff --git a/tests/boundary/filesystem/clientConfigurationDialects.test.ts b/tests/boundary/filesystem/clientConfigurationDialects.test.ts
index 9dd850d8c..ce867aab4 100644
--- a/tests/boundary/filesystem/clientConfigurationDialects.test.ts
+++ b/tests/boundary/filesystem/clientConfigurationDialects.test.ts
@@ -37,6 +37,22 @@ const getClients = (home: string) =>
);
describe("additional client configuration dialects", () => {
+ it("treats an empty XDG config home as unset for OpenCode setup", async () => {
+ const home = await createTestTempDirectory("rea-opencode-empty-xdg-");
+ const client = supportedClients(home, "linux", {
+ XDG_CONFIG_HOME: "",
+ }).find(({ name }) => name === "opencode");
+ const expectedPath = join(home, ".config/opencode/opencode.json");
+ if (client === undefined) throw new Error("missing opencode client");
+
+ expect(client.configPath).toBe(expectedPath);
+ expect(client.configPaths).toContain(expectedPath);
+ expect(
+ await configureClientConfiguration(client, {}, command),
+ ).toMatchObject({ status: "configured" });
+ expect(await readFile(expectedPath, "utf8")).toContain('"mcp"');
+ });
+
it.each([
"opencode",
"antigravity",
From 02cedc37961a5d230b134f330c148322cd04bf37 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Tue, 13 Oct 2026 03:26:16 +0800
Subject: [PATCH 05/54] fix(readiness): validate stage evidence references once
Collect stage and check references at their owning stage boundary before evaluating required checks. Emit one missing-reference finding per stage and Evidence ID, including stages with no supplied checks, while preserving independent failed checks and cross-stage identity. The 21 readiness tests pass.
---
src/domain/reconstructionReadiness.test.ts | 62 +++++++++++++++++++
.../reconstructionReadinessJourneyFindings.ts | 15 +++--
2 files changed, 71 insertions(+), 6 deletions(-)
diff --git a/src/domain/reconstructionReadiness.test.ts b/src/domain/reconstructionReadiness.test.ts
index 9418f0dd1..2e53f1e68 100644
--- a/src/domain/reconstructionReadiness.test.ts
+++ b/src/domain/reconstructionReadiness.test.ts
@@ -181,6 +181,68 @@ describe("readiness obligation ledger integrity", () => {
);
});
+describe("readiness missing Evidence references", () => {
+ it("reports each absent Evidence ID once per stage across stage and check references", () => {
+ const value = input();
+ const stage = value.stages[0]!;
+ const missing = [`ev_${"0".repeat(64)}`, `ev_${"1".repeat(64)}`];
+ stage.evidence_ids.push(...missing);
+ for (const check of stage.checks) check.evidence_ids.push(...missing);
+
+ const report = createReconstructionReadinessReport(value);
+ expect(report.status).toBe("unknown");
+ expect(report.findings).toEqual(
+ missing.map((id) => ({
+ code: "referenced-evidence-missing",
+ stage_id: stage.stage_id,
+ status: "unknown",
+ detail: `Referenced Evidence is absent from the bundle: ${id}.`,
+ evidence_ids: [],
+ })),
+ );
+ expect(report.summary).toMatchObject({ findings: 2, unknown_findings: 2 });
+ });
+
+ it("keeps absent references distinct across stages and preserves failed checks", () => {
+ const value = input();
+ const [first, second] = value.stages;
+ if (first === undefined || second === undefined)
+ throw new TypeError("Missing conformance stages");
+ const missing = `ev_${"0".repeat(64)}`;
+ first.evidence_ids.push(missing);
+ second.checks[0]!.evidence_ids.push(missing);
+ first.checks[0]!.status = "fail";
+
+ const report = createReconstructionReadinessReport(value);
+ expect(report.status).toBe("fail");
+ expect(
+ report.findings
+ .filter(({ code }) => code === "referenced-evidence-missing")
+ .map(({ stage_id }) => stage_id)
+ .sort(),
+ ).toEqual([first.stage_id, second.stage_id].sort());
+ expect(report.summary).toMatchObject({
+ findings: 3,
+ unknown_findings: 2,
+ failed_findings: 1,
+ });
+ });
+
+ it("checks stage Evidence even when every required check is absent", () => {
+ const value = input();
+ const stage = value.stages[0]!;
+ stage.checks = [];
+ stage.evidence_ids.push(`ev_${"0".repeat(64)}`);
+
+ const report = createReconstructionReadinessReport(value);
+ expect(report.status).toBe("fail");
+ expect(report.summary).toMatchObject({ unknown_findings: 1 });
+ expect(report.findings).toContainEqual(
+ expect.objectContaining({ code: "referenced-evidence-missing" }),
+ );
+ });
+});
+
describe("readiness failure semantics", () => {
it("rejects equivalence over truncated concurrent evidence", () => {
const value = input();
diff --git a/src/domain/reconstructionReadinessJourneyFindings.ts b/src/domain/reconstructionReadinessJourneyFindings.ts
index 2acde376e..4b8a908ef 100644
--- a/src/domain/reconstructionReadinessJourneyFindings.ts
+++ b/src/domain/reconstructionReadinessJourneyFindings.ts
@@ -178,6 +178,15 @@ const stageFindings = (
"Stage check IDs must be unique.",
),
);
+ addMissingEvidenceFindings(
+ findings,
+ stageId,
+ [
+ ...stage.evidence_ids,
+ ...stage.checks.flatMap((check) => check.evidence_ids),
+ ],
+ evidenceIds,
+ );
for (const checkId of READINESS_REQUIRED_CHECKS[stageId]) {
const check = checks.get(checkId);
if (check === undefined) {
@@ -210,12 +219,6 @@ const stageFindings = (
`${checkId} has no attributable Evidence.`,
),
);
- addMissingEvidenceFindings(
- findings,
- stageId,
- [...stage.evidence_ids, ...check.evidence_ids],
- evidenceIds,
- );
}
}
return findings;
From 221c85648108e9846d9920b0964dafa7f108d581 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Tue, 13 Oct 2026 03:29:28 +0800
Subject: [PATCH 06/54] fix(browser): preserve attached service-worker policies
and ownership
---
src/browser/PlaywrightScenarioSession.test.ts | 79 ++++++++++++++++++-
src/browser/PlaywrightScenarioSession.ts | 20 +++--
2 files changed, 91 insertions(+), 8 deletions(-)
diff --git a/src/browser/PlaywrightScenarioSession.test.ts b/src/browser/PlaywrightScenarioSession.test.ts
index ca26ff308..dbc170880 100644
--- a/src/browser/PlaywrightScenarioSession.test.ts
+++ b/src/browser/PlaywrightScenarioSession.test.ts
@@ -82,6 +82,8 @@ const fixture = () => {
const page = Object.assign(new EventEmitter(), {
url: () => "about:blank",
goto: vi.fn(async () => undefined),
+ evaluate: vi.fn(async (_script: unknown) => false),
+ addInitScript: vi.fn(async (_script: unknown) => undefined),
context: () => context,
});
const context = Object.assign(new EventEmitter(), {
@@ -116,7 +118,7 @@ const fixture = () => {
settle: vi.fn(async () => undefined),
close: vi.fn(async () => undefined),
};
- return { cleanup, storage: mocks.storage };
+ return { cleanup, page, storage: mocks.storage };
};
beforeEach(() => {
@@ -137,6 +139,81 @@ it("uses browser disconnect as terminal storage release after detach failure", a
expect(storage.close).toHaveBeenCalledTimes(1);
});
+it("leaves attached service-worker state alone when the policy allows it", async () => {
+ const { cleanup, page } = fixture();
+ const attached = browserScenarioSchema.parse({
+ ...scenario,
+ browser: {
+ mode: "connect",
+ cdp_endpoint: "http://127.0.0.1:9222",
+ target_id: "target",
+ },
+ environment: { service_workers: "allow" },
+ });
+ const session = await PlaywrightScenarioSession.open(attached, {}, {});
+
+ expect(mocks.openBrowser).toHaveBeenCalledWith(
+ attached,
+ {},
+ expect.any(Object),
+ );
+ expect(page.evaluate).not.toHaveBeenCalled();
+ expect(page.addInitScript).not.toHaveBeenCalled();
+ await expect(session.close()).resolves.toBe("disconnected-external");
+ expect(cleanup.close).toHaveBeenCalledTimes(1);
+});
+
+it("blocks new attached service-worker registration without removing existing registrations", async () => {
+ const { cleanup, page } = fixture();
+ const attached = browserScenarioSchema.parse({
+ ...scenario,
+ browser: {
+ mode: "connect",
+ cdp_endpoint: "http://127.0.0.1:9222",
+ target_id: "target",
+ },
+ environment: { service_workers: "block" },
+ });
+ const session = await PlaywrightScenarioSession.open(attached, {}, {});
+
+ expect(page.evaluate).toHaveBeenCalledTimes(2);
+ expect(page.addInitScript).toHaveBeenCalledTimes(1);
+ expect(page.addInitScript).toHaveBeenCalledWith(
+ expect.stringContaining("service workers are blocked by scenario policy"),
+ );
+ expect(page.addInitScript).toHaveBeenCalledWith(
+ expect.not.stringContaining("getRegistrations"),
+ );
+ expect(page.addInitScript).toHaveBeenCalledWith(
+ expect.not.stringContaining("unregister"),
+ );
+ await expect(session.close()).resolves.toBe("disconnected-external");
+ expect(cleanup.close).toHaveBeenCalledTimes(1);
+});
+
+it("rejects attached block when caller-owned registrations already exist", async () => {
+ const { cleanup, page } = fixture();
+ page.evaluate.mockResolvedValueOnce(true);
+ const attached = browserScenarioSchema.parse({
+ ...scenario,
+ browser: {
+ mode: "connect",
+ cdp_endpoint: "http://127.0.0.1:9222",
+ target_id: "target",
+ },
+ environment: { service_workers: "block" },
+ });
+
+ await expect(
+ PlaywrightScenarioSession.open(attached, {}, {}),
+ ).rejects.toMatchObject({
+ _tag: "BrowserObservationError",
+ reason: "target_not_allowed",
+ });
+ expect(page.addInitScript).not.toHaveBeenCalled();
+ expect(cleanup.close).toHaveBeenCalledTimes(1);
+});
+
it("preserves both cleanup failures and retries retained owners", async () => {
const { cleanup, storage } = fixture();
const detachFailure = new Error("CDP detach rejected");
diff --git a/src/browser/PlaywrightScenarioSession.ts b/src/browser/PlaywrightScenarioSession.ts
index 745561574..486f555ea 100644
--- a/src/browser/PlaywrightScenarioSession.ts
+++ b/src/browser/PlaywrightScenarioSession.ts
@@ -51,15 +51,18 @@ const installCookies = async (
};
const blockAttachedServiceWorkers = async (page: Page): Promise => {
- const controller = await page.evaluate(
- "Boolean(navigator.serviceWorker?.controller)",
- );
- if (controller)
+ const hasServiceWorker = await page.evaluate(`(async () => {
+ if (!("serviceWorker" in navigator)) return false;
+ const serviceWorker = navigator.serviceWorker;
+ if (serviceWorker.controller !== null) return true;
+ return (await serviceWorker.getRegistrations()).length > 0;
+ })()`);
+ // An attached context belongs to the caller. Reject a block request when it
+ // already has a worker instead of unregistering that caller-owned resource.
+ if (hasServiceWorker)
throw new BrowserObservationError(OPERATION, "target_not_allowed");
const blockRegistration = `(() => {
if (!("serviceWorker" in navigator)) return;
- void navigator.serviceWorker.getRegistrations()
- .then((registrations) => Promise.all(registrations.map((item) => item.unregister())));
Object.defineProperty(ServiceWorkerContainer.prototype, "register", {
configurable: false,
value: () => Promise.reject(new Error("service workers are blocked by scenario policy"))
@@ -77,7 +80,10 @@ const initializePage = async (
): Promise => {
context.setDefaultTimeout(0);
context.setDefaultNavigationTimeout(0);
- if (scenario.browser.mode === "connect")
+ if (
+ scenario.browser.mode === "connect" &&
+ scenario.environment.service_workers === "block"
+ )
await blockAttachedServiceWorkers(page);
await installCookies(context, scenario, secrets);
};
From 570c40cde55d31e455ef9bc484b7b908658ded58 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Tue, 13 Oct 2026 03:33:27 +0800
Subject: [PATCH 07/54] fix(cli): preserve failure semantics across full-output
formats
---
package-lock.json | 1 +
package.json | 1 +
scripts/bundle-runtime.mjs | 2 +-
scripts/prepack.mjs | 2 +-
scripts/rea.mjs | 8 +-
scripts/verify/javascript/output.mjs | 4 +-
src/cli.ts | 2 +-
...reamedJsonOutput.ts => cliResultOutput.ts} | 155 ++++++---
src/cli/jsonOutput.ts | 7 +-
src/cliLogging.ts | 76 ++++-
src/cliOutput.ts | 13 +-
tests/boundary/cli/dispatcher.test.ts | 4 +-
tests/boundary/cli/jsonOutput.test.ts | 295 +++++++++++++++++-
tests/boundary/process/runtimeBundle.test.ts | 6 +-
14 files changed, 494 insertions(+), 82 deletions(-)
rename src/cli/{streamedJsonOutput.ts => cliResultOutput.ts} (53%)
diff --git a/package-lock.json b/package-lock.json
index 749f4614f..5af71e98e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -41,6 +41,7 @@
"smol-toml": "1.9.0",
"stream-chain": "4.2.6",
"stream-json": "3.7.0",
+ "tokenx": "1.3.0",
"write-file-atomic": "7.0.0",
"ws": "8.21.0",
"yaml": "2.9.0",
diff --git a/package.json b/package.json
index 8a58184c8..5635c6d3c 100644
--- a/package.json
+++ b/package.json
@@ -320,6 +320,7 @@
"smol-toml": "1.9.0",
"stream-chain": "4.2.6",
"stream-json": "3.7.0",
+ "tokenx": "1.3.0",
"write-file-atomic": "7.0.0",
"ws": "8.21.0",
"yaml": "2.9.0",
diff --git a/scripts/bundle-runtime.mjs b/scripts/bundle-runtime.mjs
index bac18ed2c..6b6b45140 100644
--- a/scripts/bundle-runtime.mjs
+++ b/scripts/bundle-runtime.mjs
@@ -24,7 +24,7 @@ export const bundleRuntime = async (root) => {
{
cli: "cli.js",
cliOutput: "cliOutput.js",
- streamedJsonOutput: "cli/streamedJsonOutput.js",
+ cliResultOutput: "cli/cliResultOutput.js",
mcpDoctor: "mcpDoctor.js",
},
],
diff --git a/scripts/prepack.mjs b/scripts/prepack.mjs
index 9d0958d8e..edf3072e5 100644
--- a/scripts/prepack.mjs
+++ b/scripts/prepack.mjs
@@ -49,7 +49,7 @@ if (await pathExists(join(root, "src"))) {
"dist/mcp/main.js",
"dist/cli-runtime/cli.js",
"dist/cli-runtime/cliOutput.js",
- "dist/cli-runtime/streamedJsonOutput.js",
+ "dist/cli-runtime/cliResultOutput.js",
"dist/cli-runtime/mcpDoctor.js",
"dist/mcpDoctor.js",
"dist/cli.js",
diff --git a/scripts/rea.mjs b/scripts/rea.mjs
index d3380c9c2..78ffbdd21 100755
--- a/scripts/rea.mjs
+++ b/scripts/rea.mjs
@@ -37,7 +37,7 @@ const runtimeFiles = isMcpMode
: [
"dist/cli-runtime/cli.js",
"dist/cli-runtime/cliOutput.js",
- "dist/cli-runtime/streamedJsonOutput.js",
+ "dist/cli-runtime/cliResultOutput.js",
];
if (!(await compiledRuntimeExists(runtimeFiles))) {
@@ -60,8 +60,8 @@ if (!(await compiledRuntimeExists(runtimeFiles))) {
} else {
const { cliConfigurationError, createCli } =
await import("../dist/cli-runtime/cli.js");
- const { createStreamedCliJsonOutput } =
- await import("../dist/cli-runtime/streamedJsonOutput.js");
+ const { createCliResultOutput } =
+ await import("../dist/cli-runtime/cliResultOutput.js");
const {
renderCliOutputArgumentError,
renderEmptyFilteredCliOutput,
@@ -77,7 +77,7 @@ if (!(await compiledRuntimeExists(runtimeFiles))) {
process.exitCode = 1;
} else {
let wroteOutput = false;
- const resultOutput = createStreamedCliJsonOutput(args, process.stdout);
+ const resultOutput = createCliResultOutput(args, process.stdout);
await createCli(process.env, resultOutput).serve(args, {
stdout: (output) => {
if (resultOutput?.handled) {
diff --git a/scripts/verify/javascript/output.mjs b/scripts/verify/javascript/output.mjs
index dbdfdc340..e9bc9e588 100644
--- a/scripts/verify/javascript/output.mjs
+++ b/scripts/verify/javascript/output.mjs
@@ -10,7 +10,7 @@ import { finished } from "node:stream/promises";
import { Cli } from "incur";
-import { createStreamedCliJsonOutput } from "../../../dist/cli/streamedJsonOutput.js";
+import { createCliResultOutput } from "../../../dist/cli/cliResultOutput.js";
import { createEvidence } from "../../../dist/domain/evidence.js";
// This opt-in format-boundary check writes one temporary file larger than the
@@ -79,7 +79,7 @@ try {
destination = createWriteStream(path, { flags: "wx", mode: 0o600 });
const argv = [metadata.command, "--format", format, "--full-output"];
- const output = createStreamedCliJsonOutput(argv, destination);
+ const output = createCliResultOutput(argv, destination);
assert.ok(output);
let unexpectedOutputBytes = 0;
let exitCode = 0;
diff --git a/src/cli.ts b/src/cli.ts
index cfb83b71e..238f8387d 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -44,7 +44,7 @@ import type { CliInstance } from "./cli/types.js";
import {
streamCliCommandResults,
type CliResultOutput,
-} from "./cli/streamedJsonOutput.js";
+} from "./cli/cliResultOutput.js";
/** Describe CLI settings that are invalid before any command runs, as MCP does. */
export const cliConfigurationError = (
diff --git a/src/cli/streamedJsonOutput.ts b/src/cli/cliResultOutput.ts
similarity index 53%
rename from src/cli/streamedJsonOutput.ts
rename to src/cli/cliResultOutput.ts
index 9d21eec0f..67e745b0b 100644
--- a/src/cli/streamedJsonOutput.ts
+++ b/src/cli/cliResultOutput.ts
@@ -1,15 +1,24 @@
import { constants } from "node:buffer";
import type { Writable } from "node:stream";
-import { Cli, Filter } from "incur";
+import { Cli, Filter, Formatter } from "incur";
+import { estimateTokenCount, sliceByTokens } from "tokenx";
-import { parseCliOutputArguments } from "../cliOutput.js";
+import {
+ parseCliOutputArguments,
+ validateCliOutputArguments,
+} from "../cliOutput.js";
+import { cliOperationFailurePayload } from "../cliLogging.js";
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
import {
projectAnalysisError,
type AnalysisErrorProjection,
} from "../domain/analysisErrorProjection.js";
-import { jsonOutputParts, writeJsonOutput } from "./jsonOutput.js";
+import {
+ jsonOutputParts,
+ writeJsonOutput,
+ writeOutputText,
+} from "./jsonOutput.js";
import type { CliInstance } from "./types.js";
/** Result metadata supplied by the command that actually ran. */
@@ -100,19 +109,15 @@ const wrapCommand = (
};
};
-/** Preserve Incur's JSON controls while streaming the complete result. */
-export const createStreamedCliJsonOutput = (
+/** Preserve Incur output controls and stream JSON while framing failures. */
+export const createCliResultOutput = (
arguments_: readonly string[],
destination: Writable,
): CliResultOutput | undefined => {
const options = parseCliOutputArguments(arguments_);
- if (
- options.parseError ||
- options.tokenWindow ||
- (options.format !== "json" && options.format !== "jsonl")
- )
+ if (options.parseError || !validateCliOutputArguments(arguments_).ok)
return undefined;
- const format = options.format;
+ const format = options.format as "json" | "jsonl" | "yaml" | "toon" | "md";
let handled = false;
let failed = false;
let error: AnalysisErrorProjection | undefined;
@@ -128,27 +133,53 @@ export const createStreamedCliJsonOutput = (
},
async write(value, metadata) {
if (metadata.format !== format) return false;
+ const failure = options.fullOutput
+ ? cliOperationFailurePayload(value)
+ : undefined;
const filtered: unknown = options.filterOutput
? Filter.apply(value, Filter.parse(options.filterOutput))
: value;
- const meta = {
- command: metadata.command,
- duration: metadata.duration,
- };
+ // Leave successful YAML and bare YAML rendering to Incur. The custom
+ // boundary is needed only for a full failure envelope, whose error
+ // sentinel otherwise drops category, remediation, and details.
+ if (format !== "json" && format !== "jsonl" && failure === undefined)
+ return false;
if (options.tokenCount) {
- // Incur/tokenx materialize the formatted value. Measure its UTF-16
- // expansion before allowing that allocation, independently of UTF-8 bytes.
+ // Incur/tokenx materialize JSON. Measure its UTF-16 expansion before
+ // allowing that allocation, independently of UTF-8 bytes. Other formats
+ // retain Incur's materializing behavior.
+ const tokenValue = failure ?? filtered;
let characters = 0;
if (
- filtered !== undefined &&
- filtered !== null &&
- typeof filtered !== "function" &&
- typeof filtered !== "symbol"
- )
- for (const part of jsonOutputParts(filtered, format))
- characters += part.length;
- characters = Math.max(0, characters - 1);
- if (characters <= constants.MAX_STRING_LENGTH) return false;
+ tokenValue !== undefined &&
+ tokenValue !== null &&
+ typeof tokenValue !== "function" &&
+ typeof tokenValue !== "symbol"
+ ) {
+ if (format === "json" || format === "jsonl") {
+ for (const part of jsonOutputParts(
+ tokenValue,
+ format,
+ format === "json",
+ ))
+ characters += part.length;
+ characters = Math.max(0, characters - 1);
+ }
+ }
+ if (characters <= constants.MAX_STRING_LENGTH) {
+ if (failure === undefined) return false;
+ handled = true;
+ try {
+ await writeOutputText(
+ destination,
+ `${estimateTokenCount(Formatter.format(failure, format))}\n`,
+ );
+ return true;
+ } catch (cause: unknown) {
+ failed = true;
+ throw cause;
+ }
+ }
error = projectAnalysisError(
new AnalysisResourceConstraintError(
metadata.command,
@@ -165,10 +196,26 @@ export const createStreamedCliJsonOutput = (
),
);
}
+ const meta = {
+ command: metadata.command,
+ duration: metadata.duration,
+ };
+ const errorDocument =
+ options.fullOutput && failure !== undefined
+ ? fullFailureEnvelope(
+ failure,
+ meta,
+ format,
+ options.tokenLimit,
+ options.tokenOffset,
+ )
+ : undefined;
const document = options.fullOutput
- ? filtered === undefined
- ? { ok: true, meta }
- : { ok: true, data: filtered, meta }
+ ? failure !== undefined
+ ? errorDocument
+ : filtered === undefined
+ ? { ok: true, meta }
+ : { ok: true, data: filtered, meta }
: filtered === undefined ||
filtered === null ||
typeof filtered === "function" ||
@@ -179,15 +226,24 @@ export const createStreamedCliJsonOutput = (
// document from Incur's error formatter.
handled = true;
try {
- await writeJsonOutput(
- error === undefined
- ? document
- : options.fullOutput
- ? { ok: false, error, meta }
- : error,
- destination,
- format,
- );
+ if (failure !== undefined && format !== "json" && format !== "jsonl") {
+ // Incur's error sentinel only carries code/message/retryable. Render
+ // the full caller-visible failure at this output boundary.
+ await writeOutputText(
+ destination,
+ `${Formatter.format(document, format)}\n`,
+ );
+ } else {
+ await writeJsonOutput(
+ error === undefined
+ ? document
+ : options.fullOutput
+ ? { ok: false, error, meta }
+ : error,
+ destination,
+ format as "json" | "jsonl",
+ );
+ }
} catch (cause: unknown) {
failed = true;
throw cause;
@@ -196,3 +252,26 @@ export const createStreamedCliJsonOutput = (
},
};
};
+
+const fullFailureEnvelope = (
+ failure: unknown,
+ meta: Readonly>,
+ format: "json" | "jsonl" | "yaml" | "toon" | "md",
+ tokenLimit: number | undefined,
+ tokenOffset: number | undefined,
+): Readonly> => {
+ if (tokenLimit === undefined && tokenOffset === undefined)
+ return { ok: false, error: failure, meta };
+ const formatted = Formatter.format(failure, format);
+ const total = estimateTokenCount(formatted);
+ const offset = tokenOffset ?? 0;
+ const end = tokenLimit === undefined ? total : offset + tokenLimit;
+ if (offset === 0 && end >= total) return { ok: false, error: failure, meta };
+ const actualEnd = Math.min(end, total);
+ const nextOffset = actualEnd < total ? actualEnd : undefined;
+ return {
+ ok: false,
+ error: `${sliceByTokens(formatted, offset, end)}\n[truncated: showing tokens ${offset}–${actualEnd} of ${total}]`,
+ meta: { ...meta, ...(nextOffset === undefined ? {} : { nextOffset }) },
+ };
+};
diff --git a/src/cli/jsonOutput.ts b/src/cli/jsonOutput.ts
index f7422a7bf..f3b2bcaa0 100644
--- a/src/cli/jsonOutput.ts
+++ b/src/cli/jsonOutput.ts
@@ -19,13 +19,16 @@ export const writeJsonOutput = async (
for (const part of bufferedJsonParts(
jsonOutputParts(value, format, isTerminal(destination)),
))
- await writePart(destination, part);
+ await writeOutputText(destination, part);
};
const isTerminal = (destination: Writable): boolean =>
"isTTY" in destination && destination.isTTY === true;
-const writePart = (destination: Writable, part: string): Promise =>
+export const writeOutputText = (
+ destination: Writable,
+ part: string,
+): Promise =>
new Promise((resolve, reject) => {
const onError = (cause: unknown): void => reject(cause);
destination.once("error", onError);
diff --git a/src/cliLogging.ts b/src/cliLogging.ts
index c74c43ab4..3a47dd257 100644
--- a/src/cliLogging.ts
+++ b/src/cliLogging.ts
@@ -12,20 +12,64 @@ import type { Logger } from "pino";
const isRecord = (value: unknown): value is Readonly> =>
typeof value === "object" && value !== null && !Array.isArray(value);
-/** Identify caller-visible CLI outcomes that mean the requested operation failed. */
-export const isCliOperationFailure = (value: unknown): boolean => {
- if (!isRecord(value)) return false;
- if (
- isRecord(value.error) &&
- analysisErrorProjectionSchema.safeParse(value.error).success
- )
- return true;
- if (analysisCliErrorEnvelopeSchema.safeParse(value).success) return true;
- if (analysisErrorProjectionSchema.safeParse(value).success) return true;
- if (value.healthy === false) return true;
- return false;
+const loggedFailures = new WeakMap