Files
reverse-engineering-anything/src/domain/analysisErrorProjection.test.ts
T
0f6b330cb6 refactor(ghidra): classify Ghidra file failures through the shared provider classifier (#10873)
* 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.

* refactor(captures): classify TShark, sigrok and pcap failures through the shared provider classifier

TsharkCaptureProvider and SigrokRecordingProvider replace #failure with a dialect, and PcapProvider replaces analysisFailure and the tool-identity classifier. ArtifactAnalysisResources exposes its command context and a readCleanupFailure composer so the readCleanup hook keeps each provider's cleanup report shape.

* refactor(jeb): classify JEB failures through the shared provider classifier

JEB's raw MCP failures go through classifyProviderFailure with a JEB dialect;
a typed attribution step reports a shared phase's failure under the REA
operation. Each MCP phase deadline now reports its own interruption when it
aborts, deciding a cancellation's owner from the caller's own signal instead
of comparing abort reasons. A refusal carrying the JVM's OutOfMemoryError
report becomes a resource constraint naming JEB's Java heap.

* fix(jeb): advise the JVM limit that governs the reported memory area

* refactor(ghidra): classify Ghidra failures through the shared provider classifier

PSP extension inspection reports through classifyProviderFailure with a
Ghidra dialect. The startup deadline decides at abort time whether the shared
startup owner closed it, so Ghidra and Hopper no longer compare the abort
reason with the owner's sentinel, and Ghidra's startup no longer compares a
producer cancellation's reason with the deadline's. Three helpers that only
construct one error kind now name that kind instead of AnalysisError.

* refactor(hopper): classify original-source read failures through the shared provider classifier (#10838)

* test(ghidra): pin the aborted startup deadline over a producer cancellation

* refactor(kuna): classify Kuna failures through the shared provider classifier

Session operations, the workspace copy and the project export report raw
failures through classifyProviderFailure with Kuna dialects; the copy and
export keep their cleanup report shapes through the readCleanup hook.

* refactor(adb): report a pulled file's digest failure from its own type

* refactor(sqlite): classify worker-reply read failures through the shared provider classifier

* refactor(ida): classify IDA operation failures through the shared provider classifier

* refactor(process): let artifact-resource consumers classify through the shared provider classifier (#10867)

* test(providers): pin attribution of a cleanup-failed read's typed primary

* refactor(sqlite): classify database failures through the shared provider classifier

* refactor(providers): keep a cancelled read's partial observation and provider diagnostics

* refactor(ghidra): classify Ghidra file failures through the shared provider classifier

* refactor(ghidra): classify Ghidra failures through the shared provider classifier (#10836)

* refactor(ghidra): classify Ghidra failures through the shared provider classifier

PSP extension inspection reports through classifyProviderFailure with a
Ghidra dialect. The startup deadline decides at abort time whether the shared
startup owner closed it, so Ghidra and Hopper no longer compare the abort
reason with the owner's sentinel, and Ghidra's startup no longer compares a
producer cancellation's reason with the deadline's. Three helpers that only
construct one error kind now name that kind instead of AnalysisError.

* refactor(hopper): classify original-source read failures through the shared provider classifier (#10838)

* test(ghidra): pin the aborted startup deadline over a producer cancellation

* refactor(kuna): classify Kuna failures through the shared provider classifier (#10843)

Session operations, the workspace copy and the project export report raw
failures through classifyProviderFailure with Kuna dialects; the copy and
export keep their cleanup report shapes through the readCleanup hook.

* chore(guards): shrink the cancellation construction baseline after merging the base

* refactor(kuna): report a retained installation read's cleanup from its reader type (#10877)

* refactor(kuna): report a retained installation read's cleanup from its reader type

* refactor(process): share the JVM option that governs each reported memory area (#10881)

* refactor(ida): classify IDA operation failures through the shared provider classifier (#10859)

* refactor(ida): classify IDA operation failures through the shared provider classifier

* refactor(process): let artifact-resource consumers classify through the shared provider classifier (#10867)

* test(providers): pin attribution of a cleanup-failed read's typed primary

* fix(javascript): read analysis workers' V8 heap exhaustion from streamed output, not retained stderr (#10890)

* refactor(kuna): report a retained installation read's cleanup from its reader type

* refactor(process): share the JVM option that governs each reported memory area (#10881)

* fix(javascript): read analysis workers' V8 heap exhaustion from streamed output, not retained stderr

* test(browser): pin web-bundle heap exhaustion reported past the retained stderr budget

* refactor(process): recognise a signal's own abort through one owner (#10896)

* refactor(process): recognise a signal's own abort through one owner

* chore(verify): lower the direct cancellation construction baselines the stack's migrations removed

* refactor(sqlite): read the owned worker's heap ceiling from one limit (#10907)

* refactor(sqlite): classify the owned worker's outcomes through the shared provider classifier (#10912)

* refactor(process): call the signal abort owner directly and match NaN reasons

* chore(verify): lower the SQLite cancellation construction baseline the worker migration removed

* feat(rizin): report a shell refusal as a typed refusal record beside rejected completion (#10925)

* refactor(kuna): report installation inspection failures through one Kuna dialect (#10913)

* refactor(errors): let Hopper errors carry their own presentation so the domain presenter no longer imports them (#10944)

* refactor(process): recognise the remaining command aborts through the signal owner (#10906)

* refactor(process): recognise the remaining command aborts through the signal owner

* test(process): cover a NaN abort reason on both execFileOutput cancellation paths

* fix(process): keep a successful execFile callback when the caller aborts with a null reason

* test(process): abort execFileOutput while a released descendant still holds its pipes

* test(process): join the late-abort command in finally so a failed readiness check still releases its descendant

* refactor(errors): move Hopper errors to src/hopper and drop their tags from the domain union (#10964)

* refactor(errors): move Hopper errors to src/hopper and drop their tags from the domain union

* refactor(process): recognise SQLite, WABT and Flutter aborts through the signal owner (#10975)

* refactor(kuna): report doctor installation failures through the shared Kuna installation dialect (#10978)

* refactor(process): recognise SQLite, WABT and Flutter aborts through the signal owner

* refactor(kuna): report doctor installation failures through the shared Kuna installation dialect

* fix(kuna): keep installation facts on a composed read-and-close failure

* style(hopper): format the moved Hopper lease and cache publisher fixture

* fix(sqlite): count only the caller's own abort as a SQLite inspection cancellation (#11018)

* fix(ida): count only the caller's own abort of the busy-health pause as cancellation (#11013)

* test(kuna): assert the cleanup-incomplete doctor check by code and facts, not its wording

* refactor(errors): report an unrecognised command outcome with the outcome the classifier examined (#11003)

* refactor(errors): report an unrecognised command outcome with the outcome the classifier examined

* fix(errors): add a dialect's unclassified diagnostics to the context's instead of replacing them

* fix(evm): count only the caller's own abort as an EVMole inspection cancellation (#11011)

* fix(server): report only startup's own abort as the caller's HTTP listen cancellation (#11017)

* refactor(errors): classify domain errors from one table and generate the error catalogue from it (#11060)

docs(errors): generate the error catalogue from the classification tables

* refactor(errors): report unrecognised pcap, WABT and producer-command outcomes with the examined outcome (#11044)

* refactor(errors): report unrecognised pcap, WABT and producer-command outcomes with the examined outcome

* fix(pcap): keep the packet summary when only the DNS wire pass reports an unrecognised outcome

* refactor(ida): require the host platform for IDA MCP connections and snapshot the child environment with it (#11073)

* refactor(verify): count plain throws in parser-folder process-lifecycle owners (#11071)

JadxWorkspaceRoot and PwntoolsDecoder are exempt from parser-plain-throw because their plain throws report a private helper's process failures. The exemption left later throws in those files unchecked. A counted lifecycle-plain-throw guard now records their current throws (4 and 1); the baseline may only shrink, so a parse fault or defect added there must use ParseFailureError or invariantViolation.

* fix(native): report a signature inspection defect as an adapter failure (#11069)

withSignatureTarget wrapped every throw from the inspection callback as
AnalysisOutputError("Native output parsing failed"), so an
InternalInvariantError (a REA defect) was reported as malformed native
command output. A defect now leaves the owned work, so runOwned releases
the private signature copy first and reports the defect as the native
provider's adapter failure. If releasing the copy also fails, the defect
stays primary and the cleanup failure joins it through the shared cleanup
composition (analysisErrorWithCleanupFailure + bindCleanupDependencies).

* refactor(verify): give the javascript verifiers' roots to VerifierFixture (#11068)

* refactor(verify): give the javascript verifiers' roots to VerifierFixture

VerifierFixture.retain(reason) keeps a root that an owned command whose
cleanup is incomplete may still use, replacing each verifier's local
retain flag and cleanup closure.

* refactor(verify): give the Ghidra COM, DOS, 6502, NativeAOT and raw verifiers' workspaces to VerifierFixture (#11070)

* refactor(verify): give the Ghidra COM, DOS, 6502, NativeAOT and raw verifiers' workspaces to VerifierFixture

* refactor(verify): keep the Ghidra decompiler-failure, decompile-timeout and no-return workspaces through VerifierFixture until owned cleanup is verified (#11077)

* feat(artifacts): surface the named integrity check in public artifact errors (#11052)

* feat(artifacts): surface the named integrity check in public artifact errors

ArtifactOperationError now carries integrityCheck from the reader failure
and projects it as details.integrity_check, including with artifact
integrity details. Rebuild sites copied a different subset of reader facts
each (ProcessCli.artifactFailureFacts, withCleanup, desktop, file-operation
cleanup, resource export, DMG inventory, safe output tree); they now spread
ArtifactReaderFailure.primaryFacts(), so a new reader fact has one owner.
ArtifactIntegrityCheck moves to the domain beside ArtifactAdmissionLimit.

* test(artifacts): check rebuilt cleanup failures keep the named integrity check

* refactor(adb): report a pulled file's digest failure from its own type (#10848)

* 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.

* refactor(captures): classify TShark, sigrok and pcap failures through the shared provider classifier

TsharkCaptureProvider and SigrokRecordingProvider replace #failure with a dialect, and PcapProvider replaces analysisFailure and the tool-identity classifier. ArtifactAnalysisResources exposes its command context and a readCleanupFailure composer so the readCleanup hook keeps each provider's cleanup report shape.

* refactor(jeb): classify JEB failures through the shared provider classifier

JEB's raw MCP failures go through classifyProviderFailure with a JEB dialect;
a typed attribution step reports a shared phase's failure under the REA
operation. Each MCP phase deadline now reports its own interruption when it
aborts, deciding a cancellation's owner from the caller's own signal instead
of comparing abort reasons. A refusal carrying the JVM's OutOfMemoryError
report becomes a resource constraint naming JEB's Java heap.

* fix(jeb): advise the JVM limit that governs the reported memory area

* refactor(ghidra): classify Ghidra failures through the shared provider classifier

PSP extension inspection reports through classifyProviderFailure with a
Ghidra dialect. The startup deadline decides at abort time whether the shared
startup owner closed it, so Ghidra and Hopper no longer compare the abort
reason with the owner's sentinel, and Ghidra's startup no longer compares a
producer cancellation's reason with the deadline's. Three helpers that only
construct one error kind now name that kind instead of AnalysisError.

* refactor(hopper): classify original-source read failures through the shared provider classifier (#10838)

* test(ghidra): pin the aborted startup deadline over a producer cancellation

* refactor(kuna): classify Kuna failures through the shared provider classifier

Session operations, the workspace copy and the project export report raw
failures through classifyProviderFailure with Kuna dialects; the copy and
export keep their cleanup report shapes through the readCleanup hook.

* refactor(adb): report a pulled file's digest failure from its own type

* refactor(ghidra): classify Ghidra failures through the shared provider classifier (#10836)

* refactor(ghidra): classify Ghidra failures through the shared provider classifier

PSP extension inspection reports through classifyProviderFailure with a
Ghidra dialect. The startup deadline decides at abort time whether the shared
startup owner closed it, so Ghidra and Hopper no longer compare the abort
reason with the owner's sentinel, and Ghidra's startup no longer compares a
producer cancellation's reason with the deadline's. Three helpers that only
construct one error kind now name that kind instead of AnalysisError.

* refactor(hopper): classify original-source read failures through the shared provider classifier (#10838)

* test(ghidra): pin the aborted startup deadline over a producer cancellation

* refactor(kuna): classify Kuna failures through the shared provider classifier (#10843)

Session operations, the workspace copy and the project export report raw
failures through classifyProviderFailure with Kuna dialects; the copy and
export keep their cleanup report shapes through the readCleanup hook.

* chore(guards): shrink the cancellation construction baseline after merging the base

* refactor(ida): let IDA close failures read the session's later close (#10811)

* refactor(errors): read cleanup completion from dependencies instead of pushing it to dependents

AnalysisError.cleanupIncomplete becomes a getter over the error's own unresolved state and its bound dependencies. The WeakRef dependents graph and resolveCleanup's push propagation are removed, and subclasses mark their initial state through markCleanupIncomplete instead of overriding a public mutable field.

* fix(errors): settle bound dependencies before binding more

A composite whose dependencies had released but whose status was never read
stayed incomplete when a later dependency was bound.

* refactor(errors): let errors read a lease group's release instead of resolving them (#10759)

AnalysisCleanupLeaseGroup no longer calls resolveCleanup() on its error.
The error holds the group as a release claim and reads cleanupReleased when
asked, so completion follows the lease owner without a push.

* chore(verify): count resolveCleanup and bindCleanupDependencies calls so they only shrink (#10763)

* refactor(errors): let errors read a lease group's release instead of resolving them

AnalysisCleanupLeaseGroup no longer calls resolveCleanup() on its error.
The error holds the group as a release claim and reads cleanupReleased when
asked, so completion follows the lease owner without a push.

* chore(verify): count resolveCleanup and bindCleanupDependencies calls so they only shrink

* refactor(process): let worker cleanup errors read their root epoch's release

OwnedWorkerRuntime's root epoch is now an AnalysisCleanupReleaseClaim. Errors bound to it read its release when asked instead of the epoch pushing resolveCleanup() through weak references, and a runtime without a retained root binds an already-released owner. Removes the OwnedWorkerCleanupFailure structural type and four resolveCleanup() pushes; the counted baseline shrinks accordingly.

* refactor(pcap): let pcap cleanup errors read command and snapshot release (#10792)

Retained pcap commands, retained snapshot failures and snapshot completion descriptors now own their release and errors read it: commands and snapshot failures implement AnalysisCleanupReleaseClaim, and a failed completion-descriptor close is retried through an AnalysisCleanupLease bound to its error. Removes four resolveCleanup() pushes; the counted baseline shrinks accordingly.

* refactor(process): let Darwin helper cleanup errors read their owner's release

Darwin helper cache and run-token reader root cleanup now record an AnalysisCleanupRelease that every failure reports; a successful retry confirms it. Replaces the first-failure anchor that later failures depended on and the resolveCleanup() push. Removes two resolveCleanup() and two bindCleanupDependencies() calls; both counted baselines shrink.

* refactor(ghidra): let Ghidra cleanup errors read the client's and checkpoint's release

GhidraClient and GhidraCheckpoint bind each cleanup failure to an AnalysisCleanupRelease and confirm it when a later close or retry releases everything, instead of keeping a set of failures and pushing resolveCleanup() to each. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(process): let debugger session cleanup errors read a confirmed stop

OwnedDebuggerSessionRegistry binds each retained gdb or rizin cleanup failure to the session's AnalysisCleanupRelease and confirms it when a stop is confirmed, keeping the latest failure for retry reporting, instead of pushing resolveCleanup() to a set of failures. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(process): drop the debugger registry's unused closeOperation option

Returning the latest retained failure removed the last reader of closeOperation; remove the option and the values gdb and rizin supplied.

* refactor(server): let environment shutdown errors read a successful close

serveEnvironment binds each shutdown failure to an AnalysisCleanupRelease that a later successful close confirms, instead of pushing resolveCleanup() to a set of failures. The state-file retry test now also requires the earlier report to read the release. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(desktop): release retained screen-judge cleanup through its lease

Each retained judge or screenshot cleanup owner is wrapped in an AnalysisCleanupLease bound to its failure; close() releases the lease, which records the release the failure reads, instead of closing the owner and pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(ida): let IDA close failures read the session's later close

IdaSessionClient's close failure binds an owner that is both its resource owner and its release claim, read from the client's closed state, instead of keeping weak references and pushing resolveCleanup() after a successful retry. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(javascript): let source-map codec cleanup errors read a later close (#10814)

* refactor(javascript): let source-map codec cleanup errors read a later close

OwnedCodec binds each close failure to an AnalysisCleanupRelease that a later successful close confirms, replacing the first-failure anchor that later failures depended on and the resolveCleanup() push. Removes one resolveCleanup() and one bindCleanupDependencies() call; both counted baselines shrink.

* refactor(cutter): let pending Cutter command errors read the completion receipt (#10815)

* refactor(cutter): let pending Cutter command errors read the completion receipt

Each pending Cutter command keeps an AnalysisCleanupRelease bound to its timeout failure; the producer's terminal completion receipt confirms it instead of pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(application): let provider candidate cleanup errors read the candidate's close (#10817)

* refactor(application): let provider candidate cleanup errors read the candidate's close

AnalysisProviderRegistry keeps one AnalysisCleanupRelease per candidate whose resource close is unconfirmed; failures bind to it and a later confirmed close confirms it, instead of pushing resolveCleanup() to a set of failures. Removes one resolveCleanup() call; the counted baseline shrinks.

* fix(errors): bind a cleanup release claim to an error at most once

AnalysisError kept release claims in an array, so a provider whose retried close returned the same error bound the same claim again on every retry and each cleanupIncomplete read scanned the duplicates. Keep the claims in a set.

* refactor(application): let reverse-tool cleanup errors read a verified stop (#10819)

* refactor(application): let reverse-tool cleanup errors read a verified stop

Each retained provider process group in ReverseEngineeringService keeps an AnalysisCleanupRelease; its command and retry failures bind to it and a later verified stop confirms it, instead of collecting failures and pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(sqlite): let SQLite worker and root cleanup errors read their release (#10821)

Each retained SQLite snapshot cleanup records an AnalysisCleanupRelease for its worker and for its runtime root; the resource failures bind to them and a verified stop or root removal confirms them, instead of pushing resolveCleanup(). Composite failures keep reading those resource failures. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(application): let JADX and session close failures read their owner's release (#10854)

* refactor(android): let JADX cleanup errors read their retained cleanup's release

Each retained JADX cleanup records an AnalysisCleanupRelease for the admission failure's descriptor owners and one for the whole retained cleanup. The admission failure and every error the cleanup reports bind to them, and a confirmed close confirms them, instead of pushing resolveCleanup() through WeakRefs to reported errors. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(application): let session close failures read the client's later close

A retained session cleanup records an AnalysisCleanupRelease; unowned cleanup failures the client's close reported bind to it and the successful close confirms it, instead of the session collecting them and pushing resolveCleanup(). Failures that already follow their own owner keep reading it. Adds a regression for an unowned close failure. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(browser): parse Runtime and Debugger events once by registered schemas (#10742)

* refactor(browser): parse frame lifecycle events once by a registered event schema

CdpConnection admits each event through protocol/CdpEvents.ts, which parses
the five Page frame lifecycle events once into identity facts plus a frame
URL observation, like a frame-tree node. Screenshot, page capture, the
observation timeline, WebMCP, Electron inspection and the execution window
read those facts instead of re-parsing the raw payload; CdpFrameFacts no
longer carries the raw source record. Playwright CDP session subscriptions
name an event from Playwright's protocol table, and an architecture guard
counts the remaining raw event payload reads so they can only shrink.

* refactor(browser): parse Runtime and Debugger events once by registered schemas

Register Debugger.scriptParsed, Debugger.scriptFailedToParse,
Runtime.executionContextCreated, Runtime.executionContextDestroyed and
Runtime.consoleAPICalled. Script and context payloads carry both the
tolerant facts passive capture uses and the active runtime's strict
declaration, derived from one parse, plus the declaration's byte size for
the runtime retention budget. Page capture, Electron script capture, the
V8 Inspector provider and the runtime source inventory now read the
registered payload. The cdp-raw-event-params baseline drops from 20 to 7.

* refactor(browser): admit transport events through the registered-event owner

Remove the unused cdpFrameUrl wrapper; its fragment cases now exercise
observeCdpFrameUrl. Add a connection-level test that two subscribers share
one parsed payload and the raw params.

* fix(browser): report an unserializable event declaration's size instead of throwing

JSON.stringify can throw on a declaration JSON.parse accepted (nesting
deeper than the serializer's stack). The registry sized script and context
declarations inside the connection's WebSocket callback, so such an event
escaped as an uncaught exception. The size is now a Result; the runtime
source inventory raises the failure inside its own catch, as before.

* refactor(browser): parse Network events once by registered schemas (#10743)

* refactor(browser): parse Network events once by registered schemas

Register Network.requestWillBeSent, responseReceived, loadingFinished,
loadingFailed, webSocketCreated and webSocketFrameSent/Received. The
request payload carries the tolerant facts page capture and the timeline
read plus the active runtime's strict declaration. Page capture's network
and WebSocket handlers, the timeline's request tracking and the runtime
request inventory now read the registered payload. The
cdp-raw-event-params baseline drops from 7 to 5.

* refactor(browser): drop payload helpers the capture handlers no longer use

* refactor(browser): read every CDP event payload through the registry (#10745)

* refactor(browser): read every CDP event payload through the registry

Register Target.attachedToTarget, Target.detachedFromTarget,
Page.lifecycleEvent and WebMCP.toolsAdded/toolsRemoved, and carry a
requested navigation's reason and a commit's transition type in the
frame-event payload. The timeline no longer threads raw params into its
entries: each entry receives its timestamp, frame and loader identity
explicitly. WebMCP discovery, the service-worker policy blocker and the
target-event matcher read the registered payload. With no raw reads left,
the cdp-raw-event-params guard is enforced at zero instead of counted.

* refactor(browser): drop raw payload helpers the timeline and worker blocker no longer use

* refactor(browser): type Playwright CDP session events by the registry (#10751)

PlaywrightCdpSession.on subscribes only to registered events and hands
the listener the payload parsed by its registered schema, returning the
unsubscribe function. Private storage seeding reads registered payloads,
including the events of non-flat child sessions, and applies its strict
seeding policy to the parsed facts. Its local attach, detach, nested
message and pause schemas and the storage-only script/context schemas are
removed; Debugger.paused, Runtime.executionContextsCleared and
Target.receivedMessageFromTarget join the registry.

* test(browser): admit fake policy events through the event registry

The service-worker policy now reads event.registered, but the PlaywrightScenarioSession fake connection delivered raw events, so three detached-target tests never reached the policy. The fake now admits each event with receiveCdpEvent as CdpConnection does.

* fix(browser): fail the CDP session closed when an event listener throws (#10758)

* fix(browser): fail the CDP session closed when an event listener throws

An exception from a CDP event subscriber escaped CdpTransportCore's socket message callback uncaught (for example the service-worker blocker's protocol_error on a Target event without a sessionId). The transport now stops delivery, fails the connection as a protocol error whose cause is the listener's exception, rejects pending and later commands with it, and notifies protocol-failure subscribers. The Playwright CDP session relay applies the same rule to its event listeners.

* fix(browser): report a failed service-worker policy connection at the next policy check

The policy's event listener rejects a malformed Target event, which now fails its connection. With no policy command pending, nothing reported it and later iframe targets went unprotected. The policy records its connection's protocol failure and assertBlocked, run before each scenario step, rethrows it.

* fix(browser): keep cleanup commands available after a listener failure

A listener failure no longer marks the wire as broken. The transport still rejects pending commands, notifies protocol-failure subscribers, stops delivering events and refuses reuse, but it keeps reading replies and admits commands sent in cleanup grace. The service-worker policy can then remove its init scripts, restore the main realm, detach and release its socket. Wire-level protocol errors still refuse every later command. The PlaywrightScenarioSession policy fake gains onProtocolFailure, which the policy now subscribes to.

* refactor(browser): keep raw CDP event payloads out of the received event (#10764)

* refactor(browser): keep raw CDP event payloads out of the received event

CdpReceivedEvent and CdpTransportEvent no longer carry params: receiveCdpEvent hands the raw payload only to the registered schema, so a subscriber cannot read it by property access, destructuring or computed keys. This supersedes the event.params text guard in architecture-guards, which is removed.

* refactor(browser): read registered event payloads in the JavaScript verifiers

The runtime, storage and URL-userinfo verifiers subscribe to CdpConnection, which no longer hands subscribers raw params. They now read event.registered. A test scans every scripts/ onEvent callback for raw payload reads, since the TypeScript check does not cover them. The storage verifier's pause trace records a malformed pause instead of the unregistered reason member.

* refactor(browser): track the timeline's main frame with the document tracker (#10779)

TimelineCapture kept its own mutable main frame id and replaced it on a root replacement. It now holds the CdpDocumentTracker that CdpTargetSession owns and observes the replacement document through it; every main-frame check (lifecycle, navigation, document request, redirect) reads the tracker's current frame. A characterization test pins that the replaced root's lifecycle events are no longer recorded.

* refactor(browser): select CDP events only by their registered name (#10829)

CdpReceivedEvent carried the wire method as a plain string, so a subscriber
could compare it with a misspelt or unregistered name and the check compiled
but never matched. Three owners selected Inspector.targetCrashed, an
unregistered event, that way.

Register Inspector.targetCrashed and drop the wire method from the received
event. Subscribers select events by registered.method, whose type is the
registered event names. The capture coverage start keeps reading the
wire domain, now the event's domain field.

* fix(browser): retire a policy child session that CDP reports gone

After a listener failure the connection stops delivering events, so an
iframe's Target.detachedFromTarget never retires its policy target. Cleanup
then sent Page.removeScriptToEvaluateOnNewDocument to the dead session,
kept the stale child, and every retry failed before detaching the root.

The service-worker policy owner now treats CDP's session-not-found
rejection as proof that the child is gone and retires it. The classifier
moves from CdpTargetSession to CdpCommandRejection, its owner, and the
target-session detach path uses the same one.

* refactor(browser): route target events through one session owner (#10835)

* refactor(browser): route target events through one session owner

Page capture, WebMCP discovery, screenshot capture and the runtime sources
each compared the envelope session ID themselves, while the observation
window and execution collection used cdpTargetEventMatches, which also
routes the root Target.detachedFromTarget that names the target's session.

onCdpTargetEvent in CdpTargetEvents.ts now subscribes every target consumer
with that one rule; the matcher is private and the per-subscriber
comparisons are removed. Electron inspection keeps its own filter while
its capture isolation awaits a maintainer decision.

* fix(browser): report WebMCP subframe tools whose document is unverified (#10839)

* fix(browser): report WebMCP subframe tools whose document is unverified

A committed subframe navigation kept the frame's tools silently when CDP
reported no loader at the same URL, and removed them on any URL change even
when the loader proved the same document.

Each frame now carries a CdpDocumentTracker, the session's document
identity owner. Only a proven change removes the frame's tools. An unknown
comparison keeps them visible, marks webmcp_tools attach-limited and names
the frames whose document identity could not be established.

* test(browser): prove an unverified live subframe limits WebMCP coverage

* fix(browser): key a WebMCP registration by its frame and tool name

A subframe tool kept across a committed navigation that changed the URL
but not the loader was stored under a key built from the old URL, so a
later toolsAdded for the same frame and name added a second entry.
Registrations are now keyed by frame and name; tool_key still records the
registering frame URL.

* test(browser): deliver fake CDP events through the transport's admission (#10840)

Event fakes each rebuilt the received event: CdpAgentHints typed its
listeners as raw wire events behind an unknown cast, and the Electron,
scenario-session and routing tests each wrapped receiveCdpEvent by hand.

fakeCdpEvents (tests/fixtures) is a CdpConnection.onEvent fake whose emit
admits each raw event with receiveCdpEvent and the wire byte count, so a
change to the received event shape fails at the fake instead of silently
not exercising subscribers.

* refactor(browser): own the selected page generation in one target document tracker (#10860)

* refactor(browser): own the selected page generation in one target document tracker

Page capture, screenshot, the observation window, the runtime session and
the execution window each built a document tracker or rule of their own
from root-frame navigation events. CdpTargetDocument now follows the target
session's root-frame events and the frame-tree replies its consumers read,
classifies root identity once, and reports each navigation to consumers
that decide only what it means for their evidence.

* fix(browser): report a lost scenario policy connection before the next step (#10864)

* fix(browser): report a lost scenario policy connection before the next step

The service-worker policy recorded only protocol failures. When its CDP
socket closed or its page session detached, later documents lost the
blocking script, but the scenario learned of it only when a frame check
found an unprotected realm. The owner now records the disconnect or
detach when CDP reports it; the next policy check and the next step's
action report it first.

* fix(browser): refuse an unregistered CDP command before it reaches the browser (#10868)

JavaScript verifiers can name any command, and the send owners refused an
unregistered one only when its reply arrived, after the browser had acted
on it. CdpConnection and the Playwright session now refuse the name before
sending, and the Playwright session refuses an unregistered event name
instead of subscribing to events no listener receives. The verifier text
scan stays as an early warning and documents what it cannot see.

* fix(browser): keep a proven root change and the loaderless selection's uncertainty

Two review findings on the target document owner. A root event naming
another frame with a malformed loader set `changed` but was announced as
unidentified, so the execution window failed with protocol_error and
dropped what it had collected; the owner now announces it as the proven
change it is. The runtime session compared each frame-tree reply with the
tracker's current document, which can learn a loader from an event, so a
loaderless selection followed by an event and a reply with that loader
compared as same; it now compares the reply with the selected document
through the owner, and reports target_changed as before.

* test(browser): refuse the next scenario step after the policy session detaches

* refactor(browser): read WebMCP document identity from the target document owner (#10884)

* refactor(browser): read WebMCP document identity from the target document owner

WebMCP discovery compared the first and last frame-tree roots itself and
kept a document tracker per subframe. CdpTargetDocument now follows the
selected root and each committed subframe for it: the final frame tree
feeds the owner, a root change proven by a navigation event during
discovery is target_changed as in page capture, and a subframe whose
committed document changed loses its tools. A subframe navigation without
a loader still keeps the tools and reports them as unverified.

* fix(browser): start a subframe first seen within its document with an unknown loader

A subframe absent from the initial frame tree and first seen through Page.navigatedWithinDocument had no document tracker, so a later commit started a fresh one and the tools it registered meanwhile lost the unverified-document limitation. The owner now starts such a subframe with an unknown loader.

* fix(browser): refuse a verifier's unregistered CDP event name at subscription (#10885)

JavaScript verifiers subscribed to every event with CdpConnection.onEvent
and compared registered.method with a string literal. A misspelt or
unregistered name never matched and the verifier waited until its timeout.
CdpConnection.onRegisteredEvent now takes one event name, refuses an
unregistered one before subscribing (the same registry check the Playwright
session applies), and hands the listener only that event's registered
parse. The verifiers subscribe only through it, and the evaluation test
rejects a raw onEvent subscription in scripts.

* fix(browser): keep subframe documents by frame and loader without their URLs

* refactor(domain): give strict UTF-8 decoding one owner with an explicit BOM policy (#10728)

* refactor(domain): give strict UTF-8 decoding one owner with an explicit BOM policy

* fix(domain): keep the leading-BOM behaviour every migrated UTF-8 decoder had

* refactor(domain): read the domain layer's strict UTF-8 through the BOM-policy owner (#10803)

Twelve domain decoders built their own fatal TextDecoder with ignoreBOM: true. They now use strictUtf8Decoder("preserve"), which keeps that behaviour: each reads bytes where a leading U+FEFF is content (binary-format names and fields, JSON and XML read byte-for-byte, recorded bodies, registry seeds whose kept bytes are re-emitted). The counted baseline drops from 74 to 62.

* refactor(artifacts): read artifact readers' strict UTF-8 through the BOM-policy owner (#10871)

Fourteen artifact reader modules (17 sites) built their own fatal TextDecoder. They now take it from strictUtf8Decoder with the policy each had: every one kept a leading BOM (ignoreBOM: true), so they use "preserve"; JavaScriptArtifactFiles keeps it for JavaScript and HTML entries and strips it otherwise, as before. The strict-utf8-decoder baseline drops those 17 sites.

* refactor(domain): drop TextDecoder imports left by the strict UTF-8 migration

* refactor(application): read MCP registration metadata through the strict UTF-8 owner

* refactor(formats): read binary-format readers' strict UTF-8 through the BOM-policy owner (#10903)

* refactor(formats): read binary-format readers' strict UTF-8 through the BOM-policy owner

* refactor(formats): drop the model readers' unused TextDecoder imports

* refactor(browser): read browser capture and fetch strict UTF-8 through the BOM-policy owner (#10935)

* refactor(browser): read browser capture and fetch strict UTF-8 through the BOM-policy owner

* refactor(native): read LLDB and Mach-O name strict UTF-8 through the BOM-policy owner (#10936)

* refactor(native): read LLDB and Mach-O name strict UTF-8 through the BOM-policy owner

* refactor(process): read MCP and NDJSON transport frames' strict UTF-8 through the BOM-policy owner (#10937)

* refactor(process): read MCP and NDJSON transport frames' strict UTF-8 through the BOM-policy owner

* refactor(application): read JSON and file inputs' strict UTF-8 through the BOM-policy owner (#10938)

* refactor(application): read JSON and file inputs' strict UTF-8 through the BOM-policy owner

* refactor(providers): read IDA, Electron, Ghidra and reference strict UTF-8 through the BOM-policy owner (#10939)

* refactor(providers): read IDA, Electron, Ghidra and reference strict UTF-8 through the BOM-policy owner

* refactor(evm): read the hex bytecode carrier's strict UTF-8 through the owner and refuse new local decoders (#10940)

* refactor(evm): read the hex bytecode carrier's strict UTF-8 through the BOM-policy owner

* chore(architecture): match local strict UTF-8 decoders in any option order

* fix(il2cpp): resolve ELF ABS64 and GLOB_DAT image definitions (#11075)

Derive bounded ELF ABS64 and GLOB_DAT link-image values for IL2CPP module
scanning while preserving the default conservative relocation policy.
Retain ambiguous hash declarations, validate complete hash-table mappings,
and disclose runtime-binding limitations in CLI and MCP evidence.

Validation: 408 focused tests, check:fast and docs:check passed. Public
CLI/MCP and independently linked ARM64/x86-64 ELF arithmetic were checked;
the original Unity binaries remain unavailable.

Refs #10478
Related: #10495

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* fix(il2cpp): read ELF hash-table words through BinaryReader (#11083)

* test(pcap): check the retained DNS-pass summary by coverage, not limitation wording

* refactor(reverse): fake objdump and Rizin commands only through the owned supervisor (#11076)

* refactor(reverse): fake objdump and Rizin commands only through the owned supervisor

* test(reverse): fake launch refusals and failed exits as the owned supervisor reports them

* refactor(reverse): name objdump and Rizin command repairs through the command port (#11080)

* refactor(desktop): let build-computer and agentenv cleanup errors read their owner's release (#10855)

* refactor(errors): read cleanup completion from dependencies instead of pushing it to dependents

AnalysisError.cleanupIncomplete becomes a getter over the error's own unresolved state and its bound dependencies. The WeakRef dependents graph and resolveCleanup's push propagation are removed, and subclasses mark their initial state through markCleanupIncomplete instead of overriding a public mutable field.

* fix(errors): settle bound dependencies before binding more

A composite whose dependencies had released but whose status was never read
stayed incomplete when a later dependency was bound.

* refactor(errors): let errors read a lease group's release instead of resolving them (#10759)

AnalysisCleanupLeaseGroup no longer calls resolveCleanup() on its error.
The error holds the group as a release claim and reads cleanupReleased when
asked, so completion follows the lease owner without a push.

* chore(verify): count resolveCleanup and bindCleanupDependencies calls so they only shrink (#10763)

* refactor(errors): let errors read a lease group's release instead of resolving them

AnalysisCleanupLeaseGroup no longer calls resolveCleanup() on its error.
The error holds the group as a release claim and reads cleanupReleased when
asked, so completion follows the lease owner without a push.

* chore(verify): count resolveCleanup and bindCleanupDependencies calls so they only shrink

* refactor(process): let worker cleanup errors read their root epoch's release

OwnedWorkerRuntime's root epoch is now an AnalysisCleanupReleaseClaim. Errors bound to it read its release when asked instead of the epoch pushing resolveCleanup() through weak references, and a runtime without a retained root binds an already-released owner. Removes the OwnedWorkerCleanupFailure structural type and four resolveCleanup() pushes; the counted baseline shrinks accordingly.

* refactor(pcap): let pcap cleanup errors read command and snapshot release (#10792)

Retained pcap commands, retained snapshot failures and snapshot completion descriptors now own their release and errors read it: commands and snapshot failures implement AnalysisCleanupReleaseClaim, and a failed completion-descriptor close is retried through an AnalysisCleanupLease bound to its error. Removes four resolveCleanup() pushes; the counted baseline shrinks accordingly.

* refactor(process): let Darwin helper cleanup errors read their owner's release

Darwin helper cache and run-token reader root cleanup now record an AnalysisCleanupRelease that every failure reports; a successful retry confirms it. Replaces the first-failure anchor that later failures depended on and the resolveCleanup() push. Removes two resolveCleanup() and two bindCleanupDependencies() calls; both counted baselines shrink.

* refactor(ghidra): let Ghidra cleanup errors read the client's and checkpoint's release

GhidraClient and GhidraCheckpoint bind each cleanup failure to an AnalysisCleanupRelease and confirm it when a later close or retry releases everything, instead of keeping a set of failures and pushing resolveCleanup() to each. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(process): let debugger session cleanup errors read a confirmed stop

OwnedDebuggerSessionRegistry binds each retained gdb or rizin cleanup failure to the session's AnalysisCleanupRelease and confirms it when a stop is confirmed, keeping the latest failure for retry reporting, instead of pushing resolveCleanup() to a set of failures. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(process): drop the debugger registry's unused closeOperation option

Returning the latest retained failure removed the last reader of closeOperation; remove the option and the values gdb and rizin supplied.

* refactor(server): let environment shutdown errors read a successful close

serveEnvironment binds each shutdown failure to an AnalysisCleanupRelease that a later successful close confirms, instead of pushing resolveCleanup() to a set of failures. The state-file retry test now also requires the earlier report to read the release. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(desktop): release retained screen-judge cleanup through its lease

Each retained judge or screenshot cleanup owner is wrapped in an AnalysisCleanupLease bound to its failure; close() releases the lease, which records the release the failure reads, instead of closing the owner and pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(ida): let IDA close failures read the session's later close

IdaSessionClient's close failure binds an owner that is both its resource owner and its release claim, read from the client's closed state, instead of keeping weak references and pushing resolveCleanup() after a successful retry. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(javascript): let source-map codec cleanup errors read a later close (#10814)

* refactor(javascript): let source-map codec cleanup errors read a later close

OwnedCodec binds each close failure to an AnalysisCleanupRelease that a later successful close confirms, replacing the first-failure anchor that later failures depended on and the resolveCleanup() push. Removes one resolveCleanup() and one bindCleanupDependencies() call; both counted baselines shrink.

* refactor(cutter): let pending Cutter command errors read the completion receipt (#10815)

* refactor(cutter): let pending Cutter command errors read the completion receipt

Each pending Cutter command keeps an AnalysisCleanupRelease bound to its timeout failure; the producer's terminal completion receipt confirms it instead of pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(application): let provider candidate cleanup errors read the candidate's close (#10817)

* refactor(application): let provider candidate cleanup errors read the candidate's close

AnalysisProviderRegistry keeps one AnalysisCleanupRelease per candidate whose resource close is unconfirmed; failures bind to it and a later confirmed close confirms it, instead of pushing resolveCleanup() to a set of failures. Removes one resolveCleanup() call; the counted baseline shrinks.

* fix(errors): bind a cleanup release claim to an error at most once

AnalysisError kept release claims in an array, so a provider whose retried close returned the same error bound the same claim again on every retry and each cleanupIncomplete read scanned the duplicates. Keep the claims in a set.

* refactor(application): let reverse-tool cleanup errors read a verified stop (#10819)

* refactor(application): let reverse-tool cleanup errors read a verified stop

Each retained provider process group in ReverseEngineeringService keeps an AnalysisCleanupRelease; its command and retry failures bind to it and a later verified stop confirms it, instead of collecting failures and pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(sqlite): let SQLite worker and root cleanup errors read their release (#10821)

Each retained SQLite snapshot cleanup records an AnalysisCleanupRelease for its worker and for its runtime root; the resource failures bind to them and a verified stop or root removal confirms them, instead of pushing resolveCleanup(). Composite failures keep reading those resource failures. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(android): let JADX cleanup errors read their retained cleanup's release

Each retained JADX cleanup records an AnalysisCleanupRelease for the admission failure's descriptor owners and one for the whole retained cleanup. The admission failure and every error the cleanup reports bind to them, and a confirmed close confirms them, instead of pushing resolveCleanup() through WeakRefs to reported errors. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(application): let session close failures read the client's later close

A retained session cleanup records an AnalysisCleanupRelease; unowned cleanup failures the client's close reported bind to it and the successful close confirms it, instead of the session collecting them and pushing resolveCleanup(). Failures that already follow their own owner keep reading it. Adds a regression for an unowned close failure. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(desktop): let build-computer and agentenv cleanup errors read their owner's release

Build-computer teardown, retained task readers, remote reader folders and agentenv solve sandboxes each record an AnalysisCleanupRelease that their bound failures read; a verified teardown or stop confirms it instead of pushing resolveCleanup() through WeakRef sets. Long-run job failures read whether every job they name has confirmed its stop, so a failure naming two jobs no longer reads complete when only one stops (regression added). WeakRef sets kept only where late facts (completion receipts, reader views) are still retained as diagnostics. Removes six resolveCleanup() calls; the counted baseline shrinks.

* refactor(kuna): let source-map and Kuna cache cleanup errors read their owner's release (#10856)

* refactor(browser): let late source-map fetch errors read their response's release

A pending source-map fetch and a response cancellation each record an AnalysisCleanupRelease that their cancellation or deadline failure reads; releasing the late response or the reader lock confirms it instead of pushing resolveCleanup(). Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(kuna): let project-cache cleanup errors read each owner's release

Each retained Kuna resource owner (process, staging, hash descriptor, retired file) records a release that the errors reporting it read; an error completes once every owner it reports confirms, and retirement that moves staging to a retained file forwards the staging owner's release to the file's. Replaces the WeakRef report list, its pruning and the resolveCleanup() push. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(process): forbid resolveCleanup() pushes; native markers read their supervisor's release (#10857)

* refactor(providers): let an attributed client failure read its source's completed cleanup

Re-attributing a failure whose source cleanup already completed now binds a claim reading that source's release instead of pushing resolveCleanup() onto the new error; a pending source is still bound as a dependency. Resources stay as history, as before. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(process): let native command markers read their supervisor's release

ProviderProcessSupervisor records an AnalysisCleanupRelease that a stop proving the process ended confirms. Native command and LLDB resolver cleanup markers bind to their supervisor's release, so a verified stop by either owner completes them, instead of each owner pushing resolveCleanup() onto the markers it tracks. Removes the last two resolveCleanup() calls outside the error base; the counted baseline is empty.

* chore(verify): forbid resolveCleanup() pushes outside the error base

Every production owner now confirms a release its errors read, so the counted baseline is empty. The guard becomes an outright ban with no baseline entry.

* test(native): complete native command and LLDB markers through a direct supervisor stop

* refactor(errors): complete an error's cleanup from its owner's record and every dependency (#10892)

* refactor(errors): complete an error's cleanup from its owner's record and every dependency

* refactor(errors): complete test errors through an owner release and delete resolveCleanup() (#10898)

* refactor(android): compose JADX and Apktool cleanup failures through one shared owner (#10900)

* refactor(android): compose JADX and Apktool cleanup failures through one shared owner

* refactor(application): compose service cleanup failures through the shared owner (#10902)

* refactor(sqlite): classify worker-reply read failures through the shared provider classifier (#10849)

* 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.
…

---------

Co-authored-by: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com>
Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
2026-11-16 10:59:18 +08:00

1518 lines
50 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
AnalysisCapabilityUnavailableError,
AnalysisUnsupportedTargetError,
AnalysisInputError,
AnalysisOutputError,
AnalysisCancelledError,
AnalysisTimeoutError,
AnalysisResourceConstraintError,
AnalysisArtifactChangedError,
} from "./analysisErrorCore.js";
import { ArtifactOperationError } from "./artifactOperationError.js";
import {
BinaryTargetError,
ConfigurationError,
} from "./configurationErrors.js";
import { BrowserObservationError } from "./browserObservationError.js";
import { EvidenceFileError, EvidenceIntegrityError } from "./evidenceErrors.js";
import { ProviderAdapterError } from "./providerAdapterError.js";
import { UnknownRegistryError } from "./unknownRegistryError.js";
import {
childFailureDiagnostics,
projectAnalysisError,
projectAnalysisErrorWithoutPartialObservation,
} from "./analysisErrorProjection.js";
import {
analysisErrorRemediationAction,
analysisErrorUserMessage,
} from "./analysisErrorPresentation.js";
import { ProviderSelectionError } from "./providerSelectionError.js";
import { analysisErrorProjectionSchema } from "./analysisErrorProjectionSchema.js";
import { nativeCallPartialObservationSchema } from "./native/nativeCallPartialObservation.js";
import { analysisSettingLimit } from "./analysisSettingDefinitions.js";
import { redactExplicitFailure } from "./explicitSensitiveFailure.js";
import { redactExplicitText } from "./explicitSensitiveValues.js";
import { analysisErrorWithCleanupFailure } from "./analysisErrorCleanup.js";
import {
AnalysisError,
ProviderOwnedAnalysisError,
providerErrorTag,
type AnalysisCallerLifetime,
type AnalysisErrorOwnPresentation,
} from "./analysisErrorBase.js";
import { ProviderCleanupError } from "./providerCleanupError.js";
import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js";
it("projects nested workflow-publication recovery for the actual caller lifetime", () => {
const child = new UnknownRegistryError(
"limit",
).retainWorkflowUnknownPublication({
evidence_id: `ev_${"a".repeat(64)}`,
evidence_retention: "retained",
total_questions: 3,
created_questions: 1,
existing_questions: 0,
next_question_index: 1,
});
const error = new AnalysisCancelledError(
"trace_feature",
childFailureDiagnostics({ child: { error: child } }),
);
const continuing = projectAnalysisError(error);
const invocation = projectAnalysisError(error, "invocation");
const childOf = (value: typeof continuing) => {
const diagnostics = value.details?.diagnostics;
if (
typeof diagnostics !== "object" ||
diagnostics === null ||
Array.isArray(diagnostics)
)
throw new Error("Expected child diagnostics");
return analysisErrorProjectionSchema.parse(diagnostics.child);
};
expect(
childOf(continuing).details?.workflow_unknown_publication,
).toMatchObject({
evidence_retention: "retained",
created_questions: 1,
next_question_index: 1,
});
expect(childOf(continuing).remediation.action).toContain(
"get_evidence_bundle",
);
expect(
childOf(invocation).details?.workflow_unknown_publication,
).toMatchObject({
evidence_retention: "invocation-only",
created_questions: 1,
next_question_index: 1,
});
expect(childOf(invocation).remediation.action).not.toContain(
"get_evidence_bundle",
);
});
describe("agent recovery metadata", () => {
it("does not mark deterministic input validation as retryable", () => {
const projected = projectAnalysisError(
new AnalysisInputError("extract_firmware", undefined, [
{ path: ["range", "length"], reason: "missing_argument" },
]),
);
expect(projected).toMatchObject({
code: "invalid_request",
retryable: false,
recovery: {
kind: "inspect_input_contract",
operation: "extract_firmware",
},
});
expect(analysisErrorProjectionSchema.parse(projected)).toEqual(projected);
});
it("distinguishes deterministic duplicate identities from stale update revisions", () => {
const duplicate = projectAnalysisError(
new UnknownRegistryError("already-exists"),
);
expect(duplicate).toMatchObject({
code: "invalid_request",
category: "invalid_input",
retryable: false,
details: { reason: "already-exists" },
});
expect(analysisErrorProjectionSchema.parse(duplicate)).toEqual(duplicate);
expect(
projectAnalysisError(new UnknownRegistryError("revision-conflict")),
).toMatchObject({ code: "revision_conflict", retryable: true });
});
it.each(["history_gap", "revision_chain"] as const)(
"preserves %s as an integrity failure with producer facts",
(kind) => {
const constraint = { kind, unknown_id: `unk_${"0".repeat(64)}` };
const projected = projectAnalysisError(
new UnknownRegistryError(constraint, {
cause: new Error("Unrelated private diagnostic"),
}),
);
expect(projected).toMatchObject({
code: "evidence_integrity_mismatch",
retryable: false,
details: { reason: "integrity", constraint },
});
expect(projected.message).toContain(constraint.unknown_id);
expect(JSON.stringify(projected)).not.toContain(
"Unrelated private diagnostic",
);
expect(analysisErrorProjectionSchema.parse(projected)).toEqual(projected);
},
);
it("keeps retryability for provider timeouts", () => {
expect(
projectAnalysisError(
new AnalysisTimeoutError("inspect_binary_layout", 2500),
),
).toMatchObject({ code: "provider_timeout", retryable: true });
});
it("names the input contract for malformed analysis arguments", () => {
const projected = projectAnalysisError(
new AnalysisInputError("inspect_analysis_view", undefined, [
{
path: ["view", "kind"],
reason: "invalid_value",
expected: ["summary", "module"],
},
]),
);
expect(projected).toMatchObject({
recovery: {
kind: "inspect_input_contract",
operation: "inspect_analysis_view",
},
remediation: {
action: expect.stringContaining("inspect_analysis_view"),
},
});
expect(projected.remediation.action).toContain("tools/list");
expect(analysisErrorProjectionSchema.parse(projected)).toEqual(projected);
});
it("omits schema recovery when a conforming request lacks a target fact", () => {
const issue = {
path: ["address"],
reason: "invalid_value",
message: "Address 0x2000 is in uninitialized memory block .bss",
observed: { address: "0x2000", file_mapping: "uninitialized" },
} as const;
const projected = projectAnalysisError(
new AnalysisInputError(
"address_to_file_offset",
{
userMessage: "No exact original-file offset exists.",
remediationAction: "Select an address inside a file-backed mapping.",
conformsToInputContract: true,
},
[issue],
),
);
expect(projected).toEqual({
code: "invalid_request",
category: "invalid_input",
message: "No exact original-file offset exists.",
retryable: false,
remediation: {
action: "Select an address inside a file-backed mapping.",
},
details: { operation: "address_to_file_offset", issues: [issue] },
});
expect(analysisErrorProjectionSchema.parse(projected)).toEqual(projected);
});
it("separates timeout-state inspection from client deadline recovery", () => {
const projected = projectAnalysisError(
new AnalysisTimeoutError("inspect_binary_layout", 2_500),
);
expect(projected).toMatchObject({
code: "provider_timeout",
recovery: {
kind: "inspect_timeout_state",
operation: "inspect_binary_layout",
timeout_ms: 2_500,
},
});
expect(analysisErrorProjectionSchema.parse(projected)).toEqual(projected);
});
});
describe("capability failure retry disposition", () => {
it.each([
{ options: {}, retryable: false, category: "unsupported_provider" },
{
options: { retryable: false },
retryable: false,
category: "unsupported_provider",
},
{ options: { retryable: true }, retryable: true, category: "unavailable" },
] as const)(
"preserves the producer's $retryable disposition",
({ options, retryable, category }) => {
const reason = "Native self-test failed with a sharing violation";
const error = new AnalysisCapabilityUnavailableError(
"fixture-provider",
"inspect",
reason,
options,
);
const projected = projectAnalysisError(error);
expect(projected).toMatchObject({
code: "capability_unavailable",
category,
retryable,
details: { reason },
});
if (retryable) {
expect(projected.message).toBe(
"Required runtime controls are unavailable for this attempt.",
);
expect(projected.remediation.action).toBe(
analysisErrorRemediationAction(error),
);
}
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(
true,
);
},
);
it("preserves a caller-selected message for a retryable failure", () => {
expect(
projectAnalysisError(
new AnalysisCapabilityUnavailableError(
"fixture-provider",
"inspect",
"temporary failure",
{
retryable: true,
userMessage: "Selected runtime diagnostic",
},
),
).message,
).toBe("Selected runtime diagnostic");
});
it("uses generic recovery only when no more specific recovery exists", () => {
const project = (options: {
fallbackRemediationAction?: string;
remediationAction?: string;
retryable?: boolean;
}) =>
projectAnalysisError(
new AnalysisCapabilityUnavailableError(
"fixture",
"inspect",
"unavailable",
options,
),
);
expect(
project({ fallbackRemediationAction: "Generic" }).remediation.action,
).toBe("Generic");
expect(
project({
fallbackRemediationAction: "Generic",
remediationAction: "Specific",
}).remediation.action,
).toBe("Specific");
const retry = project({ retryable: true });
const retryWithFallback = project({
fallbackRemediationAction: "Generic",
retryable: true,
});
expect(retryWithFallback.retryable).toBe(true);
expect(retryWithFallback.remediation.action).toBe(retry.remediation.action);
});
it("retains cleanup ownership before allowing a transient operation to retry", () => {
expect(
projectAnalysisError(
new AnalysisCapabilityUnavailableError(
"fixture-provider",
"inspect",
"temporary failure",
{
retryable: true,
cleanup: {
reason: "owned handle is still live",
resources: ["native-owner"],
},
},
),
),
).toMatchObject({
code: "cleanup_incomplete",
retryable: false,
details: {
cleanup: "incomplete",
resources: ["native-owner"],
execution_failure: "capability_unavailable",
},
});
});
});
it("projects a published file receipt alongside retained cleanup failure", () => {
const projected = projectAnalysisError(
new EvidenceFileError("write", "io", {
path: "/tmp/evidence.json",
published: { path: "/tmp/evidence.json", bytes: 42 },
cleanup: {
reason: "staging directory is still owned",
resources: ["/tmp/.rea-write-abc"],
},
cause: new Error("cleanup incomplete"),
}),
);
expect(projected).toMatchObject({
code: "cleanup_incomplete",
message: expect.stringMatching(/published.*staging cleanup.*incomplete/iu),
remediation: {
action: expect.stringMatching(
/published.*details\.published_path.*cleanup/iu,
),
},
details: {
operation: "write",
path: "/tmp/evidence.json",
published: true,
published_path: "/tmp/evidence.json",
bytes: 42,
resources: ["/tmp/.rea-write-abc"],
},
});
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(true);
});
const nativeCallPartialObservation = nativeCallPartialObservationSchema.parse({
kind: "native-call-observation",
target: {
path: "/tmp/selected-app",
sha256: "a".repeat(64),
architecture: "arm64",
arguments: [],
environment: {},
working_directory: null,
},
process: {
pid: 4242,
stdout: {
text: "partial stdout",
bytes: 13,
truncated: false,
complete: false,
},
stderr: null,
other_stops: [],
},
debugger: { version: null },
events: [],
coverage: { status: "partial", reason: "cancelled" },
limitations: ["Observation ended before the requested window completed."],
});
const retainedOutput = {
stdout: "selected output\u0000",
stderr: "upstream warning",
truncated: true,
};
it("distinguishes unsupported target formats from unavailable provider capabilities", () => {
const projected = projectAnalysisError(
new AnalysisUnsupportedTargetError(
"inspect_evm_interface",
"/selected/runtime.hex",
"EOF-style EF00 container is unsupported.",
{ capturedOutput: retainedOutput },
),
);
expect(projected).toMatchObject({
code: "unsupported_target",
category: "unsupported_target",
retryable: false,
details: {
operation: "inspect_evm_interface",
path: "/selected/runtime.hex",
reason: "EOF-style EF00 container is unsupported.",
captured_output: retainedOutput,
},
});
expect(projected.message).toContain("EF00");
expect(projected.remediation.action).toContain("target format");
expect(projected.remediation.action).not.toContain("doctor");
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(true);
});
it("keeps a refusing provider's recovery on a target selection failure", () => {
const selection = {
reason: "target_unsupported" as const,
requestedProviderId: "ghidra",
candidateIds: ["ghidra"],
userMessage: "Unsupported target: the configured extension is x86-64 only.",
};
expect(
projectAnalysisError(
new ProviderSelectionError({
...selection,
remediationAction: "Omit the extension setting for this target.",
}),
),
).toMatchObject({
code: "capability_unavailable",
message: selection.userMessage,
remediation: { action: "Omit the extension setting for this target." },
details: { selection_reason: "target_unsupported" },
});
expect(
projectAnalysisError(new ProviderSelectionError(selection)).remediation
.action,
).toBe(selection.userMessage);
});
it.each([false, true])(
"marks occupied capacity retryable only while cleanup is confirmed: %s",
(cleanupIncomplete) => {
const projected = projectAnalysisError(
new AnalysisResourceConstraintError(
"inspect_sqlite_database",
"capacity",
"Inspection slots are occupied",
{ max_concurrent_inspections: 2 },
cleanupIncomplete
? {
cleanup: {
reason: "Snapshot removal denied",
resources: ["/private/snapshot"],
},
}
: undefined,
),
);
expect(projected.retryable).toBe(!cleanupIncomplete);
expect(projected.code).toBe(
cleanupIncomplete ? "cleanup_incomplete" : "resource_constraint",
);
expect(projected.details).toMatchObject({
resource: "capacity",
reported_limits: { max_concurrent_inspections: 2 },
});
expect(projected.remediation.action).toContain("Wait");
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(
true,
);
},
);
it.each([
["memory", null],
["memory", { address_space_bytes: 67108864 }],
["cpu", null],
["cpu", { cpu_seconds: 1 }],
["file-size", null],
["file-size", { file_size_bytes: 1024 }],
["transport", { result_budget_bytes: 10485760 }],
] as const)(
"projects reported %s constraints with observed or unknown limits: %j",
(resource, limits) => {
const projected = projectAnalysisError(
new AnalysisResourceConstraintError(
"inspect_binary_layout",
resource,
resource === "memory"
? "Memory allocation failed; exact cause unknown."
: "Observed SIGXCPU; exact signal cause unknown.",
limits,
{ capturedOutput: retainedOutput },
),
);
expect(projected).toMatchObject({
code: "resource_constraint",
category: "resource_constraint",
retryable: false,
details: {
resource,
reported_limits: limits,
captured_output: retainedOutput,
},
});
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(
true,
);
},
);
it.each([
new AnalysisInputError("inspect", { capturedOutput: retainedOutput }),
new AnalysisOutputError("inspect", "invalid reply", {
capturedOutput: retainedOutput,
}),
new AnalysisCapabilityUnavailableError(
"provider",
"inspect",
"unsupported profile",
{ capturedOutput: retainedOutput },
),
new AnalysisCancelledError("inspect", { capturedOutput: retainedOutput }),
new AnalysisTimeoutError("inspect", 30, { capturedOutput: retainedOutput }),
new ProviderSelectionError({
operation: "inspect",
reason: "provider_unavailable",
requestedProviderId: "provider",
candidateIds: [],
capturedOutput: retainedOutput,
}),
])(
"retains captured output without changing the typed primary failure: $._tag",
(failure) => {
expect(projectAnalysisError(failure).details?.captured_output).toEqual(
retainedOutput,
);
},
);
it.each([
new AnalysisCancelledError("observe_native_calls", {
cleanup: {
reason: "target process termination could not be verified",
resources: ["native-target:4242"],
},
}),
new AnalysisTimeoutError("observe_native_calls", 65_000, {
cleanup: {
reason: "target process identity was unavailable",
resources: ["native-target:4242"],
},
}),
])("retains incomplete cleanup for lifecycle failures: $._tag", (failure) => {
expect(projectAnalysisError(failure)).toMatchObject({
code: "cleanup_incomplete",
details: {
cleanup: "incomplete",
cleanup_reason: expect.any(String),
resources: ["native-target:4242"],
},
});
});
it("retains the original failure tag and code when cleanup is incomplete", () => {
const error = new EvidenceIntegrityError(
"The launched native target did not match its selected digest",
{
cleanup: {
reason: "target survivor identity could not be verified",
resources: ["native-target:4242"],
},
},
);
expect(error._tag).toBe("EvidenceIntegrityError");
expect(projectAnalysisError(error)).toMatchObject({
code: "cleanup_incomplete",
category: "integrity_mismatch",
details: {
cleanup: "incomplete",
cleanup_reason: "target survivor identity could not be verified",
resources: ["native-target:4242"],
execution_failure: "evidence_integrity_mismatch",
},
});
});
it("projects native partial observations through healthy cancellation failures", () => {
const projected = projectAnalysisError(
new AnalysisCancelledError("observe_native_calls", {
partialObservation: nativeCallPartialObservation,
}),
);
expect(projected).toMatchObject({
code: "cancelled",
details: {
operation: "observe_native_calls",
cleanup: "complete",
partial_observation: nativeCallPartialObservation,
},
});
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(true);
});
it("retains native partial observations and cleanup uncertainty on provider failures", () => {
const projected = projectAnalysisError(
new ProviderAdapterError("native-lldb", "observe_native_calls", {
partialObservation: nativeCallPartialObservation,
cleanup: {
reason: "target process termination could not be verified",
resources: ["native-target:4242"],
},
}),
);
expect(projected).toMatchObject({
code: "cleanup_incomplete",
details: {
provider_id: "native-lldb",
operation: "observe_native_calls",
cleanup: "incomplete",
cleanup_reason: "target process termination could not be verified",
resources: ["native-target:4242"],
execution_failure: "execution_failure",
partial_observation: nativeCallPartialObservation,
},
});
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(true);
});
describe("analysis error projection: browser provider failures", () => {
it("explains the service-worker policy refusal and names its recovery", () => {
const projected = projectAnalysisError(
new BrowserObservationError(
"capture_browser_scenario",
"service_worker_blocked",
),
);
expect(projected).toMatchObject({
code: "target_unavailable",
category: "unavailable",
retryable: false,
message: expect.stringContaining("service-worker policy is block"),
remediation: {
action: expect.stringContaining("environment.service_workers to allow"),
},
details: {
operation: "capture_browser_scenario",
reason: "service_worker_blocked",
},
});
});
it("projects the primary browser failure alongside incomplete cleanup", () => {
const projected = projectAnalysisError(
new BrowserObservationError(
"observe_javascript_runtime",
"cleanup_failed",
{
cause: new AggregateError([
new BrowserObservationError(
"observe_javascript_runtime",
"target_changed",
),
new Error("socket close failed"),
]),
},
),
);
expect(projected).toMatchObject({
code: "cleanup_incomplete",
details: {
operation: "observe_javascript_runtime",
reason: "cleanup_failed",
cleanup: "incomplete",
resources: ["browser_transport"],
primary_reason: "target_changed",
},
});
});
it("keeps producer facts when a browser failure is attributed to another operation", () => {
const partial = { kind: "browser-test-partial" } as never;
const original = new BrowserObservationError(
"inspect_web_page",
"cleanup_failed",
{
detail: "Target page-1 closed while REA released its session.",
remediationAction: "Release session page-1, then retry.",
cleanup: { reason: "socket close failed", resources: ["page-1"] },
diagnostics: { endpoint: "loopback" },
partialObservation: partial,
cause: new AggregateError([
new BrowserObservationError("inspect_web_page", "target_changed"),
new Error("socket close failed"),
]),
},
);
const relabelled = original.forOperation("capture_web_screenshot");
expect(relabelled).toMatchObject({
operation: "capture_web_screenshot",
reason: "cleanup_failed",
cause: original.cause,
diagnostics: { endpoint: "loopback" },
partialObservation: partial,
});
const { details, ...projected } = projectAnalysisError(relabelled);
const { details: originalDetails, ...originalProjected } =
projectAnalysisError(original);
expect(projected).toEqual(originalProjected);
expect(projected).toMatchObject({
code: "cleanup_incomplete",
message: "Target page-1 closed while REA released its session.",
remediation: { action: "Release session page-1, then retry." },
});
expect(details).toEqual({
...originalDetails,
operation: "capture_web_screenshot",
});
expect(details).toMatchObject({
resources: ["page-1"],
primary_reason: "target_changed",
});
});
it("derives default browser guidance for the attributed operation", () => {
const original = new BrowserObservationError(
"inspect_web_page",
"target_not_found",
);
expect(original.forOperation("inspect_web_page")).toBe(original);
const relabelled = original.forOperation("discover_webmcp_tools");
const projected = projectAnalysisError(relabelled);
expect(projected).toMatchObject({
code: "target_unavailable",
message: expect.stringMatching(/^discover_webmcp_tools could not find/),
details: {
operation: "discover_webmcp_tools",
reason: "target_not_found",
},
});
expect(projected.message).not.toContain("inspect_web_page");
expect(
projectAnalysisError(
new BrowserObservationError("inspect_web_page", "timeout").forOperation(
"observe_web_session",
),
),
).toMatchObject({
code: projectAnalysisError(
new BrowserObservationError("observe_web_session", "timeout"),
).code,
details: { operation: "observe_web_session", reason: "timeout" },
});
});
});
describe("analysis error projection: detached provider diagnostics", () => {
it.each(["adapter", "cancelled", "timeout"])(
"preserves detached, actionable diagnostics for %s errors",
(kind) => {
const diagnostics = {
runtime_root: "/tmp/rea-ghidra-fixture",
profile_digest: "a".repeat(64),
exit_code: 1,
};
const error =
kind === "adapter"
? new ProviderAdapterError("ghidra", "health", { diagnostics })
: kind === "cancelled"
? new AnalysisCancelledError("health", { diagnostics })
: new AnalysisTimeoutError("health", 250, { diagnostics });
expect(error.diagnostics).not.toBe(diagnostics);
expect(projectAnalysisError(error)).toMatchObject({
details: {
...(kind === "adapter" ? { provider_id: "ghidra" } : {}),
operation: "health",
diagnostics,
},
});
diagnostics.exit_code = 2;
expect(error.diagnostics?.exit_code).toBe(1);
},
);
});
describe("analysis error projection: unclassified failures", () => {
it.each(["hopper", "ghidra", "ida", "jadx", "kuna"])(
"names doctor only with the provider it can check (%s)",
(providerId) => {
const projected = projectAnalysisError(
new ProviderAdapterError(providerId, "open_binary"),
);
expect(projected.code).toBe("execution_failure");
expect(projected.message).toContain(
`${providerId} provider could not complete open_binary, and REA did not classify the failure`,
);
expect(projected.message).not.toContain("doctor");
expect(projected.remediation.action).toContain(
`\`rea doctor --provider ${providerId}\``,
);
},
);
it.each(["firmware", "native-macos", "rizin", "rea-cdp-browser", "rea"])(
"does not send %s failures to a doctor that cannot check them",
(providerId) => {
const projected = projectAnalysisError(
new ProviderAdapterError(providerId, "inspect"),
);
expect(projected.message).toContain("did not classify the failure");
for (const text of [projected.message, projected.remediation.action])
expect(text).not.toContain("doctor");
},
);
it("keeps an authored provider message as the recovery", () => {
const projected = projectAnalysisError(
new ProviderAdapterError("firmware", "inspect", {
userMessage: "Select a smaller firmware image.",
}),
);
expect(projected.remediation.action).toBe(
"Select a smaller firmware image.",
);
});
it("does not attribute an unreadable result to provider readiness", () => {
const projected = projectAnalysisError(
new AnalysisOutputError("decompile", "failed"),
);
expect(projected.code).toBe("unreadable_output");
for (const text of [projected.message, projected.remediation.action])
expect(text).not.toContain("doctor");
});
});
describe("analysis error projection: caller contract", () => {
it("preserves the reported output constraint without exposing its internal cause", () => {
const projected = projectAnalysisError(
new AnalysisOutputError(
"extract_firmware",
"Report exceeded the declared byte budget",
{ cause: new Error("private internal cause") },
),
);
expect(projected).toMatchObject({
code: "unreadable_output",
details: {
operation: "extract_firmware",
reason: "Report exceeded the declared byte budget",
},
});
expect(JSON.stringify(projected)).not.toContain("private internal cause");
});
it("maps representative failures without exposing causes", () => {
const secretCause = new Error("secret-token");
const projected = [
projectAnalysisError(
new AnalysisInputError("overview", { cause: secretCause }),
),
projectAnalysisError(
new AnalysisCapabilityUnavailableError("fixture", "overview", "absent"),
),
projectAnalysisError(
new BinaryTargetError("/local/targets/app", "invalid", {
cause: secretCause,
}),
),
];
expect(projected.map(({ code }) => code)).toEqual([
"invalid_request",
"capability_unavailable",
"target_unavailable",
]);
expect(projected[1]).toMatchObject({
category: "unsupported_provider",
message: expect.stringMatching(/unavailable.*target/iu),
details: {
provider_id: "fixture",
operation: "overview",
reason: "absent",
},
});
expect(projected[2]).toMatchObject({
details: { path: "/local/targets/app" },
});
expect(JSON.stringify(projected)).not.toContain("secret-token");
});
it.each(["EACCES", "EPERM"] as const)(
"reports a target the host refused to read (%s) as access_denied",
(systemCode) => {
const denied = Object.assign(new Error("denied"), { code: systemCode });
const reason = `permission denied while reading target: ${systemCode}`;
expect(
projectAnalysisError(
new BinaryTargetError("/local/targets/app", reason, {
cause: denied,
}),
),
).toMatchObject({
code: "access_denied",
category: "unavailable",
retryable: false,
remediation: {
action: expect.stringMatching(
/read access.*selected path.*readable local file/iu,
),
},
details: {
path: "/local/targets/app",
reason,
system_code: systemCode,
boundary: "filesystem-read",
},
});
expect(
projectAnalysisError(
new BinaryTargetError("/local/targets/app", "missing", {
cause: Object.assign(new Error("missing"), { code: "ENOENT" }),
}),
),
).toMatchObject({ code: "target_unavailable" });
},
);
it("uses explicit capability recovery while retaining the constraint", () => {
const projected = projectAnalysisError(
new AnalysisCapabilityUnavailableError(
"fixture",
"capture",
"host constraint",
{
userMessage: "Use the supported host workflow.",
cause: new Error("private internal cause"),
},
),
);
expect(projected).toMatchObject({
code: "capability_unavailable",
category: "unsupported_provider",
message: "Use the supported host workflow.",
details: {
provider_id: "fixture",
operation: "capture",
reason: "host constraint",
},
});
expect(JSON.stringify(projected)).not.toContain("private internal cause");
});
it("preserves exact artifact-integrity coordinates", () => {
expect(
projectAnalysisError(
new ArtifactOperationError("inventory_artifact", "integrity", {
logicalPath: "main.js",
declaredSha256: "a".repeat(64),
calculatedSha256: "b".repeat(64),
unpacked: true,
}),
),
).toMatchObject({
category: "integrity_mismatch",
details: {
logical_path: "main.js",
declared_sha256: "a".repeat(64),
calculated_sha256: "b".repeat(64),
unpacked: true,
},
});
});
it("gives missing residual unknowns lookup-specific remediation", () => {
expect(
projectAnalysisError(new UnknownRegistryError("not-found")),
).toMatchObject({
code: "execution_failure",
message: expect.stringMatching(
/residual unknown.*does not exist.*unknown_id/iu,
),
remediation: {
action: expect.stringMatching(/unknown_id.*session.*retry/iu),
},
details: { reason: "not-found" },
});
});
});
describe("analysis error projection: evidence files", () => {
it.each([
["read", "missing", "invalid_request", "invalid_input"],
["read", "not-file", "invalid_request", "invalid_input"],
["write", "missing", "invalid_request", "invalid_input"],
["write", "exists", "invalid_request", "invalid_input"],
["write", "path-limit", "resource_constraint", "resource_constraint"],
[
"read",
"invalid-json",
"evidence_integrity_mismatch",
"execution_failure",
],
["read", "io", "execution_failure", "execution_failure"],
] as const)(
"classifies a %s %s evidence file by who can correct it",
(operation, reason, code, category) => {
const projected = projectAnalysisError(
new EvidenceFileError(operation, reason, { path: "/selected.json" }),
);
expect(projected).toMatchObject({
code,
category,
details: { operation, reason, path: "/selected.json" },
});
expect(analysisErrorProjectionSchema.parse(projected)).toEqual(projected);
},
);
});
it("retains the primary failure and both cleanup reports after a secondary failure", () => {
const callerReason = { caller: "stop" };
const primary = new AnalysisCancelledError("execute_rizin_command", {
cause: callerReason,
capturedOutput: {
stdout: "partial",
stderr: "diagnostic",
truncated: false,
},
cleanup: { reason: "writer remains", resources: ["writer"] },
});
const secondary = new AnalysisOutputError("open_binary", "cannot rebind", {
cleanup: { reason: "provider remains", resources: ["provider", "writer"] },
});
const enriched = primary.retainSecondaryFailure(secondary, {
rebind_error: projectAnalysisError(secondary),
});
expect(enriched).toBe(primary);
expect(enriched._tag).toBe("AnalysisCancelledError");
expect(enriched.cause).toBe(callerReason);
expect(enriched.secondaryFailures).toEqual([secondary]);
expect(projectAnalysisError(enriched)).toMatchObject({
code: "cleanup_incomplete",
details: {
execution_failure: "cancelled",
resources: ["writer"],
cleanup_reason: "writer remains",
captured_output: { stdout: "partial", stderr: "diagnostic" },
diagnostics: { rebind_error: { code: "cleanup_incomplete" } },
},
});
});
it("retains secondary failures when the primary error has no cause", () => {
const primary = new AnalysisCancelledError("execute_rizin_command");
const secondary = new AnalysisOutputError("open_binary", "cannot rebind");
primary.retainSecondaryFailure(secondary, {});
expect(primary.cause).toBeUndefined();
expect(primary.secondaryFailures).toEqual([secondary]);
});
it.each([false, true])(
"preserves producer capability recovery with retryable=%s",
(retryable) => {
const recovery =
"Choose an explicit disposition, then retry the same session.";
const projected = projectAnalysisError(
new AnalysisCapabilityUnavailableError("fixture", "close", "live state", {
retryable,
remediationAction: recovery,
}),
);
expect(projected).toMatchObject({
code: "capability_unavailable",
retryable,
remediation: { action: recovery },
details: {
provider_id: "fixture",
operation: "close",
reason: "live state",
},
});
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(
true,
);
},
);
it("does not offer entry-policy retries for integrity refusals without a declared-versus-observed entry contradiction", () => {
const native = projectAnalysisError(
new ArtifactOperationError(
"inspect_artifact",
"integrity",
undefined,
"hdiutil verify failed: invalid checksum",
),
);
expect(native.category).toBe("integrity_mismatch");
expect(native.details).toMatchObject({
reason: "integrity",
detail: "hdiutil verify failed: invalid checksum",
});
expect(native.message).not.toContain("record-and-continue");
expect(native.remediation.action).not.toContain("record-and-continue");
});
it.each([undefined, false, true])(
"projects whether a refused request was sent (%s) and omits an unknown value",
(requestSent) => {
const details = projectAnalysisError(
new AnalysisResourceConstraintError(
"cutter_command",
"transport",
"Cutter request exceeds its frame limit",
{ max_request_bytes: 8192 },
requestSent === undefined ? {} : { requestSent },
),
).details;
if (requestSent === undefined)
expect(details).not.toHaveProperty("request_sent");
else expect(details).toMatchObject({ request_sent: requestSent });
},
);
it("preserves ordinary configuration recovery and projects a producer-owned session repair", () => {
const settings = [{ setting: "REA_EXAMPLE", constraint: "must be positive" }];
const original = projectAnalysisError(
new ConfigurationError("Invalid setting", { settings }),
);
const repairing = projectAnalysisError(
new ConfigurationError("Invalid setting", {
settings,
remediationAction: "Repair the running session, then retry.",
}),
);
expect(original.remediation.action).toMatch(
/correct.*REA_EXAMPLE.*environment.*shell.*MCP.*registration.*rerun/iu,
);
expect(repairing).toEqual({
...original,
remediation: { action: "Repair the running session, then retry." },
});
expect(repairing.code).toBe("configuration_invalid");
});
const continuingOnly = {
userMessage: "The fixture session remains usable.",
remediationAction: "Update the fixture runtime setting on this session.",
};
describe("analysis error projection: caller lifetime", () => {
it.each([
new AnalysisTimeoutError("procedure_pseudo_code", 5000, {
userMessage: "Only this request stopped.",
remediationAction: "Rerun with a longer launch deadline.",
continuingCallerGuidance: continuingOnly,
}),
new ProviderAdapterError("fixture", "procedure_pseudo_code", {
userMessage: "Only this request stopped.",
remediationAction: "Rerun with a longer launch deadline.",
continuingCallerGuidance: continuingOnly,
}),
new AnalysisResourceConstraintError(
"search_strings",
"cpu",
"Only this request stopped.",
null,
{
remediationAction: "Rerun with a longer launch deadline.",
continuingCallerGuidance: continuingOnly,
},
),
])(
"states continuing-session guidance only to a continuing caller ($_tag)",
(error) => {
expect(projectAnalysisError(error)).toMatchObject({
message:
"Only this request stopped. The fixture session remains usable.",
remediation: {
action: "Update the fixture runtime setting on this session.",
},
});
const invocation = projectAnalysisError(error, "invocation");
expect(invocation).toMatchObject({
code: projectAnalysisError(error).code,
message: "Only this request stopped.",
remediation: { action: "Rerun with a longer launch deadline." },
});
expect(analysisErrorUserMessage(error, "invocation")).toBe(
"Only this request stopped.",
);
expect(analysisErrorRemediationAction(error, "invocation")).toBe(
"Rerun with a longer launch deadline.",
);
},
);
it("re-scopes a limit for a finished invocation and keeps its enforced facts", () => {
const limit = analysisSettingLimit(
"regex.matching_deadline_ms",
250,
"setting",
);
const error = new AnalysisResourceConstraintError(
"search_strings",
"cpu",
"Regex matching exceeded its deadline.",
null,
{ limit },
);
expect(projectAnalysisError(error).details?.limit).toEqual(limit);
expect(projectAnalysisError(error, "invocation").details?.limit).toEqual({
setting: "regex.matching_deadline_ms",
effective_value: 250,
source: "setting",
unit: "ms",
minimum: limit.minimum,
maximum: limit.maximum,
agent_editable: true,
update_mode: "runtime",
pending_restart: false,
applies_at: "next_invocation",
scope: "rea-invocation",
environment: "REA_REGEX_MATCHING_DEADLINE_MS",
});
// The error keeps its runtime facts for other projections.
expect(error.limit).toEqual(limit);
});
it("names a per-call parameter, not an environment, when a setting has no launch seed", () => {
const error = new AnalysisTimeoutError("inspect_wasm_artifact", 100, {
limit: analysisSettingLimit("wasm.command_timeout_ms", 100, "request"),
});
expect(projectAnalysisError(error, "invocation").details?.limit).toEqual(
expect.objectContaining({
setting: "wasm.command_timeout_ms",
source: "request",
update_mode: "parameter",
parameter: "command_timeout_ms",
applies_at: "next_invocation",
scope: "rea-invocation",
}),
);
expect(
analysisSettingLimit("wasm.command_timeout_ms", 100, "runtime"),
).toMatchObject({ source: "runtime", update_mode: "runtime" });
expect(
analysisSettingLimit("javascript.max_heap_mb", 128, "request"),
).toMatchObject({
source: "request",
update_mode: "parameter",
parameter: "max_heap_mb",
});
expect(
analysisSettingLimit("javascript.analysis_timeout_ms", 1, "default"),
).toMatchObject({ source: "default", update_mode: "runtime" });
expect(
projectAnalysisError(error, "invocation").details?.limit,
).not.toHaveProperty("environment");
});
});
describe("analysis error projection: composed failures for a caller lifetime", () => {
it("projects a composed cleanup failure's children for the caller and keeps their history", () => {
const limit = analysisSettingLimit(
"regex.matching_deadline_ms",
250,
"setting",
);
const primary = new AnalysisTimeoutError("search_strings", 250, {
limit,
userMessage: "Only this request stopped.",
remediationAction: "Rerun with a longer launch deadline.",
continuingCallerGuidance: continuingOnly,
});
const cleanup = new ProviderCleanupError(
"fixture",
["fixture-process"],
{ reason: "exit unconfirmed" },
{ remediationAction: "Close the retained fixture process." },
);
const composed = analysisErrorWithCleanupFailure(
primary,
cleanup,
).bindCleanupDependencies([primary, cleanup]);
const child = (lifetime: AnalysisCallerLifetime) =>
projectAnalysisError(composed, lifetime).details;
expect(child("invocation")).toMatchObject({
limit: { scope: "rea-invocation" },
diagnostics: {
primary_error: projectAnalysisError(primary, "invocation"),
cleanup_error: { code: "cleanup_incomplete" },
},
});
expect(child("continuing")).toMatchObject({
limit: { scope: "rea-runtime" },
diagnostics: { primary_error: projectAnalysisError(primary) },
});
expect(projectAnalysisError(composed, "invocation").message).toBe(
"Only this request stopped.",
);
expect(projectAnalysisError(composed).message).toBe(
`Only this request stopped. ${continuingOnly.userMessage}`,
);
// After cleanup resolves, history keeps the composition-time snapshot.
releaseOwnedCleanup(cleanup);
for (const lifetime of ["continuing", "invocation"] as const)
expect(child(lifetime)?.cleanup_history).toMatchObject({
primary_error: projectAnalysisError(primary, lifetime),
cleanup_error: { code: "cleanup_incomplete" },
});
});
it("keeps caller lifetime for a secondary failure embedded in child diagnostics", () => {
const primary = new AnalysisInputError("read_bytes", undefined, []);
const secondary = new AnalysisTimeoutError("search_strings", 250, {
limit: analysisSettingLimit("regex.matching_deadline_ms", 250, "setting"),
continuingCallerGuidance: continuingOnly,
});
primary.retainSecondaryFailure(secondary);
const history = childFailureDiagnostics({
primary_error: { error: primary },
});
expect(history.diagnostics?.primary_error).toEqual(
projectAnalysisError(primary, "continuing"),
);
expect(history.invocationDiagnostics?.primary_error).toEqual(
projectAnalysisError(primary, "invocation"),
);
});
it("records one lifetime form when no child depends on the caller", () => {
const composed = analysisErrorWithCleanupFailure(
new AnalysisInputError("read_bytes", undefined, [
{ path: ["address"], reason: "invalid_format" },
]),
new ProviderCleanupError("fixture", ["fixture-process"], {}),
);
expect(composed.invocationDiagnostics).toBeUndefined();
expect(projectAnalysisError(composed, "invocation").details).toEqual(
projectAnalysisError(composed).details,
);
});
it("keeps the named integrity check when redaction rebuilds an artifact change", () => {
const error = new AnalysisArtifactChangedError(
"inspect_artifact",
"/target/secret-token.bin",
"member changed",
{ integrityCheck: "member-identity" },
);
const redacted = redactExplicitFailure(error, ["secret-token"]);
expect(redacted).not.toBe(error);
expect(projectAnalysisError(redacted)).toMatchObject({
code: "artifact_changed",
details: { integrity_check: "member-identity" },
});
});
it("keeps continuing guidance through redaction and redacts its text", () => {
const guidance = {
userMessage: "The session for secret-token remains usable.",
remediationAction: "Retry secret-token on this session.",
};
const error = new AnalysisTimeoutError("procedure_pseudo_code", 5000, {
userMessage: "Only this request stopped.",
remediationAction: "Rerun with a longer launch deadline.",
continuingCallerGuidance: guidance,
});
const redact = (text: string) => redactExplicitText(text, ["secret-token"]);
const redacted = redactExplicitFailure(error, ["secret-token"]);
expect(projectAnalysisError(redacted)).toMatchObject({
message: `Only this request stopped. ${redact(guidance.userMessage)}`,
remediation: { action: redact(guidance.remediationAction) },
});
expect(JSON.stringify(projectAnalysisError(redacted))).not.toContain(
"secret-token",
);
expect(projectAnalysisError(redacted, "invocation")).toMatchObject({
message: "Only this request stopped.",
remediation: { action: "Rerun with a longer launch deadline." },
});
});
});
describe("analysis error projection: provider-owned errors", () => {
class ExampleProviderError extends ProviderOwnedAnalysisError {
readonly _tag = providerErrorTag("ExampleProviderError");
constructor() {
super("Example provider stopped with internal state");
}
override ownPresentation(): AnalysisErrorOwnPresentation {
return {
code: "provider_unavailable",
category: "unavailable",
message: "The example provider stopped.",
remediation: "Restart the example provider, then retry.",
details: { stage: "launch" },
};
}
}
it("projects a tag outside the domain set through the error's own presentation", () => {
const projection = projectAnalysisError(new ExampleProviderError());
expect(projection).toMatchObject({
code: "provider_unavailable",
category: "unavailable",
message: "The example provider stopped.",
remediation: { action: "Restart the example provider, then retry." },
details: { stage: "launch" },
});
expect(analysisErrorProjectionSchema.parse(projection)).toEqual(projection);
});
it("refuses an error whose tag is neither a domain tag nor provider-owned", () => {
class StrayError extends AnalysisError {
readonly _tag = "StrayError" as unknown as AnalysisError["_tag"];
}
expect(() => projectAnalysisError(new StrayError("stray"))).toThrow(
"Unknown analysis error tag",
);
});
});
describe("analysis error projection: composite argument observations", () => {
const left = { kind: "retained-evidence", evidence_id: "left" } as const;
const right = { kind: "retained-evidence", evidence_id: "right" } as const;
const own = { kind: "retained-evidence", evidence_id: "comparison" } as const;
it("keeps each argument's observation beside the failure's own partial", () => {
const failure = new AnalysisCancelledError("compare_managed_members", {
partialObservation: own,
})
.retainArgumentObservation("left", left)
.retainArgumentObservation("right", right)
.retainArgumentObservation("left", right);
expect(projectAnalysisError(failure).details).toMatchObject({
partial_observation: own,
argument_observations: [
{ argument: "left", observation: left },
{ argument: "right", observation: right },
],
});
expect(
projectAnalysisErrorWithoutPartialObservation(failure).details,
).not.toHaveProperty("argument_observations");
expect(
projectAnalysisError(
new AnalysisCancelledError("compare_managed_members"),
).details,
).not.toHaveProperty("argument_observations");
});
it("reads an inner failure's argument observations through cleanup before and after it settles", () => {
const primary = new AnalysisInputError(
"compare_managed_members",
).retainArgumentObservation("left", left);
const cleanup = new ProviderCleanupError("fixture", ["fixture-file"], {});
const composed = analysisErrorWithCleanupFailure(
primary,
cleanup,
).bindCleanupDependencies([cleanup]);
const expected = [{ argument: "left", observation: left }];
expect(projectAnalysisError(composed).details).toMatchObject({
cleanup: "incomplete",
argument_observations: expected,
});
expect(
projectAnalysisErrorWithoutPartialObservation(composed).details,
).not.toHaveProperty("argument_observations");
releaseOwnedCleanup(cleanup);
expect(
projectAnalysisError(composed).details?.argument_observations,
).toEqual(expected);
});
});