Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
feat(firmware): make analysis deadlines recoverable per call
gensokyo-devaa53c065387c
diff --git a/docs/firmware-analysis.md b/docs/firmware-analysis.mdindex b529ac6d0..b0f92c14d 100644--- a/docs/firmware-analysis.md+++ b/docs/firmware-analysis.md@@ -158,7 +158,13 @@ tree semantics, vulnerability scanning, emulation or hardware runtime capture.Supply a stable copy within the allowance. No in-place source modification.- One queued heavy operation per provider instance; Binwalk one thread andUnblob one worker. No automatic parallel extraction engines.-- **120-second** analysis deadline through inventory. Publication and final+- Analysis defaults to **120 seconds**, from tool resolution and input snapshot+ through inspection and its final private-workspace cleanup, or extraction+ through report consumption and inventory, excluding queue waiting and retained+ cleanup admission. Inspection has no publication phase. Select `analysis_timeout_ms` in either MCP operation or+ `--analysis-timeout-ms` in either CLI command for slower analysis. Current+ results retain the actual budget; an absent historical value means unknown.+ Extraction publication and its finalcleanup start a separate **120-second** budget; select`publication_timeout_ms` in MCP or `--publication-timeout-ms` in CLI for a slowdestination. Valid budgets are integers from 1 through 2,147,483,647 ms (the@@ -168,6 +174,11 @@ tree semantics, vulnerability scanning, emulation or hardware runtime capture.both phases and final cleanup. Phase handoff, publication commit and finalcompletion also check monotonic elapsed time, so delayed timer callbackscannot revive an expired budget.+- Analysis timeout recovery names the selected budget and the analysis control,+ not the later publication control. Keep the client call timeout above analysis,+ publication and cleanup headroom; keep the input/range/question unchanged.+ Resolve any reported incomplete cleanup before retrying. Raising wall time+ does not raise fixed CPU, memory, report, diagnostic or input limits.- Inherited **1 GiB per-process address-space** limit,120 CPU seconds and zero core-dump allowance through `prlimit`.- JSON reports: at most **8 MiB** and valid UTF-8; malformed encoding anddiff --git a/src/application/binary/AnalysisClientCleanup.test.ts b/src/application/binary/AnalysisClientCleanup.test.tsindex fff856c74..23944836c 100644--- a/src/application/binary/AnalysisClientCleanup.test.ts+++ b/src/application/binary/AnalysisClientCleanup.test.ts@@ -1,6 +1,9 @@import { expect, it } from "vitest";-import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";+import {+ projectAnalysisError,+ projectAnalysisErrorWithoutCapturedOutput,+} from "../../domain/analysisErrorProjection.js";import { ProviderAdapterError } from "../../domain/providerAdapterError.js";import { ProviderCleanupError } from "../../domain/providerCleanupError.js";import { err } from "../../domain/result.js";@@ -59,18 +62,26 @@ it("preserves the original explanation and collected output alongside cleanup unreason: "Process termination was not confirmed",});const combined = analysisErrorWithCleanupFailure(primary, cleanup);- expect(projectAnalysisError(combined)).toMatchObject({+ const projected = projectAnalysisError(combined);+ expect(projected).toMatchObject({code: "cleanup_incomplete",message: primary.userMessage,details: {resources: ["owned-process"],captured_output: primary.capturedOutput,diagnostics: {- primary_error: projectAnalysisError(primary),+ primary_error: projectAnalysisErrorWithoutCapturedOutput(primary),cleanup_error: projectAnalysisError(cleanup),},},});+ expect(projected).not.toHaveProperty(+ "details.diagnostics.primary_error.details.captured_output",+ );+ expect(JSON.stringify(projected).split("partial observation")).toHaveLength(+ 2,+ );+ expect(JSON.stringify(projected).split("native reason")).toHaveLength(2);expect(combined.cause).toBeInstanceOf(AggregateError);expect(combined.cause).toMatchObject({cause: primary,diff --git a/src/application/firmware/FirmwareAnalysisService.test.ts b/src/application/firmware/FirmwareAnalysisService.test.tsindex 91520fd9d..b060608d1 100644--- a/src/application/firmware/FirmwareAnalysisService.test.ts+++ b/src/application/firmware/FirmwareAnalysisService.test.ts@@ -2,59 +2,72 @@ import { expect, it } from "vitest";import { FirmwareAnalysisService } from "./FirmwareAnalysisService.js";import { createAnalysisExecution } from "../AnalysisProvider.js";-import { firmwareResultSchemas } from "../../domain/firmware/firmwareAnalysis.js";+import {+ firmwareResultSchemas,+ type FirmwareOperation,+} from "../../domain/firmware/firmwareAnalysis.js";import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";import { err, ok } from "../../domain/result.js";+const fixture = (+ operation: FirmwareOperation,+ budget: number | null = 120_000,+) => {+ const path = "/owned-fixture/input.bin";+ const input = {+ path,+ ...(operation === "extract_firmware"+ ? { output_directory: "/owned-fixture/output" }+ : {}),+ };+ const engine = {+ name: "fixture",+ version: "1",+ executable_path: "/fixture/engine",+ executable_sha256: "b".repeat(64),+ source_revision: null,+ worker_count: 1,+ };+ const normalized = firmwareResultSchemas[operation].parse(+ operation === "inspect_firmware_regions"+ ? { engine, input_size: 1, regions: [], coverage: "signature_scan" }+ : {+ engine,+ selection: { offset: 0, length: 1, sha256: "a".repeat(64) },+ output_directory: "/owned-fixture/output",+ coverage: "complete",+ files: [],+ unpublished_entries: [],+ chunks: [],+ derivations: [],+ depth_limited_paths: [],+ diagnostics: [],+ extraction_gaps: [],+ extraction_continuations: [],+ published_bytes: 0,+ },+ );+ const execution = createAnalysisExecution(+ budget === null+ ? normalized+ : { ...normalized, analysis_timeout_ms: budget },+ { id: "fixture", name: "Fixture firmware", version: "1" },+ {+ subject: {+ path,+ format: "file",+ sha256: "a".repeat(64),+ },+ rawResult: { source: "controlled producer" },+ },+ );+ return { input, execution };+};+it.each(["inspect_firmware_regions", "extract_firmware"] as const)("retains %s Evidence after late cancellation and preserves provider failure precedence",async (operation) => {- const path = "/owned-fixture/input.bin";- const input = {- path,- ...(operation === "extract_firmware"- ? { output_directory: "/owned-fixture/output" }- : {}),- };- const engine = {- name: "fixture",- version: "1",- executable_path: "/fixture/engine",- executable_sha256: "b".repeat(64),- source_revision: null,- worker_count: 1,- };- const normalized = firmwareResultSchemas[operation].parse(- operation === "inspect_firmware_regions"- ? { engine, input_size: 1, regions: [], coverage: "signature_scan" }- : {- engine,- selection: { offset: 0, length: 1, sha256: "a".repeat(64) },- output_directory: "/owned-fixture/output",- coverage: "complete",- files: [],- unpublished_entries: [],- chunks: [],- derivations: [],- depth_limited_paths: [],- diagnostics: [],- extraction_gaps: [],- extraction_continuations: [],- published_bytes: 0,- },- );- const execution = createAnalysisExecution(- normalized,- { id: "fixture", name: "Fixture firmware", version: "1" },- {- subject: {- path,- format: "file",- sha256: "a".repeat(64),- },- rawResult: { source: "controlled producer" },- },- );+ const { input, execution } = fixture(operation);const control = await new FirmwareAnalysisService({execute: async () => ok(execution),}).execute(operation, input);@@ -89,3 +102,72 @@ it.each(["inspect_firmware_regions", "extract_firmware"] as const)().toEqual(err(failure));},);++for (const operation of [+ "inspect_firmware_regions",+ "extract_firmware",+] as const) {+ it(`preserves a selected ${operation} analysis budget independently of publication`, async () => {+ const { input, execution } = fixture(operation, 1234);+ const service = new FirmwareAnalysisService({+ execute: async (request) => {+ expect(request.input).toMatchObject({ analysis_timeout_ms: 1234 });+ if (request.operation === "extract_firmware")+ expect(request.input.publication_timeout_ms).toBe(120_000);+ return ok(execution);+ },+ });+ const result = await service.execute(operation, {+ ...input,+ analysis_timeout_ms: 1234,+ });+ if (!result.ok) throw result.error;+ expect(result.value.normalized_result).toMatchObject({+ analysis_timeout_ms: 1234,+ });+ expect(result.value.parameters).toMatchObject({+ analysis_timeout_ms: 1234,+ });+ });++ it(`retains the known ${operation} default without inventing an explicit input`, async () => {+ const { input, execution } = fixture(operation);+ const result = await new FirmwareAnalysisService({+ execute: async () => ok(execution),+ }).execute(operation, input);+ if (!result.ok) throw result.error;+ expect(result.value.normalized_result).toMatchObject({+ analysis_timeout_ms: 120_000,+ });+ expect(result.value.parameters).not.toHaveProperty("analysis_timeout_ms");+ });++ it.each([+ { selected: undefined, reported: null },+ { selected: undefined, reported: 1234 },+ { selected: 1234, reported: null },+ { selected: 1234, reported: 120_000 },+ ])(+ `rejects missing or changed fresh ${operation} settings: %j`,+ async ({ selected, reported }) => {+ const { input, execution } = fixture(operation, reported);+ const result = await new FirmwareAnalysisService({+ execute: async () => ok(execution),+ }).execute(operation, {+ ...input,+ ...(selected === undefined ? {} : { analysis_timeout_ms: selected }),+ });+ expect(result).toMatchObject({+ ok: false,+ error: { _tag: "AnalysisOutputError" },+ });+ },+ );++ it(`keeps historical ${operation} budget omissions unknown`, () => {+ const { execution } = fixture(operation, null);+ expect(+ firmwareResultSchemas[operation].parse(execution.result),+ ).not.toHaveProperty("analysis_timeout_ms");+ });+}diff --git a/src/application/firmware/FirmwareAnalysisService.ts b/src/application/firmware/FirmwareAnalysisService.tsindex 0d3344646..ba1b774d4 100644--- a/src/application/firmware/FirmwareAnalysisService.ts+++ b/src/application/firmware/FirmwareAnalysisService.ts@@ -2,6 +2,8 @@ import type { ExecutionOptions } from "../AnalysisProvider.js";import type { FirmwareAnalysisPort } from "./FirmwareAnalysisPort.js";import {firmwareRequestSchema,+ firmwareExecutionBudgetSchema,+ DEFAULT_FIRMWARE_ANALYSIS_TIMEOUT_MS,type FirmwareOperation,} from "../../domain/firmware/firmwareAnalysis.js";import {@@ -53,6 +55,21 @@ export class FirmwareAnalysisService {"Firmware execution did not bind its source artifact",),);+ // Providers own normalized facts. Check only fresh execution metadata here,+ // without reparsing/copying potentially large extraction inventories.+ const budget = firmwareExecutionBudgetSchema.safeParse(execution.result);+ if (+ !budget.success ||+ budget.data.analysis_timeout_ms !==+ (parsed.data.input.analysis_timeout_ms ??+ DEFAULT_FIRMWARE_ANALYSIS_TIMEOUT_MS)+ )+ return err(+ new AnalysisOutputError(+ operation,+ "Firmware execution did not retain its selected analysis budget",+ ),+ );return completeProviderEvidence(createEvidence(execution.subject, execution.provider, {operation,diff --git a/src/cli/firmwareCommands.ts b/src/cli/firmwareCommands.tsindex 742dd9210..5b0e274cf 100644--- a/src/cli/firmwareCommands.ts+++ b/src/cli/firmwareCommands.ts@@ -46,12 +46,18 @@ export const registerFirmwareCommands = (description:"Inspect firmware signature candidates without extracting them",args: z.object({ path }),- run: ({ args }) =>+ options: z.object({ analysisTimeoutMs: extractInput.analysis_timeout_ms }),+ run: ({ args, options }) =>execute(CLI_COMMANDS.inspectFirmwareRegions,"inspect_firmware_regions",// CLI paths are operator-relative; resolve before shared validation.- { path: absoluteCallerPath(args.path) },+ {+ path: absoluteCallerPath(args.path),+ ...(options.analysisTimeoutMs === undefined+ ? {}+ : { analysis_timeout_ms: options.analysisTimeoutMs }),+ },),});cli.command(CLI_COMMANDS.extractFirmware, {@@ -74,6 +80,7 @@ export const registerFirmwareCommands = (maxOutputBytes: extractInput.max_output_bytes,maxOutputFiles: extractInput.max_output_files,publicationTimeoutMs: extractInput.publication_timeout_ms,+ analysisTimeoutMs: extractInput.analysis_timeout_ms,}),run: ({ args, options }) =>execute(CLI_COMMANDS.extractFirmware, "extract_firmware", {@@ -86,6 +93,9 @@ export const registerFirmwareCommands = (max_output_bytes: options.maxOutputBytes,max_output_files: options.maxOutputFiles,publication_timeout_ms: options.publicationTimeoutMs,+ ...(options.analysisTimeoutMs === undefined+ ? {}+ : { analysis_timeout_ms: options.analysisTimeoutMs }),}),});};diff --git a/src/contracts/firmware/firmwareToolContracts.ts b/src/contracts/firmware/firmwareToolContracts.tsindex 00b1e373b..e458298e2 100644--- a/src/contracts/firmware/firmwareToolContracts.ts+++ b/src/contracts/firmware/firmwareToolContracts.ts@@ -13,7 +13,7 @@ export const FIRMWARE_TOOL_CONTRACTS = [...toolContractMetadata("inspect_firmware_regions"),kind: "firmware-provider",description:- "Inspect signature candidates in a local firmware file with Binwalk 3.1.x (verified with 3.1.0). Returns offsets, reported lengths, descriptions and raw confidence values. Length validation and runtime addresses remain unknown. No extraction or target execution. Linux, caller-supplied tool and util-linux prlimit required; 128 MiB input limit, one worker and 120-second deadline.",+ "Inspect signature candidates in a local firmware file with Binwalk 3.1.x (verified with 3.1.0). Returns offsets, reported lengths, descriptions and raw confidence values. Length validation and runtime addresses remain unknown. No extraction or target execution. Linux, caller-supplied tool and util-linux prlimit required; 128 MiB input limit, one worker. Adjust analysis_timeout_ms for the analysis wall-clock budget (default 120000); fixed per-process limits are unchanged.",inputSchema: firmwareInputSchemas.inspect_firmware_regions,outputSchema: evidenceResultOf(firmwareResultSchemas.inspect_firmware_regions,diff --git a/src/domain/analysisErrorCleanup.test.ts b/src/domain/analysisErrorCleanup.test.tsindex 41ce5abcf..3ae95dba1 100644--- a/src/domain/analysisErrorCleanup.test.ts+++ b/src/domain/analysisErrorCleanup.test.ts@@ -7,7 +7,10 @@ import {AnalysisTimeoutError,} from "./analysisErrorCore.js";import { analysisErrorWithCleanupFailure } from "./analysisErrorCleanup.js";-import { projectAnalysisError } from "./analysisErrorProjection.js";+import {+ projectAnalysisError,+ projectAnalysisErrorWithoutCapturedOutput,+} from "./analysisErrorProjection.js";import {analysisErrorCategory,analysisErrorRemediationAction,@@ -16,6 +19,60 @@ import {import { ProviderCleanupError } from "./providerCleanupError.js";import { createEvidence } from "./evidence.js";+it.each([false, true])(+ "keeps each owner's capture without text-based deduplication (matching: %s)",+ (matching) => {+ const primary = new AnalysisTimeoutError("inspect", 1234, {+ capturedOutput: {+ stdout: "primary-capture-sentinel",+ stderr: "",+ truncated: false,+ },+ });+ const cleanup = new ProviderCleanupError(+ "fixture",+ ["owned-worker"],+ {},+ {+ capturedOutput: {+ stdout: matching+ ? "primary-capture-sentinel"+ : "cleanup-capture-sentinel",+ stderr: "",+ truncated: true,+ },+ },+ );+ const composed = analysisErrorWithCleanupFailure(+ primary,+ cleanup,+ "inspect",+ );+ const projected = projectAnalysisError(composed);+ expect(projected.details?.captured_output).toEqual(primary.capturedOutput);+ expect(projected.details?.diagnostics).toMatchObject({+ primary_error: {+ code: "provider_timeout",+ details: { timeout_ms: 1234 },+ },+ cleanup_error: { details: { captured_output: cleanup.capturedOutput } },+ });+ expect(+ JSON.stringify(projected).split("primary-capture-sentinel"),+ ).toHaveLength(matching ? 3 : 2);+ if (!matching)+ expect(+ JSON.stringify(projected).split("cleanup-capture-sentinel"),+ ).toHaveLength(2);+ expect(+ projectAnalysisErrorWithoutCapturedOutput(primary).details,+ ).not.toHaveProperty("captured_output");+ expect(projectAnalysisError(primary).details?.captured_output).toEqual(+ primary.capturedOutput,+ );+ },+);+it("keeps dependency-owned resources empty after the final owner releases", () => {const file = new ProviderCleanupError("fixture", ["file-owner"], {});const trace = new ProviderCleanupError("fixture", ["trace-owner"], {});@@ -113,7 +170,10 @@ it.each([const projected = projectAnalysisError(composed);expect(projected).toMatchObject(original);expect(projected.details?.cleanup_history).toMatchObject({- primary_error: original,+ primary_error:+ primary.capturedOutput === undefined+ ? original+ : projectAnalysisErrorWithoutCapturedOutput(primary),cleanup_error: { code: "cleanup_incomplete" },});expect(projected.details).not.toHaveProperty("cleanup", "incomplete");diff --git a/src/domain/analysisErrorCleanup.ts b/src/domain/analysisErrorCleanup.tsindex ab7b6d43e..748a92182 100644--- a/src/domain/analysisErrorCleanup.ts+++ b/src/domain/analysisErrorCleanup.ts@@ -1,5 +1,8 @@import { ProviderAdapterError } from "./providerAdapterError.js";-import { projectAnalysisError } from "./analysisErrorProjection.js";+import {+ projectAnalysisError,+ projectAnalysisErrorWithoutCapturedOutput,+} from "./analysisErrorProjection.js";import type { AnalysisError } from "./analysisErrorBase.js";/** Preserve the original lifecycle failure alongside incomplete cleanup. */@@ -37,7 +40,10 @@ export const analysisErrorWithCleanupFailure = (],},diagnostics: {- primary_error: projectAnalysisError(primary),+ primary_error:+ primary.capturedOutput === undefined+ ? projectAnalysisError(primary)+ : projectAnalysisErrorWithoutCapturedOutput(primary),cleanup_error: projected,},},diff --git a/src/domain/analysisErrorProjection.ts b/src/domain/analysisErrorProjection.tsindex 43cd286d3..0cd1ffcca 100644--- a/src/domain/analysisErrorProjection.ts+++ b/src/domain/analysisErrorProjection.ts@@ -51,6 +51,16 @@ import {/** Project expected failures into exhaustive, secret-safe caller fields. */export const projectAnalysisError = (error: AnalysisError,+): AnalysisErrorProjection => projectError(error, true);++/** Cleanup history references output retained by its enclosing error owner. */+export const projectAnalysisErrorWithoutCapturedOutput = (+ error: AnalysisError,+): AnalysisErrorProjection => projectError(error, false);++const projectError = (+ error: AnalysisError,+ includeCapturedOutput: boolean,): AnalysisErrorProjection => {const composed = error;error = resolvedAnalysisError(error);@@ -88,7 +98,7 @@ export const projectAnalysisError = (primaryDetails?.execution_failure ?? underlyingCode,}: {}),- ...(capturedOutput === undefined+ ...(!includeCapturedOutput || capturedOutput === undefined? {}: {captured_output: {diff --git a/src/domain/firmware/firmwareAnalysis.ts b/src/domain/firmware/firmwareAnalysis.tsindex a434af391..841ba2055 100644--- a/src/domain/firmware/firmwareAnalysis.ts+++ b/src/domain/firmware/firmwareAnalysis.ts@@ -5,10 +5,20 @@ import { absoluteLocalPathStringSchema } from "../localPath.js";const bytes = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);const range = z.strictObject({ offset: bytes, length: bytes.positive() });+/** Default analysis phase budget, excluding queue admission and publication. */+export const DEFAULT_FIRMWARE_ANALYSIS_TIMEOUT_MS = 120_000;+/** Largest delay supported without overflowing Node timers. */+export const MAX_FIRMWARE_TIMEOUT_MS = 2_147_483_647;+const timeout = z.number().int().min(1).max(MAX_FIRMWARE_TIMEOUT_MS);const target = {path: absoluteLocalPathStringSchema.describe("Absolute local firmware file; never executed. Relative paths are rejected.",),+ analysis_timeout_ms: timeout+ .optional()+ .describe(+ "Analysis wall-clock budget in milliseconds (default 120000), from tool resolution through inspection and its final workspace cleanup, or extraction through inventory. Excludes queue admission and extraction publication. Does not raise fixed CPU, memory or byte limits.",+ ),};/** Explicit firmware inspection and extraction intent, independent of engines. */@@ -45,12 +55,7 @@ export const firmwareInputSchemas = {.max(100_000).default(10_000).describe("Staging entry budget, including directories and links"),- publication_timeout_ms: z- .number()- .int()- .min(1)- // Node timers cannot represent longer delays without overflow.- .max(2_147_483_647)+ publication_timeout_ms: timeout.default(120_000).describe("Publication and final cleanup budget in milliseconds, started after extraction and inventory; increase for a slow destination",@@ -87,6 +92,14 @@ const engine = z.strictObject({source_revision: z.null(),worker_count: z.literal(1),});+/** Small execution metadata contract; historical omissions remain unknown. */+export const firmwareExecutionBudgetSchema = z.object({+ analysis_timeout_ms: timeout+ .exactOptional()+ .describe(+ "Actual analysis phase budget in milliseconds; absent in historical Evidence means unknown",+ ),+});const selection = z.strictObject({ ...range.shape, sha256: digestSchema });const chunk = z.strictObject({input_path: z.string(),@@ -134,6 +147,7 @@ export interface FirmwarePartialObservation {/** Portable results retain reported boundaries, unknowns and extraction lineage. */export const firmwareResultSchemas = {inspect_firmware_regions: z.strictObject({+ ...firmwareExecutionBudgetSchema.shape,engine,input_size: bytes,regions: z.array(@@ -150,6 +164,7 @@ export const firmwareResultSchemas = {coverage: z.literal("signature_scan"),}),extract_firmware: z.strictObject({+ ...firmwareExecutionBudgetSchema.shape,engine,selection,output_directory: z.string(),diff --git a/src/firmware/FirmwareCommand.test.ts b/src/firmware/FirmwareCommand.test.tsindex 45b6ac216..6d8027d6f 100644--- a/src/firmware/FirmwareCommand.test.ts+++ b/src/firmware/FirmwareCommand.test.ts@@ -1,16 +1,111 @@import { chmod, mkdir, writeFile } from "node:fs/promises";import { join } from "node:path";-import { expect, it as test } from "vitest";+import { expect, it as test, vi } 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";+import {+ resolveFirmwareCommand,+ runFirmwareCommand,+} from "./FirmwareCommand.js";+import { spawnOwnedProviderProcess } from "../process/ProviderProcess.js";+import { AnalysisError } from "../domain/analysisErrorBase.js";+import { ExecFileOutputCancelledError } from "../process/ExecFileOutput.js";const it = test.skipIf(process.platform !== "linux");+it.each([+ { source: "analysis", wrapped: false },+ { source: "caller", wrapped: false },+ { source: "analysis", wrapped: true },+ { source: "caller", wrapped: true },+] as const)(+ "classifies $source cancellation during launcher admission (wrapped: $wrapped)",+ async ({ source, wrapped }) => {+ const analysis = new AbortController();+ const caller = new AbortController();+ const reason =+ source === "analysis"+ ? new DOMException("selected deadline", "TimeoutError")+ : { caller: "opaque admission cancellation" };+ const retainCleanup = vi.fn();+ const failure: unknown = await runFirmwareCommand({+ engine: "binwalk",+ operation: "inspect_firmware_regions",+ command: "/usr/bin/true",+ limiter: "/usr/bin/true",+ args: ["--version"],+ cwd: await createTestTempDirectory("rea-firmware-admission-"),+ environment: process.env,+ signal: AbortSignal.any([analysis.signal, caller.signal]),+ deadline: {+ phase: "analysis",+ signal: analysis.signal,+ timeoutMs: 1234,+ expiresAtMs: performance.now() + 1234,+ },+ launcher: async (options) => {+ // Real launcher is paused at its first ownership-preparation await;+ // it must reject before acquiring a child after this cancellation.+ const admission = wrapped+ ? undefined+ : spawnOwnedProviderProcess(options);+ (source === "analysis" ? analysis : caller).abort(reason);+ if (admission !== undefined) return admission;+ throw new ExecFileOutputCancelledError(reason);+ },+ retainCleanup,+ }).catch((cause: unknown) => cause);+ expect(failure).toBeInstanceOf(AnalysisError);+ if (!(failure instanceof AnalysisError))+ throw new Error("Expected typed admission interruption");+ expect(failure.cause).toBe(reason);+ expect(projectAnalysisError(failure)).toMatchObject(+ source === "analysis"+ ? {+ code: "provider_timeout",+ details: { timeout_ms: 1234, diagnostics: { phase: "analysis" } },+ remediation: {+ action: expect.stringContaining("analysis_timeout_ms"),+ },+ }+ : { code: "cancelled" },+ );+ expect(retainCleanup).not.toHaveBeenCalled();+ },+);++it("does not relabel an unrelated launch failure when a deadline also fires", async () => {+ const analysis = new AbortController();+ const failure = new Error("distinct launch refusal");+ await expect(+ runFirmwareCommand({+ engine: "binwalk",+ operation: "inspect_firmware_regions",+ command: "/usr/bin/true",+ limiter: "/usr/bin/true",+ args: [],+ cwd: await createTestTempDirectory("rea-firmware-admission-error-"),+ environment: process.env,+ signal: analysis.signal,+ deadline: {+ phase: "analysis",+ signal: analysis.signal,+ timeoutMs: 1234,+ expiresAtMs: performance.now() + 1234,+ },+ launcher: async () => {+ analysis.abort();+ throw failure;+ },+ retainCleanup: vi.fn(),+ }),+ ).rejects.toBe(failure);+});+test("names the host and tool requirement of an unconfigured engine", async () => {const refusal: unknown = await resolveFirmwareCommand({},diff --git a/src/firmware/FirmwareCommand.ts b/src/firmware/FirmwareCommand.tsindex d8eef7fef..1b4362c47 100644--- a/src/firmware/FirmwareCommand.ts+++ b/src/firmware/FirmwareCommand.ts@@ -5,12 +5,18 @@ import { constants } from "node:fs";import { isAbsolute } from "node:path";import {AnalysisCapabilityUnavailableError,- AnalysisCancelledError,- AnalysisTimeoutError,AnalysisOutputError,} from "../domain/analysisErrorCore.js";import { ProviderAdapterError } from "../domain/providerAdapterError.js";import { ProviderCleanupError } from "../domain/providerCleanupError.js";+import type { AnalysisError } from "../domain/analysisErrorBase.js";+import { projectAnalysisErrorWithoutCapturedOutput } from "../domain/analysisErrorProjection.js";+import type { FirmwareDeadline } from "./FirmwareDeadline.js";+import {+ firmwareFailure,+ firmwareCancellation,+ firmwarePhaseInterruption,+} from "./FirmwareFailures.js";import {spawnOwnedProviderProcess,ProviderProcessSupervisor,@@ -113,14 +119,22 @@ export const runFirmwareCommand = async (context: {cwd: string;environment: Readonly<Record<string, string | undefined>>;signal: AbortSignal;+ deadline: FirmwareDeadline;launcher?: FirmwareLauncher;outputBudget?: { root: string; bytes: number; entries: number };acceptReportedExtractionFailure?: boolean;retainCleanup(supervisor: ProviderProcessSupervisor): void;}) => {const { engine, operation, signal } = context;- if (signal.aborted)- throw new AnalysisCancelledError(operation, { cause: signal.reason });+ const checkInterruption = () => {+ const failure = firmwarePhaseInterruption(+ operation,+ signal,+ context.deadline,+ );+ if (failure !== undefined) throw failure;+ };+ checkInterruption();const runId = `rea-firmware-${randomUUID()}`;const spawned = await (context.launcher ?? spawnOwnedProviderProcess)({command: context.limiter,@@ -128,7 +142,7 @@ export const runFirmwareCommand = async (context: {`--as=${FIRMWARE_LIMITS.addressSpaceBytes}`,`--fsize=${context.outputBudget?.bytes ?? FIRMWARE_LIMITS.reportBytes}`,"--core=0",- "--cpu=120",+ `--cpu=${FIRMWARE_LIMITS.cpuSeconds}`,"--",context.command,...context.args,@@ -145,6 +159,19 @@ export const runFirmwareCommand = async (context: {RAYON_NUM_THREADS: "1",NO_COLOR: "1",},+ }).catch((cause: unknown) => {+ // Owned admission can reject before a supervisor/child exists. Attribute+ // only this signal's raw reason or a linked Node AbortError, never an+ // unrelated failure merely because a timer also fired.+ if (+ signal.aborted &&+ (cause === signal.reason ||+ (cause instanceof Error &&+ cause.name === "AbortError" &&+ cause.cause === signal.reason))+ )+ throw firmwareCancellation(operation, signal.reason, context.deadline);+ throw cause;});let diagnosticTruncated = false;const supervisor = new ProviderProcessSupervisor(@@ -178,15 +205,11 @@ export const runFirmwareCommand = async (context: {);}};- let failure: unknown;+ let failure: AnalysisError | undefined;try {- const deadline = performance.now() + FIRMWARE_LIMITS.timeoutMs;while (!(await supervisor.waitForOutputClose(100))) {checkDiagnostics();- if (signal.aborted)- throw new AnalysisCancelledError(operation, { cause: signal.reason });- if (performance.now() >= deadline)- throw new AnalysisTimeoutError(operation, FIRMWARE_LIMITS.timeoutMs);+ checkInterruption();if (context.outputBudget !== undefined)await inventoryFirmwareOutput(context.outputBudget.root,@@ -197,27 +220,45 @@ export const runFirmwareCommand = async (context: {);}checkDiagnostics();- if (signal.aborted)- throw new AnalysisCancelledError(operation, { cause: signal.reason });+ checkInterruption();} catch (cause: unknown) {- failure = cause;+ failure = firmwareFailure(cause, context);}const stopped = await supervisor.stop();+ // Cleanup is an awaited part of this phase. Preserve a prior observed failure,+ // otherwise retain an interruption that arrived while stopping owned resources.+ failure ??= firmwarePhaseInterruption(operation, signal, context.deadline);const snapshot = supervisor.snapshot();if (stopped.status === "incomplete") {context.retainCleanup(supervisor);- throw new ProviderCleanupError(engine, [runId, context.cwd], {- reason: stopped.reason,- leader_pid: spawned.ownership.leaderPid,- process_group_id: spawned.ownership.processGroupId,- exit_code: snapshot.exitCode ?? null,- signal: snapshot.signal ?? null,- stdout: snapshot.stdout.text,- stderr: snapshot.stderr.text,- stdout_bytes: snapshot.stdout.bytes,- stderr_bytes: snapshot.stderr.bytes,- previous_error: failure instanceof Error ? failure.message : null,- });+ const previous =+ failure === undefined+ ? undefined+ : projectAnalysisErrorWithoutCapturedOutput(failure);+ // Retain typed recovery history, but give captured output exactly one owner.+ throw new ProviderCleanupError(+ engine,+ [runId, context.cwd],+ {+ reason: stopped.reason,+ leader_pid: spawned.ownership.leaderPid,+ process_group_id: spawned.ownership.processGroupId,+ previous_error: previous ?? null,+ },+ {+ operation,+ cleanupPrimary: failure,+ capturedOutput: {+ stdout: snapshot.stdout.text,+ stderr: snapshot.stderr.text,+ stdout_bytes: snapshot.stdout.bytes,+ stderr_bytes: snapshot.stderr.bytes,+ exit_code: snapshot.exitCode ?? null,+ signal: snapshot.signal ?? null,+ truncated: snapshot.diagnosticTruncated === true,+ },+ },+ );}if (failure !== undefined) throw failure;if (diff --git a/src/firmware/FirmwareDeadline.test.ts b/src/firmware/FirmwareDeadline.test.tsindex 5b953ba99..6e4f56813 100644--- a/src/firmware/FirmwareDeadline.test.ts+++ b/src/firmware/FirmwareDeadline.test.ts@@ -10,6 +10,31 @@ import { startFirmwareDeadline } from "./FirmwareDeadline.js";afterEach(() => vi.restoreAllMocks());+it.each(["inspect_firmware_regions", "extract_firmware"] as const)(+ "validates %s analysis timer boundaries and preserves omission",+ (operation) => {+ const parse = (settings: Record<string, unknown>) =>+ firmwareRequestSchema.parse({+ operation,+ input: {+ path: "/firmware.bin",+ ...(operation === "extract_firmware"+ ? { output_directory: "/output" }+ : {}),+ ...settings,+ },+ });+ expect(parse({}).input).not.toHaveProperty("analysis_timeout_ms");+ for (const value of [1, 2_147_483_647])+ expect(parse({ analysis_timeout_ms: value }).input).toHaveProperty(+ "analysis_timeout_ms",+ value,+ );+ for (const value of [0, -1, 0.5, 2_147_483_648, null, "120000"])+ expect(() => parse({ analysis_timeout_ms: value })).toThrow();+ },+);+it("enforces absolute expiry before the timer callback while preserving observed caller cancellation", () => {const now = vi.spyOn(performance, "now").mockReturnValue(100);const deadline = startFirmwareDeadline("publication", 1_000);@@ -109,3 +134,34 @@ it("keeps a distinct caller cancellation when the phase deadline has also expire}),).toBe(original);});++it.each([1234, 2_147_483_647])(+ "names the actual adjustable analysis budget %s without suggesting publication repair",+ (timeoutMs) => {+ const reason = new Error("analysis deadline");+ const failure = firmwareFailure(+ new AnalysisCancelledError("inspect_firmware_regions", { cause: reason }),+ {+ engine: "binwalk",+ operation: "inspect_firmware_regions",+ deadline: {+ phase: "analysis",+ signal: AbortSignal.abort(reason),+ timeoutMs,+ expiresAtMs: 0,+ },+ },+ );+ const projected = projectAnalysisError(failure);+ expect(projected).toMatchObject({+ code: "provider_timeout",+ details: { timeout_ms: timeoutMs, diagnostics: { phase: "analysis" } },+ remediation: { action: expect.stringContaining("analysis_timeout_ms") },+ });+ expect(projected.remediation.action).toContain("--analysis-timeout-ms");+ expect(projected.remediation.action).toContain("publication_timeout_ms");+ expect(projected.remediation.action).toContain("CPU");+ if (timeoutMs === 2_147_483_647)+ expect(projected.remediation.action).toContain("maximum");+ },+);diff --git a/src/firmware/FirmwareFailures.ts b/src/firmware/FirmwareFailures.tsindex 3aa66ec9b..4a80be6bc 100644--- a/src/firmware/FirmwareFailures.ts+++ b/src/firmware/FirmwareFailures.ts@@ -18,6 +18,7 @@ import type { FirmwareDeadline } from "./FirmwareDeadline.js";import { firmwareDeadlineElapsed } from "./FirmwareDeadline.js";import type { AnalysisErrorOptions } from "../domain/analysisErrorBase.js";import { z } from "zod";+import { MAX_FIRMWARE_TIMEOUT_MS } from "../domain/firmware/firmwareAnalysis.js";type FirmwarePublicationProgress = {readonly output_directory: string;@@ -56,7 +57,10 @@ const timeoutFailure = (remediationAction:"Read any retained publication receipt first. For a retry, choose an absent local output directory or increase publication_timeout_ms (--publication-timeout-ms in the CLI).",}- : {}),+ : {+ userMessage: `Firmware analysis exceeded its ${deadline.timeoutMs}ms wall-clock budget${operation === "extract_firmware" ? " before publication" : " during inspection or its final workspace cleanup"}.`,+ remediationAction: `Retry the same operation and preserve the selected input and analysis question. ${deadline.timeoutMs < MAX_FIRMWARE_TIMEOUT_MS ? `Increase analysis_timeout_ms (--analysis-timeout-ms in the CLI), an integer from 1 to ${MAX_FIRMWARE_TIMEOUT_MS} (default 120000).` : `analysis_timeout_ms (--analysis-timeout-ms in the CLI) is already at the maximum ${MAX_FIRMWARE_TIMEOUT_MS}; do not increase it further.`} Set the client tool-call timeout above the analysis budget plus publication and cleanup headroom. publication_timeout_ms only controls the later publication phase and cannot repair this analysis timeout. Fixed per-process CPU, memory and byte limits are unchanged. If cleanup is incomplete, resolve the reported owned resources before retrying; no server restart is needed after confirmed cleanup.`,+ }),});/** Translate the producing file owner's outcome without guessing from a later signal. */diff --git a/src/firmware/FirmwareProvider.ts b/src/firmware/FirmwareProvider.tsindex 07a6dfff0..a7a43c233 100644--- a/src/firmware/FirmwareProvider.ts+++ b/src/firmware/FirmwareProvider.ts@@ -7,6 +7,7 @@ import {} from "../application/AnalysisProvider.js";import {firmwareResultSchemas,+ DEFAULT_FIRMWARE_ANALYSIS_TIMEOUT_MS,type FirmwareRequest,type FirmwarePartialObservation,} from "../domain/firmware/firmwareAnalysis.js";@@ -26,7 +27,6 @@ import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js";import type { SafeOutputTree } from "../artifacts/SafeOutputTree.js";import { publishFirmwareExtraction } from "./FirmwarePublication.js";import {- FIRMWARE_LIMITS,BINWALK_PROVIDER_IDENTITY,UNBLOB_PROVIDER_IDENTITY,} from "./FirmwareRelease.js";@@ -324,7 +324,9 @@ export class FirmwareProvider implements FirmwareAnalysisPort {: AbortSignal.any([options.signal, phase.signal]);// Extraction and publication have separate budgets: publication time depends on the// destination filesystem, so it must not be charged to the extraction deadline.- let deadline = startFirmwareDeadline("analysis", FIRMWARE_LIMITS.timeoutMs);+ const analysisTimeoutMs =+ request.input.analysis_timeout_ms ?? DEFAULT_FIRMWARE_ANALYSIS_TIMEOUT_MS;+ let deadline = startFirmwareDeadline("analysis", analysisTimeoutMs);let signal = withCaller(deadline);let outcome: Outcome;try {@@ -356,6 +358,7 @@ export class FirmwareProvider implements FirmwareAnalysisPort {cwd: root?.path ?? "",environment: this.environment,signal,+ deadline,retainCleanup: (supervisor) => {this.#pendingCleanup.set(ownedRoot.path, {supervisor,@@ -415,6 +418,7 @@ export class FirmwareProvider implements FirmwareAnalysisPort {signal,});result = firmwareResultSchemas.inspect_firmware_regions.parse({+ analysis_timeout_ms: analysisTimeoutMs,engine,input_size: target.size,regions: normalizeBinwalkReport(@@ -497,6 +501,7 @@ export class FirmwareProvider implements FirmwareAnalysisPort {);signal = withCaller(deadline);result = await publishFirmwareExtraction({+ analysisTimeoutMs,files: this.#files,workspacePath: root.path,deadline,diff --git a/src/firmware/FirmwarePublication.ts b/src/firmware/FirmwarePublication.tsindex 78d339daf..d2313cdfc 100644--- a/src/firmware/FirmwarePublication.ts+++ b/src/firmware/FirmwarePublication.ts@@ -91,6 +91,7 @@ export const publishFirmwareExtraction = async (context: {files: FirmwareFileAccess;workspacePath: string;deadline: FirmwareDeadline;+ analysisTimeoutMs: number;outputDirectory: string;entries: readonly FirmwareEntry[];normalized: ReturnType<typeof normalizeUnblobReport>;@@ -169,6 +170,7 @@ export const publishFirmwareExtraction = async (context: {});}result = firmwareResultSchemas.extract_firmware.parse({+ analysis_timeout_ms: context.analysisTimeoutMs,engine: context.engine,selection: context.selection,output_directory: tree.outputRoot,diff --git a/src/firmware/FirmwareRelease.ts b/src/firmware/FirmwareRelease.tsindex 8699013c3..7a62ae98b 100644--- a/src/firmware/FirmwareRelease.ts+++ b/src/firmware/FirmwareRelease.ts@@ -31,5 +31,5 @@ export const FIRMWARE_LIMITS = {reportBytes: 8 * 1024 * 1024,diagnosticBytes: 8 * 1024 * 1024,addressSpaceBytes: 1024 * 1024 * 1024,- timeoutMs: 120_000,+ cpuSeconds: 120,} as const;diff --git a/src/sqlite/SqliteDatabaseFailures.ts b/src/sqlite/SqliteDatabaseFailures.tsindex 9b2fc071d..2b26822ae 100644--- a/src/sqlite/SqliteDatabaseFailures.ts+++ b/src/sqlite/SqliteDatabaseFailures.ts@@ -4,7 +4,10 @@ import {bindArtifactFileCleanup,artifactFileCancellationCause,} from "../artifacts/ArtifactFileOperation.js";-import { projectAnalysisError } from "../domain/analysisErrorProjection.js";+import {+ projectAnalysisError,+ projectAnalysisErrorWithoutCapturedOutput,+} from "../domain/analysisErrorProjection.js";import {AnalysisError,type AnalysisCapturedOutput,@@ -48,15 +51,12 @@ export const createSqliteCleanupError = (): ProviderCleanupError => {const capturedOutput =options.capturedOutput ?? options.cleanupPrimary?.capturedOutput;- let previous =+ const previous =options.cleanupPrimary === undefined? null- : projectAnalysisError(options.cleanupPrimary);- // History carries facts/recovery; the wrapper delivers output only once.- if (capturedOutput !== undefined && previous?.details !== undefined) {- const { captured_output: _capturedOutput, ...metadata } = previous.details;- previous = { ...previous, details: metadata };- }+ : capturedOutput === undefined+ ? projectAnalysisError(options.cleanupPrimary)+ : projectAnalysisErrorWithoutCapturedOutput(options.cleanupPrimary);return new ProviderCleanupError(SQLITE_PROVIDER_IDENTITY.id,resources,diff --git a/tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.ts b/tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.tsindex a16496b56..bd6a2aa55 100644--- a/tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.ts+++ b/tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.ts@@ -123,10 +123,10 @@ it.runIf(!unsupportedHost)(if (result.ok) throw new Error("Expected compounded lifecycle failure");expect(result.error).toMatchObject({cleanupIncomplete: true,+ capturedOutput: { truncated: true, stderr: "" },diagnostics: {primary_error: {code: "unreadable_output",- details: { captured_output: { truncated: true, stderr: "" } },},cleanup_error: {code: "cleanup_incomplete",@@ -136,6 +136,22 @@ it.runIf(!unsupportedHost)(},},});+ const projected = projectAnalysisError(result.error);+ expect(projected.details?.captured_output).toEqual(+ result.error.capturedOutput,+ );+ expect(projected).not.toHaveProperty(+ "details.diagnostics.primary_error.details.captured_output",+ );+ const output = result.error.capturedOutput?.stdout;+ if (!output) throw new Error("Expected retained truncated worker output");+ // Preserve the cleanup owner's separate snapshot, but not a redundant+ // captured_output copy in generic primary history.+ expect(projected).toHaveProperty(+ "details.diagnostics.cleanup_error.details.diagnostics.captured_output.stdout",+ output,+ );+ expect(JSON.stringify(projected).split(output)).toHaveLength(3);await expect(access(ownedPath)).resolves.toBeUndefined();cleanupAllowed = true;await provider.close();diff --git a/tests/composition/directAnalysisCleanup.test.ts b/tests/composition/directAnalysisCleanup.test.tsindex 8735177d9..54a917b9f 100644--- a/tests/composition/directAnalysisCleanup.test.ts+++ b/tests/composition/directAnalysisCleanup.test.ts@@ -9,7 +9,10 @@ import { parseConfig } from "../../src/config/parseConfig.js";import { analysisCliErrorEnvelopeSchema } from "../../src/contracts/errorSchemas.js";import type { AnalysisError } from "../../src/domain/analysisErrorBase.js";import { AnalysisTimeoutError } from "../../src/domain/analysisErrorCore.js";-import { projectAnalysisError } from "../../src/domain/analysisErrorProjection.js";+import {+ projectAnalysisError,+ projectAnalysisErrorWithoutCapturedOutput,+} from "../../src/domain/analysisErrorProjection.js";import { parseEvidence } from "../../src/domain/evidence.js";import { ProviderCleanupError } from "../../src/domain/providerCleanupError.js";import { err, ok } from "../../src/domain/result.js";@@ -270,15 +273,24 @@ describe("managed one-shot cleanup outcomes", () => {cause: primaryError,errors: [primaryError, cleanupError],});- expect(projectAnalysisError(result.error)).toMatchObject({+ const projected = projectAnalysisError(result.error);+ expect(projected).toMatchObject({code: "cleanup_incomplete",details: {+ captured_output: primaryError.capturedOutput,diagnostics: {- primary_error: projectAnalysisError(primaryError),+ primary_error:+ projectAnalysisErrorWithoutCapturedOutput(primaryError),cleanup_error: projectAnalysisError(cleanupError),},},});+ expect(projected).not.toHaveProperty(+ "details.diagnostics.primary_error.details.captured_output",+ );+ expect(+ JSON.stringify(projected).split("retained observation"),+ ).toHaveLength(2);});it("exposes managed cleanup failure to the CLI error classifier", async () => {diff --git a/tests/process-global/firmwareFileLifetime.test.ts b/tests/process-global/firmwareFileLifetime.test.tsindex a0bc4a004..0b05c688c 100644--- a/tests/process-global/firmwareFileLifetime.test.ts+++ b/tests/process-global/firmwareFileLifetime.test.ts@@ -689,6 +689,7 @@ const publication = async (files: new FirmwareFileAccess(),workspacePath,deadline,+ analysisTimeoutMs: 120_000,outputDirectory: join(root, "published"),entries: [],normalized,diff --git a/tests/process-global/firmwarePublicationDeadline.test.ts b/tests/process-global/firmwarePublicationDeadline.test.tsindex cbd1692ef..88dbf433c 100644--- a/tests/process-global/firmwarePublicationDeadline.test.ts+++ b/tests/process-global/firmwarePublicationDeadline.test.ts@@ -4,8 +4,11 @@ import { afterEach, expect, it, vi } from "vitest";import * as firmwareFiles from "../../src/firmware/FirmwareFiles.js";import { SafeOutputTree } from "../../src/artifacts/SafeOutputTree.js";import { PrivateRuntimeRoot } from "../../src/process/PrivateRuntimeRoot.js";-import { FIRMWARE_LIMITS } from "../../src/firmware/FirmwareRelease.js";+import { DEFAULT_FIRMWARE_ANALYSIS_TIMEOUT_MS } from "../../src/domain/firmware/firmwareAnalysis.js";import { projectAnalysisError } from "../../src/domain/analysisErrorProjection.js";+import { ProviderProcessSupervisor } from "../../src/process/ProviderProcess.js";+import { finishAnalysisCommand } from "../../src/cli/finishAnalysisCommand.js";+import { AnalysisOutputError } from "../../src/domain/analysisErrorCore.js";import {firmwareFixture,assertFirmwareCleanup,@@ -36,13 +39,16 @@ test("preserves an already aborted caller reason without launching firmware workawait fixture.close();});-const phases = (publicationMs: number = FIRMWARE_LIMITS.timeoutMs) => {+const phases = (+ publicationMs: number = DEFAULT_FIRMWARE_ANALYSIS_TIMEOUT_MS,+ analysisMs: number = DEFAULT_FIRMWARE_ANALYSIS_TIMEOUT_MS,+) => {const analysis = new AbortController();const publication = new AbortController();const budgets: number[] = [];const timeout = AbortSignal.timeout;vi.spyOn(AbortSignal, "timeout").mockImplementation((ms) => {- if (budgets.length === 0 && ms === FIRMWARE_LIMITS.timeoutMs) {+ if (budgets.length === 0 && ms === analysisMs) {budgets.push(ms);return analysis.signal;}@@ -64,6 +70,43 @@ const phaseClock = () => {};};+test("charges inspection workspace cleanup to its selectable analysis budget, without a hidden publication phase", async () => {+ const phase = phases(120_000, 1234);+ const advance = phaseClock();+ const fixture = await firmwareFixture();+ const close = PrivateRuntimeRoot.prototype.close;+ vi.spyOn(PrivateRuntimeRoot.prototype, "close").mockImplementation(+ async function (this: PrivateRuntimeRoot) {+ await close.call(this);+ advance(1235);+ },+ );+ const result = await fixture.service.execute("inspect_firmware_regions", {+ path: fixture.path,+ analysis_timeout_ms: 1234,+ });+ if (result.ok)+ throw new Error(+ "Expected inspection cleanup to exceed its analysis budget",+ );+ expect(phase.budgets).toEqual([1234]);+ expect(phase.analysis.signal.aborted).toBe(false);+ expect(projectAnalysisError(result.error)).toMatchObject({+ code: "provider_timeout",+ details: {+ timeout_ms: 1234,+ diagnostics: { phase: "analysis" },+ partial_observation: {+ kind: "firmware",+ result: { analysis_timeout_ms: 1234, coverage: "signature_scan" },+ },+ },+ remediation: { action: expect.stringContaining("analysis_timeout_ms") },+ });+ await fixture.close();+ await assertFirmwareCleanup(fixture.launches);+});+test("allows publication after the analysis phase expires", async () => {const phase = phases();const fixture = await firmwareFixture();@@ -136,7 +179,7 @@ test.each(["signal", "clock"] as const)(},);-test("keeps each queued request's publication budget", async () => {+test("keeps each queued request's independent analysis and publication budgets", async () => {const fixture = await firmwareFixture();const budgets: number[] = [];const timeout = AbortSignal.timeout;@@ -172,6 +215,7 @@ test("keeps each queued request's publication budget", async () => {path: fixture.path,output_directory: fixture.output,publication_timeout_ms: 123_456,+ analysis_timeout_ms: 234_567,});try {await entered;@@ -179,8 +223,9 @@ test("keeps each queued request's publication budget", async () => {path: fixture.path,output_directory: join(fixture.root, "second-output"),publication_timeout_ms: 654_321,+ analysis_timeout_ms: 765_432,});- expect(budgets).toEqual([120_000, 123_456]);+ expect(budgets).toEqual([234_567, 123_456]);release();const results = await Promise.all([pending, queued]);expect(@@ -190,7 +235,13 @@ test("keeps each queued request's publication budget", async () => {: result.error.message,),).toEqual([123_456, 654_321]);- expect(budgets).toEqual([120_000, 123_456, 120_000, 654_321]);+ expect(+ results.map((result) => result.ok && result.value.normalized_result),+ ).toMatchObject([+ { analysis_timeout_ms: 234_567 },+ { analysis_timeout_ms: 765_432 },+ ]);+ expect(budgets).toEqual([234_567, 123_456, 765_432, 654_321]);} finally {release();}@@ -198,6 +249,204 @@ test("keeps each queued request's publication budget", async () => {await assertFirmwareCleanup(fixture.launches);});+test("uses the selected phase deadline inside an owned command beyond the former 120-second cap", async () => {+ const fixture = await firmwareFixture();+ const advance = phaseClock();+ const wait = ProviderProcessSupervisor.prototype.waitForOutputClose;+ let advanced = false;+ vi.spyOn(+ ProviderProcessSupervisor.prototype,+ "waitForOutputClose",+ ).mockImplementation(async function (+ this: ProviderProcessSupervisor,+ ...args+ ) {+ const closed = await wait.apply(this, args);+ if (!advanced) {+ advanced = true;+ advance(120_001);+ return false;+ }+ return closed;+ });+ const result = await fixture.service.execute("inspect_firmware_regions", {+ path: fixture.path,+ analysis_timeout_ms: 240_000,+ });+ if (!result.ok) throw result.error;+ expect(result.value.normalized_result).toMatchObject({+ analysis_timeout_ms: 240_000,+ });+ expect(fixture.launches).toHaveLength(2);+ expect(+ fixture.launches.every((launch) => launch.args.includes("--cpu=120")),+ ).toBe(true);+ await fixture.close();+ await assertFirmwareCleanup(fixture.launches);+});++test.each([false, true])(+ "retains typed analysis timeout recovery through failed command cleanup (one-shot close: %s)",+ async (oneShot) => {+ const fixture = await firmwareFixture("cleanup-failure");+ const analysis = new AbortController();+ const timeout = AbortSignal.timeout;+ const timer = vi+ .spyOn(AbortSignal, "timeout")+ .mockImplementation((ms) =>+ ms === 1234 ? analysis.signal : timeout(ms),+ );+ const wait = ProviderProcessSupervisor.prototype.waitForOutputClose;+ const waiter = vi+ .spyOn(ProviderProcessSupervisor.prototype, "waitForOutputClose")+ .mockImplementation(async function (+ this: ProviderProcessSupervisor,+ ...args+ ) {+ const closed = await wait.apply(this, args);+ if (closed)+ analysis.abort(+ new DOMException("controlled analysis expiry", "TimeoutError"),+ );+ return closed;+ });+ const result = await fixture.service.execute("inspect_firmware_regions", {+ path: fixture.path,+ analysis_timeout_ms: 1234,+ });+ if (result.ok) throw new Error("Expected timeout with retained cleanup");+ expect(result.error.cleanupPrimary).toMatchObject({+ _tag: "AnalysisTimeoutError",+ timeoutMs: 1234,+ });+ const projected = projectAnalysisError(result.error);+ expect(projected).toMatchObject({+ code: "cleanup_incomplete",+ details: {+ diagnostics: {+ previous_error: {+ code: "provider_timeout",+ details: { timeout_ms: 1234 },+ },+ },+ captured_output: { stdout: expect.stringContaining("binwalk 3.1.0") },+ },+ });+ expect(JSON.stringify(projected).split("binwalk 3.1.0")).toHaveLength(2);+ timer.mockRestore();+ waiter.mockRestore();+ if (oneShot) {+ const delivered = await finishAnalysisCommand(+ async () => result,+ fixture.service,+ "binwalk",+ "inspect_firmware_regions",+ new AbortController().signal,+ );+ expect(delivered).toMatchObject({ code: "cleanup_incomplete" });+ expect(JSON.stringify(delivered).split("binwalk 3.1.0")).toHaveLength(2);+ }+ fixture.restoreCleanup();+ if (oneShot) await fixture.close();+ else {+ const retried = await fixture.service.execute(+ "inspect_firmware_regions",+ {+ path: fixture.path,+ },+ );+ if (!retried.ok) throw retried.error;+ }+ expect(result.error.cleanupIncomplete).toBe(false);+ expect(projectAnalysisError(result.error)).toMatchObject({+ code: "provider_timeout",+ details: { timeout_ms: 1234 },+ });+ await fixture.close();+ await assertFirmwareCleanup(fixture.launches);+ },+);++test.each(["analysis", "clock", "caller", "prior-failure"] as const)(+ "retains an interruption observed during incomplete command cleanup: %s",+ async (interruption) => {+ const phase = phases(120_000, 54_321);+ const advance = phaseClock();+ const fixture = await firmwareFixture("cleanup-failure");+ const caller = new AbortController();+ const reason = { caller: "during owned command cleanup" };+ const original = new AnalysisOutputError(+ "inspect_firmware_regions",+ "earlier command failure",+ );+ const stop = ProviderProcessSupervisor.prototype.stop;+ const stopper = vi+ .spyOn(ProviderProcessSupervisor.prototype, "stop")+ .mockImplementation(async function (+ this: ProviderProcessSupervisor,+ ...args+ ) {+ const stopped = await stop.apply(this, args);+ if (interruption === "clock") advance(54_322);+ else if (interruption === "caller") caller.abort(reason);+ else+ phase.analysis.abort(+ new DOMException("during owned command cleanup", "TimeoutError"),+ );+ return stopped;+ });+ if (interruption === "prior-failure")+ vi.spyOn(+ ProviderProcessSupervisor.prototype,+ "waitForOutputClose",+ ).mockRejectedValueOnce(original);+ const result = await fixture.service.execute(+ "inspect_firmware_regions",+ {+ path: fixture.path,+ analysis_timeout_ms: 54_321,+ },+ { signal: caller.signal },+ );+ if (result.ok) throw new Error("Expected retained command cleanup");+ const expected =+ interruption === "caller"+ ? "cancelled"+ : interruption === "prior-failure"+ ? "unreadable_output"+ : "provider_timeout";+ expect(projectAnalysisError(result.error)).toMatchObject({+ code: "cleanup_incomplete",+ details: { diagnostics: { previous_error: { code: expected } } },+ });+ const primary = result.error.cleanupPrimary;+ if (primary === undefined)+ throw new Error("Expected typed cleanup primary");+ if (interruption === "prior-failure") expect(primary).toBe(original);+ else {+ expect(primary._tag).toBe(+ interruption === "caller"+ ? "AnalysisCancelledError"+ : "AnalysisTimeoutError",+ );+ if (interruption !== "caller")+ expect(projectAnalysisError(primary).details).toMatchObject({+ timeout_ms: 54_321,+ diagnostics: { phase: "analysis" },+ });+ if (interruption === "caller") expect(primary.cause).toBe(reason);+ if (interruption === "analysis")+ expect(primary.cause).toBe(phase.analysis.signal.reason);+ }+ stopper.mockRestore();+ fixture.restoreCleanup();+ await fixture.close();+ expect(result.error.cleanupIncomplete).toBe(false);+ expect(projectAnalysisError(result.error).code).toBe(expected);+ await assertFirmwareCleanup(fixture.launches);+ },+);+test.each(["none", "caller", "publication", "clock"] as const)("preserves the selected budget, verified progress and rollback at commit: %s",async (interruption) => {@@ -288,7 +537,7 @@ test.each([] as const)("retains committed output and late timeout through workspace cleanup: $expiry, denied: $denied",async ({ expiry, denied }) => {- const phase = phases(654_321);+ const phase = phases(654_321, 234_567);const advance = phaseClock();const fixture = await firmwareFixture();const commit = SafeOutputTree.prototype.commit;@@ -318,9 +567,11 @@ test.each([const result = await fixture.service.execute("extract_firmware", {path: fixture.path,output_directory: fixture.output,+ analysis_timeout_ms: 234_567,publication_timeout_ms: 654_321,});if (result.ok) throw new Error("Expected timeout during final cleanup");+ expect(phase.budgets).toEqual([234_567, 654_321]);expect(phase.publication.signal.aborted).toBe(expiry === "signal");const projected = projectAnalysisError(result.error);expect(@@ -331,7 +582,10 @@ test.each([});expect(result.error.partialObservation).toMatchObject({kind: "firmware",- result: { output_directory: fixture.output },+ result: {+ output_directory: fixture.output,+ analysis_timeout_ms: 234_567,+ },});expect(await readFile(join(fixture.output, "rootfs/config"), "utf8")).toBe("firmware=true\n",diff --git a/tests/process-global/pwntoolsCleanup.test.ts b/tests/process-global/pwntoolsCleanup.test.tsindex 6260e65f0..7735c8ba9 100644--- a/tests/process-global/pwntoolsCleanup.test.ts+++ b/tests/process-global/pwntoolsCleanup.test.ts@@ -15,6 +15,7 @@ import { spawnOwnedProviderProcess } from "../../src/process/ProviderProcess.js"import { cleanupOwnedProcessGroup } from "../../src/process/ProcessOwnership.js";import { prepareProcessOwnershipInspection } from "../../src/process/ProcessOwnershipObservation.js";import { stopProviderProcessFixture } from "../fixtures/providerProcess.js";+import { projectAnalysisError } from "../../src/domain/analysisErrorProjection.js";import {createTestWorkspace,removeTestWorkspace,@@ -113,14 +114,30 @@ it.runIf(supportedHost)(throw new Error("Expected output overflow and failed cleanup");expect(result.error).toMatchObject({cleanupIncomplete: true,+ capturedOutput: { truncated: true },diagnostics: {primary_error: {code: "unreadable_output",- details: { captured_output: { truncated: true } },},cleanup_error: { code: "cleanup_incomplete" },},});+ const projected = projectAnalysisError(result.error);+ expect(projected.details?.captured_output).toEqual(+ result.error.capturedOutput,+ );+ expect(projected).not.toHaveProperty(+ "details.diagnostics.primary_error.details.captured_output",+ );+ const output = result.error.capturedOutput?.stdout;+ if (!output) throw new Error("Expected retained truncated worker output");+ // The cleanup owner also retains a bounded worker snapshot for its own+ // failed-close receipt. Generic primary history must not add a third copy.+ expect(projected).toHaveProperty(+ "details.diagnostics.cleanup_error.details.diagnostics.captured_output.stdout",+ output,+ );+ expect(JSON.stringify(projected).split(output)).toHaveLength(3);if (pid === undefined)throw new Error("The fixture did not acquire a process");const workerPid = pid;