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(firmware): own file access through publication and cleanup retry
morluto2d163c12b18c
diff --git a/src/cli/firmwareCommands.ts b/src/cli/firmwareCommands.tsindex a19307a08..89d3e6774 100644--- a/src/cli/firmwareCommands.ts+++ b/src/cli/firmwareCommands.ts@@ -35,6 +35,8 @@ export const registerFirmwareCommands = (service,operation === "inspect_firmware_regions" ? "binwalk" : "unblob",operation,+ undefined,+ signal,),),);diff --git a/src/firmware/FirmwareCommand.test.ts b/src/firmware/FirmwareCommand.test.tsindex cbfa0925a..45b6ac216 100644--- a/src/firmware/FirmwareCommand.test.ts+++ b/src/firmware/FirmwareCommand.test.ts@@ -6,6 +6,7 @@ import { expect, it as test } from "vitest";import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";import { projectAnalysisError } from "../domain/analysisErrorProjection.js";+import { FirmwareFileAccess } from "./FirmwareFiles.js";import { resolveFirmwareCommand } from "./FirmwareCommand.js";const it = test.skipIf(process.platform !== "linux");@@ -15,6 +16,7 @@ test("names the host and tool requirement of an unconfigured engine", async () ={},"binwalk","inspect_firmware_regions",+ new FirmwareFileAccess(),).catch((cause: unknown) => cause);expect(refusal).toMatchObject({@@ -44,6 +46,7 @@ it("rejects a directory configured as the firmware engine executable", async ()},"binwalk","inspect_firmware_regions",+ new FirmwareFileAccess(),),).rejects.toMatchObject({_tag: "AnalysisCapabilityUnavailableError",@@ -65,6 +68,7 @@ it("classifies an unusable firmware engine as an unavailable capability", async},"binwalk","inspect_firmware_regions",+ new FirmwareFileAccess(),),).rejects.toMatchObject({_tag: "AnalysisCapabilityUnavailableError",@@ -86,6 +90,7 @@ it("rejects a directory configured as the resource limiter executable", async ()},"binwalk","inspect_firmware_regions",+ new FirmwareFileAccess(),),).rejects.toMatchObject({_tag: "AnalysisCapabilityUnavailableError",diff --git a/src/firmware/FirmwareCommand.ts b/src/firmware/FirmwareCommand.tsindex 1604de901..d8eef7fef 100644--- a/src/firmware/FirmwareCommand.ts+++ b/src/firmware/FirmwareCommand.ts@@ -1,3 +1,4 @@+import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";import { randomUUID } from "node:crypto";import { access, realpath, stat } from "node:fs/promises";import { constants } from "node:fs";@@ -19,9 +20,8 @@ import {import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js";import { FIRMWARE_LIMITS } from "./FirmwareRelease.js";import {- hashFirmwareFile,+ FirmwareFileAccess,inventoryFirmwareOutput,- readFirmwareReport,} from "./FirmwareFiles.js";/** Injectable owned launcher for production protocol and lifecycle tests. */@@ -44,6 +44,8 @@ export const resolveFirmwareCommand = async (environment: Readonly<Record<string, string | undefined>>,engine: "binwalk" | "unblob",operation: string,+ files: FirmwareFileAccess,+ signal?: AbortSignal,) => {const variable =engine === "binwalk" ? "REA_BINWALK_COMMAND" : "REA_UNBLOB_COMMAND";@@ -70,8 +72,9 @@ export const resolveFirmwareCommand = async (await access(command, constants.R_OK | constants.X_OK);if (!(await stat(command)).isFile())throw new TypeError("Configured path is not a regular file");- sha256 = await hashFirmwareFile(command);+ sha256 = await files.hash(command, signal);} catch (cause: unknown) {+ if (cause instanceof ArtifactReaderFailure) throw cause;throw firmwareToolUnavailable(engine,operation,@@ -116,7 +119,8 @@ export const runFirmwareCommand = async (context: {retainCleanup(supervisor: ProviderProcessSupervisor): void;}) => {const { engine, operation, signal } = context;- signal.throwIfAborted();+ if (signal.aborted)+ throw new AnalysisCancelledError(operation, { cause: signal.reason });const runId = `rea-firmware-${randomUUID()}`;const spawned = await (context.launcher ?? spawnOwnedProviderProcess)({command: context.limiter,@@ -179,7 +183,8 @@ export const runFirmwareCommand = async (context: {const deadline = performance.now() + FIRMWARE_LIMITS.timeoutMs;while (!(await supervisor.waitForOutputClose(100))) {checkDiagnostics();- if (signal.aborted) throw new AnalysisCancelledError(operation);+ if (signal.aborted)+ throw new AnalysisCancelledError(operation, { cause: signal.reason });if (performance.now() >= deadline)throw new AnalysisTimeoutError(operation, FIRMWARE_LIMITS.timeoutMs);if (context.outputBudget !== undefined)@@ -192,7 +197,8 @@ export const runFirmwareCommand = async (context: {);}checkDiagnostics();- if (signal.aborted) throw new AnalysisCancelledError(operation);+ if (signal.aborted)+ throw new AnalysisCancelledError(operation, { cause: signal.reason });} catch (cause: unknown) {failure = cause;}@@ -250,10 +256,17 @@ export const readFirmwareCommandReport = async (context: {engine: string;operation: string;execution: Awaited<ReturnType<typeof runFirmwareCommand>>;+ files: FirmwareFileAccess;+ signal?: AbortSignal;}): Promise<unknown> => {try {- return await readFirmwareReport(context.path, context.operation);+ return await context.files.report(+ context.path,+ context.operation,+ context.signal,+ );} catch (cause: unknown) {+ if (cause instanceof ArtifactReaderFailure) throw cause;if (context.execution.exit_code === 1)throw new ProviderAdapterError(context.engine, context.operation, {cause,diff --git a/src/firmware/FirmwareFailures.ts b/src/firmware/FirmwareFailures.tsnew file mode 100644index 000000000..0cf56ddbc--- /dev/null+++ b/src/firmware/FirmwareFailures.ts@@ -0,0 +1,119 @@+import type { AnalysisCleanupLease } from "../artifacts/AnalysisCleanupLease.js";+import { ArtifactResourceRetryFailure } from "../artifacts/ArtifactResourceScope.js";+import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";+import {+ ArtifactFileCleanupFailure,+ artifactFileCancellationCause,+ bindArtifactFileCleanup,+} from "../artifacts/ArtifactFileOperation.js";+import { AnalysisError } from "../domain/analysisErrorBase.js";+import {+ AnalysisCancelledError,+ AnalysisTimeoutError,+ AnalysisOutputError,+} from "../domain/analysisErrorCore.js";+import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";+import { ProviderAdapterError } from "../domain/providerAdapterError.js";+import { ProviderCleanupError } from "../domain/providerCleanupError.js";+import { FIRMWARE_LIMITS } from "./FirmwareRelease.js";+import { z } from "zod";++/** Translate the producing file owner's outcome without guessing from a later signal. */+export const firmwareFailure = (+ cause: unknown,+ engine: string,+ operation: string,+ deadline?: AbortSignal,+ treeCleanupLease?: AnalysisCleanupLease,+): AnalysisError => {+ if (+ cause instanceof AnalysisCancelledError &&+ deadline?.aborted &&+ cause.cause === deadline.reason+ )+ return new AnalysisTimeoutError(operation, FIRMWARE_LIMITS.timeoutMs, {+ cause: cause.cause,+ partialObservation: cause.partialObservation,+ });+ if (cause instanceof AnalysisError) return cause;+ if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined) {+ const cleanup = new ProviderCleanupError(+ engine,+ cause.cleanup.resources,+ { reason: cause.cleanup.reason },+ { operation, cause },+ );+ bindArtifactFileCleanup(cause, cleanup);+ if (+ !(cause instanceof ArtifactFileCleanupFailure) &&+ !(cause instanceof ArtifactResourceRetryFailure)+ )+ treeCleanupLease?.bindCleanupError(cleanup);+ if (cause instanceof ArtifactFileCleanupFailure) {+ const outcome = cause.fileCleanupFailure.outcome;+ const primary =+ outcome.kind === "failed"+ ? firmwareFailure(+ outcome.cause,+ engine,+ operation,+ deadline,+ treeCleanupLease,+ )+ : cause.completionCancellation !== undefined+ ? firmwareCancellation(+ operation,+ cause.completionCancellation.reason,+ deadline,+ )+ : undefined;+ if (primary !== undefined)+ return analysisErrorWithCleanupFailure(+ primary,+ cleanup,+ operation,+ ).bindCleanupDependencies([primary, cleanup]);+ }+ if (cause.reason === "cancelled")+ return analysisErrorWithCleanupFailure(+ firmwareCancellation(+ operation,+ artifactFileCancellationCause(cause),+ deadline,+ ),+ cleanup,+ operation,+ ).bindCleanupDependencies([cleanup]);+ return cleanup;+ }+ if (cause instanceof ArtifactReaderFailure && cause.reason === "cancelled")+ return firmwareCancellation(+ operation,+ artifactFileCancellationCause(cause),+ deadline,+ );+ if (cause instanceof z.ZodError)+ return new AnalysisOutputError(+ operation,+ "Tool report violated the pinned producer protocol",+ { cause },+ );+ return new ProviderAdapterError(engine, operation, {+ cause,+ diagnostics: {+ reason: cause instanceof Error ? cause.message : String(cause),+ },+ });+};++/** Classify the interruption actually observed, before composing cleanup failures. */+export const firmwareCancellation = (+ operation: string,+ reason: unknown,+ deadline?: AbortSignal,+): AnalysisError =>+ deadline?.aborted && reason === deadline.reason+ ? new AnalysisTimeoutError(operation, FIRMWARE_LIMITS.timeoutMs, {+ cause: reason,+ })+ : new AnalysisCancelledError(operation, { cause: reason });diff --git a/src/firmware/FirmwareFiles.ts b/src/firmware/FirmwareFiles.tsindex 11e0b9e1b..2f6cdb851 100644--- a/src/firmware/FirmwareFiles.ts+++ b/src/firmware/FirmwareFiles.ts@@ -1,13 +1,6 @@import { createHash } from "node:crypto";-import { constants, createReadStream, createWriteStream } from "node:fs";-import {- chmod,- lstat,- opendir,- open,- readlink,- realpath,-} from "node:fs/promises";+import { createWriteStream } from "node:fs";+import { chmod, lstat, opendir, readlink, realpath } from "node:fs/promises";import { isAbsolute, join, relative, sep } from "node:path";import { Transform } from "node:stream";import { pipeline } from "node:stream/promises";@@ -21,6 +14,15 @@ import { absoluteCallerPath } from "../filesystem/callerPath.js";import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";import { FIRMWARE_LIMITS } from "./FirmwareRelease.js";import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";+import type { SafeOutputTree } from "../artifacts/SafeOutputTree.js";+import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";+import {+ withArtifactRegularFile,+ assertArtifactReadActive,+ mapArtifactFileFailure,+} from "../artifacts/ArtifactFileOperation.js";+import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";+import { NonRegularFileReadError } from "../filesystem/RegularFile.js";/** One regular file or unpublished filesystem entry in a private extraction. */export interface FirmwareEntry {@@ -35,151 +37,257 @@ const throwIfFirmwareInventoryCancelled = (signal: AbortSignal | undefined,operation: string,): void => {- if (signal?.aborted === true) throw new AnalysisCancelledError(operation);+ if (signal?.aborted === true)+ throw new AnalysisCancelledError(operation, { cause: signal.reason });};-/** Hash a regular tool or extracted file without retaining its bytes in memory. */-export const hashFirmwareFile = async (- path: string,- signal?: AbortSignal,-): Promise<string> => {- const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);- const hash = createHash("sha256");- try {- if (!(await handle.stat()).isFile())- throw new Error(`Not a regular file: ${path}`);- for await (const chunk of handle.createReadStream({ autoClose: false })) {- signal?.throwIfAborted();- hash.update(chunk);- }- } finally {- await handle.close();+/** Own all firmware reads, including rejected admission and final descriptor cleanup. */+export class FirmwareFileAccess {+ readonly #resources = new ArtifactResourceScope();++ /** Retry retained descriptors without closing admission for future operations. */+ retryCleanup(): Promise<void> {+ return this.#resources.retryCleanup();}- return hash.digest("hex");-};-/** Copy and identify the exact bytes consumed by firmware providers. */-export const snapshotFirmware = async (- request: FirmwareRequest,- root: string,- signal: AbortSignal,-) => {- const sourcePath = absoluteCallerPath(request.input.path);- const source = await realpath(sourcePath);- const handle = await open(source, constants.O_RDONLY | constants.O_NOFOLLOW);- const fullPath = join(root, "firmware.bin");- const hash = createHash("sha256");- let size = 0;- try {- const stat = await handle.stat();- if (- !stat.isFile() ||- stat.size === 0 ||- stat.size > FIRMWARE_LIMITS.inputBytes- )+ /** Wait for admitted operations and retry every retained descriptor. */+ close(): Promise<void> {+ return this.#resources.close();+ }++ /** Hash one admitted regular file without retaining its bytes in memory. */+ hash(path: string, signal?: AbortSignal): Promise<string> {+ return this.#resources.run(() => this.#hash(path, signal));+ }++ async #hash(path: string, signal?: AbortSignal): Promise<string> {+ return withArtifactRegularFile(+ path,+ this.#resources,+ signal,+ async (handle) => {+ const hash = createHash("sha256");+ try {+ for await (const chunk of handle.createReadStream({+ autoClose: false,+ signal,+ })) {+ assertArtifactReadActive(signal);+ hash.update(chunk);+ }+ } catch (cause: unknown) {+ throwFirmwareStreamFailure(cause, signal);+ }+ assertArtifactReadActive(signal);+ return hash.digest("hex");+ },+ );+ }++ /** Copy and identify the exact bytes consumed by firmware providers. */+ snapshot(request: FirmwareRequest, root: string, signal: AbortSignal) {+ return this.#resources.run(() => this.#snapshot(request, root, signal));+ }++ async #snapshot(request: FirmwareRequest, root: string, signal: AbortSignal) {+ const sourcePath = absoluteCallerPath(request.input.path);+ const source = await realpath(sourcePath);+ const fullPath = join(root, "firmware.bin");+ const copied = await withArtifactRegularFile(+ source,+ this.#resources,+ signal,+ async (handle) => {+ const stat = await handle.stat();+ if (stat.size === 0 || stat.size > FIRMWARE_LIMITS.inputBytes)+ throw firmwareInputFailure(request.operation);+ const hash = createHash("sha256");+ let size = 0;+ const meter = new Transform({+ transform(chunk: Buffer, _encoding, callback) {+ size += chunk.length;+ if (size > FIRMWARE_LIMITS.inputBytes) {+ callback(new Error("Firmware grew beyond the input byte budget"));+ return;+ }+ hash.update(chunk);+ callback(null, chunk);+ },+ });+ await pipeline(+ handle.createReadStream({ autoClose: false }),+ meter,+ createWriteStream(fullPath, { flags: "wx", mode: 0o600 }),+ { signal },+ ).catch((cause: unknown) => throwFirmwareStreamFailure(cause, signal));+ return { size, sha256: hash.digest("hex") };+ },+ ).catch((cause: unknown) => {+ throw firmwareAdmissionFailure(cause, (primary) =>+ firmwareInputFailure(request.operation, primary),+ );+ });+ const { size, sha256 } = copied;+ await chmod(fullPath, 0o400);+ const selected =+ request.operation === "extract_firmware"+ ? request.input.range+ : undefined;+ const offset = selected?.offset ?? 0;+ const length = selected?.length ?? size;+ if (length === 0 || offset > size || length > size - offset)throw new AnalysisInputError(request.operation, undefined, [{- path: ["path"],+ path: ["range"],reason: "out_of_range",- message: `Firmware must be a nonempty regular file no larger than ${FIRMWARE_LIMITS.inputBytes} bytes`,+ message: `Selected range must be within the ${size}-byte firmware file`,},]);- const meter = new Transform({- transform(chunk: Buffer, _encoding, callback) {- size += chunk.length;- if (size > FIRMWARE_LIMITS.inputBytes) {- callback(new Error("Firmware grew beyond the input byte budget"));- return;- }- hash.update(chunk);- callback(null, chunk);+ let inputPath = fullPath;+ if (selected !== undefined) {+ inputPath = join(root, "selected.bin");+ await withArtifactRegularFile(+ fullPath,+ this.#resources,+ signal,+ async (handle) => {+ await pipeline(+ handle.createReadStream({+ start: offset,+ end: offset + length - 1,+ autoClose: false,+ }),+ createWriteStream(inputPath, { flags: "wx", mode: 0o600 }),+ { signal },+ ).catch((cause: unknown) =>+ throwFirmwareStreamFailure(cause, signal),+ );+ },+ );+ await chmod(inputPath, 0o400);+ }+ return {+ subject: { path: sourcePath, sha256, format: "file" as const },+ size,+ inputPath,+ selection: {+ offset,+ length,+ sha256:+ selected === undefined ? sha256 : await this.#hash(inputPath, signal),},- });- await pipeline(- handle.createReadStream({ autoClose: false }),- meter,- createWriteStream(fullPath, { flags: "wx", mode: 0o600 }),- { signal },- );- } finally {- await handle.close();+ };}- await chmod(fullPath, 0o400);- const sha256 = hash.digest("hex");- const selected =- request.operation === "extract_firmware" ? request.input.range : undefined;- const offset = selected?.offset ?? 0;- const length = selected?.length ?? size;- if (length === 0 || offset > size || length > size - offset)- throw new AnalysisInputError(request.operation, undefined, [- {- path: ["range"],- reason: "out_of_range",- message: `Selected range must be within the ${size}-byte firmware file`,- },- ]);- let inputPath = fullPath;- if (selected !== undefined) {- inputPath = join(root, "selected.bin");- await pipeline(- createReadStream(fullPath, { start: offset, end: offset + length - 1 }),- createWriteStream(inputPath, { flags: "wx", mode: 0o600 }),- { signal },++ /** Own the exact source descriptor consumed by publication through its final close. */+ publish(+ entry: FirmwareEntry,+ sha256: string,+ tree: SafeOutputTree,+ signal: AbortSignal,+ ) {+ return this.#resources.run(() =>+ withArtifactRegularFile(+ entry.path,+ this.#resources,+ signal,+ async (handle) => {+ try {+ return await tree.write(+ entry.relativePath,+ handle.createReadStream({ autoClose: false, signal }),+ { sha256, bytes: entry.size },+ signal,+ );+ } catch (cause: unknown) {+ return throwFirmwareStreamFailure(cause, signal);+ }+ },+ ),);- await chmod(inputPath, 0o400);}- return {- subject: { path: sourcePath, sha256, format: "file" as const },- size,- inputPath,- selection: {- offset,- length,- sha256:- selected === undefined- ? sha256- : await hashFirmwareFile(inputPath, signal),- },- };-};-/** Read a complete bounded report; oversized data is never reported as complete. */-export const readFirmwareReport = async (- path: string,- operation: string,-): Promise<unknown> => {- const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);- try {- if (!(await handle.stat()).isFile())- throw new AnalysisOutputError(operation, "Report is not a regular file");- const bytes = await readBoundedFileBytes(- handle,- FIRMWARE_LIMITS.reportBytes,+ /** Read a complete bounded report; oversized data is never reported as complete. */+ async report(+ path: string,+ operation: string,+ signal?: AbortSignal,+ ): Promise<unknown> {+ return this.#resources.run(() =>+ withArtifactRegularFile(path, this.#resources, signal, async (handle) => {+ const bytes = await readBoundedFileBytes(+ handle,+ FIRMWARE_LIMITS.reportBytes,+ );+ if (bytes === undefined)+ throw new AnalysisOutputError(+ operation,+ `Report exceeded ${FIRMWARE_LIMITS.reportBytes} bytes`,+ );+ assertArtifactReadActive(signal);+ try {+ const value: unknown = JSON.parse(+ new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(+ bytes,+ ),+ );+ return value;+ } catch (cause: unknown) {+ throw new AnalysisOutputError(+ operation,+ "Tool report is not valid complete JSON",+ { cause },+ );+ }+ }).catch((cause: unknown) => {+ throw firmwareAdmissionFailure(+ cause,+ (primary) =>+ new AnalysisOutputError(operation, "Report is not a regular file", {+ cause: primary,+ }),+ );+ }),);- if (bytes === undefined)- throw new AnalysisOutputError(- operation,- `Report exceeded ${FIRMWARE_LIMITS.reportBytes} bytes`,- );- try {- const value: unknown = JSON.parse(- new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(- bytes,- ),- );- return value;- } catch (cause: unknown) {- throw new AnalysisOutputError(- operation,- "Tool report is not valid complete JSON",- { cause },- );- }- } finally {- await handle.close();}+}++/** Preserve admission semantics inside the same exact owner's physical outcome. */+const firmwareAdmissionFailure = (+ cause: unknown,+ classify: (cause: NonRegularFileReadError) => Error,+): unknown => {+ return mapArtifactFileFailure(cause, (primary) =>+ primary instanceof NonRegularFileReadError ? classify(primary) : primary,+ );};+const throwFirmwareStreamFailure = (+ cause: unknown,+ signal?: AbortSignal,+): never => {+ if (+ cause instanceof Error &&+ cause.name === "AbortError" &&+ "code" in cause &&+ cause.code === "ABORT_ERR" &&+ signal?.aborted+ )+ throw new ArtifactReaderFailure("cancelled", "Firmware stream cancelled", {+ cause: signal.reason,+ });+ throw cause;+};++const firmwareInputFailure = (operation: string, cause?: unknown) =>+ new AnalysisInputError(operation, { cause }, [+ {+ path: ["path"],+ reason: "out_of_range",+ message: `Firmware must be a nonempty regular file no larger than ${FIRMWARE_LIMITS.inputBytes} bytes`,+ },+ ]);+/** Inventory private output without following links, enforcing aggregate staging budgets. */export const inventoryFirmwareOutput = async (root: string,diff --git a/src/firmware/FirmwareProvider.ts b/src/firmware/FirmwareProvider.tsindex b4c2badeb..e8416122f 100644--- a/src/firmware/FirmwareProvider.ts+++ b/src/firmware/FirmwareProvider.ts@@ -1,5 +1,4 @@import { join, isAbsolute } from "node:path";-import { z } from "zod";import type { FirmwareAnalysisPort } from "../application/firmware/FirmwareAnalysisPort.js";import {createAnalysisExecution,@@ -17,7 +16,6 @@ import {AnalysisCancelledError,AnalysisInputError,AnalysisOutputError,- AnalysisTimeoutError,} from "../domain/analysisErrorCore.js";import { ProviderAdapterError } from "../domain/providerAdapterError.js";import { ProviderCleanupError } from "../domain/providerCleanupError.js";@@ -40,29 +38,47 @@ import {readFirmwareCommandReport,type FirmwareLauncher,} from "./FirmwareCommand.js";-import { inventoryFirmwareOutput, snapshotFirmware } from "./FirmwareFiles.js";+import {+ inventoryFirmwareOutput,+ FirmwareFileAccess,+} from "./FirmwareFiles.js";import {normalizeBinwalkReport,normalizeUnblobReport,} from "./FirmwareReports.js";+import { firmwareFailure, firmwareCancellation } from "./FirmwareFailures.js";+import { AnalysisCleanupLease } from "../artifacts/AnalysisCleanupLease.js";+type Outcome = Awaited<ReturnType<FirmwareAnalysisPort["execute"]>>;interface PendingFirmwareCleanup {supervisor?: ProviderProcessSupervisor;- tree?: SafeOutputTree;+ tree?: {+ readonly tree: SafeOutputTree;+ readonly lease: AnalysisCleanupLease;+ };readonly root: PrivateRuntimeRoot;+ readonly rootLease: AnalysisCleanupLease;readonly engine: string;readonly operation: string;}+const bindWorkspaceFailure = (+ pending: PendingFirmwareCleanup,+ failure: AnalysisError,+): AnalysisError => {+ pending.rootLease.bindCleanupError(failure);+ return failure;+};+interface FirmwareCleanupAttempt {- readonly failure: ProviderCleanupError | undefined;- readonly processUnverified: boolean;+ readonly failure: AnalysisError | undefined;+ readonly executionBlocked: boolean;}const combineCleanupFailures = (- failures: readonly ProviderCleanupError[],-): ProviderCleanupError | undefined => {+ failures: readonly AnalysisError[],+): AnalysisError | undefined => {if (failures.length < 2) return failures[0];return new ProviderCleanupError("firmware",@@ -70,14 +86,20 @@ const combineCleanupFailures = ({reason: "Multiple owned firmware resources could not be cleaned",failures: failures.map((failure) => ({- engine: failure.providerId,- operation: failure.operation,+ engine:+ failure instanceof ProviderAdapterError+ ? failure.providerId+ : "firmware",+ operation:+ failure instanceof ProviderAdapterError+ ? failure.operation+ : "close_firmware",resources: [...failure.cleanupResources],reason: failure.diagnostics?.reason ?? failure.message,})),},{ operation: "close_firmware", cause: new AggregateError(failures) },- );+ ).bindCleanupDependencies(failures);};const waitForPredecessor = (predecessor: Promise<void>,@@ -85,7 +107,8 @@ const waitForPredecessor = (signal?: AbortSignal,): Promise<void> =>new Promise((resolve, reject) => {- const abort = () => reject(new AnalysisCancelledError(operation));+ const abort = () =>+ reject(new AnalysisCancelledError(operation, { cause: signal?.reason }));signal?.addEventListener("abort", abort, { once: true });if (signal?.aborted === true) abort();void predecessor.then(() => {@@ -105,6 +128,8 @@ const limitations = [export class FirmwareProvider implements FirmwareAnalysisPort {#tail: Promise<void> = Promise.resolve();#closed = false;+ #closing: Promise<void> | undefined;+ readonly #files = new FirmwareFileAccess();readonly #pendingCleanup = new Map<string, PendingFirmwareCleanup>();constructor(readonly environment: Readonly<@@ -139,7 +164,7 @@ export class FirmwareProvider implements FirmwareAnalysisPort {if (this.#closed)return err(new AnalysisCancelledError(request.operation));const cleanup = await this.#retryCleanup();- if (cleanup.processUnverified && cleanup.failure !== undefined)+ if (cleanup.executionBlocked && cleanup.failure !== undefined)return err(cleanup.failure);return await this.#execute(request, options);} finally {@@ -148,76 +173,126 @@ export class FirmwareProvider implements FirmwareAnalysisPort {}/** Retry every retained owner, reporting failures without discarding other roots. */- async close(): Promise<void> {+ close(): Promise<void> {this.#closed = true;+ return (this.#closing ??= this.#close().finally(() => {+ this.#closing = undefined;+ }));+ }++ async #close(): Promise<void> {await this.#tail;- const cleanup = await this.#retryCleanup();- if (cleanup.failure !== undefined) throw cleanup.failure;+ const failures: AnalysisError[] = [];+ try {+ await this.#files.close();+ } catch (cause: unknown) {+ failures.push(firmwareFailure(cause, "firmware", "close_firmware"));+ }+ const workspace = await this.#retryWorkspaceCleanup();+ if (workspace.failure !== undefined) failures.push(workspace.failure);+ const failure = combineCleanupFailures(failures);+ if (failure !== undefined) throw failure;}async #retryCleanup(): Promise<FirmwareCleanupAttempt> {- const failures: ProviderCleanupError[] = [];- let processUnverified = false;+ let fileFailure: AnalysisError | undefined;+ try {+ await this.#files.retryCleanup();+ } catch (cause: unknown) {+ fileFailure = firmwareFailure(cause, "firmware", "close_firmware");+ }+ const workspace = await this.#retryWorkspaceCleanup();+ return {+ failure: combineCleanupFailures([+ ...(fileFailure === undefined ? [] : [fileFailure]),+ ...(workspace.failure === undefined ? [] : [workspace.failure]),+ ]),+ executionBlocked: fileFailure !== undefined || workspace.executionBlocked,+ };+ }++ async #retryWorkspaceCleanup(): Promise<FirmwareCleanupAttempt> {+ const failures: AnalysisError[] = [];+ let executionBlocked = false;for (const [path, pending] of this.#pendingCleanup) {try {const stopped = await pending.supervisor?.stop();if (stopped?.status === "incomplete") {- processUnverified = true;+ executionBlocked = true;failures.push(- new ProviderCleanupError(- pending.engine,- [path],- { reason: stopped.reason },- { operation: pending.operation },+ bindWorkspaceFailure(+ pending,+ new ProviderCleanupError(+ pending.engine,+ [path],+ { reason: stopped.reason },+ { operation: pending.operation },+ ),),);continue;}delete pending.supervisor;} catch (cause: unknown) {- processUnverified = true;+ executionBlocked = true;failures.push(- new ProviderCleanupError(- pending.engine,- [path],- { reason: cause instanceof Error ? cause.message : String(cause) },- { operation: pending.operation, cause },+ bindWorkspaceFailure(+ pending,+ new ProviderCleanupError(+ pending.engine,+ [path],+ {+ reason: cause instanceof Error ? cause.message : String(cause),+ },+ { operation: pending.operation, cause },+ ),),);continue;}try {if (pending.tree !== undefined) {- await pending.tree.rollback();+ await pending.tree.lease.release();delete pending.tree;}} catch (cause: unknown) {failures.push(- new ProviderCleanupError(- pending.engine,- [path, pending.tree?.outputRoot ?? path],- { reason: cause instanceof Error ? cause.message : String(cause) },- { operation: pending.operation, cause },+ bindWorkspaceFailure(+ pending,+ new ProviderCleanupError(+ pending.engine,+ [path, pending.tree?.tree.outputRoot ?? path],+ {+ reason: cause instanceof Error ? cause.message : String(cause),+ },+ { operation: pending.operation, cause },+ ),),);}+ if (pending.tree !== undefined) continue;try {- await pending.root.close();- if (pending.tree === undefined) this.#pendingCleanup.delete(path);+ await pending.rootLease.release();+ this.#pendingCleanup.delete(path);} catch (cause: unknown) {// A verified stopped process cannot use this root. Keep ownership for// later removal without blocking a new operation's disjoint workspace.failures.push(- new ProviderCleanupError(- pending.engine,- [path],- { reason: cause instanceof Error ? cause.message : String(cause) },- { operation: pending.operation, cause },+ bindWorkspaceFailure(+ pending,+ new ProviderCleanupError(+ pending.engine,+ [path],+ {+ reason: cause instanceof Error ? cause.message : String(cause),+ },+ { operation: pending.operation, cause },+ ),),);}}- return { failure: combineCleanupFailures(failures), processUnverified };+ return { failure: combineCleanupFailures(failures), executionBlocked };}async #execute(@@ -225,6 +300,7 @@ export class FirmwareProvider implements FirmwareAnalysisPort {options?: ExecutionOptions,): Promise<Outcome> {let root: PrivateRuntimeRoot | undefined;+ let rootLease: AnalysisCleanupLease | undefined;const engineName =request.operation === "inspect_firmware_regions" ? "binwalk" : "unblob";const deadline = AbortSignal.timeout(FIRMWARE_LIMITS.timeoutMs);@@ -234,15 +310,22 @@ export class FirmwareProvider implements FirmwareAnalysisPort {: AbortSignal.any([options.signal, deadline]);let outcome: Outcome;try {- if (signal.aborted) throw new AnalysisCancelledError(request.operation);+ if (signal.aborted)+ throw new AnalysisCancelledError(request.operation, {+ cause: signal.reason,+ });const command = await resolveFirmwareCommand(this.environment,engineName,request.operation,+ this.#files,+ signal,);root = await PrivateRuntimeRoot.create({ prefix: "rea-firmware-" });const ownedRoot = root;- const target = await snapshotFirmware(request, root.path, signal);+ const ownedRootLease = new AnalysisCleanupLease(() => ownedRoot.close());+ rootLease = ownedRootLease;+ const target = await this.#files.snapshot(request, root.path, signal);const run = (args: readonly string[],outputBudget?: { root: string; bytes: number; entries: number },@@ -259,6 +342,7 @@ export class FirmwareProvider implements FirmwareAnalysisPort {this.#pendingCleanup.set(ownedRoot.path, {supervisor,root: ownedRoot,+ rootLease: ownedRootLease,engine: engineName,operation: request.operation,});@@ -309,6 +393,8 @@ export class FirmwareProvider implements FirmwareAnalysisPort {engine: engineName,operation: request.operation,execution: processRun,+ files: this.#files,+ signal,});result = firmwareResultSchemas.inspect_firmware_regions.parse({engine,@@ -358,6 +444,8 @@ export class FirmwareProvider implements FirmwareAnalysisPort {engine: engineName,operation: request.operation,execution: processRun,+ files: this.#files,+ signal,});const normalized = normalizeUnblobReport(report, {inputPath: target.inputPath,@@ -378,6 +466,9 @@ export class FirmwareProvider implements FirmwareAnalysisPort {signal,);result = await publishFirmwareExtraction({+ files: this.#files,+ workspacePath: root.path,+ deadline,outputDirectory: request.input.output_directory,entries,normalized,@@ -385,15 +476,17 @@ export class FirmwareProvider implements FirmwareAnalysisPort {maxDepth: request.input.max_depth,engine,signal,- retainCleanup: (tree) => {+ retainCleanup: (tree, lease, failure) => {+ ownedRootLease.bindCleanupError(failure);const pending: PendingFirmwareCleanup = this.#pendingCleanup.get(ownedRoot.path,) ?? {root: ownedRoot,+ rootLease: ownedRootLease,engine: engineName,operation: request.operation,};- pending.tree = tree;+ pending.tree = { tree, lease };this.#pendingCleanup.set(ownedRoot.path, pending);},});@@ -427,88 +520,76 @@ export class FirmwareProvider implements FirmwareAnalysisPort {),);} catch (cause: unknown) {- outcome = err(- cause instanceof ProviderCleanupError- ? cause- : options?.signal?.aborted === true- ? new AnalysisCancelledError(request.operation)- : deadline.aborted- ? new AnalysisTimeoutError(- request.operation,- FIRMWARE_LIMITS.timeoutMs,- )- : cause instanceof AnalysisError- ? cause- : cause instanceof z.ZodError- ? new AnalysisOutputError(- request.operation,- "Tool report violated the pinned producer protocol",- { cause },- )- : new ProviderAdapterError(engineName, request.operation, {- cause,- diagnostics: {- reason:- cause instanceof Error- ? cause.message- : String(cause),- },- }),+ const failure = firmwareFailure(+ cause,+ engineName,+ request.operation,+ deadline,);+ outcome = err(failure);}const finished = await finishFirmwareWorkspace(root,outcome,engineName,request,+ rootLease,+ signal,+ deadline,);if (!finished.ok &&finished.error.cleanupIncomplete &&root !== undefined &&+ rootLease !== undefined &&+ finished.error.cleanupResources.includes(root.path) &&!this.#pendingCleanup.has(root.path))this.#pendingCleanup.set(root.path, {root,+ rootLease,engine: engineName,operation: request.operation,});+ if (+ !finished.ok &&+ root !== undefined &&+ rootLease !== undefined &&+ finished.error.cleanupResources.includes(root.path)+ )+ rootLease.bindCleanupError(finished.error);+ if (finished.ok && signal.aborted)+ return err(+ firmwareCancellation(+ request.operation,+ signal.reason,+ deadline,+ ).retainPartialObservation(+ completedFirmwareObservation(finished.value),+ ),+ );return finished;}}/** Keep a completed extraction beside cleanup failure, or skip removal when ownership is uncertain. */-export const finishFirmwareWorkspace = async (+const finishFirmwareWorkspace = async (root: { readonly path: string; close(): Promise<void> } | undefined,outcome: Outcome,engineName: string,request: FirmwareRequest,+ rootLease: AnalysisCleanupLease | undefined,+ signal: AbortSignal,+ deadline: AbortSignal,): Promise<Outcome> => {- if (!outcome.ok && outcome.error.cleanupIncomplete) {- if (- root === undefined ||- outcome.error.cleanupResources.includes(root.path)- )- return outcome;- return err(- new ProviderCleanupError(- engineName,- [...outcome.error.cleanupResources, root.path],- outcome.error instanceof ProviderAdapterError- ? (outcome.error.diagnostics ?? { reason: outcome.error.message })- : { reason: outcome.error.message },- {- cause: outcome.error,- operation: request.operation,- ...(outcome.error.partialObservation === undefined- ? {}- : { partialObservation: outcome.error.partialObservation }),- },- ),- );- }+ if (+ !outcome.ok &&+ outcome.error.cleanupIncomplete &&+ (root === undefined || outcome.error.cleanupResources.includes(root.path))+ )+ return outcome;try {- await root?.close();+ await rootLease?.release();} catch (cause: unknown) {const cleanup = new ProviderCleanupError(engineName,@@ -531,6 +612,24 @@ export const finishFirmwareWorkspace = async (: { partialObservation: outcome.error.partialObservation }),},);+ rootLease?.bindCleanupError(cleanup);+ if (outcome.ok && signal.aborted) {+ const primary = firmwareCancellation(+ request.operation,+ signal.reason,+ deadline,+ );+ primary.retainPartialObservation(+ completedFirmwareObservation(outcome.value),+ );+ return err(+ analysisErrorWithCleanupFailure(+ primary,+ cleanup,+ request.operation,+ ).bindCleanupDependencies([cleanup]),+ );+ }return err(outcome.ok? cleanup@@ -538,7 +637,7 @@ export const finishFirmwareWorkspace = async (outcome.error,cleanup,request.operation,- ),+ ).bindCleanupDependencies([outcome.error, cleanup]),);}return outcome;diff --git a/src/firmware/FirmwarePublication.ts b/src/firmware/FirmwarePublication.tsindex 274a884b5..92741c7e4 100644--- a/src/firmware/FirmwarePublication.ts+++ b/src/firmware/FirmwarePublication.ts@@ -1,14 +1,20 @@+import { AnalysisCleanupLease } from "../artifacts/AnalysisCleanupLease.js";+import { AnalysisError } from "../domain/analysisErrorBase.js";+import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";+import { firmwareFailure } from "./FirmwareFailures.js";import { createHash } from "node:crypto";-import { createReadStream } from "node:fs";import { join } from "node:path";import type { z } from "zod";import { SafeOutputTree } from "../artifacts/SafeOutputTree.js";import { SafeOutputTreeCreationFailure } from "../artifacts/SafeOutputTreeCreationFailure.js";-import { AnalysisOutputError } from "../domain/analysisErrorCore.js";+import {+ AnalysisOutputError,+ AnalysisCancelledError,+} from "../domain/analysisErrorCore.js";import { ProviderCleanupError } from "../domain/providerCleanupError.js";import { jsonValueSchema } from "../domain/jsonValue.js";import { firmwareResultSchemas } from "../domain/firmware/firmwareAnalysis.js";-import { hashFirmwareFile, type FirmwareEntry } from "./FirmwareFiles.js";+import type { FirmwareFileAccess, FirmwareEntry } from "./FirmwareFiles.js";import type { normalizeUnblobReport } from "./FirmwareReports.js";import type { extractionGap } from "../domain/firmware/firmwareAnalysis.js";@@ -81,6 +87,9 @@ const gapSortKey = (gap: ExtractionGap): string =>/** Publish verified regular files, preserving links as metadata and rolling back failed writes. */export const publishFirmwareExtraction = async (context: {+ files: FirmwareFileAccess;+ workspacePath: string;+ deadline: AbortSignal;outputDirectory: string;entries: readonly FirmwareEntry[];normalized: ReturnType<typeof normalizeUnblobReport>;@@ -89,7 +98,11 @@ export const publishFirmwareExtraction = async (context: {maxDepth: number;engine: z.infer<typeof firmwareResultSchemas.extract_firmware>["engine"];signal: AbortSignal;- retainCleanup: (tree: SafeOutputTree) => void;+ retainCleanup: (+ tree: SafeOutputTree,+ lease: AnalysisCleanupLease,+ failure: AnalysisError,+ ) => void;}) => {let tree: SafeOutputTree | undefined;let result:@@ -122,7 +135,7 @@ export const publishFirmwareExtraction = async (context: {}const logicalPath = `$output/${entry.relativePath}`;const reported = context.normalized.files.get(logicalPath);- const sha256 = await hashFirmwareFile(entry.path, context.signal);+ const sha256 = await context.files.hash(entry.path, context.signal);if ((reported?.sha256 !== null &&reported?.sha256 !== undefined &&@@ -134,12 +147,7 @@ export const publishFirmwareExtraction = async (context: {"extract_firmware",`Extracted bytes disagree with provider report: ${entry.relativePath}`,);- await tree.write(- entry.relativePath,- createReadStream(entry.path),- { sha256, bytes: entry.size },- context.signal,- );+ await context.files.publish(entry, sha256, tree, context.signal);files.push({relative_path: entry.relativePath,path: join(tree.outputRoot, entry.relativePath),@@ -172,15 +180,31 @@ export const publishFirmwareExtraction = async (context: {),published_bytes: files.reduce((sum, file) => sum + file.size, 0),});- context.signal.throwIfAborted();+ if (context.signal.aborted)+ throw new AnalysisCancelledError("extract_firmware", {+ cause: context.signal.reason,+ });await tree.commit(context.signal);return result;} catch (cause: unknown) {if (cause instanceof SafeOutputTreeCreationFailure) tree = cause.tree;+ const ownedTree = tree;+ const treeLease =+ ownedTree === undefined+ ? undefined+ : new AnalysisCleanupLease(async () => {+ await ownedTree.rollback();+ });+ const primary = firmwareFailure(+ cause,+ "unblob",+ "extract_firmware",+ context.deadline,+ treeLease,+ );try {- await tree?.rollback();+ await treeLease?.release();} catch (cleanupCause: unknown) {- if (tree !== undefined) context.retainCleanup(tree);const publishedResult =tree?.published === true && result !== undefined? {@@ -188,9 +212,9 @@ export const publishFirmwareExtraction = async (context: {result: jsonValueSchema.parse(result),}: undefined;- throw new ProviderCleanupError(+ const cleanup = new ProviderCleanupError("unblob",- [context.outputDirectory],+ [context.outputDirectory, context.workspacePath],{reason:cleanupCause instanceof Error@@ -207,9 +231,18 @@ export const publishFirmwareExtraction = async (context: {: { partialObservation: publishedResult }),},);+ if (tree !== undefined && treeLease !== undefined)+ context.retainCleanup(tree, treeLease, cleanup);+ if (publishedResult !== undefined)+ primary.retainPartialObservation(publishedResult);+ throw analysisErrorWithCleanupFailure(+ primary,+ cleanup,+ "extract_firmware",+ ).bindCleanupDependencies([primary, cleanup]);}if (tree?.published === true && result !== undefined) return result;- throw cause;+ throw primary;}};diff --git a/tests/boundary/filesystem/symlinkParentOwners.test.ts b/tests/boundary/filesystem/symlinkParentOwners.test.tsindex 62953a290..35ae0a71c 100644--- a/tests/boundary/filesystem/symlinkParentOwners.test.ts+++ b/tests/boundary/filesystem/symlinkParentOwners.test.ts@@ -14,7 +14,7 @@ import { describe, expect, it } from "vitest";import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";import { SafeOutputTree } from "../../../src/artifacts/SafeOutputTree.js";import { absoluteCallerPath } from "../../../src/filesystem/callerPath.js";-import { snapshotFirmware } from "../../../src/firmware/FirmwareFiles.js";+import { FirmwareFileAccess } from "../../../src/firmware/FirmwareFiles.js";import { associateWasmGlue } from "../../../src/wasm/WasmGlueAdapter.js";import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";@@ -37,7 +37,7 @@ describe.skipIf(process.platform === "win32")(const work = await createTestTempDirectory("rea-firmware-snapshot-");// Concatenate: path.join would collapse `link/..` itself.const path = `${root}/link/../image.bin`;- const snapshot = await snapshotFirmware(+ const snapshot = await new FirmwareFileAccess().snapshot({ operation: "inspect_firmware_regions", input: { path } },work,new AbortController().signal,diff --git a/tests/boundary/firmware/firmwareReportFiles.test.ts b/tests/boundary/firmware/firmwareReportFiles.test.tsindex c63b81893..69360ef25 100644--- a/tests/boundary/firmware/firmwareReportFiles.test.ts+++ b/tests/boundary/firmware/firmwareReportFiles.test.ts@@ -4,7 +4,7 @@ import { expect, it } from "vitest";import {inventoryFirmwareOutput,- readFirmwareReport,+ FirmwareFileAccess,} from "../../../src/firmware/FirmwareFiles.js";import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";@@ -27,7 +27,7 @@ it.each([]),);await expect(- readFirmwareReport(path, "inspect_firmware_regions"),+ new FirmwareFileAccess().report(path, "inspect_firmware_regions"),).rejects.toMatchObject({_tag: "AnalysisOutputError",reason: "Tool report is not valid complete JSON",@@ -40,9 +40,9 @@ it("preserves valid Unicode and a literal replacement character in producer JSONconst path = join(root, "report.json");const report = { description: "固件 🧩 \ufffd", path: "/输入/firmware.bin" };await writeFile(path, JSON.stringify(report));- expect(await readFirmwareReport(path, "inspect_firmware_regions")).toEqual(- report,- );+ expect(+ await new FirmwareFileAccess().report(path, "inspect_firmware_regions"),+ ).toEqual(report);});it("orders extracted firmware paths by code point independently of host locale", async () => {diff --git a/tests/process-global/firmwareFileLifetime.test.ts b/tests/process-global/firmwareFileLifetime.test.tsnew file mode 100644index 000000000..412193dff--- /dev/null+++ b/tests/process-global/firmwareFileLifetime.test.ts@@ -0,0 +1,815 @@+import { execFile } from "node:child_process";+import { createHash } from "node:crypto";+import {+ access,+ mkdir,+ rm,+ writeFile,+ type FileHandle,+} from "node:fs/promises";+import { join } from "node:path";+import { pathToFileURL } from "node:url";+import { promisify } from "node:util";+import { afterEach, beforeEach, expect, it, vi } from "vitest";++const fault = vi.hoisted(() => ({+ selected: "",+ handles: [] as FileHandle[],+ blocked: new Set<FileHandle>(),+ onClose: undefined as (() => Promise<void>) | undefined,+ malformed: false,+ onSync: undefined as (() => void) | undefined,+}));+vi.mock("node:fs/promises", async (importOriginal) => {+ const original = await importOriginal<typeof import("node:fs/promises")>();+ return {+ ...original,+ open: async (...args: Parameters<typeof original.open>) => {+ const handle = await original.open(...args);+ if (+ !fault.selected ||+ !String(args[0]).endsWith(fault.selected) ||+ typeof args[1] !== "number"+ )+ return handle;+ const close = handle.close.bind(handle);+ const sync = handle.sync.bind(handle);+ handle.sync = async () => {+ await sync();+ fault.onSync?.();+ };+ fault.handles.push(handle);+ fault.blocked.add(handle);+ handle.close = async () => {+ await fault.onClose?.();+ if (fault.blocked.has(handle))+ throw new Error("controlled firmware descriptor close failure");+ await close();+ };+ return handle;+ },+ };+});+// Only host/tool admission and producer execution are simulated. File IO,+// normalization, provider finalization and cleanup ownership remain production code.+vi.mock("../../src/firmware/FirmwareCommand.js", async (importOriginal) => {+ const original =+ await importOriginal<+ typeof import("../../src/firmware/FirmwareCommand.js")+ >();+ return {+ ...original,+ resolveFirmwareCommand: async () => ({+ command: "/fixture/binwalk",+ limiter: "/fixture/prlimit",+ sha256: "0".repeat(64),+ }),+ runFirmwareCommand: async (+ context: Parameters<typeof original.runFirmwareCommand>[0],+ ) => {+ const version = context.args[0] === "--version";+ if (!version) {+ const report = context.args[context.args.indexOf("--log") + 1];+ if (report === undefined)+ throw new Error("Missing fixture report path");+ await writeFile(+ report,+ fault.malformed+ ? "{"+ : JSON.stringify([+ {+ Analysis: {+ file_path: context.args.at(-1),+ file_map: [],+ extractions: {},+ },+ },+ ]),+ );+ }+ const text = version ? "binwalk 3.1.0" : "";+ return {+ stdout: { text, bytes: Buffer.byteLength(text), truncated: false },+ stderr: { text: "", bytes: 0, truncated: false },+ exit_code: 0,+ signal: null,+ command: context.command,+ args: context.args,+ resource_limiter: context.limiter,+ };+ },+ };+});++import { FirmwareFileAccess } from "../../src/firmware/FirmwareFiles.js";+import { publishFirmwareExtraction } from "../../src/firmware/FirmwarePublication.js";+import { normalizeUnblobReport } from "../../src/firmware/FirmwareReports.js";+import { SafeOutputTree } from "../../src/artifacts/SafeOutputTree.js";+import { AnalysisCleanupLease } from "../../src/artifacts/AnalysisCleanupLease.js";+import { ArtifactReaderFailure } from "../../src/artifacts/ArtifactReader.js";+import { FirmwareProvider } from "../../src/firmware/FirmwareProvider.js";+import { firmwareFailure } from "../../src/firmware/FirmwareFailures.js";+import { ArtifactFileCleanupFailure } from "../../src/artifacts/ArtifactFileOperation.js";+import { AnalysisError } from "../../src/domain/analysisErrorBase.js";+import { AnalysisCancelledError } from "../../src/domain/analysisErrorCore.js";+import { PrivateRuntimeRoot } from "../../src/process/PrivateRuntimeRoot.js";+import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";++const providers: FirmwareProvider[] = [];+beforeEach(() => {+ fault.selected = "";+ fault.handles = [];+ fault.blocked.clear();+ fault.onClose = undefined;+ fault.malformed = false;+ fault.onSync = undefined;+});+afterEach(async () => {+ fault.blocked.clear();+ fault.onClose = undefined;+ vi.restoreAllMocks();+ for (const handle of fault.handles) await handle.close();+ await Promise.all(providers.splice(0).map((provider) => provider.close()));+});++it.skipIf(process.platform === "win32")(+ "rejects writerless FIFO input, hash and report through the compiled reader",+ async () => {+ const root = await createTestTempDirectory("rea-firmware-fifo-");+ const fifo = join(root, "input.fifo");+ const work = join(root, "work");+ await mkdir(work);+ await promisify(execFile)("mkfifo", [fifo]);+ const module = pathToFileURL(+ join(process.cwd(), "dist/firmware/FirmwareFiles.js"),+ ).href;+ const script = `import { FirmwareFileAccess } from ${JSON.stringify(module)};+ const files = new FirmwareFileAccess();+ const outcomes = [];+ for (const run of [() => files.hash(process.argv[1]), () => files.report(process.argv[1], 'inspect_firmware_regions'), () => files.snapshot({ operation: 'inspect_firmware_regions', input: { path: process.argv[1] } }, process.argv[2], new AbortController().signal)]) {+ try { await run(); outcomes.push('unexpected-success'); } catch (error) { outcomes.push(error._tag ?? error.name); }+ }+ await files.close(); console.log(JSON.stringify(outcomes));`;+ const { stdout } = await promisify(execFile)(+ process.execPath,+ ["--input-type=module", "-e", script, fifo, work],+ { timeout: 3000 },+ );+ expect(JSON.parse(stdout)).toEqual([+ "NonRegularFileReadError",+ "AnalysisOutputError",+ "AnalysisInputError",+ ]);+ },+);++it.each(["hash", "report"] as const)(+ "retains completed %s and exact owner across rejected retry",+ async (kind) => {+ const root = await createTestTempDirectory("rea-firmware-read-owner-");+ const path = join(root, "selected.bin");+ await writeFile(path, '{"value":"固件"}');+ fault.selected = path;+ const files = new FirmwareFileAccess();+ const raw = await (+ kind === "hash"+ ? files.hash(path)+ : files.report(path, "inspect_firmware_regions")+ ).catch((cause: unknown) => cause);+ expect(raw).toBeInstanceOf(ArtifactFileCleanupFailure);+ if (!(raw instanceof ArtifactFileCleanupFailure))+ throw new Error("Missing physical file outcome");+ expect(raw.fileCleanupFailure.outcome).toEqual({+ kind: "completed",+ value:+ kind === "hash"+ ? createHash("sha256").update('{"value":"固件"}').digest("hex")+ : { value: "固件" },+ });+ const original = firmwareFailure(+ raw,+ "binwalk",+ "inspect_firmware_regions",+ );+ const retry = await files+ .retryCleanup()+ .catch((cause: unknown) =>+ firmwareFailure(cause, "binwalk", "inspect_firmware_regions"),+ );+ expect(retry).toBeInstanceOf(AnalysisError);+ expect(fault.handles).toHaveLength(1);+ const handle = fault.handles[0];+ if (handle === undefined) throw new Error("Missing exact descriptor");+ expect(handle.fd).toBeGreaterThanOrEqual(0);+ fault.blocked.delete(handle);+ await files.close();+ expect(handle.fd).toBe(-1);+ expect(original.cleanupIncomplete).toBe(false);+ if (retry instanceof AnalysisError)+ expect(retry.cleanupIncomplete).toBe(false);+ },+);++it("preserves malformed-report failure when cancellation arrives during failed close", async () => {+ const root = await createTestTempDirectory("rea-firmware-primary-");+ const path = join(root, "report.json");+ await writeFile(path, "{");+ fault.selected = path;+ const controller = new AbortController();+ fault.onClose = async () => controller.abort("late close cancellation");+ const files = new FirmwareFileAccess();+ const raw = await files+ .report(path, "inspect_firmware_regions", controller.signal)+ .catch((cause: unknown) => cause);+ const error = firmwareFailure(raw, "binwalk", "inspect_firmware_regions");+ expect(error.diagnostics?.primary_error).toMatchObject({+ code: "unreadable_output",+ });+ fault.blocked.clear();+ await files.close();+ expect(error.cleanupIncomplete).toBe(false);+});++it.each([null, "caller cancellation", new Error("caller cancellation")])(+ "preserves exact cancellation during final close: %s",+ async (reason) => {+ const root = await createTestTempDirectory("rea-firmware-final-cancel-");+ const path = join(root, "report.json");+ await writeFile(path, "{}");+ fault.selected = path;+ const controller = new AbortController();+ fault.onClose = async () => {+ controller.abort(reason);+ fault.blocked.clear();+ };+ const files = new FirmwareFileAccess();+ const raw = await files+ .report(path, "inspect_firmware_regions", controller.signal)+ .catch((cause: unknown) => cause);+ const error = firmwareFailure(raw, "binwalk", "inspect_firmware_regions");+ expect(error).toBeInstanceOf(AnalysisCancelledError);+ expect(error.cause).toBe(reason);+ await files.close();+ },+);++it.each(["descriptor-first", "workspace-first"])(+ "keeps provider mixed-owner cleanup incomplete until both release: %s",+ async (order) => {+ const root = await createTestTempDirectory("rea-firmware-mixed-owner-");+ const path = join(root, "input.bin");+ await writeFile(path, "firmware bytes");+ fault.selected = "report.json";+ let workspaceBlocked = true;+ let workspacePath = "";+ const close = PrivateRuntimeRoot.prototype.close;+ vi.spyOn(PrivateRuntimeRoot.prototype, "close").mockImplementation(+ async function (this: PrivateRuntimeRoot) {+ workspacePath = this.path;+ if (workspaceBlocked)+ throw new Error("controlled workspace cleanup failure");+ await close.call(this);+ },+ );+ const provider = new FirmwareProvider({});+ providers.push(provider);+ const result = await provider.execute({+ operation: "inspect_firmware_regions",+ input: { path },+ });+ if (result.ok) throw new Error("Expected descriptor and workspace failure");+ expect(result.error.cleanupIncomplete).toBe(true);+ expect(result.error.cleanupResources).toContain(workspacePath);+ expect(fault.handles).toHaveLength(1);+ const blocked = await provider.execute({+ operation: "inspect_firmware_regions",+ input: { path },+ });+ expect(blocked).toMatchObject({+ ok: false,+ error: { cleanupIncomplete: true },+ });+ expect(fault.handles).toHaveLength(1);+ if (order === "descriptor-first") fault.blocked.clear();+ else workspaceBlocked = false;+ const retry = await provider.close().catch((cause: unknown) => cause);+ expect(retry).toBeInstanceOf(AnalysisError);+ expect(result.error.cleanupIncomplete).toBe(true);+ if (order === "workspace-first")+ await expect(access(workspacePath)).rejects.toMatchObject({+ code: "ENOENT",+ });+ else expect(fault.handles[0]?.fd).toBe(-1);+ fault.blocked.clear();+ workspaceBlocked = false;+ await provider.close();+ expect(result.error.cleanupIncomplete).toBe(false);+ if (retry instanceof AnalysisError)+ expect(retry.cleanupIncomplete).toBe(false);+ if (!blocked.ok) expect(blocked.error.cleanupIncomplete).toBe(false);+ },+);++it("retains completed firmware observation when cancellation arrives during workspace close", async () => {+ const root = await createTestTempDirectory("rea-firmware-workspace-cancel-");+ const path = join(root, "input.bin");+ await writeFile(path, "firmware bytes");+ const controller = new AbortController();+ const close = PrivateRuntimeRoot.prototype.close;+ vi.spyOn(PrivateRuntimeRoot.prototype, "close").mockImplementation(+ async function (this: PrivateRuntimeRoot) {+ controller.abort(null);+ await close.call(this);+ },+ );+ const provider = new FirmwareProvider({});+ providers.push(provider);+ const result = await provider.execute(+ { operation: "inspect_firmware_regions", input: { path } },+ { signal: controller.signal },+ );+ expect(result).toMatchObject({+ ok: false,+ error: {+ _tag: "AnalysisCancelledError",+ cause: null,+ partialObservation: { kind: "firmware" },+ },+ });+});++it.skipIf(process.platform === "win32").each(["snapshot", "report"] as const)(+ "retains typed %s admission failure when rejecting a directory also fails close",+ async (kind) => {+ const root = await createTestTempDirectory(+ "rea-firmware-rejected-admission-",+ );+ const path = join(root, "selected");+ const work = join(root, "work");+ await mkdir(path);+ await mkdir(work);+ fault.selected = path;+ const files = new FirmwareFileAccess();+ const raw = await (+ kind === "snapshot"+ ? files.snapshot(+ { operation: "inspect_firmware_regions", input: { path } },+ work,+ new AbortController().signal,+ )+ : files.report(path, "inspect_firmware_regions")+ ).catch((cause: unknown) => cause);+ const error = firmwareFailure(raw, "binwalk", "inspect_firmware_regions");+ expect(error.diagnostics?.primary_error).toMatchObject({+ code: kind === "snapshot" ? "invalid_request" : "unreadable_output",+ });+ expect(error.cleanupIncomplete).toBe(true);+ fault.blocked.clear();+ await files.close();+ expect(error.cleanupIncomplete).toBe(false);+ },+);++it.each([false, true])(+ "retains timeout during workspace finalization (close fails: %s)",+ async (closeFails) => {+ const root = await createTestTempDirectory("rea-firmware-final-timeout-");+ const path = join(root, "input.bin");+ await writeFile(path, "firmware bytes");+ const deadline = new AbortController();+ vi.spyOn(AbortSignal, "timeout").mockReturnValue(deadline.signal);+ let blocked = closeFails;+ const close = PrivateRuntimeRoot.prototype.close;+ vi.spyOn(PrivateRuntimeRoot.prototype, "close").mockImplementation(+ async function (this: PrivateRuntimeRoot) {+ deadline.abort(new DOMException("controlled deadline", "TimeoutError"));+ if (blocked)+ throw new Error("controlled final workspace close failure");+ await close.call(this);+ },+ );+ const provider = new FirmwareProvider({});+ providers.push(provider);+ const result = await provider.execute({+ operation: "inspect_firmware_regions",+ input: { path },+ });+ if (result.ok) throw new Error("Expected timeout");+ expect(result.error.partialObservation).toMatchObject({ kind: "firmware" });+ if (closeFails) {+ expect(result.error.diagnostics?.primary_error).toMatchObject({+ code: "provider_timeout",+ });+ expect(result.error.cleanupIncomplete).toBe(true);+ blocked = false;+ await provider.close();+ expect(result.error.cleanupIncomplete).toBe(false);+ } else+ expect(result.error).toMatchObject({+ _tag: "AnalysisTimeoutError",+ cause: deadline.signal.reason,+ });+ },+);++it("classifies a deadline before composing failed descriptor cleanup", async () => {+ const root = await createTestTempDirectory("rea-firmware-file-timeout-");+ const path = join(root, "report.json");+ await writeFile(path, "{}");+ fault.selected = path;+ const deadline = new AbortController();+ fault.onClose = async () =>+ deadline.abort(new DOMException("controlled deadline", "TimeoutError"));+ const files = new FirmwareFileAccess();+ const raw = await files+ .report(path, "inspect_firmware_regions", deadline.signal)+ .catch((cause: unknown) => cause);+ const error = firmwareFailure(+ raw,+ "binwalk",+ "inspect_firmware_regions",+ deadline.signal,+ );+ expect(error.diagnostics?.primary_error).toMatchObject({+ code: "provider_timeout",+ });+ fault.blocked.clear();+ await files.close();+ expect(error.cleanupIncomplete).toBe(false);+});++const publication = async (+ signal: AbortSignal,+ deadline = new AbortController().signal,+) => {+ const root = await createTestTempDirectory(+ "rea-firmware-publication-lifetime-",+ );+ const inputPath = join(root, "input.bin");+ const outputRoot = join(root, "extracted");+ const sha256 = "0".repeat(64);+ const normalized = normalizeUnblobReport(+ [+ {+ task: {+ path: inputPath,+ depth: 0,+ blob_id: "root",+ is_multi_file: false,+ },+ reports: [+ { __typename__: "HashReport", sha256 },+ {+ __typename__: "StatReport",+ path: inputPath,+ size: 8,+ is_dir: false,+ is_file: true,+ is_link: false,+ link_target: null,+ },+ ],+ subtasks: [],+ },+ ],+ { inputPath, outputRoot, sha256, length: 8, offset: 0, maxDepth: 3 },+ );+ const retained: AnalysisCleanupLease[] = [];+ const workspacePath = join(root, "private");+ await mkdir(workspacePath);+ const context = {+ files: new FirmwareFileAccess(),+ workspacePath,+ deadline,+ outputDirectory: join(root, "published"),+ entries: [],+ normalized,+ selection: { offset: 0, length: 8, sha256 },+ maxDepth: 3,+ engine: {+ name: "unblob",+ version: "26.6.4",+ executable_path: "/fixture/unblob",+ executable_sha256: sha256,+ source_revision: null,+ worker_count: 1 as const,+ },+ signal,+ retainCleanup: (+ _tree: SafeOutputTree,+ lease: AnalysisCleanupLease,+ failure: AnalysisError,+ ) => {+ const workspace = new AnalysisCleanupLease(() =>+ rm(workspacePath, { recursive: true, force: true }),+ );+ workspace.bindCleanupError(failure);+ retained.push(+ new AnalysisCleanupLease(async () => {+ await lease.release();+ await workspace.release();+ }),+ );+ },+ };+ return { context, retained };+};++it("preserves primitive cancellation before publication commit and rolls back the output", async () => {+ const controller = new AbortController();+ const fixture = await publication(controller.signal);+ const create = SafeOutputTree.create;+ vi.spyOn(SafeOutputTree, "create").mockImplementation(async (...args) => {+ const tree = await create(...args);+ controller.abort(null);+ return tree;+ });+ const error = await publishFirmwareExtraction(fixture.context).catch(+ (cause: unknown) => cause,+ );+ expect(error).toBeInstanceOf(AnalysisCancelledError);+ if (error instanceof AnalysisCancelledError) expect(error.cause).toBeNull();+ await expect(access(fixture.context.outputDirectory)).rejects.toMatchObject({+ code: "ENOENT",+ });+ expect(fixture.retained).toHaveLength(0);+ await fixture.context.files.close();+});++it.each(["caller", "deadline"])(+ "preserves %s cancellation during directory sync plus failed close and rollback",+ async (kind) => {+ const controller = new AbortController();+ const reason =+ kind === "caller"+ ? null+ : new DOMException("controlled deadline", "TimeoutError");+ const fixture = await publication(+ controller.signal,+ kind === "deadline" ? controller.signal : undefined,+ );+ const create = SafeOutputTree.create;+ vi.spyOn(SafeOutputTree, "create").mockImplementation(async (...args) => {+ const tree = await create(...args);+ fault.selected = tree.outputRoot;+ fault.onSync = () => controller.abort(reason);+ return tree;+ });+ const error = await publishFirmwareExtraction(fixture.context).catch(+ (cause: unknown) => cause,+ );+ if (!(error instanceof AnalysisError))+ throw new Error("Expected typed tree failure");+ expect(error.cleanupIncomplete).toBe(true);+ expect(error.diagnostics?.primary_error).toMatchObject({+ code: "cleanup_incomplete",+ details: {+ diagnostics: {+ primary_error: {+ code: kind === "caller" ? "cancelled" : "provider_timeout",+ },+ },+ },+ });+ const aggregate = error.cause;+ if (!(aggregate instanceof AggregateError))+ throw new Error("Expected primary and cleanup causes");+ const primary = aggregate.errors[0] as AnalysisError;+ const inner = primary.cause;+ if (!(inner instanceof AggregateError))+ throw new Error("Expected primary cancellation plus commit cleanup");+ expect((inner.errors[0] as AnalysisError).cause).toBe(reason);+ expect(fixture.retained).toHaveLength(1);+ fault.blocked.clear();+ await Promise.all(fixture.retained.map((lease) => lease.release()));+ expect(error.cleanupIncomplete).toBe(false);+ await expect(access(fixture.context.outputDirectory)).rejects.toMatchObject(+ { code: "ENOENT" },+ );+ await fixture.context.files.close();+ },+);++it("retains a completed published observation when commit cleanup and rollback both fail", async () => {+ const fixture = await publication(new AbortController().signal);+ const commit = SafeOutputTree.prototype.commit;+ vi.spyOn(SafeOutputTree.prototype, "commit").mockImplementation(+ async function (this: SafeOutputTree, signal) {+ await commit.call(this, signal);+ throw ArtifactReaderFailure.withCleanup(+ new Error("controlled published commit cleanup failure"),+ {+ reason: "controlled pending directory close",+ resources: [this.outputRoot],+ },+ );+ },+ );+ const rollback = SafeOutputTree.prototype.rollback;+ let blocked = true;+ vi.spyOn(SafeOutputTree.prototype, "rollback").mockImplementation(+ async function (this: SafeOutputTree) {+ if (blocked) throw new Error("controlled rollback failure");+ return rollback.call(this);+ },+ );+ const error = await publishFirmwareExtraction(fixture.context).catch(+ (cause: unknown) => cause,+ );+ if (!(error instanceof AnalysisError))+ throw new Error("Expected typed publication cleanup failure");+ expect(error.partialObservation).toMatchObject({+ kind: "firmware",+ result: { output_directory: fixture.context.outputDirectory, files: [] },+ });+ expect(error.cleanupIncomplete).toBe(true);+ blocked = false;+ await Promise.all(fixture.retained.map((lease) => lease.release()));+ expect(error.cleanupIncomplete).toBe(false);+ await expect(+ access(fixture.context.outputDirectory),+ ).resolves.toBeUndefined();+ await fixture.context.files.close();+});++it("waits through selected-range snapshot finalization when shutdown starts during source close", async () => {+ const root = await createTestTempDirectory("rea-firmware-selected-close-");+ const path = join(root, "input.bin");+ const work = join(root, "work");+ await mkdir(work);+ await writeFile(path, "firmware bytes");+ fault.selected = path;+ let enter!: () => void;+ let release!: () => void;+ const entered = new Promise<void>((resolve) => {+ enter = resolve;+ });+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ fault.onClose = async () => {+ fault.blocked.clear();+ enter();+ await gate;+ };+ const files = new FirmwareFileAccess();+ const pending = files.snapshot(+ {+ operation: "extract_firmware",+ input: {+ path,+ output_directory: join(root, "unused"),+ max_depth: 3,+ max_output_bytes: 1024,+ max_output_files: 10,+ range: { offset: 1, length: 4 },+ },+ },+ work,+ new AbortController().signal,+ );+ try {+ await entered;+ let closed = false;+ const closing = files.close().then(() => {+ closed = true;+ });+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(closed).toBe(false);+ release();+ const snapshot = await pending;+ await closing;+ expect(snapshot.selection).toMatchObject({+ offset: 1,+ length: 4,+ sha256: createHash("sha256").update("irmw").digest("hex"),+ });+ expect(fault.handles.every((handle) => handle.fd === -1)).toBe(true);+ } finally {+ release();+ await pending.catch(() => {});+ await files.close();+ }+});++it("retains the exact publication source descriptor when its final close fails", async () => {+ const fixture = await publication(new AbortController().signal);+ const path = join(fixture.context.workspacePath, "source.bin");+ const bytes = Buffer.from("published bytes");+ await writeFile(path, bytes);+ const tree = await SafeOutputTree.create(fixture.context.outputDirectory);+ fault.selected = path;+ const raw = await fixture.context.files+ .publish(+ {+ path,+ relativePath: "file.bin",+ size: bytes.length,+ kind: "file",+ linkTarget: null,+ },+ createHash("sha256").update(bytes).digest("hex"),+ tree,+ fixture.context.signal,+ )+ .catch((cause: unknown) => cause);+ expect(raw).toBeInstanceOf(ArtifactFileCleanupFailure);+ const error = firmwareFailure(raw, "unblob", "extract_firmware");+ expect(error.cleanupResources).toContain(path);+ await tree.rollback();+ expect(error.cleanupIncomplete).toBe(true);+ fault.blocked.clear();+ await fixture.context.files.close();+ expect(error.cleanupIncomplete).toBe(false);+ expect(fault.handles[0]?.fd).toBe(-1);+});++it.each(["source-first", "tree-first"])(+ "keeps nested source and destination cleanup bound to their exact owners: %s",+ async (order) => {+ const fixture = await publication(new AbortController().signal);+ const path = join(fixture.context.workspacePath, "payload.bin");+ const bytes = Buffer.from("published bytes");+ await writeFile(path, bytes);+ const hash = fixture.context.files.hash.bind(fixture.context.files);+ vi.spyOn(fixture.context.files, "hash").mockImplementation(+ async (...args) => {+ const digest = await hash(...args);+ fault.selected = "payload.bin";+ return digest;+ },+ );+ const error = await publishFirmwareExtraction({+ ...fixture.context,+ entries: [+ {+ path,+ relativePath: "payload.bin",+ size: bytes.length,+ kind: "file",+ linkTarget: null,+ },+ ],+ }).catch((cause: unknown) => cause);+ if (!(error instanceof AnalysisError))+ throw new Error("Expected nested file and tree cleanup failure");+ expect(error.cleanupIncomplete).toBe(true);+ expect(fault.handles.length).toBeGreaterThanOrEqual(2);+ expect(fixture.retained).toHaveLength(1);+ fault.blocked.clear();+ if (order === "source-first") await fixture.context.files.close();+ else await Promise.all(fixture.retained.map((lease) => lease.release()));+ expect(error.cleanupIncomplete).toBe(true);+ await fixture.context.files.close();+ await Promise.all(fixture.retained.map((lease) => lease.release()));+ expect(error.cleanupIncomplete).toBe(false);+ expect(fault.handles.every((handle) => handle.fd === -1)).toBe(true);+ },+);++it("shares one workspace cleanup attempt across concurrent shutdown callers", async () => {+ const root = await createTestTempDirectory("rea-firmware-concurrent-close-");+ const path = join(root, "input.bin");+ await writeFile(path, "firmware bytes");+ let blocked = true;+ let attempts = 0;+ let enter!: () => void;+ let release!: () => void;+ const entered = new Promise<void>((resolve) => {+ enter = resolve;+ });+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const close = PrivateRuntimeRoot.prototype.close;+ vi.spyOn(PrivateRuntimeRoot.prototype, "close").mockImplementation(+ async function (this: PrivateRuntimeRoot) {+ attempts++;+ if (blocked) throw new Error("controlled first workspace close failure");+ enter();+ await gate;+ await close.call(this);+ },+ );+ const provider = new FirmwareProvider({});+ providers.push(provider);+ const result = await provider.execute({+ operation: "inspect_firmware_regions",+ input: { path },+ });+ if (result.ok) throw new Error("Expected retained workspace cleanup");+ blocked = false;+ const first = provider.close();+ try {+ await entered;+ const second = provider.close();+ expect(second).toBe(first);+ expect(attempts).toBe(2);+ release();+ await Promise.all([first, second]);+ expect(result.error.cleanupIncomplete).toBe(false);+ } finally {+ release();+ await first;+ }+});