Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(cli): report string capacity failures during result formatting
morlutofd6da70920f9
diff --git a/scripts/rea.mjs b/scripts/rea.mjsindex da48782b8..540f23d00 100755--- a/scripts/rea.mjs+++ b/scripts/rea.mjs@@ -92,19 +92,33 @@ if (!(await compiledRuntimeExists(runtimeFiles))) {} else {let wroteOutput = false;const resultOutput = createCliResultOutput(cliArgs, process.stdout);- await createCli(process.env, resultOutput).serve(cliArgs, {- stdout: (output) => {- if (resultOutput?.handled) {- if (resultOutput.failed && !stdoutClosed)- process.stderr.write(output);- return;- }- if (output.length > 0) wroteOutput = true;- writeStdout(output);- },- // A command failure caused by the closed pipe keeps the pipe's status.- exit: (code) => process.exit(stdoutClosed ? SIGPIPE_EXIT_STATUS : code),- });+ try {+ await createCli(process.env, resultOutput).serve(cliArgs, {+ stdout: (output) => {+ if (resultOutput?.handled) {+ if (resultOutput.failed && !stdoutClosed)+ process.stderr.write(output);+ return;+ }+ if (output.length > 0) wroteOutput = true;+ writeStdout(output);+ },+ // A command failure caused by the closed pipe keeps the pipe's status.+ exit: (code) => process.exit(stdoutClosed ? SIGPIPE_EXIT_STATUS : code),+ });+ } catch (cause) {+ if (wroteOutput) throw cause;+ const recovered = await resultOutput+ ?.recoverFormattingFailure(cause)+ .catch((writeFailure) => {+ // Recovery writes outside Incur's command boundary. A reader that+ // declined this document keeps the same quiet SIGPIPE outcome.+ if (!stdoutClosed) throw writeFailure;+ return true;+ });+ if (!recovered) throw cause;+ process.exitCode = stdoutClosed ? SIGPIPE_EXIT_STATUS : 1;+ }if (!wroteOutput && !resultOutput?.handled)writeStdout(renderEmptyFilteredCliOutput(cliArgs) ?? "");}diff --git a/src/cli/cliResultOutput.ts b/src/cli/cliResultOutput.tsindex 5efde8b33..3cc98d866 100644--- a/src/cli/cliResultOutput.ts+++ b/src/cli/cliResultOutput.ts@@ -8,7 +8,10 @@ import {parseCliOutputArguments,validateCliOutputArguments,} from "../cliOutput.js";-import { cliOperationFailurePayload } from "../cliLogging.js";+import {+ cliOperationFailureIdentity,+ cliOperationFailurePayload,+} from "../cliLogging.js";import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";import {projectAnalysisError,@@ -34,6 +37,8 @@ export interface CliResultOutput {readonly failed: boolean;readonly error: AnalysisErrorProjection | undefined;write(value: unknown, metadata: CliResultOutputMetadata): Promise<boolean>;+ /** Recover only before any delegated stdout has been written. */+ recoverFormattingFailure(cause: unknown): Promise<boolean>;}type CommandMap = NonNullable<ReturnType<typeof Cli.toCommands.get>>;@@ -121,6 +126,81 @@ export const createCliResultOutput = (let handled = false;let failed = false;let error: AnalysisErrorProjection | undefined;+ let completed:+ | {+ readonly metadata: CliResultOutputMetadata;+ readonly originalFailure: ReturnType<+ typeof cliOperationFailureIdentity+ >;+ }+ | undefined;+ const recoverFormattingFailure = async (cause: unknown): Promise<boolean> => {+ // A rejected command never reaches write(). Destination failures retain+ // handled ownership. Only a completed, unwritten result can be replaced.+ if (+ completed === undefined ||+ handled ||+ !(cause instanceof RangeError) ||+ cause.message !== "Invalid string length"+ )+ return false;+ const { originalFailure } = completed;+ error = projectAnalysisError(+ new AnalysisResourceConstraintError(+ completed.metadata.command,+ "memory",+ `The ${format} result could not fit in a runtime string. The original result was not written.`,+ {+ format,+ formatted_characters: null,+ max_string_characters: constants.MAX_STRING_LENGTH,+ ...(originalFailure === undefined+ ? {}+ : { original_failure: originalFailure }),+ },+ {+ cause,+ retryable: false,+ remediationAction:+ "Use --format json to stream the complete result, or narrow it with --filter-output. Token limits are applied after formatting and cannot avoid this constraint.",+ },+ ),+ );+ const document = options.fullOutput+ ? {+ ok: false,+ error,+ meta: {+ command: completed.metadata.command,+ duration: completed.metadata.duration,+ },+ }+ : error;+ // Recovery must remain actionable even when a token window/count was+ // requested. Do not apply those controls to this small typed failure.+ const text = Formatter.format(document, format);+ handled = true;+ try {+ await writeOutputText(destination, `${text}\n`);+ } catch (writeFailure: unknown) {+ failed = true;+ throw writeFailure;+ }+ return true;+ };+ const write = async (+ value: unknown,+ metadata: CliResultOutputMetadata,+ ): Promise<boolean> => {+ completed = undefined;+ if (metadata.format !== format) return false;+ try {+ return await writeResult(value, metadata);+ } catch (cause: unknown) {+ if (await recoverFormattingFailure(cause)) return true;+ throw cause;+ }+ };return {get handled() {return handled;@@ -131,127 +211,135 @@ export const createCliResultOutput = (get error() {return error;},- 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;- // 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 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 (- 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;- }+ write,+ recoverFormattingFailure,+ };++ async function writeResult(+ value: unknown,+ metadata: CliResultOutputMetadata,+ ): Promise<boolean> {+ const failure = options.fullOutput+ ? cliOperationFailurePayload(value)+ : undefined;+ completed = {+ metadata,+ originalFailure: cliOperationFailureIdentity(value),+ };+ const filtered: unknown = options.filterOutput+ ? Filter.apply(value, Filter.parse(options.filterOutput))+ : value;+ // 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 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 (+ 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);}- error = projectAnalysisError(- new AnalysisResourceConstraintError(- metadata.command,- "memory",- "Token counting requires a formatted string larger than the runtime permits.",- {- formatted_characters: characters,- max_string_characters: constants.MAX_STRING_LENGTH,- },- {- remediationAction:- "Remove --token-count to stream the complete JSON result, or narrow it with --filter-output.",- },- ),- );}- 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- ? failure !== undefined- ? errorDocument- : filtered === undefined- ? { ok: true, meta }- : { ok: true, data: filtered, meta }- : // A selected null is a value; only a selection with no JSON value- // falls back to the empty document.- filtered === undefined ||- typeof filtered === "function" ||- typeof filtered === "symbol"- ? {}- : filtered;- // Once writing starts, a failed destination must not receive a second- // document from Incur's error formatter.- handled = true;- try {- 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",- );+ if (characters <= constants.MAX_STRING_LENGTH) {+ if (failure === undefined) return false;+ const count = estimateTokenCount(Formatter.format(failure, format));+ handled = true;+ try {+ await writeOutputText(destination, `${count}\n`);+ return true;+ } catch (cause: unknown) {+ failed = true;+ throw cause;}- } catch (cause: unknown) {- failed = true;- throw cause;}- return true;- },- };+ error = projectAnalysisError(+ new AnalysisResourceConstraintError(+ metadata.command,+ "memory",+ "Token counting requires a formatted string larger than the runtime permits.",+ {+ formatted_characters: characters,+ max_string_characters: constants.MAX_STRING_LENGTH,+ },+ {+ remediationAction:+ "Remove --token-count to stream the complete JSON result, or narrow it with --filter-output.",+ },+ ),+ );+ }+ 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+ ? failure !== undefined+ ? errorDocument+ : filtered === undefined+ ? { ok: true, meta }+ : { ok: true, data: filtered, meta }+ : // A selected null is a value; only a selection with no JSON value+ // falls back to the empty document.+ filtered === undefined ||+ typeof filtered === "function" ||+ typeof filtered === "symbol"+ ? {}+ : filtered;+ // Once writing starts, a failed destination must not receive a second+ // document from Incur's error formatter.+ const failureText =+ failure !== undefined && format !== "json" && format !== "jsonl"+ ? Formatter.format(document, format)+ : undefined;+ handled = true;+ try {+ if (failureText !== undefined) {+ // Incur's error sentinel only carries code/message/retryable. Render+ // the full caller-visible failure at this output boundary.+ await writeOutputText(destination, `${failureText}\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;+ }+ return true;+ }};const fullFailureEnvelope = (diff --git a/src/cliLogging.ts b/src/cliLogging.tsindex 3a47dd257..81d068d14 100644--- a/src/cliLogging.ts+++ b/src/cliLogging.ts@@ -12,7 +12,26 @@ import type { Logger } from "pino";const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>typeof value === "object" && value !== null && !Array.isArray(value);-const loggedFailures = new WeakMap<object, unknown>();+type CliFailureIdentity = Pick<+ AnalysisErrorProjection,+ "code" | "category" | "retryable"+>;+interface CliOperationFailure {+ readonly payload: unknown;+ readonly identity?: CliFailureIdentity;+}+const loggedFailures = new WeakMap<object, CliOperationFailure | undefined>();++const canonicalFailure = (+ projection: AnalysisErrorProjection,+): CliOperationFailure => ({+ payload: projection,+ identity: {+ code: projection.code,+ category: projection.category,+ retryable: projection.retryable,+ },+});/** Return the canonical failure projection owned by the CLI result boundary. */const projectCliOperationFailure = (@@ -50,11 +69,13 @@ const projectCliOperationFailure = (return undefined;};-/** Return the canonical projection or original record classified as failed. */-const inferCliOperationFailure = (value: unknown): unknown | undefined => {+/** Keep the classified payload and its canonical identity under one owner. */+const inferCliOperationFailure = (+ value: unknown,+): CliOperationFailure | undefined => {const projection = projectCliOperationFailure(value);- if (projection !== undefined) return projection;- if (isRecord(value) && value.healthy === false) return value;+ if (projection !== undefined) return canonicalFailure(projection);+ if (isRecord(value) && value.healthy === false) return { payload: value };return undefined;};@@ -62,14 +83,23 @@ export const cliOperationFailurePayload = (value: unknown,): unknown | undefined => {if (isRecord(value) && loggedFailures.has(value))- return loggedFailures.get(value);- return inferCliOperationFailure(value);+ return loggedFailures.get(value)?.payload;+ const failure = inferCliOperationFailure(value);+ if (failure !== undefined && isRecord(value))+ loggedFailures.set(value, failure);+ return failure?.payload;};/** Identify caller-visible CLI outcomes that mean the requested operation failed. */export const isCliOperationFailure = (value: unknown): boolean =>cliOperationFailurePayload(value) !== undefined;+/** Already classified identity, without traversing payloads during recovery. */+export const cliOperationFailureIdentity = (+ value: unknown,+): CliFailureIdentity | undefined =>+ isRecord(value) ? loggedFailures.get(value)?.identity : undefined;+/** Log one CLI command with duration and a stable success or failure status. */export const logCliCommand = async <Value>(logger: Logger,@@ -85,7 +115,7 @@ export const logCliCommand = async <Value>(if (isRecord(value))loggedFailures.set(value,- failed ? (inferredFailure ?? value) : undefined,+ failed ? (inferredFailure ?? { payload: value }) : undefined,);logger[failed ? "error" : "info"]({@@ -109,7 +139,9 @@ export const logCliCommand = async <Value>();if (cause instanceof AnalysisError) {process.exitCode = 1;- return projectAnalysisError(cause);+ const projection = projectAnalysisError(cause);+ loggedFailures.set(projection, canonicalFailure(projection));+ return projection;}throw cause;}diff --git a/tests/acceptance/cliFormattingCapacity.test.ts b/tests/acceptance/cliFormattingCapacity.test.tsnew file mode 100644index 000000000..6e91dc0de--- /dev/null+++ b/tests/acceptance/cliFormattingCapacity.test.ts@@ -0,0 +1,137 @@+import { writeFile } from "node:fs/promises";+import { resolve } from "node:path";++import { expect } from "vitest";+import { parse as parseYaml } from "yaml";++import { buildManagedPeFixture } from "../../src/dotnet/ManagedPe.fixture.js";+import { analysisErrorProjectionSchema } from "../../src/contracts/errorSchemas.js";+import { workspaceCliTest } from "../support/cli/workspaceCliFixture.js";++// Exercise the real dispatcher and pinned formatter with an authored capacity+// failure. No engine-sized document or native target execution is needed.+const formatterFailure = `+ if (fmt !== "json" && fmt !== "jsonl" &&+ (value?.operation === "inspect_managed_artifact" ||+ value?.data?.operation === "inspect_managed_artifact" ||+ value?.code === "target_unavailable" ||+ value?.error?.code === "target_unavailable")) {+ process.stderr.write("REA_AUTHORED_FORMAT_CAPACITY\\n");+ throw new RangeError("Invalid string length");+ }+`;+const formatterCapacityHook = `data:text/javascript,${encodeURIComponent(`+import { registerHooks } from "node:module";+registerHooks({+ load(url, context, next) {+ const loaded = next(url, context);+ if (!url.endsWith("/incur/dist/Formatter.js")) return loaded;+ const source = String(loaded.source);+ const signature = "export function format(value, fmt = 'toon') {";+ if (!source.includes(signature)) throw new Error("Pinned formatter boundary changed");+ return { ...loaded, source: source.replace(signature, signature + ${JSON.stringify(formatterFailure)}) };+ },+});+`)}`;++for (const scenario of [+ { name: "default TOON", arguments: [], full: false },+ { name: "human TOON", arguments: [], full: false },+ { name: "full TOON", arguments: ["--full-output"], full: true },+ { name: "TOON token count", arguments: ["--token-count"], full: false },+ { name: "TOON token window", arguments: ["--token-limit", "3"], full: false },+ {+ name: "full TOON token window",+ arguments: ["--full-output", "--token-limit", "3"],+ full: true,+ },+ { name: "YAML", arguments: ["--format", "yaml"], full: false },+ {+ name: "full YAML",+ arguments: ["--format", "yaml", "--full-output"],+ full: true,+ },+ { name: "Markdown", arguments: ["--format", "md"], full: false },+] as const)+ for (const outcome of ["success", "failure"] as const)+ workspaceCliTest(+ `${scenario.name} returns a typed formatting constraint after ${outcome}`,+ async ({ processes, workspace }) => {+ const target = resolve(workspace.root, "fixture.dll");+ if (outcome === "success")+ await writeFile(target, buildManagedPeFixture());+ const result = await processes.run(+ process.execPath,+ [+ "--import",+ scenario.name === "human TOON"+ ? `data:text/javascript,${encodeURIComponent('Object.defineProperty(process.stdout, "isTTY", { value: true });')}`+ : "data:text/javascript,",+ "--import",+ formatterCapacityHook,+ resolve("scripts/rea.mjs"),+ "inspect-managed-artifact",+ target,+ ...scenario.arguments,+ ],+ { cwd: workspace.root, env: { PATH: process.env.PATH ?? "" } },+ );+ expect(result.exitCode, result.stderr).toBe(1);+ expect(result.stderr.trim()).toBe("REA_AUTHORED_FORMAT_CAPACITY");+ expect(result.stdout).toContain("resource_constraint");+ expect(result.stdout).toContain("--format json");+ expect(result.stdout).toContain("formatted_characters");+ expect(result.stdout).not.toContain("[truncated:");+ expect(result.stdout).not.toContain("UNKNOWN");+ if (outcome === "failure")+ expect(result.stdout).toContain("target_unavailable");+ if (scenario.name.includes("YAML")) {+ const document = parseYaml(result.stdout);+ const error = scenario.full ? document.error : document;+ expect(analysisErrorProjectionSchema.parse(error)).toMatchObject({+ code: "resource_constraint",+ retryable: false,+ details: {+ resource: "memory",+ reported_limits: { formatted_characters: null },+ },+ });+ if (scenario.full)+ expect(document).toMatchObject({+ ok: false,+ meta: { command: "inspect-managed-artifact" },+ });+ }+ },+ );++workspaceCliTest.skipIf(process.platform === "win32")(+ "keeps the SIGPIPE outcome when the reader closes before formatting recovery",+ async ({ processes, workspace }) => {+ const child = processes.spawn(+ process.execPath,+ [+ "--import",+ formatterCapacityHook,+ resolve("scripts/rea.mjs"),+ "inspect-managed-artifact",+ workspace.path("missing.dll"),+ ],+ { cwd: workspace.root, env: { PATH: process.env.PATH ?? "" } },+ );+ child.stdout.destroy();+ child.stdin.end();+ let stderr = "";+ child.stderr.setEncoding("utf8");+ child.stderr.on("data", (part: string) => {+ stderr += part;+ });+ const code = await new Promise<number | null>((done) =>+ child.once("close", done),+ );+ expect({ code, stderr }).toEqual({+ code: 141,+ stderr: "REA_AUTHORED_FORMAT_CAPACITY\n",+ });+ },+);diff --git a/tests/boundary/cli/dispatcher.test.ts b/tests/boundary/cli/dispatcher.test.tsindex 68d8fb39d..35c9114c5 100644--- a/tests/boundary/cli/dispatcher.test.ts+++ b/tests/boundary/cli/dispatcher.test.ts@@ -6,6 +6,41 @@ import { describe, expect } from "vitest";import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js";describe("executable dispatcher", () => {+ workspaceCliTest(+ "does not append recovery output after delegated stdout has begun",+ async ({ processes, workspace }) => {+ await workspace.mkdir("scripts");+ await workspace.mkdir("dist/cli-runtime");+ await Promise.all([+ copyFile("scripts/rea.mjs", workspace.path("scripts/rea.mjs")),+ workspace.write(+ "package.json",+ JSON.stringify({ type: "module", version: "1.0.0" }),+ ),+ workspace.write(+ "dist/cli-runtime/cli.js",+ 'export const cliConfigurationError = () => undefined; export const createCli = () => ({ serve: (_args, options) => { options.stdout("first document\\n"); throw new RangeError("Invalid string length"); } });\n',+ ),+ workspace.write(+ "dist/cli-runtime/cliOutput.js",+ "export const normalizeCliOutputArguments = (args) => args; export const validateCliOutputArguments = () => ({ ok: true }); export const renderCliOutputArgumentError = () => ''; export const renderEmptyFilteredCliOutput = () => undefined;\n",+ ),+ workspace.write(+ "dist/cli-runtime/cliResultOutput.js",+ 'export const createCliResultOutput = () => ({ handled: false, failed: false, recoverFormattingFailure: () => { process.stdout.write("unexpected second document"); return true; } });\n',+ ),+ ]);+ const result = await processes.run(+ process.execPath,+ [workspace.path("scripts/rea.mjs"), "fixture"],+ { cwd: workspace.root },+ );+ expect(result.exitCode).toBe(1);+ expect(result.stdout).toBe("first document\n");+ expect(result.stderr).toContain("RangeError: Invalid string length");+ },+ );+workspaceCliTest("reserves production MCP routing for bare mode arguments",async ({ processes, workspace }) => {diff --git a/tests/boundary/cli/formattingRecovery.test.ts b/tests/boundary/cli/formattingRecovery.test.tsnew file mode 100644index 000000000..5228e87ae--- /dev/null+++ b/tests/boundary/cli/formattingRecovery.test.ts@@ -0,0 +1,210 @@+import { Writable } from "node:stream";++import { Cli } from "incur";+import { describe, expect, it } from "vitest";++import {+ createCliResultOutput,+ streamCliCommandResults,+} from "../../../src/cli/cliResultOutput.js";+import {+ cliOperationFailureIdentity,+ cliOperationFailurePayload,+ logCliCommand,+} from "../../../src/cliLogging.js";+import { ArtifactOperationError } from "../../../src/domain/artifactOperationError.js";+import { silentLogger } from "../../../src/logger.js";++const metadata = { command: "fixture", duration: "1ms", format: "toon" };++describe("CLI formatting stage admission", () => {+ it("preserves native CTA sentinel output", async () => {+ const replies: string[] = [];+ for (const wrapped of [false, true]) {+ const cli = Cli.create("rea-output-test", { sync: false });+ cli.command("fixture", {+ run: (context) =>+ context.ok(+ { value: 42 },+ { cta: { commands: [{ command: "next" }] } },+ ),+ });+ const output = createCliResultOutput(["fixture"], new Writable());+ if (output === undefined) throw new Error("Missing output owner");+ if (wrapped) streamCliCommandResults(cli, output);+ let reply = "";+ await cli.serve(["fixture"], {+ stdout: (text) => {+ reply += text;+ },+ });+ expect(output.handled).toBe(false);+ replies.push(reply);+ }+ expect(replies[1]).toBe(replies[0]);+ expect(replies[0]).toContain("next");+ });++ it("captures thrown integrity failures without re-reading diagnostics during recovery", async () => {+ const previousExitCode = process.exitCode;+ try {+ const value = await logCliCommand(silentLogger, "fixture", async () => {+ throw new ArtifactOperationError("inspect_artifact", "integrity", {+ logicalPath: "entry.js",+ declaredSha256: "a".repeat(64),+ calculatedSha256: "b".repeat(64),+ unpacked: false,+ });+ });+ // A second traversal would be observable here. The producer already+ // classified this exact projection before the formatter sees it.+ Object.defineProperty(value, "details", {+ get() {+ throw new Error("Diagnostics were interpreted again");+ },+ });+ expect(cliOperationFailurePayload(value)).toBe(value);+ expect(cliOperationFailureIdentity(value)).toEqual({+ code: "artifact_integrity_mismatch",+ category: "integrity_mismatch",+ retryable: false,+ });+ } finally {+ process.exitCode = previousExitCode;+ }+ });++ it("declines errors before a result or from a different failure class", async () => {+ const output = createCliResultOutput([], new Writable());+ expect(output).toBeDefined();+ expect(+ await output?.recoverFormattingFailure(+ new RangeError("Invalid string length"),+ ),+ ).toBe(false);+ await output?.write({ result: "completed" }, metadata);+ for (const cause of [+ new Error("Invalid string length"),+ new RangeError("Maximum call stack size exceeded"),+ new Error("operation failed"),+ ])+ expect(await output?.recoverFormattingFailure(cause)).toBe(false);+ expect(output?.handled).toBe(false);+ });++ it("leaves command RangeErrors under Incur's command failure protocol", async () => {+ const cli = Cli.create("rea-output-test", { sync: false });+ cli.command("fixture", {+ run: () => {+ throw new RangeError("Invalid string length");+ },+ });+ const output = createCliResultOutput([], new Writable());+ if (output === undefined) throw new Error("Missing output owner");+ streamCliCommandResults(cli, output);+ let text = "";+ let status = 0;+ await cli.serve(["fixture"], {+ stdout: (part) => {+ text += part;+ },+ exit: (code) => {+ status = code;+ },+ });+ expect(status).toBe(1);+ expect(text).toContain("UNKNOWN");+ expect(text).not.toContain("resource_constraint");+ expect(output.error).toBeUndefined();+ });+});++describe("CLI formatting recovery outcomes", () => {+ it("retains ownership if the recovery document cannot be written", async () => {+ const cause = new RangeError("Invalid string length");+ const output = createCliResultOutput(+ [],+ new Writable({+ write(_chunk, _encoding, callback) {+ callback(cause);+ },+ }),+ );+ await output?.write({ result: "completed" }, metadata);+ await expect(output?.recoverFormattingFailure(cause)).rejects.toBe(cause);+ expect(output?.handled).toBe(true);+ expect(output?.failed).toBe(true);+ expect(await output?.recoverFormattingFailure(cause)).toBe(false);+ });++ it("does not replace a failed destination, even for the same RangeError", async () => {+ const cause = new RangeError("Invalid string length");+ const output = createCliResultOutput(+ ["--json"],+ new Writable({+ write(_chunk, _encoding, callback) {+ callback(cause);+ },+ }),+ );+ await expect(+ output?.write({ result: "completed" }, { ...metadata, format: "json" }),+ ).rejects.toBe(cause);+ expect(output?.handled).toBe(true);+ expect(output?.failed).toBe(true);+ expect(await output?.recoverFormattingFailure(cause)).toBe(false);+ });++ it("retains the original failure identity and ignores large details on recovery", async () => {+ const chunks: Buffer[] = [];+ const output = createCliResultOutput(+ [],+ new Writable({+ write(chunk: Buffer, _encoding, callback) {+ chunks.push(chunk);+ callback();+ },+ }),+ );+ const previousExitCode = process.exitCode;+ try {+ const value = await logCliCommand(silentLogger, "fixture", async () => ({+ code: "target_unavailable",+ category: "unavailable",+ message: "The operation did not complete.",+ retryable: false,+ remediation: { action: "Check the selected path." },+ details: { partial_observation: { text: "captured" } },+ }));+ expect(await output?.write(value, metadata)).toBe(false);+ expect(+ await output?.recoverFormattingFailure(+ new RangeError("Invalid string length"),+ ),+ ).toBe(true);+ expect(output?.error).toMatchObject({+ code: "resource_constraint",+ details: {+ resource: "memory",+ reported_limits: {+ formatted_characters: null,+ original_failure: {+ code: "target_unavailable",+ category: "unavailable",+ },+ },+ },+ });+ const text = Buffer.concat(chunks).toString("utf8");+ expect(text).toContain("--format json");+ expect(text).not.toContain("partial_observation");+ expect(+ await output?.recoverFormattingFailure(+ new RangeError("Invalid string length"),+ ),+ ).toBe(false);+ } finally {+ process.exitCode = previousExitCode;+ }+ });+});