Files
reverse-engineering-anything/tests/acceptance/applications/javascriptFailureEvidenceOutput.test.ts
T
morluto bd353e7e5c fix(errors)!: producers declare retry class, refusal recovery and real error codes (#15372)
* fix(errors)!: derive retryable from the producer's declared retry class

`retryable` means the unchanged request may succeed, but it was computed
downstream as an OR of a code table and five class rules. Every error
classification now declares a retry class (same_call, change_first, never,
unknown_outcome); `retryable` is `same_call` after one incomplete-cleanup
check, and the RETRYABLE_CODES table is deleted.

Producer corrections:
- update_unknown revision conflicts are change_first and report
  details.current_revision; duplicate record_unknown reports
  details.existing_unknown_id.
- close_gdb_session's explicit-disposition refusal is change_first.
- Per-call artifact reader limits are change_first (never when the limit
  cannot rise).
- An exited or unreachable Hopper bridge, and a Hopper start that another
  REA session owns, are change_first.
- File-descriptor exhaustion (EMFILE/ENFILE) outside process launch is
  occupied host capacity (same_call) for private workspaces, model and GPU
  readers and JavaScript application reads.
- apktool JVM native-thread exhaustion follows the shared capacity default.

BREAKING CHANGE: these refusals now report `retryable: false` (descriptor
pressure now reports `retryable: true` as `resource_constraint`). Callers
that repeated them unchanged should follow the remediation first: re-read
the unknown and retry with details.current_revision, dispose GDB inferiors,
raise the reported reader limit, or restart the Hopper provider.

* fix(errors): require producers to name recovery for conforming refusals

A refusal whose arguments match the input schema was presented as a schema
error whenever its producer left out remediation, and many producers did.
AnalysisInputError's options are now a union: a conforming refusal must
supply both its outcome (userMessage) and next step (remediationAction),
so the compiler lists every producer; only contract violations may fall
back to the schema guidance.

Producers fixed: unknown Frida session and script, decompile_all
output-directory state, the duplicate unknown build computer factory
(collapsed), stale Cutter sessions, Mach-O architecture selection, output
roots that already exist, selected files the host refuses, Ghidra lookups
the bridge could not resolve, YARA path refusals, unresolved native symbol
names, apt key files and withheld sign-in state. A missing selected APK is
now target_unavailable like every other selected-file reader.

The capability fallback "Choose another analysis or target" is deleted; a
capability refusal without its own recovery names details.reason and
binary_session.

Refs #15312

* fix(errors): classify caller selections and target bytes by their real failure

Several refusals reported a code that reads as corruption or a crash:
- a missing unknown_id and a missing Evidence reference now report
  invalid_request instead of execution_failure and
  evidence_integrity_mismatch;
- close_binary with snapshot_path in a resource-only session reports
  invalid_request instead of evidence_integrity_mismatch;
- ADB push onto an existing device path and pulls into an occupied output
  directory are conforming invalid_request refusals naming overwrite or
  output_directory, not unreadable_output;
- damaged APK ZIP, signing-block, signer and central-directory structures
  are malformed targets, not invalid input;
- NuGet and VSIX bytes without a ZIP signature are unrecognized, not
  malformed;
- a historical source graph file whose entries contradict its root
  commitment is an integrity failure, not invalid input;
- a CDP protocol failure states what happened instead of the unclassified
  fallback message.

Refs #15319

* feat(errors): expose the producer's retry class as retry_class

Every error projection now carries retry_class (same_call, change_first, never or unknown_outcome) beside retryable, which stays true exactly for same_call. The field is additive: the error schema accepts errors retained by earlier releases without it.

Refs #15323

* fix(errors): address review of the folded error-contract PRs

Keep a provider's own capability message as its remediation; the binary_session fallback applies only to a bare declared reason. Delete the unused conformingInputRefusal helper. Compose both retry fields for a refused publication whose cleanup is incomplete. Report descriptor exhaustion from a JavaScript directory opendir as occupied capacity. Let an exited Hopper startup attempt without a setup failure code retry unchanged. Declare retry for the Ghidra superseded checkpoint and unknown IDA readiness. Redact ambiguous selector candidates. Give a Ghidra document miss its own recovery. Drop an unchanged-files claim the journal repair cannot make. Name each withheld sign-in refusal's step. Hash the source graph commitment before the cancellation yield. Keep the browser protocol_error message neutral. Add tests for mutation-audit survivors C3, C5, P2, P4, P8, H1, H4 and H5.

* fix(errors): keep a missing Evidence reference an integrity failure and state only the observed commitment mismatch

* test(desktop): assert the unknown build computer refusal's remediation, not its message

The refusal now carries its next step in remediation.action instead of the message, so the closed-computer checks assert the exact code, message and remediation facts.

* fix(errors): keep producer retry choices apart from cleanup and fixed ceilings

A capture's retryable flag no longer folds in pending cleanup, so the projection applies the cleanup rule once and a transient capture with pending cleanup reports change_first instead of never. A release-fixed artifact allowance reports never, and a stale admitted session identity reports change_first (reopen, then retry); both have catalogue rows. The bare capability-unavailable remediation names binary_session only for a binary-analysis session, so standalone bridges such as Cutter are pointed at their own reason.

* test(vsix): expect a non-ZIP selection to be refused as unrecognized

This PR reports bytes without a ZIP signature as another format (unrecognized), not a damaged package; the exact-reason assertion added on main still expected malformed.

* test(delivery): expect the capacity refusal's retry class in delivered failure facts

The exact failure facts asserted on main predate the projection's retry_class; occupied capacity reports same_call.

* fix(errors): mark a sent Hopper cancellation unknown and missing Evidence recoverable

A cancellation Hopper already received may still apply, so its retry class is unknown_outcome instead of same_call; an unsent cancellation keeps same_call. A missing EvidenceReferenceError is change_first, since importing the referenced records lets the same request succeed; other reference failures stay never. Both have catalogue rows.

* fix(hopper): ask for changed launch arguments before retrying an unencodable launch

A launcher path or argument that cannot be encoded as an AppleScript literal meets the same pre-launch guard on every attempt, so the start refusal is change_first and its retry_action is unknown; a start failure without a declared reason stays same_call.

* fix(errors): keep a one-shot cleanup failure's retry class with its cleanup state

A one-shot reply that reports cleanup_incomplete spread the primary or cleanup projection and overrode only retryable, so a timed-out read whose close also failed carried retry_class same_call. The reply now reads its retry class from the typed composed failure, and never offers the same call before cleanup settles.

* test(evtx): expect an unreadable selected log to be refused with its own recovery

This PR treats a well-formed path the host refused as a regular file as conforming input with its own remediation; the evtx boundary test still expected a schema-recovery refusal.

* test(javascript): expect a broken source-graph commitment as an integrity failure

This PR reports a well-formed historical source graph whose entries disagree with its root_sha256 as evidence_integrity_mismatch, not an input issue; the exact refusal assertion added on main still expected invalid_request.
2026-12-01 05:32:33 +00:00

674 lines
23 KiB
TypeScript

import {
mkdir,
readFile,
readdir,
realpath,
writeFile,
} from "node:fs/promises";
import { join, resolve, sep } from "node:path";
import { pathToFileURL } from "node:url";
import { expect } from "vitest";
import { z } from "zod";
import { cliRetainedEvidenceDirectory } from "../../../src/cli/cliEvidenceRetention.js";
import { PARTIAL_OBSERVATION_DELIVERY } from "../../../src/domain/agentResultBudget.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { parseEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest, type TestCli } from "../../support/cli/cliFixture.js";
// Inventory completes before the first JavaScript source reaches its 1 ms
// deadline, so the partial Evidence holds completed artifact facts and
// explicit unknowns for the sources that were not analyzed.
const application = async (): Promise<string> => {
const root = await createTestTempDirectory("rea-js-failure-evidence-");
await Promise.all(
(
[
["package.json", '{"name":"partial-delivery","main":"main.js"}'],
["main.js", "export const observed = 7;\n"],
["other.js", "localStorage.setItem('k', '1');\n"],
] as const
).map(([path, content]) => writeFile(join(root, path), content)),
);
return root;
};
const timeoutArguments = (root: string, ...extra: readonly string[]) => [
"analyze-javascript-application",
root,
"--max-heap-mb",
"128",
"--analysis-timeout-ms",
"1",
...extra,
"--format",
"json",
];
const failureSchema = z.object({
code: z.literal("provider_timeout"),
remediation: z.object({ action: z.string() }),
details: z
.object({
partial_observation: z.unknown(),
diagnostics: z.record(z.string(), z.unknown()).optional(),
})
.passthrough(),
});
const nodeKinds = (normalized: unknown) =>
javascriptApplicationAnalysisResultSchema
.parse(normalized)
.graph.nodes.map(({ kind }) => kind)
.sort();
cliTest(
"publishes partial Evidence to --evidence_output after a source deadline and keeps the reply compact",
async ({ cli }) => {
const root = await application();
const output = join(
await createTestTempDirectory("rea-js-failure-bundle-"),
"partial.json",
);
const inline = await cli.run({ arguments: timeoutArguments(root) });
expect(inline.exitCode).toBe(1);
const inlineFailure = failureSchema.parse(inline.json);
// Without --evidence_output the documented contract is unchanged.
const inlinePartial = parseEvidence(
inlineFailure.details.partial_observation,
);
expect(nodeKinds(inlinePartial.normalized_result)).toEqual(
expect.arrayContaining(["artifact", "javascript-asset", "unknown"]),
);
expect(inlineFailure.details.diagnostics?.evidence_bundle).toBeUndefined();
const summary = await cli.run({
arguments: timeoutArguments(
root,
"--detail",
"summary",
"--evidence_output",
output,
),
});
expect(summary.exitCode, summary.stderr).toBe(1);
const failure = failureSchema.parse(summary.json);
expect(failure.remediation.action).toContain("partial_observation");
const receipt = z
.object({ path: z.string(), bytes: z.number().int().positive() })
.parse(failure.details.diagnostics?.evidence_bundle);
expect(receipt.path).toBe(output);
const bundleText = await readFile(output, "utf8");
expect(Buffer.byteLength(bundleText)).toBe(receipt.bytes);
const view = z
.object({
normalized_result: z.object({
kind: z.literal("summary"),
parent_evidence_id: z.string(),
coverage: z.unknown(),
limitations: z.array(z.string()),
}),
})
.passthrough()
.parse(failure.details.partial_observation);
const record = parseEvidenceBundle(JSON.parse(bundleText)).records.find(
({ evidence_id: id }) => id === view.normalized_result.parent_evidence_id,
);
if (record === undefined)
throw new Error("The published bundle lacks the partial Evidence");
expect(record.operation).toBe("analyze_javascript_application");
expect(nodeKinds(record.normalized_result)).toEqual(
nodeKinds(inlinePartial.normalized_result),
);
expect(view.normalized_result.limitations.length).toBeGreaterThan(0);
expect(Buffer.byteLength(summary.stdout)).toBeLessThan(
Buffer.byteLength(inline.stdout),
);
},
);
cliTest(
"keeps partial Evidence inline when --evidence_output cannot be published",
async ({ cli }) => {
const root = await application();
const output = join(
await createTestTempDirectory("rea-js-failure-existing-"),
"existing.json",
);
await writeFile(output, "kept");
const response = await cli.run({
arguments: timeoutArguments(
root,
"--detail",
"summary",
"--evidence_output",
output,
),
});
expect(response.exitCode).toBe(1);
const failure = failureSchema.parse(response.json);
const partial = parseEvidence(failure.details.partial_observation);
expect(nodeKinds(partial.normalized_result)).not.toHaveLength(0);
expect(failure.details.diagnostics?.evidence_bundle).toBeUndefined();
expect(failure.details.diagnostics?.evidence_bundle_error).toMatchObject({
code: expect.any(String),
message: expect.stringContaining("already exists"),
limitation: expect.stringContaining("details.partial_observation"),
});
expect(await readFile(output, "utf8")).toBe("kept");
},
);
// A one-line module finishes well within 5 s; a string-array-style module of
// 6,000 functions takes several times longer, so it reaches the deadline.
const slowModule = (): string => {
const words = Array.from({ length: 4000 }, (_, i) => `w${i.toString(36)}`);
const key = (i: number, n: number) => `_s(${String((i * 31 + n) % 4000)})`;
return (
`const _t=${JSON.stringify(words)};function _s(i){return _t[(i*7+3)%_t.length];}\n` +
Array.from(
{ length: 6000 },
(_, i) =>
`export function f${String(i)}(a,b){const o={[${key(i, 1)}]:a,[${key(i, 2)}]:b};` +
`if(o[${key(i, 3)}]>o[${key(i, 4)}]){return o[${key(i, 5)}]+${key(i, 6)};}` +
`return window[${key(i, 7)}](o[${key(i, 8)}],o[${key(i, 9)}]);}\n`,
).join("")
);
};
cliTest(
"keeps a finished source's facts in the published partial Evidence",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-failure-finished-");
await writeFile(
join(root, "a.js"),
"localStorage.setItem('finished.key', '1');\n",
);
await writeFile(join(root, "vendor.js"), slowModule());
const output = join(
await createTestTempDirectory("rea-js-failure-finished-bundle-"),
"partial.json",
);
const response = await cli.run({
arguments: [
"analyze-javascript-application",
root,
"--analysis-timeout-ms",
"5000",
"--detail",
"summary",
"--evidence_output",
output,
"--format",
"json",
],
});
expect(response.exitCode, response.stderr).toBe(1);
const failure = failureSchema.parse(response.json);
expect(failure.details.diagnostics?.evidence_bundle).toMatchObject({
path: output,
});
const [record] = parseEvidenceBundle(
JSON.parse(await readFile(output, "utf8")),
).records.filter(
({ operation }) => operation === "analyze_javascript_application",
);
if (record === undefined)
throw new Error("The published bundle lacks the partial Evidence");
const result = javascriptApplicationAnalysisResultSchema.parse(
record.normalized_result,
);
expect(
result.graph.nodes.filter(
({ kind, identity }) =>
kind === "storage" &&
JSON.stringify(identity).includes("finished.key"),
),
).toHaveLength(1);
expect(record.limitations).toEqual(
expect.arrayContaining([
expect.stringMatching(/^vendor\.js: .*timed out after 5000ms/u),
]),
);
},
);
// Drive the real staged publication of the partial Evidence across its
// commit point, as evidenceOutputPublicationCli does for successful results.
const publishPartialWithSeam = async (
cli: TestCli,
publication: Record<string, unknown>,
) => {
const root = await application();
const work = await createTestTempDirectory("rea-js-failure-seam-");
const destination = join(work, "partial.json");
const marker = join(work, "signal.json");
const reply = await cli.run({
cwd: work,
arguments: timeoutArguments(
root,
"--detail",
"summary",
"--evidence_output",
destination,
),
environment: {
REA_TEST_EVIDENCE_PUBLICATION: JSON.stringify({
prefix: join(await realpath(work), ".rea-write-"),
marker,
...publication,
}),
NODE_OPTIONS: `--max-old-space-size=2048 --import=${pathToFileURL(resolve("tests/fixtures/evidencePublicationPreload.mjs")).href}`,
},
});
const staging = (await readdir(work)).filter((name) =>
name.startsWith(".rea-write-"),
);
const bytes = await readFile(destination);
const [record] = parseEvidenceBundle(JSON.parse(bytes.toString())).records;
if (record === undefined)
throw new Error("The published bundle lacks the partial Evidence");
const proof = JSON.parse(await readFile(marker, "utf8")) as unknown;
return { reply, destination, staging, bytes: bytes.length, record, proof };
};
cliTest(
"retains the original failure and committed receipt when staging cleanup stays incomplete",
async ({ cli }) => {
const { reply, destination, staging, bytes, record, proof } =
await publishPartialWithSeam(cli, { cleanup_failures: 1_000 });
expect(proof).toEqual({ cleanup_failure: "EBUSY" });
expect(reply.exitCode).toBe(1);
const failure = failureSchema
.extend({
code: z.literal("cleanup_incomplete"),
retryable: z.literal(false),
// Never same_call while the publication cleanup is unreleased.
retry_class: z.enum(["change_first", "never"]),
})
.parse(reply.json);
expect(failure.remediation.action).toContain("cleanup");
// The success path reports this outcome as details.published,
// published_path, bytes and cleanup; the failure keeps the same shape.
expect(failure.details).toMatchObject({
published: true,
published_path: destination,
bytes,
cleanup: "incomplete",
execution_failure: "provider_timeout",
});
expect(failure.details.diagnostics?.evidence_bundle).toEqual({
path: destination,
bytes,
});
expect(failure.details.diagnostics?.evidence_bundle_error).toMatchObject({
code: "cleanup_incomplete",
});
expect(failure.details.partial_observation).toMatchObject({
normalized_result: {
kind: "summary",
parent_evidence_id: record.evidence_id,
},
});
expect(staging).toHaveLength(1);
},
);
cliTest(
"delivers the receipt once a failed staging cleanup is confirmed by retry",
async ({ cli }) => {
const { reply, destination, staging, bytes, record, proof } =
await publishPartialWithSeam(cli, { cleanup_failures: 1 });
expect(proof).toEqual({ cleanup_failure: "EBUSY" });
expect(reply.exitCode).toBe(1);
const failure = failureSchema.parse(reply.json);
expect(failure.details.diagnostics?.evidence_bundle).toEqual({
path: destination,
bytes,
});
expect(failure.details.diagnostics).not.toHaveProperty(
"evidence_bundle_error",
);
expect(failure.details.partial_observation).toMatchObject({
normalized_result: { parent_evidence_id: record.evidence_id },
});
expect(staging).toEqual([]);
},
);
cliTest(
"keeps the original failure and the committed receipt when SIGINT arrives after commit",
async ({ cli }) => {
const delivery = process.platform === "win32" ? "event" : "os";
const { reply, destination, staging, bytes, record, proof } =
await publishPartialWithSeam(cli, {
phase: "cleanup",
signal: "SIGINT",
delivery,
});
expect(proof).toMatchObject({
phase: "cleanup",
signal: "SIGINT",
delivery,
});
expect(reply.exitCode).toBe(130);
const failure = failureSchema.parse(reply.json);
expect(failure.details.diagnostics?.evidence_bundle).toEqual({
path: destination,
bytes,
});
expect(failure.details.diagnostics?.evidence_bundle_error).toMatchObject({
code: "cancelled",
});
expect(failure.details.partial_observation).toMatchObject({
normalized_result: {
kind: "summary",
parent_evidence_id: record.evidence_id,
},
});
expect(staging).toEqual([]);
},
);
cliTest(
"retains the original failure and committed cache receipt when retained-cache staging cleanup stays incomplete",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-failure-cache-app-");
await writeFile(
join(root, "package.json"),
'{"name":"retained-seam","main":"m0.js"}',
);
await Promise.all(
Array.from({ length: 20 }, (_, index) =>
writeFile(
join(root, `m${String(index)}.js`),
`export const value_${String(index)} = ${String(index)};\n`,
),
),
);
const home = await createTestTempDirectory("rea-js-failure-cache-home-");
const cache = await createTestTempDirectory("rea-js-failure-cache-root-");
const work = await createTestTempDirectory("rea-js-failure-cache-work-");
const marker = join(work, "signal.json");
const environment = {
HOME: home,
XDG_CACHE_HOME: cache,
LOCALAPPDATA: cache,
};
const cacheDirectory = cliRetainedEvidenceDirectory(
environment,
process.platform,
);
await mkdir(cacheDirectory, { recursive: true, mode: 0o700 });
const expectedCacheReal = await realpath(cacheDirectory);
const reply = await cli.run({
cwd: work,
delivery: "budgeted",
arguments: timeoutArguments(root),
environment: {
...environment,
REA_TEST_EVIDENCE_PUBLICATION: JSON.stringify({
prefix: join(expectedCacheReal, ".rea-write-"),
marker,
cleanup_failures: 1_000,
}),
NODE_OPTIONS: `--max-old-space-size=2048 --import=${pathToFileURL(resolve("tests/fixtures/evidencePublicationPreload.mjs")).href}`,
},
});
expect(JSON.parse(await readFile(marker, "utf8"))).toEqual({
cleanup_failure: "EBUSY",
});
expect(reply.exitCode).toBe(1);
const failure = failureSchema
.extend({
code: z.literal("cleanup_incomplete"),
retryable: z.literal(false),
// Never same_call while the publication cleanup is unreleased.
retry_class: z.enum(["change_first", "never"]),
})
.parse(reply.json);
const receipt = z
.object({
path: z.string(),
bytes: z.number().int().positive(),
record_sha256: z.string().regex(/^[0-9a-f]{64}$/u),
})
.parse(failure.details.diagnostics?.evidence_bundle);
expect(failure.details).toMatchObject({
published: true,
published_path: receipt.path,
bytes: receipt.bytes,
cleanup: "incomplete",
execution_failure: "provider_timeout",
[PARTIAL_OBSERVATION_DELIVERY]: {
retained: "cache-file",
next: {
arguments: {
source: { kind: "evidence-file", path: receipt.path },
},
},
},
});
expect(failure.details.diagnostics?.evidence_bundle_error).toMatchObject({
code: "cleanup_incomplete",
limitation: expect.stringContaining("retained-Evidence cache"),
});
const [record] = parseEvidenceBundle(
JSON.parse(await readFile(receipt.path, "utf8")),
).records;
if (record === undefined)
throw new Error("The retained cache bundle lacks the partial Evidence");
expect(failure.details.partial_observation).toMatchObject({
normalized_result: {
kind: "summary",
parent_evidence_id: record.evidence_id,
},
});
const staging = (await readdir(expectedCacheReal)).filter((name) =>
name.startsWith(".rea-write-"),
);
expect(staging).toHaveLength(1);
},
);
cliTest(
"reports cleanup_incomplete and keeps complete partial Evidence when retained-cache staging cleanup fails before commit",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-failure-precommit-app-");
await writeFile(
join(root, "package.json"),
'{"name":"retained-precommit","main":"m0.js"}',
);
await Promise.all(
Array.from({ length: 20 }, (_, index) =>
writeFile(
join(root, `m${String(index)}.js`),
`export const value_${String(index)} = ${String(index)};\n`,
),
),
);
const home = await createTestTempDirectory(
"rea-js-failure-precommit-home-",
);
const cache = await createTestTempDirectory(
"rea-js-failure-precommit-cache-",
);
const work = await createTestTempDirectory(
"rea-js-failure-precommit-work-",
);
const marker = join(work, "signal.json");
const environment = {
HOME: home,
XDG_CACHE_HOME: cache,
LOCALAPPDATA: cache,
};
const cacheDirectory = cliRetainedEvidenceDirectory(
environment,
process.platform,
);
await mkdir(cacheDirectory, { recursive: true, mode: 0o700 });
const expectedCacheReal = await realpath(cacheDirectory);
const delivery = process.platform === "win32" ? "event" : "os";
const reply = await cli.run({
cwd: work,
delivery: "budgeted",
arguments: timeoutArguments(root),
environment: {
...environment,
REA_TEST_EVIDENCE_PUBLICATION: JSON.stringify({
prefix: join(expectedCacheReal, ".rea-write-"),
marker,
phase: "staging",
signal: "SIGINT",
delivery,
cleanup_failures: 1_000,
}),
NODE_OPTIONS: `--max-old-space-size=2048 --import=${pathToFileURL(resolve("tests/fixtures/evidencePublicationPreload.mjs")).href}`,
},
});
expect(JSON.parse(await readFile(marker, "utf8"))).toMatchObject({
phase: "staging",
signal: "SIGINT",
delivery,
});
expect(reply.exitCode).not.toBe(0);
const failure = failureSchema
.extend({
code: z.literal("cleanup_incomplete"),
retryable: z.literal(false),
// Never same_call while the publication cleanup is unreleased.
retry_class: z.enum(["change_first", "never"]),
})
.parse(reply.json);
expect(failure.details).toMatchObject({
cleanup: "incomplete",
execution_failure: "provider_timeout",
});
expect(Array.isArray(failure.details.resources)).toBe(true);
expect((failure.details.resources as unknown[]).length).toBeGreaterThan(0);
expect(failure.details.diagnostics?.evidence_bundle).toBeUndefined();
expect(failure.details.diagnostics?.evidence_bundle_error).toMatchObject({
code: "cleanup_incomplete",
limitation: expect.stringContaining("details.resources"),
});
// Nothing committed, so the complete partial Evidence stays inline.
expect(parseEvidence(failure.details.partial_observation).operation).toBe(
"analyze_javascript_application",
);
const staging = (await readdir(expectedCacheReal)).filter((name) =>
name.startsWith(".rea-write-"),
);
expect(staging).toHaveLength(1);
},
);
cliTest(
"reports the surviving cache receipt and paging cursor when removing an oversized failure bundle fails",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-failure-remains-app-");
await writeFile(
join(root, "package.json"),
'{"name":"retained-remains","main":"m0.js"}',
);
await Promise.all(
Array.from({ length: 20 }, (_, index) =>
writeFile(
join(root, `m${String(index)}.js`),
`export const value_${String(index)} = ${String(index)};\n`,
),
),
);
const home = await createTestTempDirectory("rea-js-failure-remains-home-");
const cache = await createTestTempDirectory(
"rea-js-failure-remains-cache-",
);
const work = await createTestTempDirectory("rea-js-failure-remains-work-");
const marker = join(work, "rm-signal.json");
const environment = {
HOME: home,
XDG_CACHE_HOME: cache,
LOCALAPPDATA: cache,
};
const cacheDirectory = cliRetainedEvidenceDirectory(
environment,
process.platform,
);
await mkdir(cacheDirectory, { recursive: true, mode: 0o700 });
const expectedCacheReal = await realpath(cacheDirectory);
// Measure the partial observation byte size so the cap admits the record
// while the wrapped bundle exceeds it and triggers post-write removal.
const baseline = await cli.run({
cwd: work,
delivery: "budgeted",
arguments: timeoutArguments(root, "--no-retain"),
environment,
});
expect(baseline.exitCode).toBe(1);
const baselineFailure = failureSchema.parse(baseline.json);
const completeBytes = z
.object({ complete_bytes: z.number().int().positive() })
.parse(
baselineFailure.details[PARTIAL_OBSERVATION_DELIVERY],
).complete_bytes;
const reply = await cli.run({
cwd: work,
delivery: "budgeted",
arguments: timeoutArguments(root),
environment: {
...environment,
REA_CLI_RETAINED_EVIDENCE_BYTES: String(completeBytes + 32),
REA_TEST_EVIDENCE_PUBLICATION: JSON.stringify({
prefix: `${expectedCacheReal}${sep}`,
marker,
rm_failures: 1,
}),
NODE_OPTIONS: `--max-old-space-size=2048 --import=${pathToFileURL(resolve("tests/fixtures/evidencePublicationPreload.mjs")).href}`,
},
});
expect(JSON.parse(await readFile(marker, "utf8"))).toEqual({
rm_failure: "EBUSY",
});
expect(reply.exitCode).toBe(1);
const failure = failureSchema.parse(reply.json);
const receipt = z
.object({
path: z.string(),
bytes: z.number().int().positive(),
record_sha256: z.string().regex(/^[0-9a-f]{64}$/u),
})
.parse(failure.details.diagnostics?.evidence_bundle);
expect(failure.details[PARTIAL_OBSERVATION_DELIVERY]).toMatchObject({
retained: "cache-file",
retention_failure: expect.stringContaining("could not be removed"),
next: {
arguments: {
source: { kind: "evidence-file", path: receipt.path },
},
},
});
expect(
(
failure.details[PARTIAL_OBSERVATION_DELIVERY] as {
readonly retention_failure?: string;
}
).retention_failure,
).toContain("larger than");
const [record] = parseEvidenceBundle(
JSON.parse(await readFile(receipt.path, "utf8")),
).records;
if (record === undefined)
throw new Error("The surviving cache bundle lacks the partial Evidence");
expect(record.operation).toBe("analyze_javascript_application");
expect(failure.details.partial_observation).toMatchObject({
normalized_result: {
kind: "summary",
parent_evidence_id: record.evidence_id,
},
});
},
);