mirror of
https://github.com/morluto/rea.git
synced 2026-11-16 19:53:50 +00:00
* fix(pcap): report a refused tool launch as an unavailable tool When a capture read's tool launch was refused with EPERM, pcap reported it as unreadable tool output (AnalysisProtocolError) instead of an unavailable tool. Pcap also never told "not executable" apart from "missing". Add classifyLaunchFailure in src/process as the one owner of which spawn errnos mean missing (ENOENT, ENOTDIR) and which mean present but not executable (EACCES, EPERM, ENOEXEC, EISDIR). Pcap, apktool and gdb used three different errno lists; all three now use it. * refactor(process): classify owned command outcomes through one owner Add ProviderOutcome, read once from the supervisor's facts, and classifyProviderOutcome, the one mapping from an outcome to a typed error. Migrate pcap and the shared artifact producer command failure (TShark, sigrok). Add the rea/provider-failure-classifier lint rule with a shrink-only baseline of per-site (cause: unknown) => AnalysisError functions. * refactor(process): classify Java and adb launch refusals with the shared owner (#10598) The Ghidra and JADX Java probes and adb's version probe now take missing-versus-not-executable from classifyLaunchFailure instead of their own errno checks. ELOOP and ENAMETOOLONG join the owner's missing set, so adb keeps its existing classification and both Java probes now treat a non-directory path component as a missing runtime. * fix(pcap): preserve command launch attribution * test(pcap): expect an unknown failing stage when a limited capture tool exits unsuccessfully * refactor(process): classify owned command outcomes through one owner Add ProviderOutcome, read once from the supervisor's facts, and classifyProviderOutcome, the one mapping from an outcome to a typed error. Migrate pcap and the shared artifact producer command failure (TShark, sigrok). Add the rea/provider-failure-classifier lint rule with a shrink-only baseline of per-site (cause: unknown) => AnalysisError functions. * test(lint): cover baselined files in the provider-failure classifier rule * fix(apktool): report the decoder JVM's heap exhaustion as memory, not a target refusal The supervisor now watches for a managed runtime's out-of-memory report while output streams (JVM java.lang.OutOfMemoryError, V8 'JavaScript heap out of memory'), so a retention budget cannot hide it. ProviderOutcome gains a runtime-exhausted kind and classifyProviderOutcome maps it once. Apktool decode opts in and moves to the shared classifier; Ghidra's single-purpose output token becomes the JVM runtime option and its area matching reuses the shared table. * fix(process): keep the runtime's out-of-memory report on the memory error it supports * fix(pcap): attribute a limited capture's exit through the prlimit wrapper * fix(process): keep a shortened out-of-memory line marked as shortened * fix(process): identify the refused executable for every launcher shape Name the executable on errnos Node throws synchronously from spawn (ENOEXEC, ENOTDIR, ...) and read the Windows native launcher's executable-launch constraint, so pcap attributes those refusals to the selected tool or limiter instead of an unknown stage. * test(pcap): prove synchronous launch naming with ENOTDIR on every POSIX host * fix(apktool): advise the JVM limit that governs the reported memory area * fix(ghidra): read the supervisor's parsed OOM area instead of reparsing lines * fix(sqlite,capture): read V8 heap exhaustion from streamed output, not retained stderr (#10724) The SQLite worker and the Node capture decoders now declare runtime: "v8", so the supervisor observes V8's heap report as output streams. Both classifiers read the runtime-exhausted outcome instead of matching retained stderr, so a report beyond the retention budget, or one whose process then overflowed its output budget, is still reported as memory exhaustion. * refactor(evm): classify EVMole worker outcomes through the shared provider classifier (#10716) * refactor(evm): classify EVMole worker outcomes through the shared provider classifier The EVMole worker's cancellation, deadline, output budget and CPU/file-size signals now go through classifyProviderOutcome; only the prlimit launch refusal and the reserved EFBIG exit remain in its dialect. The worker is opted into V8 exhaustion scanning so a heap report names its fixed 256 MiB heap. providerOutcomeOf now reads a launch refusal only from a spawn errno, so a private-storage or carrier read errno is no longer reported as a limiter launch failure. * fix(evm): keep a stream failure's exit status and update Linux worker expectations * refactor(process): read launch refusals through the launcher identity owner * refactor(wasm): classify WABT command outcomes through the shared provider classifier (#10727) * refactor(wasm): classify WABT command outcomes through the shared provider classifier WABT's cancellation, command deadline, output budget, and inherited-limit signals now go through classifyProviderOutcome; its dialect keeps only the configuration-probe and launch-refusal unavailability and the unclassified-exit output error. A tool ended by SIGXCPU/SIGXFSZ or the memory limit is now a resource constraint instead of an output error, and a refused launch in the producer phase is reported as unavailable. The shared timeout context gains the analysis setting that selected the deadline, and the output-limit context may name its exceeded budget. * fix(wasm): keep setup guidance when a WABT version probe's output cannot be collected * refactor(providers): classify raw provider failures through one owner * refactor(process): build classified cancellations with cancelledBy and the carried caller reason * chore(lint): count runOwned's close-failure mapper from main in the classifier baseline * fix(process): carry the runtime's exhaustion report on every memory error that claims it SQLite and historical-capture memory errors recognised a streamed V8 heap report but dropped it, so a report outside retained output reached callers without its source line or omission flags. One projection, runtimeExhaustionReport, now owns that shape for the shared classifier and both consumers. Also lowers the EVMole and WABT cancellation-constructor baselines. * fix(process): keep the provider's recovery for a native-thread exhaustion report The shared classifier replaced the provider-supplied recovery with generic capacity advice whenever the JVM reported it could not create a native thread, dropping Apktool's launcher guidance and flipping retryable to true. The provider's recovery now wins; the capacity advice remains the fallback for providers that supply none. * refactor(pwntools): classify pwntools failures through the shared provider classifier (#10782) * refactor(pwntools): classify pwntools failures through the shared provider classifier pwntools' per-site classifier is replaced by pwntoolsFailureDialect for classifyProviderFailure. Command outcomes go through classifyProviderOutcome, launch refusals through launcherRefusalOf instead of a 'spawn ' syscall prefix check, the input limit through the file dialect's fileSize, and the cleanup report through commandCleanup. The shared read cancellation now carries the reader's partial observation, and resource-signal reports accept provider detail. * fix(pwntools): report a failed command's output once and expect resource_constraint for overflow The shared outcome owner already attaches the command's output as capturedOutput, so the pwntools adapter fallback no longer copies the same text into diagnostics.stdout, diagnostics.stderr and diagnostics.captured_output; diagnostics keep the exit facts. Update the overflow expectations the dialect migration missed (layout provider cleanup and over-budget rows, pwntools cleanup) to resource_constraint. * refactor(wasm): leave WABT cancellation to the shared owners WabtFailures matched any Error named AbortError as a cancellation. No WABT path produces one: reads, path checks and owned commands report cancellation as ArtifactReaderFailure or OwnedCommandFailure, which classifyProviderFailure and classifyProviderOutcome already classify with the caller's reason. The provider's two signal checks now build the cancellation with cancelledBy. Lowers the AnalysisCancelledError constructor baseline for both WABT files to zero. * fix(wasm): report a cancelled snapshot write as the caller's cancellation The private snapshot write passed the caller's signal to Node's writeFile, whose abort envelope reached the dialect's unclassified output failure once the name-based AbortError guess was removed. The write now turns the envelope carrying its own signal's reason into cancelledBy at the producer. * refactor(firmware): classify firmware failures through the shared provider classifier (#10810) Firmware producers now report their own deadline expiry: the start check, the output inventory and launcher admission throw the phase timeout where they observe the abort, and a read the phase signal cancelled reports it through the dialect's interruption. The classifier no longer rereads a cancellation's reason as a timeout. A new readCleanup hook keeps firmware's cleanup report shape. * 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>
1086 lines
46 KiB
JavaScript
1086 lines
46 KiB
JavaScript
import { readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
import { join, relative, sep } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { recordPredicateCounts } from "./record-predicate-guard.mjs";
|
|
import {
|
|
compareCountedBaseline,
|
|
recordLoweredBaseline,
|
|
reconcileBaselineFile,
|
|
} from "./counted-baseline.mjs";
|
|
import { localCompletenessEnumCount } from "./completeness-enum-guard.mjs";
|
|
import { countKeyedFirstMatches } from "./keyed-first-match.mjs";
|
|
import { incurZodImportCount } from "./incur-import-guard.mjs";
|
|
import { budgetArithmeticCount } from "./budget-arithmetic-guard.mjs";
|
|
import { localLimitErrorClassCount } from "./limit-class-guard.mjs";
|
|
import { countDefaultValidationClients } from "./mcp-client-validation.mjs";
|
|
import {
|
|
isComparisonOrCountFile,
|
|
optionalFactDefaultCount,
|
|
} from "./optional-fact-default-guard.mjs";
|
|
import { unmarkedMatchCount } from "./reason-marker.mjs";
|
|
import { blankComments } from "./source-tokens.mjs";
|
|
import {
|
|
cliTextGuardSelects,
|
|
cliTextOutsideCliCount,
|
|
} from "./cli-text-guard.mjs";
|
|
import {
|
|
TOOL_REGISTRATION_OWNERS,
|
|
toolRegistrationCount,
|
|
} from "./tool-registration-guard.mjs";
|
|
|
|
// Architecture guards for the strict-identity / best-effort-inference split.
|
|
// - Composite dedup keys must not NUL-join variable-length or free-form
|
|
// MIDDLE fields: ["a\0b"] collapses with ["a", "b"] and drops a finding.
|
|
// The text check below only flags one spelling; it is not a complete audit.
|
|
// - Transparent wrappers unwrap in exactly one place
|
|
// (javascriptAstValues.unwrapJavaScriptExpression); direct isTS* unwrapping
|
|
// elsewhere drifts (the `satisfies` class of bug).
|
|
|
|
const root = fileURLToPath(new URL("../../", import.meta.url));
|
|
|
|
const listFiles = async (dir) => {
|
|
const output = [];
|
|
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
const path = join(dir, entry.name);
|
|
if (entry.isDirectory()) output.push(...(await listFiles(path)));
|
|
else if (
|
|
entry.name.endsWith(".ts") &&
|
|
!entry.name.endsWith(".test.ts") &&
|
|
!entry.name.endsWith(".spec.ts") &&
|
|
!entry.name.endsWith(".fixture.ts")
|
|
)
|
|
output.push(path);
|
|
}
|
|
return output;
|
|
};
|
|
|
|
const sources = await listFiles(join(root, "src"));
|
|
const files = await Promise.all(
|
|
sources.map(async (path) => {
|
|
const source = await readFile(path, "utf8");
|
|
return {
|
|
path: relative(root, path).split(sep).join("/"),
|
|
content: blankComments(source),
|
|
source,
|
|
};
|
|
}),
|
|
);
|
|
const failures = [];
|
|
const check = (label, selected, pattern, allow = []) => {
|
|
const offenders = selected.filter(
|
|
(file) => pattern.test(file.content) && !allow.includes(file.path),
|
|
);
|
|
if (offenders.length > 0)
|
|
failures.push(
|
|
`${label}:\n${offenders.map((file) => ` ${file.path}`).join("\n")}`,
|
|
);
|
|
};
|
|
|
|
// Completeness is a claim its producer establishes from examined input. A
|
|
// fallback or default of `true` turns an unstated claim into a complete one.
|
|
check(
|
|
"completeness defaulted to true (leave it unknown or require the producer to state it)",
|
|
files,
|
|
/\b(?:complete|exhaustive|\w+Complete|\w+Exhaustive|\w+_complete|\w+_exhaustive)\w*\s*(?:\?\?\s*true\b|(?::\s*boolean\s*)?=\s*true\s*[,)])/u,
|
|
);
|
|
|
|
// Prerequisite inspection lifetime is an application contract shared by adapters.
|
|
check(
|
|
"provider-owned inspection lifetime (use src/ports/ProviderInspectionScope)",
|
|
files,
|
|
/providers\/ProviderInspectionScope\.js/,
|
|
);
|
|
|
|
check("NUL-joined list key (use compositeKey)", files, /\.join\(["']\\0["']\)/);
|
|
|
|
// Pushed effect invalidation (docs/adr/javascript/pushed-effect-invalidation.md).
|
|
// Opaque-effect checks are private to javascriptSemanticEffectLog.ts, so the
|
|
// compiler keeps readers on its questions, and only the log and its record
|
|
// module read the recorded sites. A method read on an intrinsic
|
|
// instance asks one owner, which checks the method, the instance's prototype
|
|
// link and the intrinsic prototypes.
|
|
check(
|
|
"reader-side read of recorded opaque effects (ask javascriptSemanticEffectLog.ts or the javascriptSemanticEffectRecord.ts accessors)",
|
|
files,
|
|
/\.opaqueEffects\b/u,
|
|
[
|
|
"src/domain/javascript/javascriptSemanticEffectLog.ts",
|
|
"src/domain/javascript/javascriptSemanticEffectRecord.ts",
|
|
],
|
|
);
|
|
|
|
check(
|
|
"reader-side prototype-link member check (use isIntrinsicInstanceMethodCall)",
|
|
files,
|
|
/mayObserve\([^;]*\["__proto__"\]/u,
|
|
["src/domain/javascript/javascriptSemanticIntrinsicInstances.ts"],
|
|
);
|
|
|
|
check(
|
|
"direct transparent-wrapper unwrap outside javascriptAstValues (use unwrapJavaScriptExpression)",
|
|
files,
|
|
/isTSAsExpression|isTSSatisfiesExpression|isTSNonNullExpression|isTSTypeAssertion|isTSInstantiationExpression|isParenthesizedExpression/,
|
|
["src/domain/javascript/javascriptAstValues.ts"],
|
|
);
|
|
|
|
// A producer that pins both the soft and hard ceiling of every resource takes
|
|
// the vector from one owner. prlimitCeilingArguments is the command-less prefix
|
|
// of prlimitArgumentVector; both live in src/process/LinuxResourceLimits.ts.
|
|
// Re-audited 2026-10-22 with util-linux 2.39.3: a bare value sets both soft and
|
|
// hard, the same as soft:hard when the numbers are equal. `soft:` leaves the
|
|
// inherited hard ceiling unchanged.
|
|
// FirmwareCommand and WakaruCommand call prlimitArgumentVector and keep their
|
|
// own file-size and CPU budgets (120 CPU seconds; firmware file size is the
|
|
// call output budget or the 8 MiB report allowance; Wakaru file size is the
|
|
// 128 MiB output allowance). Their 1 GiB address space is
|
|
// BOUNDED_PRODUCER_LIMITS.address_space_bytes. PcapNativeBound calls
|
|
// prlimitCeilingArguments because PcapCommand appends the producer command.
|
|
// Its CPU ceiling stays 300 seconds and it has no resident-input budget;
|
|
// address space and file size use those shared fields.
|
|
// selectEvmWorkerLimits stays a separate selector: Result failures, unit
|
|
// checks, and a refusal when soft exceeds hard. It must not call
|
|
// clampLinuxResourceLimits.
|
|
check(
|
|
"inline paired prlimit ceilings (use prlimitArgumentVector from src/process/LinuxResourceLimits)",
|
|
files,
|
|
/--core=0:0/,
|
|
["src/process/LinuxResourceLimits.ts"],
|
|
);
|
|
|
|
check(
|
|
"bare prlimit value (a bare value sets both ceilings; use prlimitArgumentVector)",
|
|
files,
|
|
/--core=0(?!:)/,
|
|
);
|
|
|
|
// 2026-10-22: soft-only `resource:` options retain the inherited hard ceiling.
|
|
// EVMole budgets differ (3 GiB address space, 16 MiB file, 30 CPU seconds), so
|
|
// this lane must not call prlimitArgumentVector.
|
|
check(
|
|
"soft-only prlimit ceilings (paired producers use prlimitArgumentVector)",
|
|
files,
|
|
/--core=0:(?!0)/,
|
|
["src/evm/EvmoleInterfaceProvider.ts"],
|
|
);
|
|
|
|
// Resident input is the input_bytes field of BOUNDED_PRODUCER_LIMITS. CamelCase
|
|
// inputBytes values with a different policy (an overridable pwntools admission,
|
|
// historical capture intake) are not this budget.
|
|
check(
|
|
"inline resident-input budget (use BOUNDED_PRODUCER_LIMITS from src/domain/producerResourceLimits)",
|
|
files,
|
|
/input_bytes:\s*32 \* 1024 \* 1024/,
|
|
["src/domain/producerResourceLimits.ts"],
|
|
);
|
|
|
|
// Fixed-arity backtick keys audited 2026-10-10: every prefix field is NUL-free
|
|
// (hex digests, file paths, enums, numbers, or compositeKey JSON which escapes
|
|
// NUL), with free-form source strings only in final position. New backtick-\0
|
|
// keys must either meet that shape (and extend this list with justification)
|
|
// or use compositeKey.
|
|
check(
|
|
"new backtick-NUL composite key (audit against the rule above)",
|
|
files,
|
|
/`[^`\n]*\\0/,
|
|
[
|
|
// Bundle fingerprint: fixed packaged paths (no NUL/newline) and 64 hex
|
|
// digest characters per record, never guide contents. Preserve v1 locators.
|
|
"src/application/GuidanceAccess.ts",
|
|
"src/application/javascript/ElectronBoundaryAnalysis.ts",
|
|
"src/application/javascript/ElectronBoundaryGraphContext.ts",
|
|
"src/browser/CdpCaptureCompleteness.ts",
|
|
"src/browser/CdpCaptureEventHandlers.ts",
|
|
"src/browser/CdpPageCapture.ts",
|
|
"src/browser/WebSourceMapFetcher.ts",
|
|
"src/domain/javascript/electronStaticAnalysisBrowser.ts",
|
|
"src/domain/javascript/electronStaticAnalysisIpc.ts",
|
|
"src/domain/javascript/javascriptApplicationChangeGraph.ts",
|
|
"src/domain/javascript/javascriptApplicationVersionItems.ts",
|
|
"src/domain/javascript/javascriptApplicationVersionKeys.ts",
|
|
"src/domain/javascript/javascriptExportShapeSelection.ts",
|
|
"src/domain/javascript/javascriptFeatureSeed.ts",
|
|
"src/domain/javascript/javascriptFeatureTraversal.ts",
|
|
"src/domain/javascript/javascriptNativeHandoff.ts",
|
|
"src/domain/javascript/javascriptRuntimeReconciliationMatching.ts",
|
|
"src/domain/javascript/javascriptRuntimeReconciliationSchemas.ts",
|
|
"src/domain/javascript/javascriptStaticAnalysisBundler.ts",
|
|
"src/domain/javascript/javascriptStaticAnalysisCalls.ts",
|
|
"src/domain/javascript/javascriptStaticAnalysisFindings.ts",
|
|
"src/domain/localPath.ts",
|
|
"src/domain/process/processTraceEvaluation.ts",
|
|
"src/domain/process/processTraceSpecification.ts",
|
|
"src/domain/unicodeCodePointOrder.ts",
|
|
"src/domain/webBundleAnalyzerInspection.ts",
|
|
],
|
|
);
|
|
|
|
// A signal's own abort is the abort error carrying that signal's reason; a bare
|
|
// ABORT_ERR code may come from another signal or a synthetic failure.
|
|
check(
|
|
"ABORT_ERR code comparison (use isAbortOf or isAbortWithReason from src/process/SignalAbort)",
|
|
files,
|
|
/(?:===|!==)\s*["']ABORT_ERR["']|["']ABORT_ERR["']\s*(?:===|!==)/u,
|
|
["src/process/SignalAbort.ts"],
|
|
);
|
|
|
|
// Hopper's error types live with the Hopper adapter. Shared layers read the
|
|
// provider-neutral facts every AnalysisError carries (ownPresentation,
|
|
// providerWide, providerRequest) and never import a provider's error types.
|
|
check(
|
|
"import of Hopper error types outside src/hopper (use the provider-neutral AnalysisError facts)",
|
|
files.filter((file) => !file.path.startsWith("src/hopper/")),
|
|
/from "\.{1,2}\/(?:[\w-]+\/)*HopperErrors\.js"/u,
|
|
);
|
|
|
|
// An unrecognised command outcome is reported only by the shared outcome
|
|
// classifier, which attaches the outcome it examined; a provider reports it
|
|
// through the dialect's `unclassified` callback.
|
|
check(
|
|
"UnclassifiedProviderFailure construction outside classifyProviderOutcome (use the dialect's unclassified report)",
|
|
files,
|
|
/\bnew\s+UnclassifiedProviderFailure\b/u,
|
|
["src/process/classifyProviderOutcome.ts"],
|
|
);
|
|
|
|
// "Non-null object other than an array" has one owner: src/kernel/isRecord.ts.
|
|
// A local predicate with that body, under any name, is a copy. The listed files
|
|
// still hold one and may only be removed from the list; a listed file that no
|
|
// longer matches fails so the list shrinks with the code.
|
|
const RECORD_PREDICATE_COPIES = [
|
|
// Exported under a module-specific name; importers still use that name.
|
|
"src/browser/history/CaptureRedaction.ts",
|
|
"src/contracts/compactJsonSchema.ts",
|
|
"src/domain/analysisView/environmentStateRules.ts",
|
|
// Owned by the advertised-schema workstream.
|
|
"src/contracts/inputSchemaPresentation.ts",
|
|
// Narrows a protocol-specific parameter type, not unknown.
|
|
"src/browser/execution/CdpRuntimeInitiator.ts",
|
|
// Named `object`, which also spells the typeof result in these files.
|
|
"src/pcap/PcapDnsWire.ts",
|
|
"src/pcap/PcapOutput.ts",
|
|
];
|
|
const mismatchedRecordCopies = files.filter(({ path, content }) => {
|
|
if (path === "src/kernel/isRecord.ts") return false;
|
|
const { named, bodies } = recordPredicateCounts(content);
|
|
return (
|
|
named !== 0 || bodies !== (RECORD_PREDICATE_COPIES.includes(path) ? 1 : 0)
|
|
);
|
|
});
|
|
const pathsWithRecordCopies = new Set(files.map(({ path }) => path));
|
|
const missingRecordCopies = RECORD_PREDICATE_COPIES.filter(
|
|
(path) => !pathsWithRecordCopies.has(path),
|
|
);
|
|
if (mismatchedRecordCopies.length > 0)
|
|
failures.push(
|
|
`local non-array record predicate count changed (import isRecord and update the baseline):\n${mismatchedRecordCopies.map(({ path }) => ` ${path}`).join("\n")}`,
|
|
);
|
|
if (missingRecordCopies.length > 0)
|
|
failures.push(
|
|
`record predicate baseline references missing files; remove those entries:\n${missingRecordCopies.map((path) => ` ${path}`).join("\n")}`,
|
|
);
|
|
|
|
// Node clamps a timer delay above the signed 32-bit bound to 1 ms. Durations
|
|
// use MAX_NODE_TIMER_DELAY_MS or timerDurationMsSchema from their one owner.
|
|
// The allowed files bound signed 32-bit integers that are not timer delays.
|
|
check(
|
|
"signed 32-bit bound literal (use MAX_NODE_TIMER_DELAY_MS or timerDurationMsSchema from src/domain/analysisResourceLimits for durations)",
|
|
files,
|
|
/\b2_?147_?483_?647\b/u,
|
|
[
|
|
"src/domain/analysisResourceLimits.ts",
|
|
// JADX MCP `limit` argument: a Java int, not a duration.
|
|
"src/android/JadxAnalysis.ts",
|
|
// JVM `-XX:ActiveProcessorCount`: a Java int processor count.
|
|
"src/android/JadxConfiguration.ts",
|
|
// TShark `-c` packet count: a C int, not a duration.
|
|
"src/domain/captures/packetCapture.ts",
|
|
// DEX static `int` value range.
|
|
"src/domain/android/androidAnalysis.ts",
|
|
// Signed 32-bit bitmask operand range.
|
|
"src/domain/javascript/javascriptSemanticResources.ts",
|
|
// Recorded crash pid, signal number and code fields.
|
|
"src/domain/native/recordedCrash.ts",
|
|
// Java int parsing for Ghidra launch properties.
|
|
"src/ghidra/GhidraInstallationPolicy.ts",
|
|
],
|
|
);
|
|
|
|
// Native inventory results parse once against their named fact contract
|
|
// (docs/adr/native/typed-operation-facts.md). Hopper's reply table and the
|
|
// advertised output schemas own their own protocol and catalog contracts.
|
|
check(
|
|
"native inventory rows parsed outside their fact contract (use executeFact or a contract from src/domain/native/nativeOperationFacts)",
|
|
files,
|
|
/\bnativeInventoryRowsSchemas\b|z\.array\(\s*addressedValueSchema\b|\baddressedValueSchema\s*\.\s*(?:safeParse|parse|pick)\b/,
|
|
[
|
|
"src/domain/native/nativeInventory.ts",
|
|
"src/domain/native/nativeOperationFacts.ts",
|
|
"src/hopper/HopperReplyContracts.ts",
|
|
"src/contracts/toolOutputSchemaGroups.ts",
|
|
],
|
|
);
|
|
|
|
// Mach-O load-command codes have one table; a local copy drifts from it.
|
|
check(
|
|
"local Mach-O load-command code (import LC from src/domain/apple/machoLoadCommandCodes)",
|
|
files,
|
|
/\bLC_[A-Z0-9_]+\s*=\s*(?:0x[0-9a-f]+|\d+)\b/iu,
|
|
["src/domain/apple/machoLoadCommandCodes.ts"],
|
|
);
|
|
|
|
// Counted baselines record the remaining copies of a pattern that has one
|
|
// owner. A file may not gain copies and a baseline may not grow; when copies
|
|
// are removed, `--shrink-baselines` lowers the recorded counts (and never
|
|
// raises them) so the next removal cannot be undone silently. Each guard's
|
|
// baseline is its own file, scripts/verify/baselines/<key>.json, so changes
|
|
// to different guards never edit the same file.
|
|
const baselineDirectory = join(root, "scripts/verify/baselines");
|
|
const baselineTexts = new Map();
|
|
for (const name of await readdir(baselineDirectory)) {
|
|
if (!name.endsWith(".json")) {
|
|
failures.push(
|
|
`${relative(root, join(baselineDirectory, name))} is not a guard baseline; only <guard-key>.json files belong in ${relative(root, baselineDirectory)}.`,
|
|
);
|
|
continue;
|
|
}
|
|
baselineTexts.set(
|
|
name.slice(0, -".json".length),
|
|
await readFile(join(baselineDirectory, name), "utf8"),
|
|
);
|
|
}
|
|
const baselines = Object.fromEntries(
|
|
[...baselineTexts].map(([key, text]) => [key, JSON.parse(text)]),
|
|
);
|
|
const checkedBaselineKeys = new Set();
|
|
const shrinkBaselines = process.argv.includes("--shrink-baselines");
|
|
let baselinesShrunk = false;
|
|
const checkCounted = (label, key, selected, pattern, owners) => {
|
|
checkedBaselineKeys.add(key);
|
|
const counts = new Map();
|
|
for (const file of selected) {
|
|
if (owners.includes(file.path)) continue;
|
|
const count =
|
|
typeof pattern === "function"
|
|
? pattern(file.content, file)
|
|
: (file.content.match(pattern)?.length ?? 0);
|
|
if (count > 0) counts.set(file.path, count);
|
|
}
|
|
const compared = compareCountedBaseline(
|
|
counts,
|
|
baselines[key] ?? {},
|
|
shrinkBaselines,
|
|
);
|
|
const lines = (differences) =>
|
|
differences
|
|
.map(
|
|
({ path, count, allowed }) =>
|
|
` ${path}: ${count} (baseline ${allowed})`,
|
|
)
|
|
.join("\n");
|
|
if (compared.grown.length > 0)
|
|
failures.push(
|
|
`${label}; new copies are not allowed:\n${lines(compared.grown)}`,
|
|
);
|
|
if (recordLoweredBaseline(baselines, key, compared)) baselinesShrunk = true;
|
|
if (compared.stale.length > 0)
|
|
failures.push(
|
|
`${label}; copies were removed, so lower the baseline with \`node scripts/verify/architecture-guards.mjs --shrink-baselines\`:\n${lines(compared.stale)}`,
|
|
);
|
|
};
|
|
|
|
// Comparison, coverage and count code that reads an optional parsed fact with
|
|
// `?? 0`, `?? []` or `?? false` turns "not reported" into an observed zero,
|
|
// empty list or no. Keep the fact unknown (null with a limitation) instead.
|
|
checkCounted(
|
|
"optional fact defaulted to 0, [] or false in comparison or count code (keep it unknown)",
|
|
"optional-fact-default",
|
|
files.filter(({ path }) => isComparisonOrCountFile(path)),
|
|
// Exemption markers are comments, so this guard reads the unstripped source.
|
|
(_content, { source }) => optionalFactDefaultCount(source),
|
|
[],
|
|
);
|
|
|
|
// A provider failure's captured output comes from one owner,
|
|
// capturedProviderOutput in src/process; local copies drift on byte counts
|
|
// (retained or written) and on how output loss marks truncation.
|
|
checkCounted(
|
|
"captured output copied from a process snapshot (use capturedProviderOutput from src/process/capturedProviderOutput)",
|
|
"captured-output-copy",
|
|
files,
|
|
/\bstdout: [\w.]+\.stdout\.text\b/gu,
|
|
["src/process/capturedProviderOutput.ts"],
|
|
);
|
|
|
|
// Pushed effect invalidation (docs/adr/javascript/pushed-effect-invalidation.md).
|
|
// Recorded effects belong to the effect log. A reader that reads an effect
|
|
// index itself decides on its own which effect kinds and proofs apply; readers
|
|
// ask the log instead. Every reader has moved; the remaining counts are the
|
|
// producers that build these indexes (javascriptSemanticAmbientWrites.ts,
|
|
// javascriptSemanticMemberMutations.ts, and javascriptSemanticAnalysis.ts,
|
|
// which creates and settles them) and the timing-proof owner
|
|
// (javascriptSemanticMutationInitializers.ts), whose position proofs over
|
|
// recorded sites the log delegates to.
|
|
checkCounted(
|
|
"read of a JavaScript effect index outside the effect log (ask javascriptSemanticEffectLog.ts)",
|
|
"javascript-effect-index-read",
|
|
files,
|
|
/\.(?:bindingWrites|memberWrites|escapedPaths|ambientWriteEffects|ambientEscapeEffects|ambientBindingWrites|ambientWrites|ambientEscapes)\b/gu,
|
|
["src/domain/javascript/javascriptSemanticEffectLog.ts"],
|
|
);
|
|
|
|
// Effect timing has one owner (javascriptSemanticMutationInitializers.ts) and
|
|
// one consumer, the effect log. Everything else asks the log whether an effect
|
|
// may precede a read, naming the ordering it relies on.
|
|
check(
|
|
"semanticEffectTiming outside the effect log (ask semanticEffectMayPrecede or a query in javascriptSemanticEffectLog.ts)",
|
|
files,
|
|
/\bsemanticEffectTiming\b/u,
|
|
[
|
|
"src/domain/javascript/javascriptSemanticEffectLog.ts",
|
|
"src/domain/javascript/javascriptSemanticMutationInitializers.ts",
|
|
],
|
|
);
|
|
|
|
// Coverage status has one vocabulary, coverageStatusSchema in
|
|
// src/domain/coverage.ts. A local enum that contains "complete" either copies
|
|
// it or drops `unknown`, which forces an unknown producer to pick a side.
|
|
checkCounted(
|
|
"local completeness enum (use coverageStatusSchema from src/domain/coverage, or mark a detail level, lifecycle state or domain vocabulary with `// detail-level:`, `// lifecycle-state:` or `// domain-vocabulary:` and its reason)",
|
|
"local-completeness-enum",
|
|
files,
|
|
localCompletenessEnumCount,
|
|
["src/domain/coverage.ts"],
|
|
);
|
|
|
|
// Cancellation reasons are required by `cancelledBy` in analysisErrorCore; a
|
|
// direct construction can omit or replace the caller's reason.
|
|
checkCounted(
|
|
"direct AnalysisCancelledError construction (use cancelledBy from src/domain/analysisErrorCore)",
|
|
"analysis-cancelled-constructor",
|
|
files,
|
|
/new AnalysisCancelledError\(/gu,
|
|
["src/domain/analysisErrorCore.ts"],
|
|
);
|
|
|
|
// Whether an abort error is a signal's own cancellation is decided by the
|
|
// signal owner; a name comparison alone accepts another signal's abort.
|
|
checkCounted(
|
|
"AbortError name comparison (use isAbortOf or isAbortWithReason from src/process/SignalAbort)",
|
|
"abort-error-name",
|
|
files,
|
|
/\.name\s*===\s*["']AbortError["']/gu,
|
|
["src/process/SignalAbort.ts"],
|
|
);
|
|
|
|
// A refusal for a limit a parser stopped at is built from the failure's
|
|
// LimitRef by parseLimitConstraint in src/domain/parseFailureAnalysisError; a
|
|
// hand-built AnalysisResourceConstraintError spells the limit key and reason
|
|
// again beside the parser that named them (#11456). Each migrated producer
|
|
// lowers this count.
|
|
checkCounted(
|
|
"hand-built resource-constraint refusal (use parseLimitConstraint from src/domain/parseFailureAnalysisError when the cause is a parse limit)",
|
|
"resource-constraint-constructor",
|
|
files,
|
|
/new AnalysisResourceConstraintError\(/gu,
|
|
[
|
|
"src/domain/analysisErrorCore.ts",
|
|
"src/domain/parseFailureAnalysisError.ts",
|
|
],
|
|
);
|
|
|
|
// A limit a parser stopped at is a ParseFailureError<"limit"> (decodeLimit in
|
|
// src/domain/parseFailure); a refusal is an AnalysisRefusal. A local limit
|
|
// class on plain Error hides the limit's name and maximum from both; a limit
|
|
// subclass of BinaryResourceFailure keeps a second limit field beside the
|
|
// allowance its LimitRef already names. The environment-state extraction's private retention stop is control flow that
|
|
// its own entry point catches and turns into `null`; it is never reported.
|
|
checkCounted(
|
|
"local limit class (use decodeLimit from src/domain/parseFailure, a named BinaryResourceFailure allowance, or an AnalysisRefusal)",
|
|
"local-limit-error-class",
|
|
files,
|
|
localLimitErrorClassCount,
|
|
["src/domain/analysisView/EnvironmentStateExtraction.ts"],
|
|
);
|
|
|
|
// A resource allowance is charged and refunded through `Budget` in
|
|
// src/domain/budget, which refuses malformed or oversized charges without
|
|
// changing the remainder. Hand-written `remaining -=` / `retained +=`
|
|
// arithmetic repeats that admission and drifts (charge-then-check, no
|
|
// safe-integer check). A cursor, tally or retained length that is compared
|
|
// with a limit without being charged against it carries
|
|
// `// not-an-allowance: <reason>` on its field declaration (#11408).
|
|
checkCounted(
|
|
"hand-written budget arithmetic (use Budget from src/domain/budget, or mark a cursor or tally field with `// not-an-allowance: <reason>`)",
|
|
"budget-arithmetic",
|
|
files,
|
|
budgetArithmeticCount,
|
|
["src/domain/budget.ts"],
|
|
);
|
|
|
|
// A slice to a named maximum drops items; boundedList in src/domain/boundedList
|
|
// keeps the count of what it dropped beside the retained items, so a consumer
|
|
// can say that more exist and how many. Two caps drop no evidence and carry a
|
|
// reason marker instead (#11411): `// generation-cap: <reason>` limits what REA
|
|
// generates (suggested checks, guards) or the work spent finding it, and
|
|
// `// sample-cap: <reason>` limits illustrative samples whose full totals the
|
|
// same result already reports.
|
|
checkCounted(
|
|
"slice to a named maximum (use boundedList or BoundedListCollector from src/domain/boundedList so the omitted count travels with the items, or mark a generation or sample cap with its reason)",
|
|
"constant-maximum-slice",
|
|
files,
|
|
(_content, file) =>
|
|
unmarkedMatchCount(
|
|
file.source,
|
|
/\.slice\(\s*0\s*,\s*[A-Z][A-Z0-9_]*\s*\)/gu,
|
|
["generation-cap", "sample-cap"],
|
|
),
|
|
["src/domain/boundedList.ts"],
|
|
);
|
|
|
|
// Display text cut with an appended ellipsis comes from ellipsisExcerpt in
|
|
// src/domain/excerpt, which never splits a surrogate pair and marks the result
|
|
// as excerpt text. A hand-written `${text.slice(0, n)}…` does neither.
|
|
checkCounted(
|
|
"hand-written ellipsis excerpt (use ellipsisExcerpt from src/domain/excerpt)",
|
|
"ad-hoc-ellipsis",
|
|
files,
|
|
/\.slice\(\s*0\s*,[^)]*\)\)?\}(?:…|\.\.\.)/gu,
|
|
["src/domain/excerpt.ts"],
|
|
);
|
|
|
|
// A deadline is a monotonic budget owned by `Deadline` in src/domain/deadline;
|
|
// a wall-clock sum moves with clock changes and has no finalize phase. The
|
|
// remaining copy converts a monotonic budget for a browser page, which can
|
|
// only read its own wall clock.
|
|
checkCounted(
|
|
"wall-clock deadline computation (use Deadline from src/domain/deadline)",
|
|
"wall-clock-deadline",
|
|
files,
|
|
/Date\.now\(\)\s*\+/gu,
|
|
[],
|
|
);
|
|
|
|
// `tshark -T json` has one envelope reader, src/domain/pcap/tsharkJsonPackets.ts,
|
|
// which owns malformed JSON, the packet array and each packet's layers.
|
|
checkCounted(
|
|
"local tshark JSON envelope read (use parseTsharkJsonPackets or readTsharkJsonPackets from src/domain/pcap/tsharkJsonPackets)",
|
|
"tshark-json-envelope",
|
|
files,
|
|
/\b_source\s*\.\s*layers\b/gu,
|
|
["src/domain/pcap/tsharkJsonPackets.ts"],
|
|
);
|
|
|
|
// Text from an unknown caught value has one owner, src/kernel/errorMessage.ts.
|
|
// The pattern matches the inline copy with the same expression in all three
|
|
// places; a named local helper with this body is the same copy.
|
|
// Copies that run in another realm cannot import the owner and are excluded by
|
|
// name, so no slice rewrites them: the regex worker's source string and a
|
|
// fetch run inside the browser page through page.evaluate.
|
|
const ISOLATED_ERROR_MESSAGE_COPIES = new Map([
|
|
["src/browser/PlaywrightScenarioRequest.ts", 1],
|
|
["src/process/RegexMatcher.ts", 1],
|
|
]);
|
|
const inlineErrorMessage =
|
|
/(?<![\w$.])([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s+instanceof\s+Error\s*\?\s*\1\.message\s*:\s*String\(\s*\1\s*\)/gu;
|
|
checkCounted(
|
|
"inline error-to-message conversion (use errorMessage from src/kernel/errorMessage)",
|
|
"inline-error-message",
|
|
files,
|
|
(content, { path }) =>
|
|
Math.max(
|
|
0,
|
|
(content.match(inlineErrorMessage)?.length ?? 0) -
|
|
(ISOLATED_ERROR_MESSAGE_COPIES.get(path) ?? 0),
|
|
),
|
|
["src/kernel/errorMessage.ts"],
|
|
);
|
|
|
|
// Two hexadecimal digits for one byte have one owner, src/kernel/byteToHex.ts.
|
|
checkCounted(
|
|
"inline byte-to-hex formatting (use byteToHex from src/kernel/byteToHex)",
|
|
"inline-byte-hex",
|
|
files,
|
|
/\.toString\(16\)\s*\.padStart\(\s*2\s*,\s*"0"\s*\)/gu,
|
|
["src/kernel/byteToHex.ts"],
|
|
);
|
|
|
|
// A one-shot SHA-256 hex digest of an in-memory value has one owner,
|
|
// src/kernel/sha256Hex.ts. Incremental and streamed hashing (a Hash updated
|
|
// more than once) is not counted.
|
|
checkCounted(
|
|
"one-shot SHA-256 hex digest (use sha256Hex from src/kernel/sha256Hex)",
|
|
"inline-sha256-hex",
|
|
files,
|
|
/createHash\(\s*"sha256"\s*\)\s*\.update\((?:[^()]|\((?:[^()]|\((?:[^()]|\([^()]*\))*\))*\))*\)\s*\.digest\(\s*"hex"\s*\)/gu,
|
|
["src/kernel/sha256Hex.ts"],
|
|
);
|
|
|
|
// The isRecord predicate written inline in a condition is a copy of
|
|
// src/kernel/isRecord.ts. Bodies of the named copies in RECORD_PREDICATE_COPIES
|
|
// are counted by that list, not here.
|
|
const inlineRecordCheck =
|
|
/typeof\s+([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*===\s*["']object["']\s*&&\s*\1\s*!==\s*null\s*&&\s*!Array\.isArray\(\s*\1\s*\)/gu;
|
|
checkCounted(
|
|
"inline non-array record check (use isRecord from src/kernel/isRecord)",
|
|
"inline-record-check",
|
|
files,
|
|
(content) =>
|
|
Math.max(
|
|
0,
|
|
(content.match(inlineRecordCheck)?.length ?? 0) -
|
|
recordPredicateCounts(content).bodies,
|
|
),
|
|
["src/kernel/isRecord.ts"],
|
|
);
|
|
|
|
// Strict UTF-8 decoding has one owner, src/domain/strictUtf8.ts, which makes
|
|
// each site state its byte-order-mark policy. A local fatal decoder silently
|
|
// strips a leading BOM unless it remembers ignoreBOM. The pattern matches the
|
|
// options in any order and an omitted label. The remaining copy runs inside a
|
|
// browser page through page.evaluate, which cannot import the owner.
|
|
checkCounted(
|
|
"local strict UTF-8 TextDecoder (use strictUtf8Decoder, decodeStrictUtf8 or isStrictUtf8 from src/domain/strictUtf8)",
|
|
"strict-utf8-decoder",
|
|
files,
|
|
/new TextDecoder\(\s*(?:(?:["'`]utf-?8["'`]|undefined)\s*,\s*)?\{[^}]*\bfatal:\s*true/giu,
|
|
["src/domain/strictUtf8.ts"],
|
|
);
|
|
|
|
// Turning a completed result into a cancellation after cleanup is the
|
|
// finalization precedence that runOwned owns (src/providers/runOwned.ts).
|
|
checkCounted(
|
|
"completed result reclassified by a hand-read abort signal (finalize through runOwned in src/providers/runOwned)",
|
|
"completed-abort-reclassification",
|
|
files,
|
|
/\.ok\s*&&\s*(?:isAborted\(|[\w.?]*signal\??\.aborted)/gu,
|
|
["src/providers/runOwned.ts"],
|
|
);
|
|
|
|
// An abort reason names who ended the work: a typed `CallerAbort` at the CLI,
|
|
// MCP and HTTP adapters, or an `OwnerCancellation` when REA closes an owner.
|
|
// A bare `.abort()` leaves an anonymous platform AbortError as the cause.
|
|
// Playwright's `route.abort(errorCode)` takes a network error code instead;
|
|
// its call sites pass that code explicitly so the scan stays receiver-independent.
|
|
checkCounted(
|
|
"AbortController.abort() without a reason (pass a CallerAbort or OwnerCancellation from src/domain/analysisErrorCore)",
|
|
"abort-without-reason",
|
|
files,
|
|
/\.abort\(\s*\)/gu,
|
|
[],
|
|
);
|
|
|
|
// GDB MI result records have one parser, src/gdb/GdbMiRecord.ts, which
|
|
// returns typed records and typed failures. A regex over `\^done` accepts a
|
|
// malformed record by its prefix.
|
|
checkCounted(
|
|
"GDB MI result record regex (use parseGdbMiResultRecord or parseGdbMiDoneRecord from src/gdb/GdbMiRecord)",
|
|
"gdb-mi-record-regex",
|
|
files,
|
|
/\\\^\(?(?:\?:)?(?:done|running|connected|error|exit)\b/gu,
|
|
["src/gdb/GdbMiRecord.ts"],
|
|
);
|
|
|
|
// src/cli owns option and command spellings; cli-text-guard.mjs states the
|
|
// rule and its written exemptions (host-only commands, CLI-only files).
|
|
checkCounted(
|
|
"REA CLI option or command named outside the CLI layer (name the contract field or operation; src/cli owns option and command spellings)",
|
|
"cli-option-text-outside-cli",
|
|
files.filter(({ path }) => cliTextGuardSelects(path)),
|
|
cliTextOutsideCliCount,
|
|
[],
|
|
);
|
|
|
|
// tool-registration-guard.mjs states the rule and its written owners.
|
|
checkCounted(
|
|
"MCP tool registered outside the shared binding table (bind it in src/server/serviceToolBindings.ts)",
|
|
"bespoke-mcp-tool-registration",
|
|
files.filter(({ path }) => path.startsWith("src/")),
|
|
toolRegistrationCount,
|
|
[...TOOL_REGISTRATION_OWNERS.keys()],
|
|
);
|
|
|
|
// A runtime setting view throws the ConfigurationError of a malformed launch
|
|
// seed; readRuntimeSetting in src/config/runtimeAnalysisSettings.ts returns it
|
|
// as a Result. Catching it by hand mixes it into each site's own failures.
|
|
checkCounted(
|
|
"hand-caught ConfigurationError (read runtime settings with readRuntimeSetting from src/config/runtimeAnalysisSettings)",
|
|
"hand-caught-configuration-error",
|
|
files,
|
|
/\bcause instanceof ConfigurationError\b/gu,
|
|
["src/config/runtimeAnalysisSettings.ts"],
|
|
);
|
|
|
|
// Byte-format parsers read untrusted input. Bounds, truncation and failure
|
|
// kind belong to BinaryReader (src/domain/binaryContainer.ts) and
|
|
// the ParseFailure algebra (src/domain/parseFailure.ts), not to each parser.
|
|
const PARSER_FOLDERS = [
|
|
"src/android/",
|
|
"src/apkSignature/",
|
|
"src/artifacts/",
|
|
"src/dotnet/",
|
|
"src/electron/",
|
|
"src/erlang/",
|
|
"src/evm/",
|
|
"src/firmware/",
|
|
"src/flutter/",
|
|
"src/go/",
|
|
"src/gpu/",
|
|
"src/il2cpp/",
|
|
"src/model/",
|
|
"src/native/",
|
|
"src/python/",
|
|
// Shared artifact readers (ZIP, directory, ASAR header) live in resources.
|
|
"src/resources/",
|
|
"src/rust/",
|
|
"src/v8/",
|
|
"src/wasm/",
|
|
...[
|
|
"android",
|
|
"apkSignature",
|
|
"apple",
|
|
"electron",
|
|
"erlang",
|
|
"evm",
|
|
"firmware",
|
|
"flutter",
|
|
"go",
|
|
"gpu",
|
|
"il2cpp",
|
|
"managed",
|
|
"model",
|
|
"native",
|
|
"pcap",
|
|
"python",
|
|
"rust",
|
|
"v8",
|
|
"wasm",
|
|
"windows",
|
|
"zip",
|
|
].map((folder) => `src/domain/${folder}/`),
|
|
];
|
|
const parserFiles = files.filter((file) =>
|
|
PARSER_FOLDERS.some((folder) => file.path.startsWith(folder)),
|
|
);
|
|
|
|
// An unchecked Buffer or DataView read throws a bare RangeError past the end,
|
|
// which a catch site cannot tell from a host stack or string limit.
|
|
checkCounted(
|
|
"raw Buffer or DataView numeric read (use BinaryReader from src/domain/binaryContainer)",
|
|
"raw-buffer-read",
|
|
files,
|
|
/\.(?:read(?:Big)?U?Int(?:8|16|32|64)?(?:LE|BE)?|readBigUint64(?:LE|BE)|readUint(?:8|16|32)(?:LE|BE)?|read(?:Float|Double)(?:LE|BE)|get(?:Big)?(?:Uint|Int)(?:8|16|32|64)|getFloat(?:32|64))\(/gu,
|
|
["src/domain/binaryContainer.ts"],
|
|
);
|
|
|
|
// An input fault is a ParseFailureError; a broken internal assumption is a
|
|
// defect, not an input fault, and throws invariantViolation from
|
|
// src/domain/internalInvariant so callers never read it as bad bytes.
|
|
// Process-lifecycle owners in parser folders read their private helper's
|
|
// replies through schemas; their plain throws report the helper's startup,
|
|
// handshake and cleanup outcomes, which are process failures, not parse faults.
|
|
const PROCESS_LIFECYCLE_OWNERS = [
|
|
"src/android/JadxWorkspaceRoot.ts",
|
|
"src/native/pwntools/PwntoolsDecoder.ts",
|
|
];
|
|
const PLAIN_THROW = /throw new (?:Error|TypeError|RangeError)\(/gu;
|
|
checkCounted(
|
|
"plain Error, TypeError or RangeError thrown by a parser (throw a ParseFailureError from src/domain/parseFailure for an input fault, or invariantViolation from src/domain/internalInvariant for a broken internal assumption)",
|
|
"parser-plain-throw",
|
|
parserFiles.filter((file) => !PROCESS_LIFECYCLE_OWNERS.includes(file.path)),
|
|
PLAIN_THROW,
|
|
[],
|
|
);
|
|
// The lifecycle owners' existing process-failure throws are counted, so a
|
|
// parse fault or defect added there later cannot hide behind the exemption.
|
|
checkCounted(
|
|
"plain Error, TypeError or RangeError thrown by a parser-folder process-lifecycle owner (keep its existing process-failure throws; throw a ParseFailureError for an input fault or invariantViolation for a broken internal assumption)",
|
|
"lifecycle-plain-throw",
|
|
parserFiles.filter((file) => PROCESS_LIFECYCLE_OWNERS.includes(file.path)),
|
|
PLAIN_THROW,
|
|
[],
|
|
);
|
|
|
|
// A per-format failure class restates the ParseFailure algebra under its own
|
|
// spelling and needs its own catch-site translation; parsers throw a
|
|
// ParseFailureError instead. A subclass of ParseFailureError (such as
|
|
// CaptureFormatError) keeps the shared kind and is not counted. The name
|
|
// pattern covers format, parse, document, source, decode and syntax failures,
|
|
// and any property-list or archive failure (such as a nesting limit or an
|
|
// unsupported UID), built on any of the host's general error classes.
|
|
checkCounted(
|
|
"per-format failure class extending a host error (throw a ParseFailureError from src/domain/parseFailure)",
|
|
"parser-format-failure-class",
|
|
files,
|
|
/class (?:\w*(?:Format|Parse|Document|Source|Decode|Decoding|Encoding|Syntax)|\w*(?:Plist|PropertyList|Archive)\w*)(?:Failure|Error|Issue) extends (?:Error|TypeError|RangeError|SyntaxError)\b/gu,
|
|
["src/domain/parseFailure.ts"],
|
|
);
|
|
|
|
// Mach-O load-command codes have one table; a literal code in a load-command
|
|
// reader restates it and drifts from the named command it means.
|
|
checkCounted(
|
|
"literal Mach-O load-command code (use LC from src/domain/apple/machoLoadCommandCodes)",
|
|
"macho-load-command-literal",
|
|
files.filter((file) =>
|
|
/MachoLoadCommandCursor|readMachoLoadCommand|machoLoadCommandCodes/u.test(
|
|
file.content,
|
|
),
|
|
),
|
|
// An equality test, or membership in a literal list of codes.
|
|
/\b(?:frame\.command|command\.kind|command|cmd)\s*[!=]==\s*(?:0x[0-9a-fA-F]+|\d+)\b|\[\s*(?:0x[0-9a-fA-F]+|\d+)(?:\s*,\s*(?:0x[0-9a-fA-F]+|\d+))*\s*,?\s*\]\s*\.(?:includes|indexOf)\(\s*(?:\w+\.)*(?:command|cmd|kind)\s*\)/gu,
|
|
["src/domain/apple/machoLoadCommandCodes.ts"],
|
|
);
|
|
|
|
// JSON.parse keeps the last of repeated member names without saying so; a
|
|
// parser of artifact content must state its duplicate-member policy
|
|
// (src/domain/jsonDuplicateMember.ts finds a repeated name).
|
|
checkCounted(
|
|
"plain JSON.parse of parser input (state the duplicate-member policy; see src/domain/jsonDuplicateMember)",
|
|
"parser-json-parse",
|
|
parserFiles,
|
|
/JSON\.parse\(/gu,
|
|
[],
|
|
);
|
|
|
|
// Raw JSON Schema keywords and `x-rea-*` markers in `.meta()` bypass the
|
|
// canonical Zod checks and reach every JSON Schema projection, including the
|
|
// advertised one. Presentation facts are typed annotations
|
|
// (src/domain/schemaAnnotations); constraints belong in Zod checks, or in a
|
|
// src/domain/schemaConstraints helper that adds the check and its keyword
|
|
// together.
|
|
checkCounted(
|
|
"raw JSON Schema keyword or x-rea marker in Zod .meta() (use a typed annotation from src/domain/schemaAnnotations, a Zod check, or a src/domain/schemaConstraints helper)",
|
|
"raw-json-schema-meta",
|
|
files,
|
|
/\.meta\(\s*\{\s*"?(?:x-rea-[\w-]+|\$ref|not|allOf|anyOf|oneOf|if|then|else|dependentRequired|dependentSchemas|dependencies|uniqueItems|(?:min|max)(?:Length|Items|Properties|imum)|exclusive(?:Min|Max)imum|multipleOf|type|const|enum|format|pattern|patternProperties|properties|required|additionalProperties|items|prefixItems|contains|content(?:MediaType|Encoding|Schema)|propertyNames)"?\s*:/gu,
|
|
["src/domain/schemaConstraints.ts"],
|
|
);
|
|
|
|
// A RangeError can mean a stack overflow, a host string or buffer limit, a
|
|
// raw read or write past a buffer, or whatever its thrower intended. Only
|
|
// known host limits are classified; parsers throw a ParseFailureError.
|
|
checkCounted(
|
|
"direct RangeError interpretation (use hostRangeErrorKind or parseFailureFromCause from src/domain/parseFailure)",
|
|
"range-error-interpretation",
|
|
files,
|
|
/instanceof RangeError/gu,
|
|
["src/domain/parseFailure.ts"],
|
|
);
|
|
|
|
// Cleanup completion is recorded by the owner and read by errors when asked;
|
|
// AnalysisError has no push API. Composing dependency sets with
|
|
// bindCleanupDependencies() is being replaced, so it may not spread.
|
|
checkCounted(
|
|
"bindCleanupDependencies() composition outside the error base (compose through analysisErrorWithCleanupDependencies, analysisErrorWithCloseRejection(s) for close rejections whose completion may be unknown, or runOwned, or copy lease claims)",
|
|
"cleanup-dependency-binding",
|
|
files,
|
|
/\.bindCleanupDependencies\(/gu,
|
|
["src/domain/analysisErrorBase.ts", "src/domain/analysisErrorCleanup.ts"],
|
|
);
|
|
|
|
// A launcher's PATH search order (POSIX empty and relative entries and `..`;
|
|
// Windows quoted entries and PATHEXT) belongs to src/process/executableSearch;
|
|
// callers choose only how they probe each candidate.
|
|
checkCounted(
|
|
"PATH or PATHEXT split outside the executable search owner (use posixPathCandidates or windowsPathCandidates from src/process/executableSearch)",
|
|
"path-search-split",
|
|
files,
|
|
/\.split\(\s*(?:posix\.|win32\.)?(?:delimiter|pathDelimiter)\s*\)|\bPATH\b[^\n]{0,12}\.split\(":"\)|\bPATHEXT\b[^\n]{0,60}\.split\(/gu,
|
|
["src/process/executableSearch.ts"],
|
|
);
|
|
|
|
// The running host is read once by src/platform/HostPlatform; composition
|
|
// takes it from there and passes the platform or architecture on as a
|
|
// required parameter. An ambient read elsewhere mixes the host REA runs on
|
|
// with the host a caller asked about, and cannot be selected by a test.
|
|
// Named imports from node:process or node:os and os.platform()/os.arch() are
|
|
// the same read under another spelling.
|
|
const ambientHostRead = (property, osFunction) =>
|
|
new RegExp(
|
|
String.raw`\bprocess\.${property}\b|\bos\.${osFunction}\(\)|\bimport\s*(?:type\s*)?\{[^}]*\b(?:${property}|${osFunction})\b[^}]*\}\s*from\s*["'](?:node:)?(?:process|os)["']`,
|
|
"gu",
|
|
);
|
|
checkCounted(
|
|
"ambient process.platform read (take HOST_PLATFORM from src/platform/HostPlatform at composition and pass the platform as a parameter)",
|
|
"ambient-host-platform",
|
|
files,
|
|
ambientHostRead("platform", "platform"),
|
|
["src/platform/HostPlatform.ts"],
|
|
);
|
|
checkCounted(
|
|
"ambient process.arch read (take HOST_PLATFORM from src/platform/HostPlatform at composition and pass the architecture as a parameter)",
|
|
"ambient-host-architecture",
|
|
files,
|
|
ambientHostRead("arch", "arch"),
|
|
["src/platform/HostPlatform.ts"],
|
|
);
|
|
|
|
// Tests select a platform or architecture by injecting it (a parameter, a
|
|
// `host` option, or a mock of src/platform/HostPlatform). Redefining
|
|
// process.platform or process.arch stops exercising its branch once the module
|
|
// under test takes the host from HostPlatform, and still passes. Each module
|
|
// migration switches its tests to injection and lowers this baseline.
|
|
const listTestFiles = async (dir) => {
|
|
const output = [];
|
|
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
const path = join(dir, entry.name);
|
|
if (entry.isDirectory()) output.push(...(await listTestFiles(path)));
|
|
else if (/\.(?:test|spec|fixture)\.ts$/u.test(entry.name))
|
|
output.push(path);
|
|
}
|
|
return output;
|
|
};
|
|
const testFiles = await Promise.all(
|
|
[
|
|
...(await listTestFiles(join(root, "src"))),
|
|
...(await listFiles(join(root, "tests"))),
|
|
...(await listTestFiles(join(root, "tests"))),
|
|
].map(async (path) => ({
|
|
path: relative(root, path).split(sep).join("/"),
|
|
content: await readFile(path, "utf8"),
|
|
})),
|
|
);
|
|
checkCounted(
|
|
"test redefines process.platform or process.arch (inject the platform: pass it as a parameter or host option, or mock src/platform/HostPlatform)",
|
|
"test-host-platform-stub",
|
|
testFiles,
|
|
/\b(?:defineProperty|spyOn)\(\s*(?:globalThis\.)?process\s*,\s*["'`](?:platform|arch)["'`]/gu,
|
|
[],
|
|
);
|
|
|
|
// Schemas import zod directly. incur's `z` is a re-export of the same package;
|
|
// importing it through the CLI framework ties schemas to a dependency REA is
|
|
// removing (#11654). Declarations are read from code tokens, so the text in a
|
|
// comment or string fixture does not count.
|
|
checkCounted(
|
|
'zod imported through incur (import { z } from "zod")',
|
|
"incur-zod-reexport",
|
|
[...files, ...testFiles],
|
|
(_content, file) => incurZodImportCount(file.source ?? file.content),
|
|
[],
|
|
);
|
|
|
|
// `find` on a parsed section, program-header or load-command table silently
|
|
// keeps the first of repeated declarations. Select keyed entries through
|
|
// src/domain/keyedCollection (`uniqueKeyed`, `allKeyed`, or
|
|
// `firstKeyed`/`lastKeyed` with the format's precedence rule); an
|
|
// address-containment test that selects nothing uses `some`. GuidanceAccess
|
|
// looks up a guidance document's heading section by its locator identity,
|
|
// not a parsed binary section table.
|
|
checkCounted(
|
|
"first-match section, program or command lookup (select through src/domain/keyedCollection)",
|
|
"section-first-match",
|
|
files,
|
|
/\b(?:sections|programs|commands)\.find(?:Last)?\(/gu,
|
|
["src/application/GuidanceAccess.ts"],
|
|
);
|
|
|
|
// The same first-match choice, recognized by its shape rather than the
|
|
// table's variable name (see keyed-first-match.mjs). Select through
|
|
// src/domain/keyedCollection instead.
|
|
checkCounted(
|
|
"first-match lookup by key field in a parser (select through src/domain/keyedCollection)",
|
|
"keyed-first-match",
|
|
parserFiles,
|
|
countKeyedFirstMatches,
|
|
[],
|
|
);
|
|
|
|
// A verifier fixture root is removed only after the MCP clients, sessions and
|
|
// processes that may still use it confirm cleanup; otherwise it is retained
|
|
// and named. scripts/lib/verifier-fixture.mjs owns that ordering on a
|
|
// src/process PrivateRuntimeRoot, so verifiers allocate roots through it.
|
|
const verifierScripts = await Promise.all(
|
|
(await readdir(join(root, "scripts"), { recursive: true }))
|
|
.map((path) => path.split(sep).join("/"))
|
|
.filter(
|
|
(path) =>
|
|
/^(?:verify-[^/]+|verify\/.+)\.mjs$/u.test(path) &&
|
|
path !== "verify/architecture-guards.mjs",
|
|
)
|
|
.map(async (path) => ({
|
|
path: `scripts/${path}`,
|
|
content: blankComments(
|
|
await readFile(join(root, "scripts", path), "utf8"),
|
|
),
|
|
})),
|
|
);
|
|
// The Windows native lane tests PrivateRuntimeRoot itself: it calls
|
|
// PrivateRuntimeRoot.create under a parent whose DELETE lease forces a sharing
|
|
// violation and asserts the typed refusal. That call is the subject under
|
|
// test, not a verifier root, so exactly one occurrence of that expression is
|
|
// exempt; any other allocation in the file, including a second copy of it,
|
|
// still counts.
|
|
const verifierRootSubjectsUnderTest = new Map([
|
|
[
|
|
"scripts/verify-windows-native.mjs",
|
|
"PrivateRuntimeRoot.create({ parent: sharingParent.observation.path })",
|
|
],
|
|
]);
|
|
checkCounted(
|
|
"verifier fixture root allocated outside VerifierFixture (use scripts/lib/verifier-fixture.mjs)",
|
|
"verifier-fixture-root",
|
|
verifierScripts.map((file) => {
|
|
const subject = verifierRootSubjectsUnderTest.get(file.path);
|
|
return subject === undefined
|
|
? file
|
|
: { ...file, content: file.content.replace(subject, "") };
|
|
}),
|
|
/\b(?:mkdtemp(?:Sync)?|createCanonicalTemporaryDirectory)\(|\bPrivateRuntimeRoot\.create\(/gu,
|
|
[],
|
|
);
|
|
|
|
// The MCP SDK client compiles every listed tool's output schema on its first
|
|
// tool call. With the default Ajv options, REA's catalog costs gigabytes of
|
|
// allocation per client, so test clients take the lazy, reference-preserving
|
|
// validation from tests/fixtures/mcpSchemaValidation (directly, or through
|
|
// tests/support/mcp/mcpFixture). Tests of the SDK default itself stay listed.
|
|
// The counter parses each source, so comments need no stripping here. A
|
|
// client built inside a generated child script is string data, not a call, so
|
|
// it is not read (such scripts run over compiled dist/ modules, which cannot
|
|
// load the TypeScript fixture).
|
|
const mcpClientTestFiles = testFiles.filter((file) =>
|
|
file.path.startsWith("tests/"),
|
|
);
|
|
checkCounted(
|
|
"MCP SDK client without shared schema validation in tests (pass createMcpSchemaValidation from tests/fixtures/mcpSchemaValidation or use mcpTest)",
|
|
"test-mcp-client-default-validation",
|
|
mcpClientTestFiles,
|
|
countDefaultValidationClients,
|
|
[
|
|
// Checks the SDK default validator itself across catalog refreshes.
|
|
"tests/boundary/mcp/outputValidatorReuse.test.ts",
|
|
],
|
|
);
|
|
|
|
for (const key of baselineTexts.keys())
|
|
if (!checkedBaselineKeys.has(key))
|
|
failures.push(
|
|
`${relative(root, join(baselineDirectory, `${key}.json`))} names no counted guard; delete it or restore its guard.`,
|
|
);
|
|
for (const key of checkedBaselineKeys) {
|
|
const path = join(baselineDirectory, `${key}.json`);
|
|
const shown = relative(root, path);
|
|
const baselineFile = reconcileBaselineFile(
|
|
baselineTexts.get(key),
|
|
baselines[key],
|
|
shrinkBaselines,
|
|
);
|
|
if (baselineFile.action === "write") {
|
|
await writeFile(path, baselineFile.text);
|
|
console.log(`Rewrote ${shown}.`);
|
|
} else if (baselineFile.action === "delete") {
|
|
await rm(path);
|
|
console.log(`Removed ${shown}; its guard has no remaining copies.`);
|
|
} else if (baselineFile.action === "reject")
|
|
failures.push(
|
|
`${shown} is not in its written form (paths sorted by code unit); rewrite it with \`node scripts/verify/architecture-guards.mjs --shrink-baselines\`.`,
|
|
);
|
|
}
|
|
if (baselinesShrunk) console.log("Lowered counted baselines.");
|
|
|
|
if (failures.length > 0) {
|
|
console.error(`Architecture guards failed:\n\n${failures.join("\n\n")}\n`);
|
|
process.exit(1);
|
|
}
|
|
console.log(`Architecture guards passed across ${files.length} source files.`);
|