mirror of
https://github.com/morluto/rea.git
synced 2026-11-16 19:53:50 +00:00
* fix(pcap): report a refused tool launch as an unavailable tool When a capture read's tool launch was refused with EPERM, pcap reported it as unreadable tool output (AnalysisProtocolError) instead of an unavailable tool. Pcap also never told "not executable" apart from "missing". Add classifyLaunchFailure in src/process as the one owner of which spawn errnos mean missing (ENOENT, ENOTDIR) and which mean present but not executable (EACCES, EPERM, ENOEXEC, EISDIR). Pcap, apktool and gdb used three different errno lists; all three now use it. * refactor(process): classify owned command outcomes through one owner Add ProviderOutcome, read once from the supervisor's facts, and classifyProviderOutcome, the one mapping from an outcome to a typed error. Migrate pcap and the shared artifact producer command failure (TShark, sigrok). Add the rea/provider-failure-classifier lint rule with a shrink-only baseline of per-site (cause: unknown) => AnalysisError functions. * refactor(process): classify Java and adb launch refusals with the shared owner (#10598) The Ghidra and JADX Java probes and adb's version probe now take missing-versus-not-executable from classifyLaunchFailure instead of their own errno checks. ELOOP and ENAMETOOLONG join the owner's missing set, so adb keeps its existing classification and both Java probes now treat a non-directory path component as a missing runtime. * fix(pcap): preserve command launch attribution * test(pcap): expect an unknown failing stage when a limited capture tool exits unsuccessfully * refactor(process): classify owned command outcomes through one owner Add ProviderOutcome, read once from the supervisor's facts, and classifyProviderOutcome, the one mapping from an outcome to a typed error. Migrate pcap and the shared artifact producer command failure (TShark, sigrok). Add the rea/provider-failure-classifier lint rule with a shrink-only baseline of per-site (cause: unknown) => AnalysisError functions. * test(lint): cover baselined files in the provider-failure classifier rule * fix(apktool): report the decoder JVM's heap exhaustion as memory, not a target refusal The supervisor now watches for a managed runtime's out-of-memory report while output streams (JVM java.lang.OutOfMemoryError, V8 'JavaScript heap out of memory'), so a retention budget cannot hide it. ProviderOutcome gains a runtime-exhausted kind and classifyProviderOutcome maps it once. Apktool decode opts in and moves to the shared classifier; Ghidra's single-purpose output token becomes the JVM runtime option and its area matching reuses the shared table. * fix(process): keep the runtime's out-of-memory report on the memory error it supports * fix(pcap): attribute a limited capture's exit through the prlimit wrapper * fix(process): keep a shortened out-of-memory line marked as shortened * fix(process): identify the refused executable for every launcher shape Name the executable on errnos Node throws synchronously from spawn (ENOEXEC, ENOTDIR, ...) and read the Windows native launcher's executable-launch constraint, so pcap attributes those refusals to the selected tool or limiter instead of an unknown stage. * test(pcap): prove synchronous launch naming with ENOTDIR on every POSIX host * fix(apktool): advise the JVM limit that governs the reported memory area * fix(ghidra): read the supervisor's parsed OOM area instead of reparsing lines * fix(sqlite,capture): read V8 heap exhaustion from streamed output, not retained stderr (#10724) The SQLite worker and the Node capture decoders now declare runtime: "v8", so the supervisor observes V8's heap report as output streams. Both classifiers read the runtime-exhausted outcome instead of matching retained stderr, so a report beyond the retention budget, or one whose process then overflowed its output budget, is still reported as memory exhaustion. * refactor(evm): classify EVMole worker outcomes through the shared provider classifier (#10716) * refactor(evm): classify EVMole worker outcomes through the shared provider classifier The EVMole worker's cancellation, deadline, output budget and CPU/file-size signals now go through classifyProviderOutcome; only the prlimit launch refusal and the reserved EFBIG exit remain in its dialect. The worker is opted into V8 exhaustion scanning so a heap report names its fixed 256 MiB heap. providerOutcomeOf now reads a launch refusal only from a spawn errno, so a private-storage or carrier read errno is no longer reported as a limiter launch failure. * fix(evm): keep a stream failure's exit status and update Linux worker expectations * refactor(process): read launch refusals through the launcher identity owner * refactor(wasm): classify WABT command outcomes through the shared provider classifier (#10727) * refactor(wasm): classify WABT command outcomes through the shared provider classifier WABT's cancellation, command deadline, output budget, and inherited-limit signals now go through classifyProviderOutcome; its dialect keeps only the configuration-probe and launch-refusal unavailability and the unclassified-exit output error. A tool ended by SIGXCPU/SIGXFSZ or the memory limit is now a resource constraint instead of an output error, and a refused launch in the producer phase is reported as unavailable. The shared timeout context gains the analysis setting that selected the deadline, and the output-limit context may name its exceeded budget. * fix(wasm): keep setup guidance when a WABT version probe's output cannot be collected * refactor(providers): classify raw provider failures through one owner * refactor(process): build classified cancellations with cancelledBy and the carried caller reason * chore(lint): count runOwned's close-failure mapper from main in the classifier baseline * fix(process): carry the runtime's exhaustion report on every memory error that claims it SQLite and historical-capture memory errors recognised a streamed V8 heap report but dropped it, so a report outside retained output reached callers without its source line or omission flags. One projection, runtimeExhaustionReport, now owns that shape for the shared classifier and both consumers. Also lowers the EVMole and WABT cancellation-constructor baselines. * fix(process): keep the provider's recovery for a native-thread exhaustion report The shared classifier replaced the provider-supplied recovery with generic capacity advice whenever the JVM reported it could not create a native thread, dropping Apktool's launcher guidance and flipping retryable to true. The provider's recovery now wins; the capacity advice remains the fallback for providers that supply none. * refactor(pwntools): classify pwntools failures through the shared provider classifier (#10782) * refactor(pwntools): classify pwntools failures through the shared provider classifier pwntools' per-site classifier is replaced by pwntoolsFailureDialect for classifyProviderFailure. Command outcomes go through classifyProviderOutcome, launch refusals through launcherRefusalOf instead of a 'spawn ' syscall prefix check, the input limit through the file dialect's fileSize, and the cleanup report through commandCleanup. The shared read cancellation now carries the reader's partial observation, and resource-signal reports accept provider detail. * fix(pwntools): report a failed command's output once and expect resource_constraint for overflow The shared outcome owner already attaches the command's output as capturedOutput, so the pwntools adapter fallback no longer copies the same text into diagnostics.stdout, diagnostics.stderr and diagnostics.captured_output; diagnostics keep the exit facts. Update the overflow expectations the dialect migration missed (layout provider cleanup and over-budget rows, pwntools cleanup) to resource_constraint. * refactor(wasm): leave WABT cancellation to the shared owners WabtFailures matched any Error named AbortError as a cancellation. No WABT path produces one: reads, path checks and owned commands report cancellation as ArtifactReaderFailure or OwnedCommandFailure, which classifyProviderFailure and classifyProviderOutcome already classify with the caller's reason. The provider's two signal checks now build the cancellation with cancelledBy. Lowers the AnalysisCancelledError constructor baseline for both WABT files to zero. * fix(wasm): report a cancelled snapshot write as the caller's cancellation The private snapshot write passed the caller's signal to Node's writeFile, whose abort envelope reached the dialect's unclassified output failure once the name-based AbortError guess was removed. The write now turns the envelope carrying its own signal's reason into cancelledBy at the producer. * refactor(firmware): classify firmware failures through the shared provider classifier (#10810) Firmware producers now report their own deadline expiry: the start check, the output inventory and launcher admission throw the phase timeout where they observe the abort, and a read the phase signal cancelled reports it through the dialect's interruption. The classifier no longer rereads a cancellation's reason as a timeout. A new readCleanup hook keeps firmware's cleanup report shape.
526 lines
19 KiB
TypeScript
526 lines
19 KiB
TypeScript
import {
|
|
processInspectionCancellationError,
|
|
retainProcessInspectionCleanup,
|
|
} from "../providers/OwnedCommandCleanup.js";
|
|
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
|
|
import {
|
|
selectArtifactCommandPath,
|
|
type ArtifactCommandPath,
|
|
} from "../process/ArtifactCommandPath.js";
|
|
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
|
import {
|
|
FIRMWARE_TOOL_REQUIREMENTS,
|
|
type FirmwareEngineName,
|
|
} from "../contracts/firmware/firmwareToolRequirements.js";
|
|
import { randomUUID } from "node:crypto";
|
|
import { access, stat } from "node:fs/promises";
|
|
import { constants } from "node:fs";
|
|
import { isAbsolute } from "node:path";
|
|
import {
|
|
AnalysisCapabilityUnavailableError,
|
|
AnalysisOutputError,
|
|
AnalysisTimeoutError,
|
|
} from "../domain/analysisErrorCore.js";
|
|
import { classifyProviderFailure } from "../providers/classifyProviderFailure.js";
|
|
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
|
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
|
import type {
|
|
AnalysisError,
|
|
AnalysisCapturedOutput,
|
|
} from "../domain/analysisErrorBase.js";
|
|
import { projectAnalysisErrorWithoutCapturedOutput } from "../domain/analysisErrorProjection.js";
|
|
import type { FirmwareDeadline } from "./FirmwareDeadline.js";
|
|
import {
|
|
firmwareFailureDialect,
|
|
firmwareLimitRecovery,
|
|
firmwarePhaseInterruption,
|
|
firmwareProcessLimitRecovery,
|
|
firmwareSignalLimitError,
|
|
} from "./FirmwareFailures.js";
|
|
import { prlimitArgumentVector } from "../process/LinuxResourceLimits.js";
|
|
import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js";
|
|
import {
|
|
spawnOwnedProviderProcess,
|
|
ProviderProcessSupervisor,
|
|
type OwnedProviderProcessSpawnOptions,
|
|
type ProviderProcessSnapshot,
|
|
type SpawnedOwnedProviderProcess,
|
|
} from "../process/ProviderProcess.js";
|
|
import { FIRMWARE_LIMITS } from "./FirmwareRelease.js";
|
|
import {
|
|
FirmwareFileAccess,
|
|
inventoryFirmwareOutput,
|
|
} from "./FirmwareFiles.js";
|
|
|
|
/** Injectable owned launcher for production protocol and lifecycle tests. */
|
|
export type FirmwareLauncher = (
|
|
options: OwnedProviderProcessSpawnOptions,
|
|
) => Promise<SpawnedOwnedProviderProcess>;
|
|
|
|
/** Captured tool output for one finished firmware command, including byte coverage. */
|
|
const capturedFirmwareOutput = (
|
|
snapshot: ProviderProcessSnapshot,
|
|
): AnalysisCapturedOutput => ({
|
|
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,
|
|
});
|
|
|
|
/** Refuse an unmet host or tool requirement, which another target cannot satisfy. */
|
|
export const firmwareToolUnavailable = (
|
|
engine: string,
|
|
operation: string,
|
|
reason: string,
|
|
): AnalysisCapabilityUnavailableError =>
|
|
new AnalysisCapabilityUnavailableError(engine, operation, reason, {
|
|
userMessage: reason,
|
|
});
|
|
|
|
/** Firmware engines run only on Linux; discovery and execution share this check. */
|
|
export const firmwareHostSupported = (platform: NodeJS.Platform): boolean =>
|
|
platform === "linux";
|
|
|
|
/** Resolve explicitly supplied executable paths; never install or search for engines. */
|
|
export const resolveFirmwareCommand = async (
|
|
environment: Readonly<Record<string, string | undefined>>,
|
|
engine: FirmwareEngineName,
|
|
operation: string,
|
|
files: FirmwareFileAccess,
|
|
signal?: AbortSignal,
|
|
) => {
|
|
const variable = FIRMWARE_TOOL_REQUIREMENTS[engine].commandEnvironment;
|
|
const configured = environment[variable];
|
|
if (
|
|
!firmwareHostSupported(process.platform) ||
|
|
configured === undefined ||
|
|
!isAbsolute(configured)
|
|
)
|
|
throw firmwareToolUnavailable(
|
|
engine,
|
|
operation,
|
|
`This integration requires Linux and an absolute ${variable} path to the caller-supplied tool`,
|
|
);
|
|
const selection = await selectArtifactCommandPath(configured, signal).catch(
|
|
(cause: unknown) => {
|
|
if (cause instanceof ArtifactReaderFailure) throw cause;
|
|
throw firmwareToolUnavailable(
|
|
engine,
|
|
operation,
|
|
`${variable} is unavailable: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
);
|
|
},
|
|
);
|
|
const command = selection.invocationPath;
|
|
let sha256: string;
|
|
try {
|
|
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 files.hash(selection.resolvedPath, signal);
|
|
} catch (cause: unknown) {
|
|
if (cause instanceof ArtifactReaderFailure) throw cause;
|
|
throw firmwareToolUnavailable(
|
|
engine,
|
|
operation,
|
|
`${variable} is not a readable executable regular file: ${command}: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
);
|
|
}
|
|
const limiter =
|
|
environment.REA_FIRMWARE_PRLIMIT_COMMAND ?? "/usr/bin/prlimit";
|
|
if (!isAbsolute(limiter))
|
|
throw firmwareToolUnavailable(
|
|
engine,
|
|
operation,
|
|
"REA_FIRMWARE_PRLIMIT_COMMAND must be absolute",
|
|
);
|
|
let limiterSelection: ArtifactCommandPath;
|
|
try {
|
|
limiterSelection = await selectArtifactCommandPath(limiter, signal);
|
|
await access(limiterSelection.resolvedPath, constants.X_OK);
|
|
if (!(await stat(limiter)).isFile())
|
|
throw new TypeError("Configured path is not a regular file");
|
|
} catch (cause: unknown) {
|
|
if (cause instanceof ArtifactReaderFailure) throw cause;
|
|
throw firmwareToolUnavailable(
|
|
engine,
|
|
operation,
|
|
`Resource limiter is not an executable regular file: ${limiter}: ${cause instanceof Error ? cause.message : String(cause)}; provide util-linux prlimit`,
|
|
);
|
|
}
|
|
return {
|
|
command: selection,
|
|
limiter: limiterSelection,
|
|
sha256,
|
|
fileSizeCeiling: await files.fileSizeCeiling(signal),
|
|
};
|
|
};
|
|
|
|
/**
|
|
* The RLIMIT_FSIZE one producer run gets. It covers every producer file,
|
|
* including mandatory reports and logs; outputBudget inventory still governs
|
|
* aggregate payload. One byte above the largest budget makes a file the kernel
|
|
* stops at the limit exceed that budget instead of passing as complete. An
|
|
* inherited ceiling can remove that byte, so inventory also rejects files
|
|
* that reach the returned limit.
|
|
*/
|
|
export const firmwareFileSizeLimit = (
|
|
fileSizeCeiling: number,
|
|
stagingBytes?: number,
|
|
): number =>
|
|
Math.min(
|
|
fileSizeCeiling,
|
|
Math.max(
|
|
stagingBytes ?? 0,
|
|
FIRMWARE_LIMITS.reportBytes,
|
|
FIRMWARE_LIMITS.diagnosticBytes,
|
|
) + 1,
|
|
);
|
|
|
|
/**
|
|
* Whether a larger max_output_bytes would raise the per-run file limit. It is
|
|
* false when the report and diagnostic allowances or the inherited ceiling,
|
|
* including its last byte of headroom, set that limit instead.
|
|
*/
|
|
const firmwareFileSizeAdjustable = (
|
|
fileSizeCeiling: number,
|
|
stagingBytes?: number,
|
|
): boolean =>
|
|
stagingBytes !== undefined &&
|
|
firmwareFileSizeLimit(fileSizeCeiling, stagingBytes + 1) >
|
|
firmwareFileSizeLimit(fileSizeCeiling, stagingBytes);
|
|
|
|
/** Execute one bounded provider command and verify its owned descendants have stopped. */
|
|
export const runFirmwareCommand = async (context: {
|
|
engine: string;
|
|
operation: string;
|
|
command: string;
|
|
limiter: string;
|
|
/** Observed inherited soft/hard file policy; never raised by metadata headroom. */
|
|
fileSizeCeiling: number;
|
|
args: readonly string[];
|
|
cwd: string;
|
|
environment: Readonly<Record<string, string | undefined>>;
|
|
signal: AbortSignal;
|
|
deadline: FirmwareDeadline;
|
|
launcher?: FirmwareLauncher;
|
|
resources: ArtifactResourceScope;
|
|
outputBudget?: { root: string; bytes: number; entries: number };
|
|
acceptReportedExtractionFailure?: boolean;
|
|
retainCleanup(supervisor: ProviderProcessSupervisor): void;
|
|
}) => {
|
|
const { engine, operation, signal } = context;
|
|
const dialect = firmwareFailureDialect({
|
|
engine,
|
|
operation,
|
|
phase: { signal, deadline: context.deadline },
|
|
});
|
|
const fileSizeBytes = firmwareFileSizeLimit(
|
|
context.fileSizeCeiling,
|
|
context.outputBudget?.bytes,
|
|
);
|
|
const fileSizeAdjustable = firmwareFileSizeAdjustable(
|
|
context.fileSizeCeiling,
|
|
context.outputBudget?.bytes,
|
|
);
|
|
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,
|
|
arguments: [
|
|
...prlimitArgumentVector(
|
|
{
|
|
address_space_bytes: FIRMWARE_LIMITS.addressSpaceBytes,
|
|
file_bytes: fileSizeBytes,
|
|
cpu_seconds: FIRMWARE_LIMITS.cpuSeconds,
|
|
},
|
|
context.command,
|
|
),
|
|
...context.args,
|
|
],
|
|
expectedCommand: null,
|
|
runId,
|
|
cwd: context.cwd,
|
|
hostEnvironment: context.environment,
|
|
signal,
|
|
env: {
|
|
TMPDIR: context.cwd,
|
|
OMP_NUM_THREADS: "1",
|
|
OPENBLAS_NUM_THREADS: "1",
|
|
RAYON_NUM_THREADS: "1",
|
|
NO_COLOR: "1",
|
|
},
|
|
}).catch((cause: unknown) => {
|
|
const cancellation = processInspectionCancellationError(cause, operation);
|
|
// The phase deadline reports its own expiry; any other inspection
|
|
// cancellation keeps its ownership-inspection origin.
|
|
const interruption =
|
|
cancellation === undefined
|
|
? undefined
|
|
: firmwarePhaseInterruption(operation, signal, context.deadline);
|
|
const primary =
|
|
cancellation === undefined
|
|
? classifyProviderFailure(cause, dialect)
|
|
: interruption instanceof AnalysisTimeoutError
|
|
? interruption
|
|
: cancellation;
|
|
throw retainProcessInspectionCleanup(
|
|
cause,
|
|
primary,
|
|
context.resources,
|
|
operation,
|
|
);
|
|
});
|
|
let failure: AnalysisError | undefined;
|
|
const isFailedExit = (code: number | null | undefined) =>
|
|
code !== undefined &&
|
|
code !== 0 &&
|
|
!(context.acceptReportedExtractionFailure === true && code === 1);
|
|
const completedFailure = (snapshot: ProviderProcessSnapshot) => {
|
|
if (isFailedExit(snapshot.exitCode)) {
|
|
const signalLimit = firmwareSignalLimitError(
|
|
operation,
|
|
snapshot.signal,
|
|
fileSizeBytes,
|
|
fileSizeAdjustable,
|
|
capturedFirmwareOutput(snapshot),
|
|
);
|
|
if (signalLimit !== undefined) return signalLimit;
|
|
return new ProviderAdapterError(engine, operation, {
|
|
diagnostics: {
|
|
reason:
|
|
"Tool failed; inspect exit status and stderr for format, dependency, sandbox or resource-limit failures",
|
|
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,
|
|
truncated: snapshot.diagnosticTruncated === true,
|
|
},
|
|
remediationAction: `Inspect exit status and stderr for format, dependency, sandbox, or resource-limit failures. ${firmwareProcessLimitRecovery(fileSizeBytes, fileSizeAdjustable)} A format or dependency failure is not repaired by changing analysis_timeout_ms.`,
|
|
});
|
|
}
|
|
return undefined;
|
|
};
|
|
let completedFailureObserved = false;
|
|
let diagnosticTruncated = false;
|
|
const supervisor = new ProviderProcessSupervisor(
|
|
{
|
|
...spawned,
|
|
ownsProcessLifetime: true,
|
|
cleanup:
|
|
spawned.cleanup ?? (() => cleanupOwnedProcessGroup(spawned.ownership)),
|
|
},
|
|
{
|
|
maxDiagnosticBytes: FIRMWARE_LIMITS.diagnosticBytes,
|
|
onDiagnostic: (event) => {
|
|
if (event.type === "output" && event.truncated === true)
|
|
diagnosticTruncated = true;
|
|
// Root exit and inherited-pipe closure are different observations.
|
|
// Retain a completed failure before drain or cleanup can be interrupted,
|
|
// while cancellation already present at exit keeps its precedence.
|
|
if (
|
|
event.type === "exit" &&
|
|
failure === undefined &&
|
|
!diagnosticTruncated &&
|
|
firmwarePhaseInterruption(operation, signal, context.deadline) ===
|
|
undefined
|
|
)
|
|
completedFailureObserved = isFailedExit(event.code);
|
|
},
|
|
},
|
|
);
|
|
const checkDiagnostics = () => {
|
|
if (diagnosticTruncated) {
|
|
const snapshot = supervisor.snapshot();
|
|
throw new AnalysisOutputError(
|
|
operation,
|
|
`Tool diagnostics exceeded the ${FIRMWARE_LIMITS.diagnosticBytes}-byte capture budget`,
|
|
{
|
|
capturedOutput: {
|
|
stdout: snapshot.stdout.text,
|
|
stderr: snapshot.stderr.text,
|
|
truncated: true,
|
|
},
|
|
userMessage: `Firmware diagnostics exceeded the ${String(FIRMWARE_LIMITS.diagnosticBytes)}-byte capture allowance. This release has no runtime override.`,
|
|
remediationAction: firmwareLimitRecovery(
|
|
`The firmware diagnostic capture allowance is ${String(FIRMWARE_LIMITS.diagnosticBytes)} bytes`,
|
|
),
|
|
},
|
|
);
|
|
}
|
|
};
|
|
try {
|
|
while (!(await supervisor.waitForOutputClose(100))) {
|
|
checkDiagnostics();
|
|
checkInterruption();
|
|
if (context.outputBudget !== undefined)
|
|
await inventoryFirmwareOutput(
|
|
context.outputBudget.root,
|
|
context.outputBudget.bytes,
|
|
context.outputBudget.entries,
|
|
fileSizeBytes,
|
|
operation,
|
|
signal,
|
|
context.deadline,
|
|
);
|
|
}
|
|
checkDiagnostics();
|
|
checkInterruption();
|
|
} catch (cause: unknown) {
|
|
failure ??= classifyProviderFailure(cause, dialect);
|
|
}
|
|
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();
|
|
// Capture diagnostics only after owned cleanup has drained the inherited pipes.
|
|
if (completedFailureObserved) failure = completedFailure(snapshot);
|
|
if (stopped.status === "incomplete") {
|
|
context.retainCleanup(supervisor);
|
|
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: capturedFirmwareOutput(snapshot),
|
|
},
|
|
);
|
|
}
|
|
if (failure !== undefined) throw failure;
|
|
return {
|
|
stdout: snapshot.stdout,
|
|
stderr: snapshot.stderr,
|
|
exit_code: snapshot.exitCode,
|
|
signal: snapshot.signal ?? null,
|
|
command: context.command,
|
|
args: [...context.args],
|
|
resource_limiter: context.limiter,
|
|
};
|
|
};
|
|
|
|
/**
|
|
* Consume the report a completed command was asked to write. A successful exit
|
|
* status is not analysis Evidence by itself: an absent, empty or malformed report
|
|
* fails with the observed report state and command facts, without retrying or
|
|
* substituting an empty result.
|
|
*/
|
|
export const readFirmwareCommandReport = async (context: {
|
|
path: string;
|
|
engine: string;
|
|
operation: string;
|
|
execution: Awaited<ReturnType<typeof runFirmwareCommand>>;
|
|
files: FirmwareFileAccess;
|
|
signal?: AbortSignal;
|
|
deadline?: FirmwareDeadline;
|
|
}): Promise<unknown> => {
|
|
try {
|
|
return await context.files.report(
|
|
context.path,
|
|
context.operation,
|
|
context.signal,
|
|
);
|
|
} catch (cause: unknown) {
|
|
if (cause instanceof ArtifactReaderFailure) {
|
|
const { engine, operation, execution, deadline } = context;
|
|
const signal = context.signal ?? deadline?.signal;
|
|
const failure = classifyProviderFailure(
|
|
cause,
|
|
firmwareFailureDialect({
|
|
engine,
|
|
operation,
|
|
phase:
|
|
deadline === undefined || signal === undefined
|
|
? undefined
|
|
: { signal, deadline },
|
|
}),
|
|
);
|
|
if (cause.partialObservation !== undefined)
|
|
failure.retainPartialObservation(cause.partialObservation);
|
|
throw failure.retainCapturedOutput({
|
|
stdout: execution.stdout.text,
|
|
stderr: execution.stderr.text,
|
|
stdout_bytes: execution.stdout.bytes,
|
|
stderr_bytes: execution.stderr.bytes,
|
|
exit_code: execution.exit_code ?? null,
|
|
signal: execution.signal,
|
|
truncated: false,
|
|
});
|
|
}
|
|
const { engine, operation, execution } = context;
|
|
const reportFailure =
|
|
cause instanceof AnalysisOutputError
|
|
? cause.reason
|
|
: `Report could not be read: ${cause instanceof Error ? cause.message : String(cause)}`;
|
|
const diagnostics = {
|
|
...(cause instanceof AnalysisOutputError ? cause.diagnostics : {}),
|
|
report_path: context.path,
|
|
report_failure: reportFailure,
|
|
command: execution.command,
|
|
args: execution.args,
|
|
resource_limiter: execution.resource_limiter,
|
|
exit_code: execution.exit_code ?? null,
|
|
signal: execution.signal,
|
|
stdout: execution.stdout.text,
|
|
stderr: execution.stderr.text,
|
|
stdout_bytes: execution.stdout.bytes,
|
|
stderr_bytes: execution.stderr.bytes,
|
|
};
|
|
if (execution.exit_code === 1)
|
|
throw new ProviderAdapterError(engine, operation, {
|
|
cause,
|
|
diagnostics: {
|
|
reason:
|
|
"Tool exited 1 without a usable analysis report; inspect stderr for startup, sandbox or dependency failures",
|
|
...diagnostics,
|
|
},
|
|
});
|
|
const oversized =
|
|
cause instanceof AnalysisOutputError &&
|
|
cause.diagnostics?.report_state === "oversized";
|
|
const reportFacts =
|
|
"Review diagnostics.report_state, the exit status and captured stdout/stderr. REA did not retry or substitute an empty result. diagnostics.command and diagnostics.args record what ran; their workspace paths are REA-private and removed after the attempt, so they cannot be replayed as-is.";
|
|
const reportAllowance = firmwareLimitRecovery(
|
|
`The firmware report allowance is ${String(FIRMWARE_LIMITS.reportBytes)} bytes`,
|
|
);
|
|
const observed = `${engine} exited successfully but left no usable report (${reportFailure}), so ${operation} produced no Evidence. A successful exit status is not an empty or complete result.`;
|
|
throw new AnalysisOutputError(
|
|
operation,
|
|
`${engine} exited ${String(execution.exit_code)} without a usable report: ${reportFailure}`,
|
|
{
|
|
cause,
|
|
diagnostics,
|
|
userMessage: oversized ? `${observed} ${reportAllowance}` : observed,
|
|
remediationAction: oversized
|
|
? `${reportFacts} ${reportAllowance} \`rea doctor\` checks configuration only and cannot recover this report.`
|
|
: `${reportFacts} Rerun the same REA request to check whether this is intermittent; each attempt uses a fresh workspace. If it recurs, copy the selected input bytes into a new directory and run diagnostics.command with the same flags, replacing every private path with your copy and a new report path, under the documented firmware resource limits; confirm that it writes the requested report. \`rea doctor\` checks configuration only and cannot recover this report.`,
|
|
},
|
|
);
|
|
}
|
|
};
|