From 38bf511a50c042b67c9bb0098208cf6f8a231dad Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:25:08 -0500 Subject: [PATCH] fix(errors)!: report unsupported and unrecognized targets on the TargetFailure model (#14281) * feat(errors)!: add the TargetFailure model, its projection table and conformance registry Introduce one domain-owned TargetFailure value whose kind alone derives the public code, category, retryability, recovery and details, for CLI and MCP alike. Selected-file malformed and truncated refusals are the first area on it: AnalysisMalformedTargetError is replaced by AnalysisTargetFailureError, and ParseFailure's byte-structure variants are TargetFailure variants rather than a parallel type. The shared stableArtifactParserFailureCli loop is replaced by a declarative registry (tests/support/targetFailure/readers/*.ts) and one generated suite that runs every registered case through the CLI and MCP. BREAKING CHANGE: selected-file malformed and truncated refusals add details.failure_kind, and a truncated target's remediation now says to re-acquire the complete file instead of choosing another target. Codes are unchanged. Affected operations: every operation that refuses a selected file's malformed or truncated bytes, including the ELF, PE, Mach-O, DWARF, Go, Rust, BEAM, pyc, devicetree, Apple IPS, kernel module, binary hardening, managed PE/CLI and IL2CPP readers. * test(managed): name the target failure error in the merged status test * docs(reference): name the error CSV instead of linking a non-page file * fix(tests): expect the path reason for non-regular dyld inputs #14225 refuses a non-regular dyld input as ArtifactReaderFailure("path"); dylibFileLifetime still expected "format" and fails on main's shard 9. * fix(tests): expect io, invariant and path where #14225 reclassified stableArtifact expected "format" for an impossible descriptor byte count (now io) and an invalid chunk size (now InternalInvariantError); directoryArtifactReaderOpen expected "format" for a non-file entry (now path, the same change as #14238). All three fail on main. * fix(errors)!: raise container reader byte faults as malformed or truncated targets Delete the ambiguous `format` reason from ArtifactReaderFailure and ArtifactOperationError. Each container reader now raises its owner's fact once, through malformedArtifact / truncatedArtifact, with format, offset, field and measured extents. Short reads inside a measured extent are read-coverage integrity failures, path-kind refusals are `path`, foreign or recovery-requiring inputs are `unsupported`, host tool output is `io`, and REA defects are InternalInvariantError. The trace, NTFS journal, release exposure, web capture, native macOS and web artifact adapters project the reader's parsed facts as AnalysisTargetFailureError instead of invalid_request. Inventory malformed, truncated, unsupported and cancelled reasons take their code from the TargetFailure projection table, so a truncated container is unsupported_target with failure_kind "truncated" on both paths. BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact, analyze_javascript_application, inspect_desktop_application, inspect_keyed_archive, inspect_asset_catalog, inspect_nuget_nupkg, trace_dylib_resolution, trace_web_module_imports and trace_web_source_location report damaged container bytes as unsupported_target (details.reason "malformed" or "truncated", with failure_kind and format) instead of artifact_operation_failed with reason "format", and a truncated container as unsupported_target instead of truncated. inspect_playwright_trace, inspect_ntfs_journal, audit_release_exposure, the web capture inspection operations and the caller-selected import and source maps report damaged selected bytes as unsupported_target instead of invalid_request. The `format` reason no longer appears in details.reason. * test(artifacts): expect target failure codes in compiled CLI and MCP suites * fix(errors)!: refuse malformed SQLite, pwntools and EVM inputs as target failures The SQLite engine's `format` reason is renamed to `malformed` at its owner (SQLITE_INSPECTION_REASONS), and its refusal becomes an AnalysisTargetFailureError at the selected path with format "sqlite". The pwntools and EVM worker replies keep their wire reason "format", which their workers define, and the adapters translate it once into a malformed target failure with the profile's format (elf, elf-core, evm-bytecode) instead of an invalid_format argument issue. SQLite joins the target-failure conformance registry. BREAKING CHANGE: inspect_sqlite_database, inspect_binary_layout, inspect_recorded_crash and inspect_evm_interface report a selected file's malformed bytes as unsupported_target with details.failure_kind "malformed", format_failure, format and path, instead of invalid_request with an invalid_format issue on path. * fix(errors): give the integrity kind a schema-valid code and list the reference page artifact_integrity_mismatch's projection schema requires declared and calculated digests, which a TargetFailure of kind integrity does not carry, so the kind now projects artifact_operation_failed with category integrity_mismatch. The model test validates every kind's projection against analysisErrorProjectionSchema. The reference page joins the documentation sidebar. * fix(artifacts): report a short carrier read as a changed file and keep unsupported desktop probes local A Bun or Node SEA short read inside a range already checked against the measured size meant the file changed, not that it was truncated. The carrier range reader and Bun's readExact now raise read-coverage integrity for it, and keep 'outside the file' as the truncated case. DesktopFileInspection records an unsupported managed-metadata probe as a row issue again, so later file checks still run. * test(errors): expect target failure facts in the pwntools and EVM reply suites The literal-replacement scenario now reads the failure's detail instead of an issues[] message, and a malformed reply wrapped by cleanup failure reports category unsupported_target. * test(errors): register PE DOS-signature and truncated IPS refusals and drop their per-command copies The non-MZ PE imports and load-config cases (PE32/PE32+, ZZ and high-bit signatures) and the truncated Apple IPS body move into the conformance registry, which runs them through the CLI and MCP and now also checks that a refusal leaves the selected file unchanged. The per-command tests keep only their valid-image controls. * test(sqlite): drop the malformed-database provider test the conformance registry covers inspect_sqlite_database/not-a-database in the target-failure registry runs the same non-SQLite bytes through the CLI and MCP, asserts the malformed target facts and checks the selected file is unchanged. * feat(errors)!: make failure_kind the identifier and derive code and retry from it Apply the owner review on #14239 to the TargetFailure model: - remove details.format_failure; failure_kind is the only identifier; - give integrity, conflict and io their own codes (target_integrity_mismatch, input_conflict, host_io_failed) and derive inventory malformed, truncated and unsupported codes from the same table; - add a retry hint (none, backoff, after_change) derived from the kind, with io refined by its transient errno fact; retryable stays the unchanged-retry flag and is true exactly for backoff; - rename the limit-cut result code and category truncated to partial; - drop cancelled and resource from the target kinds and spell identifiers in American English (unrecognized); - return a target failure a tool handler throws as a projected isError result instead of letting the SDK flatten it to text. BREAKING CHANGE: details.format_failure is removed (read details.failure_kind). The truncated result code and category are now partial. Target integrity failures report target_integrity_mismatch, host read failures host_io_failed and disagreeing inputs input_conflict. Inventory operations (inventory_artifact, inspect_artifact, extract_artifact and the other inventory callers) report truncated container bytes as unsupported_target. Every target failure carries a top-level retry hint. * test(sqlite): expect a malformed target for non-database bytes in the CLI suite * fix(artifacts): keep changed-file short reads, invalid offsets and EOF declarations apart PyInstaller reads inside the measured size, and .NET bundle manifest refills, now raise read-coverage integrity on a zero-byte read instead of truncated. A .NET bundle field and a Godot PCK directory entry that extend past the file are truncated (with offset and extents) instead of malformed. An absent or invalid ASAR packed offset is malformed; only a valid range past the archive is truncated. The .NET manifest string offset is reported in file coordinates. * fix(pwntools): report a short ELF header as a truncated target The layout and recorded-crash workers raise a distinct truncated reason when the file ends inside the ELF identification or header, and the decoder projects it as failure_kind truncated instead of inferring it from the message. * fix(errors)!: report managed coverage gaps and IL2CPP pair conflicts as target failures Managed readers interpret an issue code once, in managedIssueTargetFailure: a coverage gap is an unsupported target, every other rule violation is a malformed target, and the inventory metadata status is derived from that same fact. managedInspectionTargetFailure now returns only AnalysisTargetFailureError. An IL2CPP binary that parses but does not link to its metadata is a conflict target failure that lists both inputs and blames neither, in place of an invalid_request with two issue entries. Metadata version 108 is an unsupported target. The CLI spells each conflict input's field by the command's option name. BREAKING CHANGE: inspect_managed_artifact, inspect_managed_members, inspect_managed_native_boundaries and the managed comparison operations report unsupported metadata or signature forms as an AnalysisTargetFailureError (failure_kind unsupported, format pe-cli, field, offset) instead of a bare unsupported target. inspect_il2cpp_metadata reports a binary/metadata pair that does not link as code input_conflict with failure_kind conflict and details.inputs, instead of invalid_request with details.issues, and metadata version 108 with failure_kind unsupported. * fix(artifacts): verify the carrier before blaming a short read on the bytes The NTFS $MFT decoder, positional members (FIT, uImage, Bun, Deno) and .NET bundle members now re-verify the source before reporting a short stream as malformed, so a file that changed during the read reports the change. The truncation site builds the model's measured extent. * fix(errors)!: report inventory refusals as target failures of the selected path An inventory, inspection or extraction refused damaged or unsupported container bytes as an ArtifactOperationError whose reason repeated the format owner's kind. It carried no path or retry hint, so the conformance registry could not express container cases. translateArtifactFailure now takes the selected path and returns the reader's TargetFailure as an AnalysisTargetFailureError. The malformed, truncated and unsupported reasons, their classification rows and their presentation branch are deleted from ArtifactOperationError. Readers' unsupported refusals carry their format facts through unsupportedArtifact. Container cases move into the conformance registry, which now opens the target first for session tools such as inspect_artifact. BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact and the bundle readers report a refused container as a target failure of details.path with a top-level retry. details.reason is the owner's description and details.detail is removed. * docs(il2cpp): describe pair conflicts as input_conflict with both inputs * docs(android): name unsupported_target for truncated boot image structures * fix(errors)!: report a target that changed during the read as failure_kind changed Inventory integrity failures whose check means the target moved under the read (container, member and unpacked-entry identity, read coverage, traversal coverage) now take the model's changed projection: code artifact_changed, retry backoff and details.failure_kind changed. A selected target that no longer matches the one the session admitted gets its own admitted-identity check and keeps its reopen recovery. BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact and the other inventory operations report a target that changed during the read as artifact_changed (retryable, failure_kind changed) instead of artifact_operation_failed. Admission-identity refusals report integrity_check admitted-identity instead of container-identity. * test(artifacts): raise the cleanup fixture's decode refusal with its format facts * fix(errors)!: report unsupported and unrecognized targets on the TargetFailure model AnalysisUnsupportedTargetError carried a free-text reason and remediation beside the TargetFailure model, so unsupported refusals had no format, failure_kind or retry hint, and their recovery was prose written at each producer. The class is deleted. Producers raise unsupportedTarget or unrecognizedTarget with the owner's format, and consumers read targetFailureOfKind. The projection table renders the recovery and names the operations the owner lists in related.operations. The foreign-bytes identity loop moves into the conformance registry. BREAKING CHANGE: unsupported and unrecognized targets report failure_kind, format and retry. Their remediation comes from the target-failure table; producer-written remediation sentences are folded into details.reason or replaced by details.related_operations. * test(artifacts): expect admitted-identity for selections replaced before admission A selected source replaced before admission fails the admitted-identity check rather than container-identity since the changed/admitted split. * test(go): name the fixture and result when an MZ carrier is not refused through MCP * style: format the migrated target-failure tests * test(errors): expect the PE readers' native-binary format label for foreign bytes * test(verify): expect target failures for damaged ELF, core and EVM inputs in real-provider verifiers The binary-layout, recorded-crash and EVM verifiers still expected invalid_input for malformed or truncated selected bytes. The pwntools and EVM adapters now report those as unsupported_target with failure_kind; a missing path remains invalid_input. * test(web): expect the partial code for a refused source-map admission The limit-cut code is partial; this Windows-lane test arrived from main with the old truncated spelling. * fix(artifacts): keep refusal facts on DMG verdicts and the selected bundle path hdiutil's "image not recognized" verdict raised the unsupported reason without the owner's facts, so the inventory translation treated it as a reader defect. It now carries an unsupported dmg target failure, and the reader-failure constructor requires facts for every target reason. A bundle resource refusal names the caller's selected bundle path rather than its resolved target. The real-provider verifiers and the Android, source-location acceptance tests expect the model's target-failure categories and codes. * test(errors): assert unsupported refusals' kind and format, and align verifiers and the Electron guide * test(errors): check the MCP target failure as the text clients receive The stdio transport removes the private structured carrier from every isError result, so the conformance suite asserted a field that never reaches clients and failed every case. The projected diagnostic is checked from the JSON text instead. * test(errors): raise main's new unsupported-target fixtures through the model * test(artifacts): expect artifact_changed when selected bytes change after inventory Bundle resources replaced after open and unselected JavaScript sources rewritten after inventory now fail a change check, so they report artifact_changed with retry backoff rather than artifact_operation_failed. * fix(errors): report a session digest mismatch as admitted-identity The digest the session admitted does not change when the same request is repeated, so targetDigestChangedFailure was inviting a backoff retry that fails the same way. It now names admitted-identity, which stays artifact_operation_failed and not retryable, and tells the caller to reopen. Co-authored-by: morluto * fix(artifacts): classify unused PyInstaller compressed input as layout zlib stops at the first complete stream, so a declared span that arrives intact but is not fully consumed is trailing junk or a second stream, not a file that changed. A source that ends before that span stays read-coverage. The cached-carrier test replaces the file with a different size so a shared timestamp cannot hide the rewrite. Co-authored-by: morluto * test(applications): expect unsupported_target for a damaged trace stream A trace member whose CRC fails is a malformed zip target. The partial Evidence assertion now checks that code, failure_kind and format. Co-authored-by: morluto * test(artifacts): assert Android refusal kinds and drop the SEA registry case details.reason is the owner's description, so the boot-image refusals assert failure_kind and format. A malformed SEA blob inside an ELF stays an outer-format inventory with a recognition limitation, which the Node SEA reader tests already cover, so it is not an inspect_artifact refusal. Co-authored-by: morluto * fix(artifacts): pass the selected path into translated target failures translateArtifactFailure names the caller-selected path on a format refusal. Directory inspection and a retained artifact scope both know that path and now supply it. Co-authored-by: morluto * fix(artifacts): charge global pax records against the tar metadata budget Repeated pax global headers were copied into one map without a charge, so each header could stay inside the extended-header allowance while the map grew without a bound. The retained metadata budget is charged for the merged map's keys, values and entries before that map is allocated. Co-authored-by: morluto * test(dylib): expect admitted-identity when the opened target is replaced The session keeps the digest it admitted, so replacing the executable and repeating trace_dylib_resolution is not a retryable container change. Co-authored-by: morluto * style: format the inventory path translation and conformance suite * fix(artifacts): keep the unsupported-target migration in files the inventory merge replaced * test(errors): expect target failures for ZIP inventory refusals and input_conflict for an unlinked IL2CPP pair * test(artifacts): expect a malformed target failure for an ISO 9660 directory cycle * test(web): expect a malformed target failure on the captured source path * test(artifacts): expect a malformed ZIP target failure for a corrupt Zstandard member * test(javascript): read the owner's input facts from details.reason and recovery from the projection * test(iso9660): assert the malformed target failure fields details.reason is the owner's description. The compiled CLI refusal is identified by failure_kind and format. Co-authored-by: morluto * test(errors): assert selection and unsupported view fields A desktop root that is not a directory is a selection failure, so the CLI reports invalid_request. An analysis view the parent cannot supply is unsupported evidence; the tests read failure_kind, format, field and related_operations. Co-authored-by: morluto * fix(errors): keep binary plist UID facts on unsupported targets Pass the reader's UnsupportedBinaryPlistUidError failure through instead of rebuilding a bplist refusal that drops field and undecodedContent. Co-authored-by: morluto * test(errors): keep oversized binary plist UID facts on keyed archives Assert the reader projects format, field, and undecoded content from the parser failure instead of a rebuilt bplist refusal. Co-authored-by: morluto --------- Co-authored-by: Cursor Agent Co-authored-by: morluto --- .../guides/javascript/electron-observation.md | 2 +- docs/reference/target-failures.md | 1 + docs/user-visible-errors.csv | 1 - scripts/verify-evm-interface.mjs | 3 +- scripts/verify/apple/dispatch.mjs | 7 +- src/adb/AdbAppOperations.ts | 14 ++- src/adb/AdbCommand.test.ts | 12 +- src/adb/AdbCommand.ts | 18 ++- src/adb/AdbProvider.test.ts | 2 +- src/adb/AdbProvider.ts | 8 +- src/adb/AdbShellOperations.ts | 5 +- src/apkSignature/ApkSignatureProvider.test.ts | 2 +- src/apkSignature/apkSignatureFailures.ts | 19 ++-- src/apktool/ApktoolCommandRecovery.test.ts | 2 +- src/apktool/ApktoolProvider.test.ts | 2 +- src/apktool/ApktoolProvider.ts | 5 +- .../analysisView/AnalysisViewService.test.ts | 8 +- .../apiContract/ApiContractService.test.ts | 2 +- .../artifacts/ArtifactPathInspection.ts | 4 +- .../binary/AnalysisProviderEvaluation.ts | 12 +- .../binary/AnalysisProviderRegistry.test.ts | 15 ++- .../binary/AnalysisProviderRegistry.ts | 16 ++- .../JavaScriptArtifactReconstruction.ts | 19 ++-- .../ReleaseExposureService.test.ts | 26 +++-- .../releaseExposure/ReleaseExposureService.ts | 16 ++- src/artifacts/ArtifactProvider.ts | 8 +- src/artifacts/DesktopApplicationReader.ts | 20 ++-- .../apple/KeyedArchiveReader.test.ts | 48 ++++++++ src/artifacts/apple/KeyedArchiveReader.ts | 44 +++++--- .../extraction/ArtifactExtraction.ts | 20 ++-- src/artifacts/tar/TarArtifactReader.test.ts | 38 +++++++ src/artifacts/tar/TarWalk.ts | 47 +++++++- .../PlaywrightElectronActiveFuses.test.ts | 10 +- src/browser/PlaywrightElectronActiveFuses.ts | 18 +-- .../PlaywrightElectronActiveProvider.test.ts | 4 +- .../PlaywrightTraceDecoder.test.ts | 5 +- .../playwrightTrace/PlaywrightTraceDecoder.ts | 5 +- .../PlaywrightTraceLifecycle.test.ts | 5 +- .../history/playwrightTrace/TraceStream.ts | 5 +- src/domain/analysisErrorBase.ts | 6 +- src/domain/analysisErrorClassification.ts | 4 - src/domain/analysisErrorCore.ts | 85 +++++++++++---- src/domain/analysisErrorPresentation.ts | 23 ++-- src/domain/analysisErrorProjection.test.ts | 7 +- src/domain/analysisErrorProjection.ts | 10 +- .../WebNetworkProjectionAccumulator.ts | 24 ++-- src/domain/analysisView/analysisView.test.ts | 2 +- src/domain/analysisView/analysisView.ts | 17 ++- src/domain/analysisView/cyclonedxView.test.ts | 9 +- src/domain/analysisView/cyclonedxView.ts | 5 +- .../environmentCoverageView.test.ts | 2 +- .../environmentManifestView.test.ts | 10 +- .../analysisView/environmentManifestView.ts | 5 +- .../analysisView/environmentStateView.test.ts | 2 +- .../analysisView/scenarioCaptureRecords.ts | 5 +- .../webNetworkApiSurfaceView.test.ts | 14 ++- .../analysisView/webNetworkApiSurfaceView.ts | 5 +- .../apiContract/parseApiContract.test.ts | 5 +- src/domain/apiContract/parseApiContract.ts | 5 +- src/domain/apple/machoSliceSelection.ts | 7 +- src/domain/apple/plistScalars.test.ts | 9 +- src/domain/parseFailureAnalysisError.test.ts | 11 +- src/domain/parseFailureAnalysisError.ts | 9 +- src/domain/pngVisualDiff.test.ts | 4 +- src/domain/pngVisualDiff.ts | 8 +- src/domain/reconstructionVerification.ts | 9 +- src/domain/targetFailure.ts | 103 ++++++++++++++++-- src/dotnet/ManagedStaticProvider.ts | 5 +- src/electron/ElectronFuseProvider.test.ts | 2 +- src/evm/EvmoleInterfaceProvider.ts | 5 +- src/flutter/FlutterBuildProvider.ts | 11 +- src/ghidra/GhidraAnalysisProfile.ts | 8 +- src/ghidra/GhidraMipsProfile.test.ts | 8 +- src/ghidra/GhidraPowerPcProfile.test.ts | 4 +- .../extensions/GhidraExtensions.test.ts | 12 +- src/ghidra/extensions/GhidraExtensions.ts | 8 +- .../AppleDispatchMetadata.failure.test.ts | 8 +- src/native/AppleDispatchMetadata.ts | 17 +-- src/native/NativeMacOSProvider.ts | 6 +- src/native/NativeMachoInspection.test.ts | 2 +- src/native/NativeMachoInspection.ts | 18 +-- .../metadata/MachoSliceSelection.test.ts | 3 +- src/native/pwntools/PwntoolsDecoder.ts | 5 +- src/pcap/PcapCommand.ts | 5 +- tests/acceptance/androidBootImageCli.test.ts | 3 +- tests/acceptance/managedCliOutput.test.ts | 8 +- .../stableArtifactParserFailureCli.test.ts | 55 ---------- .../cli/cliHumanFailureOutput.test.ts | 5 +- .../cli/desktopApplicationCli.test.ts | 12 +- .../evm/evmoleInterfaceProvider.test.ts | 2 +- .../artifactAdmittedIdentity.test.ts | 2 +- .../filesystem/artifactZipIntegrity.test.ts | 8 +- .../filesystem/binaryHardening.test.ts | 2 +- .../filesystem/dotnetBundleArtifacts.test.ts | 2 +- tests/boundary/filesystem/dwarfUnits.test.ts | 6 +- .../filesystem/flutterBuildProvider.test.ts | 2 +- .../filesystem/ghidraPspExtension.test.ts | 6 +- ...avascriptApplicationInputSelection.test.ts | 14 ++- .../filesystem/keyedArchiveSelection.test.ts | 27 +++-- .../boundary/filesystem/nativeExports.test.ts | 4 +- tests/boundary/gpu/codeObjects.test.ts | 8 +- .../il2cpp/il2cppMetadataProvider.test.ts | 14 ++- tests/boundary/mcp/analysisViewMcp.test.ts | 35 +++--- .../boundary/mcp/androidBootImageMcp.test.ts | 3 +- .../mcp/errorHintExclusionMcp.test.ts | 5 +- tests/boundary/mcp/serverLifecycleMcp.test.ts | 5 +- tests/boundary/model/modelArtifact.test.ts | 12 +- tests/boundary/pcap/pcapCommand.test.ts | 4 +- .../boundary/process/providerOutcome.test.ts | 4 +- .../adb/adbCommandFinalization.test.ts | 2 +- .../managed/managedStaticProvider.test.ts | 6 +- ...tifactProvider.extractionAdmission.test.ts | 4 +- .../artifactProvider.extractionFormat.test.ts | 18 +-- .../nativeMachoUuidlessInspection.test.ts | 9 +- .../targetFailure/readers/foreignBytes.ts | 48 ++++++++ 115 files changed, 880 insertions(+), 485 deletions(-) delete mode 100644 tests/acceptance/stableArtifactParserFailureCli.test.ts create mode 100644 tests/support/targetFailure/readers/foreignBytes.ts diff --git a/docs/guides/javascript/electron-observation.md b/docs/guides/javascript/electron-observation.md index 631d041bf8..46f21a5eb9 100644 --- a/docs/guides/javascript/electron-observation.md +++ b/docs/guides/javascript/electron-observation.md @@ -323,7 +323,7 @@ and do not establish IPC delivery or successful removal. Active scenario capture requires that the target Electron executable honors Node CLI inspector flags (`--inspect` or `--remote-debugging-port`) so that Playwright can establish its DevTools protocol session. -When an Electron executable explicitly disables the `EnableNodeCliInspectArguments` fuse (or removes the capability), `capture-electron-scenario` fails immediately before process launch with an `AnalysisUnsupportedTargetError` ("unsupported_target") rather than waiting for the startup deadline. For targets with disabled inspector fuses, use passive CDP inspection via `inspect_electron_page` or run against an unrestricted development binary with the extracted `app.asar`. +When an Electron executable explicitly disables the `EnableNodeCliInspectArguments` fuse (or removes the capability), `capture-electron-scenario` fails immediately before process launch with an `unsupported_target` error whose `details.failure_kind` is `unsupported` and `details.format` is `electron` rather than waiting for the startup deadline. For targets with disabled inspector fuses, use passive CDP inspection via `inspect_electron_page` or run against an unrestricted development binary with the extracted `app.asar`. The real verifier exercises compiled CLI and stdio MCP discovery, page/script inspection, static/runtime reconciliation, active observation, and CLI SIGTERM diff --git a/docs/reference/target-failures.md b/docs/reference/target-failures.md index e35e9670bf..cb1ea373ea 100644 --- a/docs/reference/target-failures.md +++ b/docs/reference/target-failures.md @@ -72,5 +72,6 @@ Container and inventory readers (ZIP, ASAR, PyInstaller, .NET bundles, Node SEA, - `inspect_sqlite_database`, `inspect_binary_layout`, `inspect_recorded_crash` and `inspect_evm_interface` also report a damaged selected file as `unsupported_target` (`failure_kind: "malformed"`, with `format` `sqlite`, `elf`, `elf-core` or `evm-bytecode`), not `invalid_request`. - A short read after REA measured the file is now an integrity failure with `details.integrity_check: "read-coverage"` (the file changed during the read), not a format error. - An inventory, inspection or extraction of a container (`inventory_artifact`, `inspect_artifact`, `extract_artifact` and the bundle readers such as `inspect_keyed_archive`) reports damaged or unsupported bytes as a target failure of the selected `path`, with top-level `retry`, like every other operation. `details.reason` is now the owner's description, and `details.detail` is gone. Before, these refusals reported `details.reason: "malformed"`, `"truncated"` or `"unsupported"` with the description in `details.detail`, and no `path`. +- Every unsupported or unrecognized target is now a target failure too: `failure_kind` is `unsupported` or `unrecognized`, with the owner's `format`, top-level `retry`, and a recovery from the table. Where the owner knows which operations read the target, the recovery names them and `details.related_operations` lists them. Producer-written remediation sentences are gone; their guidance is in `details.reason`. Related: [settings, limits and recovery](limits-and-recovery.md) for limit failures, and `docs/user-visible-errors.csv` for every error case and its code. diff --git a/docs/user-visible-errors.csv b/docs/user-visible-errors.csv index b37c70e53e..b88a0eb2b4 100644 --- a/docs/user-visible-errors.csv +++ b/docs/user-visible-errors.csv @@ -5,7 +5,6 @@ AnalysisInputError,,invalid_request,invalid_input,false AnalysisAccessDeniedError,,access_denied,unavailable,false AnalysisArtifactChangedError,,artifact_changed,integrity_mismatch,true AnalysisCapabilityUnavailableError,,capability_unavailable,unsupported_provider,false -AnalysisUnsupportedTargetError,,unsupported_target,unsupported_target,false AnalysisCancelledError,,cancelled,cancelled,true AnalysisTimeoutError,,provider_timeout,timeout,true AnalysisResourceConstraintError,,resource_constraint,resource_constraint,false diff --git a/scripts/verify-evm-interface.mjs b/scripts/verify-evm-interface.mjs index 7506311b39..92e19f3720 100644 --- a/scripts/verify-evm-interface.mjs +++ b/scripts/verify-evm-interface.mjs @@ -313,7 +313,8 @@ try { assert.equal(failure.code, "unsupported_target"); assert.equal(failure.details.path, path); assert.match(failure.details.reason, /EF00/); - assert.match(failure.remediation.action, /target format/); + assert.equal(failure.details.failure_kind, "unsupported"); + assert.equal(failure.details.format, "evm-bytecode"); cases++; } } diff --git a/scripts/verify/apple/dispatch.mjs b/scripts/verify/apple/dispatch.mjs index 2fb9d401a5..36af6ab1a9 100644 --- a/scripts/verify/apple/dispatch.mjs +++ b/scripts/verify/apple/dispatch.mjs @@ -399,7 +399,12 @@ await withVerifierFixture(fixture, async () => { } assert.equal(cliFailure.code, "unsupported_target"); assert.equal(cliFailure.category, "unsupported_target"); - assert.deepEqual(cliFailure.details, { + // The refusal is the format owner's target failure: its kind and format + // are facts, beside the operation, path and the owner's description. + const { failure_kind: kind, format, ...located } = cliFailure.details; + assert.equal(kind, "malformed"); + assert.equal(typeof format, "string"); + assert.deepEqual(located, { operation: "inspect_native_dispatch_metadata", path: target.value.path, reason, diff --git a/src/adb/AdbAppOperations.ts b/src/adb/AdbAppOperations.ts index c05f7e7e3e..d41f22b56a 100644 --- a/src/adb/AdbAppOperations.ts +++ b/src/adb/AdbAppOperations.ts @@ -2,7 +2,7 @@ import type { AnalysisCapturedOutput } from "../domain/analysisErrorBase.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { AnalysisOutputError, - AnalysisUnsupportedTargetError, + unsupportedTarget, } from "../domain/analysisErrorCore.js"; import { adbResultSchemas, @@ -80,9 +80,10 @@ export const uninstallAdbPackageOperation = async ( ); if (verdict.status === "failure") return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( operation, input.serial, + "android-package", verdict.reason, ), ); @@ -136,9 +137,10 @@ export const startAdbAppOperation = async ( const component = parseResolveActivityOutput(resolved.value.stdout); if (component === null) return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( operation, input.serial, + "android-package", `No launcher activity is declared for ${input.package}`, ), ); @@ -279,9 +281,10 @@ const runAmStart = async ( if (verdict.status !== "refused" || verdict.startedActivity === null) return failure; const { partialObservation } = buildActivityObservation(verdict); - return new AnalysisUnsupportedTargetError( + return unsupportedTarget( operation, serial, + "android-package", verdict.reason ?? "am start refused the intent", { capturedOutput: run.capturedOutput, partialObservation }, ); @@ -299,9 +302,10 @@ const runAmStart = async ( const { result, partialObservation } = buildActivityObservation(verdict); if (verdict.status === "refused") { return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( operation, serial, + "android-package", verdict.reason ?? "am start refused the intent", { capturedOutput, partialObservation }, ), diff --git a/src/adb/AdbCommand.test.ts b/src/adb/AdbCommand.test.ts index 6635d48902..e42a6ada11 100644 --- a/src/adb/AdbCommand.test.ts +++ b/src/adb/AdbCommand.test.ts @@ -87,9 +87,9 @@ it("classifies the complete diagnostic before shortening its displayed reason", ).resolves.toMatchObject({ ok: false, error: { - _tag: "AnalysisUnsupportedTargetError", + _tag: "AnalysisTargetFailureError", path: localPath, - reason: `${stderr.slice(0, 512)}…`, + failure: { detail: `${stderr.slice(0, 512)}…` }, }, }); }); @@ -432,9 +432,9 @@ it("keeps a completed adb refusal primary when post-exit cleanup fails or is can ); if (cancelledResult.ok) throw new Error("Expected refusal"); expect(primaryAnalysisError(cancelledResult.error)).toMatchObject({ - _tag: "AnalysisUnsupportedTargetError", + _tag: "AnalysisTargetFailureError", path: "emulator-5554", - reason: "INSTALL_FAILED_INVALID_APK", + failure: { detail: "INSTALL_FAILED_INVALID_APK" }, }); expect(cancelledResult.error.secondaryFailures).toMatchObject([ { _tag: "AnalysisCancelledError", cause: "late abort during sweep" }, @@ -473,9 +473,9 @@ it("keeps a completed adb refusal primary when post-exit cleanup fails or is can ); if (cleanupResult.ok) throw new Error("Expected refusal with cleanup error"); expect(primaryAnalysisError(cleanupResult.error)).toMatchObject({ - _tag: "AnalysisUnsupportedTargetError", + _tag: "AnalysisTargetFailureError", path: "emulator-5554", - reason: "INSTALL_FAILED_INVALID_APK", + failure: { detail: "INSTALL_FAILED_INVALID_APK" }, }); expect(projectAnalysisError(cleanupResult.error)).toMatchObject({ code: "cleanup_incomplete", diff --git a/src/adb/AdbCommand.ts b/src/adb/AdbCommand.ts index 4926026248..ca96871b5e 100644 --- a/src/adb/AdbCommand.ts +++ b/src/adb/AdbCommand.ts @@ -2,8 +2,8 @@ import { AnalysisProtocolError, AnalysisResourceConstraintError, AnalysisTimeoutError, - AnalysisUnsupportedTargetError, cancelledBy, + unsupportedTarget, } from "../domain/analysisErrorCore.js"; import { primaryAnalysisError, @@ -221,9 +221,10 @@ export const adbExitFailure = ( diagnostic, ) ) - return new AnalysisUnsupportedTargetError( + return unsupportedTarget( operation, target.device, + "android-device", excerpt, detail, ); @@ -242,7 +243,13 @@ export const adbExitFailure = ( ) ? localPath : (target.path ?? target.device); - return new AnalysisUnsupportedTargetError(operation, path, excerpt, detail); + return unsupportedTarget( + operation, + path, + "android-device", + excerpt, + detail, + ); } const protocolError = new AdbProtocolError( excerpt === "" @@ -258,9 +265,10 @@ export const adbExitFailure = ( `${run.capturedOutput.stdout}\n${run.stderr}`, ); if (reason !== null) - return new AnalysisUnsupportedTargetError( + return unsupportedTarget( operation, target.device, + "android-package", reason, { cause: protocolError }, ); @@ -303,7 +311,7 @@ export const packageChangeRefusal = ( return reason === null ? undefined : err( - new AnalysisUnsupportedTargetError(operation, serial, reason, { + unsupportedTarget(operation, serial, "android-package", reason, { cause: error, }), ); diff --git a/src/adb/AdbProvider.test.ts b/src/adb/AdbProvider.test.ts index 6f4effe871..bf924f59ad 100644 --- a/src/adb/AdbProvider.test.ts +++ b/src/adb/AdbProvider.test.ts @@ -1351,7 +1351,7 @@ exit 91`, expect(projected).toMatchObject({ code: "unsupported_target", details: { operation, path, reason }, - message: `Unsupported target for ${operation} at ${path}: ${reason}`, + message: `Unsupported android-device target for ${operation} at ${path}: ${reason}`, }); }, ); diff --git a/src/adb/AdbProvider.ts b/src/adb/AdbProvider.ts index 87bd6fc451..c8fb1ae81a 100644 --- a/src/adb/AdbProvider.ts +++ b/src/adb/AdbProvider.ts @@ -40,10 +40,10 @@ import { AnalysisProtocolError, AnalysisResourceConstraintError, AnalysisTimeoutError, - AnalysisUnsupportedTargetError, cancelledBy, OwnerCancellation, isAborted, + unsupportedTarget, } from "../domain/analysisErrorCore.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import { @@ -937,9 +937,10 @@ export class AdbProvider { } if (parsed.paths.length === 0 && parsed.unparsedLines.total === 0) return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( operation, serial, + "android-package", `Package Manager reported no APK paths for ${packageName}; it may not be installed for user 0`, ), ); @@ -1721,9 +1722,10 @@ export class AdbProvider { ); if (verdict.status === "failure") return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( operation, input.serial, + "android-package", verdict.reason, ), ); diff --git a/src/adb/AdbShellOperations.ts b/src/adb/AdbShellOperations.ts index 3add484090..d1af0d3b8d 100644 --- a/src/adb/AdbShellOperations.ts +++ b/src/adb/AdbShellOperations.ts @@ -11,7 +11,7 @@ import { import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { AnalysisProtocolError, - AnalysisUnsupportedTargetError, + unsupportedTarget, } from "../domain/analysisErrorCore.js"; import { err, ok, type Result } from "../domain/result.js"; import { adbArguments, runAdbCapture } from "./AdbCommand.js"; @@ -185,9 +185,10 @@ export const inspectAdbPackageOperation = async ({ const stdout = ran.value.stdout; if (/Unable to find package:/u.test(stdout) || stdout.trim() === "") return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( operation, request.input.serial, + "android-package", `Package Manager did not report details for ${request.input.package}; it may not be installed for user 0`, ), ); diff --git a/src/apkSignature/ApkSignatureProvider.test.ts b/src/apkSignature/ApkSignatureProvider.test.ts index 88b0a3204a..c255d820b6 100644 --- a/src/apkSignature/ApkSignatureProvider.test.ts +++ b/src/apkSignature/ApkSignatureProvider.test.ts @@ -431,7 +431,7 @@ const registerSignatureInputAdmissionCases = () => { }); expect(result.ok).toBe(false); if (result.ok) return; - expect(result.error._tag).toBe("AnalysisUnsupportedTargetError"); + expect(result.error._tag).toBe("AnalysisTargetFailureError"); }); it("reports a damaged supported Zip64 end record as input failure while accepting the intact and restored controls", async () => { diff --git a/src/apkSignature/apkSignatureFailures.ts b/src/apkSignature/apkSignatureFailures.ts index 0436905d92..d42a9579bf 100644 --- a/src/apkSignature/apkSignatureFailures.ts +++ b/src/apkSignature/apkSignatureFailures.ts @@ -16,9 +16,10 @@ import { AnalysisAccessDeniedError, AnalysisInputError, AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, cancelledBy, carriedReason, + unsupportedTarget, + unrecognizedTarget, } from "../domain/analysisErrorCore.js"; import { parseLimitConstraint } from "../domain/parseFailureAnalysisError.js"; import type { ApkSchemeError } from "../domain/apkSignature/apkSignatureSchemes.js"; @@ -45,24 +46,26 @@ export const mapApkBlockError = ( ): AnalysisError => { switch (error.kind) { case "not-a-zip": - return new AnalysisUnsupportedTargetError( + return unrecognizedTarget( OPERATION, path, - `The selected file is not a ZIP/APK (${error.detail}).`, - { remediationAction: "Select a local .apk/.zip/.aab archive." }, + "zip", + `The selected file is not a ZIP/APK (${error.detail}). Select a local .apk/.zip/.aab archive.`, ); case "zip64-unsupported": - return new AnalysisUnsupportedTargetError( + return unsupportedTarget( OPERATION, path, + "zip", `This archive uses a Zip64 structure this reader does not decode (${error.detail}).`, + { undecodedContent: true }, ); case "multi-disk-unsupported": - return new AnalysisUnsupportedTargetError( + return unsupportedTarget( OPERATION, path, - `The selected archive declares an unsupported multi-disk ZIP layout (${error.detail}).`, - { remediationAction: "Select a complete single-disk APK/ZIP archive." }, + "zip", + `The selected archive declares an unsupported multi-disk ZIP layout (${error.detail}). Select a complete single-disk APK/ZIP archive.`, ); case "malformed-zip": return inputError( diff --git a/src/apktool/ApktoolCommandRecovery.test.ts b/src/apktool/ApktoolCommandRecovery.test.ts index 39ae791a45..bfc1fa2b86 100644 --- a/src/apktool/ApktoolCommandRecovery.test.ts +++ b/src/apktool/ApktoolCommandRecovery.test.ts @@ -462,7 +462,7 @@ it.each([ if (result.ok) throw new Error("Expected authored failure"); if (kind === "refusal") { expect(result.error).toMatchObject({ - _tag: "AnalysisUnsupportedTargetError", + _tag: "AnalysisTargetFailureError", path, }); expect(result.error.message).toContain(path); diff --git a/src/apktool/ApktoolProvider.test.ts b/src/apktool/ApktoolProvider.test.ts index 0c40f11844..e894871486 100644 --- a/src/apktool/ApktoolProvider.test.ts +++ b/src/apktool/ApktoolProvider.test.ts @@ -1368,7 +1368,7 @@ it.each(["decode", "projection"] as const)( expect(controller.signal.aborted).toBe(true); expect(result.error._tag).toBe( stage === "decode" - ? "AnalysisUnsupportedTargetError" + ? "AnalysisTargetFailureError" : "AnalysisProtocolError", ); if (stage === "decode") diff --git a/src/apktool/ApktoolProvider.ts b/src/apktool/ApktoolProvider.ts index 5533e76a1a..46611d06bf 100644 --- a/src/apktool/ApktoolProvider.ts +++ b/src/apktool/ApktoolProvider.ts @@ -47,10 +47,10 @@ import { projectApktoolStringTables } from "./ApktoolStringTables.js"; import { AnalysisCapabilityUnavailableError, AnalysisProtocolError, - AnalysisUnsupportedTargetError, cancelledBy, OwnerCancellation, carriedReason, + unsupportedTarget, } from "../domain/analysisErrorCore.js"; import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js"; @@ -259,9 +259,10 @@ const apktoolCommandFailure = ( exit.output?.truncated !== false ) return unclassified({ userMessage, diagnostics }); - return new AnalysisUnsupportedTargetError( + return unsupportedTarget( operation, targetPath, + "apk", ellipsisExcerpt( exit.output.snapshot.stderr.text.trim(), STDERR_EXCERPT_CHARACTERS, diff --git a/src/application/analysisView/AnalysisViewService.test.ts b/src/application/analysisView/AnalysisViewService.test.ts index 3ea8d51ced..2c03270cf8 100644 --- a/src/application/analysisView/AnalysisViewService.test.ts +++ b/src/application/analysisView/AnalysisViewService.test.ts @@ -603,7 +603,7 @@ it("rejects stale retained IDs and unsupported parent operations", async () => { }); expect(rejected).toMatchObject({ ok: false, - error: { _tag: "AnalysisUnsupportedTargetError" }, + error: { _tag: "AnalysisTargetFailureError" }, }); expect( await inspectAnalysisView({ @@ -758,7 +758,7 @@ it("seals inferred and literal HAR pages, including a null artifact digest", asy }), ).toMatchObject({ ok: false, - error: { _tag: "AnalysisUnsupportedTargetError" }, + error: { _tag: "AnalysisTargetFailureError" }, }); }); @@ -866,7 +866,7 @@ it("seals an inferred environment manifest and a derived manifest without templa }), ).toMatchObject({ ok: false, - error: { _tag: "AnalysisUnsupportedTargetError" }, + error: { _tag: "AnalysisTargetFailureError" }, }); }); @@ -1713,7 +1713,7 @@ it.each(["file", "bundle"] as const)( expect(controller.signal.aborted).toBe(true); expect(result).toMatchObject({ ok: false, - error: { _tag: "AnalysisUnsupportedTargetError" }, + error: { _tag: "AnalysisTargetFailureError" }, }); } finally { interrupt.mockRestore(); diff --git a/src/application/apiContract/ApiContractService.test.ts b/src/application/apiContract/ApiContractService.test.ts index 2c2aec2ca5..ff26074211 100644 --- a/src/application/apiContract/ApiContractService.test.ts +++ b/src/application/apiContract/ApiContractService.test.ts @@ -231,7 +231,7 @@ it("keeps native JSON source excerpts internal while preserving the failure caus }); it.each([ - [{ openapi: "2.0" }, "AnalysisUnsupportedTargetError"], + [{ openapi: "2.0" }, "AnalysisTargetFailureError"], [ { openapi: "3.1.2", diff --git a/src/application/artifacts/ArtifactPathInspection.ts b/src/application/artifacts/ArtifactPathInspection.ts index 1749cc599f..e0de716ae5 100644 --- a/src/application/artifacts/ArtifactPathInspection.ts +++ b/src/application/artifacts/ArtifactPathInspection.ts @@ -2,7 +2,7 @@ import { stat } from "node:fs/promises"; import { absoluteCallerPath } from "../../filesystem/callerPath.js"; -import type { AnalysisError } from "../../domain/analysisErrorBase.js"; +import { AnalysisError } from "../../domain/analysisErrorBase.js"; import type { JsonValue } from "../../domain/jsonValue.js"; import { err, ok, type Result } from "../../domain/result.js"; import { AnalysisOutputError } from "../../domain/analysisErrorCore.js"; @@ -17,8 +17,8 @@ import type { RetainedResourceScope, } from "../../ports/AnalysisProvider.js"; import { - translateArtifactFailure, type ArtifactResourceScope, + translateArtifactFailure, } from "../../resources/index.js"; import type { InspectArtifactDirectory } from "../../ports/artifacts/ArtifactDirectoryInspectionPort.js"; import type { DirectAnalysisDependencies } from "../DirectAnalysisDependencies.js"; diff --git a/src/application/binary/AnalysisProviderEvaluation.ts b/src/application/binary/AnalysisProviderEvaluation.ts index bffad59d16..58a8543a3e 100644 --- a/src/application/binary/AnalysisProviderEvaluation.ts +++ b/src/application/binary/AnalysisProviderEvaluation.ts @@ -5,9 +5,10 @@ import { import type { BinaryTarget } from "../../domain/binaryTargetTypes.js"; import { AnalysisCancelledError, - AnalysisUnsupportedTargetError, isAborted, cancelledBy, + AnalysisTargetFailureError, + targetFailureOfKind, } from "../../domain/analysisErrorCore.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; import { jsonObjectSchema, type JsonValue } from "../../domain/jsonValue.js"; @@ -71,8 +72,13 @@ export const evaluateAnalysisProviderCandidate = async ( return err(resolved.error); if (!resolved.ok) { const error = resolved.error; + const unsupported = targetFailureOfKind( + error, + "unsupported", + "unrecognized", + ); const rejection = - error instanceof AnalysisUnsupportedTargetError + unsupported !== undefined && error instanceof AnalysisTargetFailureError ? { candidate, status: withCandidateRejections({ @@ -80,7 +86,7 @@ export const evaluateAnalysisProviderCandidate = async ( targetSupport: { status: "unsupported" as const, code: "target_format_unsupported" as const, - reason: error.reason, + reason: unsupported.detail, diagnostics: { path: error.path, error_tag: error._tag }, }, }), diff --git a/src/application/binary/AnalysisProviderRegistry.test.ts b/src/application/binary/AnalysisProviderRegistry.test.ts index d110a90bfc..589fd48ca2 100644 --- a/src/application/binary/AnalysisProviderRegistry.test.ts +++ b/src/application/binary/AnalysisProviderRegistry.test.ts @@ -21,8 +21,8 @@ import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; import { AnalysisCapabilityUnavailableError, - AnalysisUnsupportedTargetError, AnalysisCancelledError, + unsupportedTarget, } from "../../domain/analysisErrorCore.js"; import { ProviderSelectionError } from "../../domain/providerSelectionError.js"; import { LinuxOwnedProcessPrerequisiteError } from "../../process/ProcessOwnershipObservation.js"; @@ -1013,11 +1013,12 @@ const capability = (provider: ProviderIdentity): CapabilityDescriptor => ({ describe("analysis provider registry: explicit profile refusals", () => { const reason = "The configured extension supports x86-64 only."; const selectWithRefusal = async ( - options: ConstructorParameters[3], + options: Parameters[4], ) => { - const refusal = new AnalysisUnsupportedTargetError( + const refusal = unsupportedTarget( "resolve_analysis_profile", DATABASE_TARGET.path, + "fixture", reason, options, ); @@ -1055,7 +1056,7 @@ describe("analysis provider registry: explicit profile refusals", () => { ), } as const; const { refusal, failure } = await selectWithRefusal({ - remediationAction: "Omit the extension setting for this target.", + related: { operations: ["open_binary"] }, capturedOutput, diagnostics: { extension: "fixture" }, partialObservation: partial, @@ -1065,7 +1066,11 @@ describe("analysis provider registry: explicit profile refusals", () => { expect(projectAnalysisError(failure)).toMatchObject({ code: "capability_unavailable", message: refusal.message, - remediation: { action: "Omit the extension setting for this target." }, + // The refusal's recovery comes from the target-failure table and names + // the operation the refusing provider points to. + remediation: { + action: expect.stringContaining("Use open_binary for this target."), + }, details: { selection_reason: "target_unsupported", requested_provider_id: "ghidra", diff --git a/src/application/binary/AnalysisProviderRegistry.ts b/src/application/binary/AnalysisProviderRegistry.ts index 947b874dad..0fd1091f93 100644 --- a/src/application/binary/AnalysisProviderRegistry.ts +++ b/src/application/binary/AnalysisProviderRegistry.ts @@ -19,10 +19,11 @@ import type { ProviderReleaseVerification } from "../../domain/providerReleaseVe import type { BinaryTarget } from "../../domain/binaryTargetTypes.js"; import { AnalysisCancelledError, - AnalysisUnsupportedTargetError, isAborted, cancelledBy, carriedReason, + AnalysisTargetFailureError, + targetFailureOfKind, } from "../../domain/analysisErrorCore.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; import { AnalysisCleanupRelease } from "../../domain/analysisCleanupRelease.js"; @@ -56,6 +57,7 @@ import { import { withCandidateRejections } from "./AnalysisProviderCandidateDiagnostics.js"; import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js"; import { ownedProcessPrerequisiteAvailability } from "../../providers/ownedProcessAvailability.js"; +import { targetFailureRecovery } from "../../domain/targetFailure.js"; /** Where a selected provider's choice came from; never a priority or fallback. */ export type AnalysisProviderSelectionSource = @@ -639,16 +641,20 @@ export class AnalysisProviderRegistry { // A selected provider refusing the target is a selection outcome that keeps the // refusal's reason, recovery and evidence; unconfirmed cleanup stays with the refusal. if ( - refusal instanceof AnalysisUnsupportedTargetError && + refusal instanceof AnalysisTargetFailureError && + targetFailureOfKind(refusal, "unsupported", "unrecognized") !== + undefined && !refusal.cleanupIncomplete ) return err( selectionError("target_unsupported", providerId, statuses, { refusal: { userMessage: refusal.message, - ...(refusal.remediationAction === undefined - ? {} - : { remediationAction: refusal.remediationAction }), + remediationAction: targetFailureRecovery( + refusal.operation, + refusal.failure, + refusal.related, + ), capturedOutput: refusal.capturedOutput, diagnostics: refusal.diagnostics, partialObservation: refusal.partialObservation, diff --git a/src/application/javascript/JavaScriptArtifactReconstruction.ts b/src/application/javascript/JavaScriptArtifactReconstruction.ts index 52061051d1..02fe484dfd 100644 --- a/src/application/javascript/JavaScriptArtifactReconstruction.ts +++ b/src/application/javascript/JavaScriptArtifactReconstruction.ts @@ -25,7 +25,8 @@ import { import { AnalysisAccessDeniedError, AnalysisInputError, - AnalysisUnsupportedTargetError, + unsupportedTarget, + unrecognizedTarget, } from "../../domain/analysisErrorCore.js"; import { createJavaScriptArtifactReader as createReader } from "../../artifacts/javascript/JavaScriptArtifactReader.js"; import type { JavaScriptApplicationGraph } from "../../domain/javascript/javascriptApplicationGraph.js"; @@ -177,14 +178,13 @@ export const reconstructJavaScriptArtifact = async ( inventory: snapshot, }); if (javaScriptApplicationInputPresence(files, snapshot) === "absent") - throw new AnalysisUnsupportedTargetError( + throw unrecognizedTarget( OPERATION, path, - "the complete inventory has entries but no JavaScript, HTML, package.json, source map, or nested ASAR inputs", + snapshot.manifest.root_format, + "the complete inventory has entries but no JavaScript, HTML, package.json, source map, or nested ASAR inputs; details.diagnostics.entries_by_format lists what it holds", { diagnostics: javaScriptAbsentInputDiagnostics(files, snapshot), - remediationAction: - "Route by details.diagnostics.entries_by_format. For a native build or installation directory, call inspect_desktop_application or audit_release_exposure with the directory, or select one member file with inspect_artifact or open_binary.", related: { operations: [...JAVASCRIPT_ABSENT_INPUT_OPERATIONS] }, }, ); @@ -570,14 +570,11 @@ const resolveFormat = ( ? "asar" : undefined; if (observed === undefined) - throw new AnalysisUnsupportedTargetError( + throw unsupportedTarget( OPERATION, input.input_path, - "JavaScript application analysis accepts only a directory or an .asar file", - { - remediationAction: - "Select an extracted application directory, an app bundle, or an .asar file such as Contents/Resources/app.asar.", - }, + "file", + "JavaScript application analysis accepts only a directory or an .asar file. Select an extracted application directory, an app bundle, or an .asar file such as Contents/Resources/app.asar.", ); if (input.format !== "auto" && input.format !== observed) throw new AnalysisInputError(OPERATION, undefined, [ diff --git a/src/application/releaseExposure/ReleaseExposureService.test.ts b/src/application/releaseExposure/ReleaseExposureService.test.ts index 9d7c369d93..849c4a4cc5 100644 --- a/src/application/releaseExposure/ReleaseExposureService.test.ts +++ b/src/application/releaseExposure/ReleaseExposureService.test.ts @@ -6,7 +6,7 @@ import type { AnalysisError } from "../../domain/analysisErrorBase.js"; import { AnalysisCancelledError, AnalysisInputError, - AnalysisUnsupportedTargetError, + unsupportedTarget, } from "../../domain/analysisErrorCore.js"; import { describeElectronFuseFindings, @@ -99,9 +99,10 @@ const owners = ( const electronFuses = { inspect: vi.fn(async () => err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "inspect_electron_fuses", "/work/app", + "fixture", "unsupported", ), ), @@ -111,9 +112,10 @@ const owners = ( const goBinaries = { inspect: vi.fn(async () => err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "inspect_go_binary", "/work/app", + "fixture", "unsupported", ), ), @@ -123,9 +125,10 @@ const owners = ( const rustBinaries = { inspect: vi.fn(async () => err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "inspect_rust_binary", "/work/app", + "fixture", "unsupported", ), ), @@ -172,9 +175,10 @@ describe("ReleaseExposureService", () => { ); goBinaries.inspect.mockResolvedValue( err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "inspect_go_binary", "/work/tree/app", + "fixture", "not a Go binary", ), ), @@ -668,9 +672,10 @@ describe("ReleaseExposureService fuse image identity", () => { (input as { path: string }).path === "/work/app" ? ok(evidence(fuseReport([slice(0)]))) : err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "inspect_electron_fuses", "/work/helper", + "fixture", "unsupported", ), ), @@ -857,9 +862,10 @@ describe("ReleaseExposureService fuse sampling", () => { desktop.inspect.mockResolvedValue(ok(evidence(electronDesktopReport()))); const unsupported = (operation: string) => err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( operation, "/work/app/MyApp.exe", + "fixture", "unsupported", ), ); @@ -1890,9 +1896,10 @@ describe("ReleaseExposureService app bundle with a sidecar", () => { [ "unsupported", err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "inspect_electron_fuses", "/work/App.app", + "fixture", "unsupported", ), ), @@ -2410,9 +2417,10 @@ describe("ReleaseExposureService undecoded metadata", () => { ] as const) owner.inspect.mockResolvedValue( err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( operation, "/work/app", + "fixture", "Compressed section", { undecodedContent }, ), diff --git a/src/application/releaseExposure/ReleaseExposureService.ts b/src/application/releaseExposure/ReleaseExposureService.ts index c1817a91df..11c1f47697 100644 --- a/src/application/releaseExposure/ReleaseExposureService.ts +++ b/src/application/releaseExposure/ReleaseExposureService.ts @@ -15,8 +15,8 @@ import { providerCleanupErrorFromCloseRejections } from "../../domain/analysisEr import { AnalysisCancelledError, AnalysisOutputError, - AnalysisUnsupportedTargetError, cancelledBy, + targetFailureOfKind, } from "../../domain/analysisErrorCore.js"; import { projectAnalysisError } from "../../domain/analysisErrorProjection.js"; import { desktopApplicationSchema } from "../../domain/desktopApplication.js"; @@ -353,7 +353,10 @@ export class ReleaseExposureService { } if (!result.ok) { if (stopsAudit(result.error)) return err(result.error); - if (result.error instanceof AnalysisUnsupportedTargetError) + if ( + targetFailureOfKind(result.error, "unsupported", "unrecognized") !== + undefined + ) return ok({ kind: "unsupported", role: candidate.role, @@ -421,9 +424,14 @@ export class ReleaseExposureService { const result = await run(); if (!result.ok) { if (stopsAudit(result.error)) return err(result.error); + const form = targetFailureOfKind( + result.error, + "unsupported", + "unrecognized", + ); if ( - result.error instanceof AnalysisUnsupportedTargetError && - !result.error.undecodedContent + form !== undefined && + !(form.kind === "unsupported" && form.undecodedContent) ) return ok({ kind: "unsupported", path }); return ok(failedMetadata(result.error.message, path)); diff --git a/src/artifacts/ArtifactProvider.ts b/src/artifacts/ArtifactProvider.ts index b614724f88..deb76ee4de 100644 --- a/src/artifacts/ArtifactProvider.ts +++ b/src/artifacts/ArtifactProvider.ts @@ -49,7 +49,8 @@ import { } from "../domain/binaryTargetTypes.js"; import { AnalysisCapabilityUnavailableError, - AnalysisUnsupportedTargetError, + unsupportedTarget, + AnalysisTargetFailureError, } from "../domain/analysisErrorCore.js"; import type { JsonValue } from "../domain/jsonValue.js"; import { interfaceBuilderLimitsSchema } from "../domain/apple/interfaceBuilderGraph.js"; @@ -499,10 +500,11 @@ class ArtifactClient implements AnalysisClient { private unsupportedTarget( operation: string, reason: string, - ): AnalysisUnsupportedTargetError { - return new AnalysisUnsupportedTargetError( + ): AnalysisTargetFailureError { + return unsupportedTarget( operation, this.target.sourcePath ?? this.target.path, + this.target.format, reason, ); } diff --git a/src/artifacts/DesktopApplicationReader.ts b/src/artifacts/DesktopApplicationReader.ts index fab7283bbd..4a833135bf 100644 --- a/src/artifacts/DesktopApplicationReader.ts +++ b/src/artifacts/DesktopApplicationReader.ts @@ -36,7 +36,7 @@ import { createDesktopApplicationEvidence } from "../domain/desktopApplicationEv import { ARTIFACT_GRAPH_PROVIDER } from "../domain/investigationProviders.js"; import { AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, + AnalysisTargetFailureError, } from "../domain/analysisErrorCore.js"; import type { AnalysisError, @@ -190,9 +190,10 @@ export class DesktopApplicationReader implements DesktopApplicationPort { } /** - * The root is the caller's selection: a non-directory is an unsupported - * target, and host failures keep the shared target-unavailable/access-denied - * classification instead of becoming artifact I/O faults. + * The root is the caller's selection: a path that is not a directory is a + * selection failure, and host failures keep the shared + * target-unavailable/access-denied classification instead of becoming + * artifact I/O faults. */ const selectedRootFailure = ( path: string, @@ -200,16 +201,15 @@ const selectedRootFailure = ( partialObservation: AnalysisPartialObservation | undefined, ): AnalysisError => failure.reason === "path" - ? new AnalysisUnsupportedTargetError( + ? new AnalysisTargetFailureError( "inspect_desktop_application", path, - failure.message, { - cause: failure, - partialObservation, - remediationAction: - "Select the application's local installation directory, such as a macOS .app bundle or the directory containing its executable.", + kind: "selection", + format: "desktop-application", + detail: `${failure.message}. Select the application's local installation directory, such as a macOS .app bundle or the directory containing its executable.`, }, + { cause: failure, partialObservation }, ) : new BinaryTargetError(path, failure.message, { cause: failure.cause, diff --git a/src/artifacts/apple/KeyedArchiveReader.test.ts b/src/artifacts/apple/KeyedArchiveReader.test.ts index a96fc82d91..c70924cc85 100644 --- a/src/artifacts/apple/KeyedArchiveReader.test.ts +++ b/src/artifacts/apple/KeyedArchiveReader.test.ts @@ -5,6 +5,8 @@ import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { build, buildBinary, type PlistValue } from "plist"; +import { AnalysisTargetFailureError } from "../../domain/analysisErrorCore.js"; +import { projectAnalysisError } from "../../domain/analysisErrorProjection.js"; import { estimateBinaryPlistExpansion } from "../../domain/apple/propertyListDecodeBudget.js"; import { decodeKeyedArchiveBytes, @@ -16,6 +18,7 @@ import { deeplyNestedXmlPlist } from "../../../tests/fixtures/keyedArchiveXmlNes import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; import { embedSubmillisecondDateInWideIntegerPayload } from "../../../tests/fixtures/binaryPlistScalarAlias.js"; import { + binaryPlistObjectTable, readBinaryPlistObjectOffset, readBinaryPlistObjectTableLayout, writeBinaryPlistObjectOffset, @@ -599,6 +602,51 @@ const dateScalar = (iso8601: string | null) => ({ const oneUnknownDate = /\b1 date value.*could not represent.*timestamps/iu; const twoUnknownDates = /\b2 date value.*could not represent.*timestamps/iu; +/** One binary-plist UID wider than an exact JavaScript integer. */ +const binaryPlistWithOversizedUid = (): Buffer => { + const width = 8; + let value = BigInt(Number.MAX_SAFE_INTEGER) + 1n; + const record = Buffer.alloc(width + 1); + record[0] = 0x80 | (width - 1); + for (let byte = width - 1; byte >= 0; byte -= 1) { + record[byte + 1] = Number(value & 0xffn); + value >>= 8n; + } + const offsetTable = 8 + record.length; + const bytes = Buffer.alloc(offsetTable + 1 + 32); + record.copy(bytes, 8); + return binaryPlistObjectTable(bytes, [8], offsetTable); +}; + +describe("binary keyed archive UID facts", () => { + it("keeps the reader's binary-plist UID facts on the target failure", async () => { + const bytes = binaryPlistWithOversizedUid(); + const root = await createTestTempDirectory("rea-keyed-oversized-uid-"); + await writeFile(join(root, "archive.plist"), bytes); + const rejected = await inspectBundleKeyedArchive({ + bundlePath: root, + targetSha256: createHash("sha256").update(bytes).digest("hex"), + parameters: { path: "archive.plist" }, + }).catch((cause: unknown) => cause); + expect(rejected).toBeInstanceOf(AnalysisTargetFailureError); + if (!(rejected instanceof AnalysisTargetFailureError)) + throw new Error("expected a target failure"); + expect(rejected.failure).toMatchObject({ + kind: "unsupported", + format: "binary-plist", + field: "uid", + undecodedContent: true, + }); + expect(projectAnalysisError(rejected).details).toMatchObject({ + operation: "inspect_keyed_archive", + path: join(root, "archive.plist"), + failure_kind: "unsupported", + format: "binary-plist", + field: "uid", + }); + }); +}); + describe("binary keyed archive dates", () => { const selection = { offset: 0, limit: 10 }; diff --git a/src/artifacts/apple/KeyedArchiveReader.ts b/src/artifacts/apple/KeyedArchiveReader.ts index 9c35846046..54471dd46b 100644 --- a/src/artifacts/apple/KeyedArchiveReader.ts +++ b/src/artifacts/apple/KeyedArchiveReader.ts @@ -35,7 +35,8 @@ import { AnalysisAccessDeniedError, AnalysisArtifactChangedError, AnalysisInputError, - AnalysisUnsupportedTargetError, + AnalysisTargetFailureError, + unrecognizedTarget, } from "../../domain/analysisErrorCore.js"; import { binaryDatePrecisionOverlapLimitation, @@ -178,16 +179,19 @@ export const decodeKeyedArchiveBytes = ( * Point to the workflow that reads the selected kind of file on this host. * decode_interface_builder is portable; inspect_plist requires macOS. */ -const keyedArchiveKindRemediation = ( - kind: KeyedArchiveKindError["fileKind"], +/** + * The refusal's description. A NIB archive is decoded on its app bundle, and + * an ordinary property list needs a macOS host for the plist reader. + */ +const keyedArchiveKindDetail = ( + cause: KeyedArchiveKindError, platform: NodeJS.Platform, -): string => { - if (kind === "nib-archive") - return "Decode compiled NIBArchive files with decode_interface_builder on the app bundle."; - return platform === "darwin" - ? "Inspect an ordinary property list with inspect_plist; inspect_keyed_archive decodes keyed archives only." - : "Select a keyed archive; inspect_keyed_archive decodes only those. inspect_plist, which reads ordinary property lists, requires a macOS host."; -}; +): string => + cause.fileKind === "nib-archive" + ? `${cause.message}; decode compiled NIBArchive files on their app bundle` + : platform === "darwin" + ? cause.message + : `${cause.message}; the ordinary property list reader requires a macOS host`; interface BundleKeyedArchiveInput { bundlePath: string; @@ -476,24 +480,28 @@ const decodeSelectedArchive = ( ) throw cause; if (cause instanceof UnsupportedBinaryPlistUidError) - throw new AnalysisUnsupportedTargetError( + throw new AnalysisTargetFailureError( "inspect_keyed_archive", input.artifactPath, - cause.message, + cause.failure, { cause }, ); // An intact file of another kind is not a damaged archive. if (cause instanceof KeyedArchiveKindError) - throw new AnalysisUnsupportedTargetError( + throw unrecognizedTarget( "inspect_keyed_archive", input.artifactPath, - cause.message, + "keyed-archive", + keyedArchiveKindDetail(cause, input.platform ?? HOST_PLATFORM.platform), { cause, - remediationAction: keyedArchiveKindRemediation( - cause.fileKind, - input.platform ?? HOST_PLATFORM.platform, - ), + related: { + operations: [ + cause.fileKind === "nib-archive" + ? "decode_interface_builder" + : "inspect_plist", + ], + }, }, ); const parserLimit = diff --git a/src/artifacts/extraction/ArtifactExtraction.ts b/src/artifacts/extraction/ArtifactExtraction.ts index 53b93b17d5..ec47b2ac29 100644 --- a/src/artifacts/extraction/ArtifactExtraction.ts +++ b/src/artifacts/extraction/ArtifactExtraction.ts @@ -48,7 +48,7 @@ import { type ArtifactNode, type ArtifactOccurrence, } from "../../domain/artifactGraph.js"; -import { AnalysisUnsupportedTargetError } from "../../domain/analysisErrorCore.js"; +import { unsupportedTarget } from "../../domain/analysisErrorCore.js"; import type { BinaryTarget } from "../../domain/binaryTargetTypes.js"; import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js"; import { scanArtifactInventoryForExtractionInScope } from "../inventory/ArtifactInventory.js"; @@ -203,27 +203,30 @@ export const materializeArtifactInventoryInScope = async ( containerMetadata?.kind === "godot-pck" && containerMetadata.directory_status !== "available" ) - throw new AnalysisUnsupportedTargetError( + throw unsupportedTarget( "extract_artifact", input.selectedPath ?? input.inputPath, + "godot-pck", `Godot PCK directory is ${containerMetadata.directory_status}; its complete contents cannot be extracted`, ); if ( containerMetadata?.kind === "unityfs" && containerMetadata.directory_status !== "available" ) - throw new AnalysisUnsupportedTargetError( + throw unsupportedTarget( "extract_artifact", input.selectedPath ?? input.inputPath, + "unityfs", `UnityFS directory is ${containerMetadata.directory_status}; its complete contents cannot be extracted`, ); if ( containerMetadata?.kind === "wxapkg" && containerMetadata.directory_status !== "available" ) - throw new AnalysisUnsupportedTargetError( + throw unsupportedTarget( "extract_artifact", input.selectedPath ?? input.inputPath, + "wxapkg", `wxapkg directory is ${containerMetadata.directory_status}; its complete contents cannot be extracted`, ); const { available, selected: activeOccurrences } = @@ -241,9 +244,10 @@ export const materializeArtifactInventoryInScope = async ( // REA never decrypts archive entries, so an encrypted entry makes the // complete extraction unsupported rather than the archive invalid. if (occurrence.encrypted) - throw new AnalysisUnsupportedTargetError( + throw unsupportedTarget( "extract_artifact", input.selectedPath ?? input.inputPath, + snapshot.manifest.root_format, `Archive entry ${occurrence.logical_path} is encrypted; REA does not decrypt archive entries, so the archive cannot be extracted completely`, ); // Inventory retains unavailable source occurrences, but extraction cannot @@ -703,9 +707,10 @@ const requireExtractableFormat = async ( }, ); if (!detected.pack) - throw new AnalysisUnsupportedTargetError( + throw unsupportedTarget( "extract_artifact", input.selectedPath ?? input.inputPath, + format, `Artifact format has no extraction reader: ${format}`, ); return detected.probeFacts; @@ -795,9 +800,10 @@ const createReader = async ( : undefined, }); if (reader === undefined) - throw new AnalysisUnsupportedTargetError( + throw unsupportedTarget( "extract_artifact", input.selectedPath ?? input.inputPath, + containerFormat, `Artifact format has no extraction reader: ${containerFormat}`, ); return reader; diff --git a/src/artifacts/tar/TarArtifactReader.test.ts b/src/artifacts/tar/TarArtifactReader.test.ts index 3ad211ef55..988d9357ef 100644 --- a/src/artifacts/tar/TarArtifactReader.test.ts +++ b/src/artifacts/tar/TarArtifactReader.test.ts @@ -21,6 +21,7 @@ import type { ArtifactTraversalOmission, } from "../../resources/index.js"; import { TarArtifactReader } from "./TarArtifactReader.js"; +import { TAR_RETAINED_METADATA_BYTES } from "./TarWalk.js"; import { GzipTarStream } from "./TarByteStream.js"; import { gzipTarFixture, @@ -465,6 +466,43 @@ describe("tar header edge cases", () => { } }); + it("refuses repeated global pax headers at the retained metadata allowance", async () => { + const value = "x".repeat(800_000); + const pieces: Buffer[] = []; + const perRecord = Buffer.byteLength("k000") + value.length + 64; + const count = Math.floor(TAR_RETAINED_METADATA_BYTES / perRecord) + 2; + for (let index = 0; index < count; index += 1) { + const key = `k${String(index).padStart(3, "0")}`; + const body = ` ${key}=${value}\n`; + let length = Buffer.byteLength(body) + 1; + while (String(length).length + Buffer.byteLength(body) !== length) + length = String(length).length + Buffer.byteLength(body); + const pax = Buffer.from(`${String(length)}${body}`); + pieces.push( + tarHeader({ name: "PaxHeader", type: "g" }, pax.length), + pax, + Buffer.alloc((512 - (pax.length % 512)) % 512), + ); + } + const reader = new TarArtifactReader( + await write("global-pax-budget.tar", Buffer.concat(pieces)), + ); + try { + await expect(async () => { + for await (const entry of reader.entries()) void entry; + }).rejects.toMatchObject({ + reason: "limit", + boundary: "memory", + fixedAllowance: { + limit: TAR_RETAINED_METADATA_BYTES, + unit: "bytes", + }, + }); + } finally { + await reader.close(); + } + }); + it("stops as malformed at a pax size that is not a number, keeping earlier members", async () => { const pax = Buffer.from("12 size=abc\n"); const result = await read( diff --git a/src/artifacts/tar/TarWalk.ts b/src/artifacts/tar/TarWalk.ts index c30db5afd5..7bec256000 100644 --- a/src/artifacts/tar/TarWalk.ts +++ b/src/artifacts/tar/TarWalk.ts @@ -28,10 +28,13 @@ import { TarStreamEnded, type TarByteStream } from "./TarByteStream.js"; export const TAR_EXTENDED_HEADER_BYTES = 1024 * 1024; /** * Retained member metadata: a fixed per-member charge plus decoded path and - * link bytes. It bounds memory for tar streams of many tiny members. + * link bytes, and the global pax map. It bounds memory for tar streams of + * many tiny members or repeated pax global headers. */ export const TAR_RETAINED_METADATA_BYTES = 64 * 1024 * 1024; const MEMBER_OVERHEAD_BYTES = 512; +/** One map entry retained with a pax keyword, besides its key and value bytes. */ +const PAX_ENTRY_OVERHEAD_BYTES = 64; const SCAN_CHUNK_BYTES = 64 * 1024; export interface TarMember { @@ -149,6 +152,29 @@ const withPax = ( return merged; }; +const paxRecordBytes = (key: string, value: string): number => + Buffer.byteLength(key) + Buffer.byteLength(value) + PAX_ENTRY_OVERHEAD_BYTES; + +/** + * How many bytes merging `records` adds to the retained global map, before + * that map is allocated. Only the changed keys are counted, so a run of tiny + * global headers costs their own size, not the whole map's. + */ +const mergedPaxBytesDelta = ( + base: TarPaxRecords, + records: TarPaxRecords, +): number => { + let bytes = 0; + for (const [key, value] of records) { + const previous = base.get(key); + if (value === "") { + if (previous !== undefined) bytes -= paxRecordBytes(key, previous); + } else if (previous === undefined) bytes += paxRecordBytes(key, value); + else bytes += Buffer.byteLength(value) - Buffer.byteLength(previous); + } + return bytes; +}; + const decimal = (value: string | undefined): bigint | undefined => value !== undefined && /^[0-9]+$/u.test(value) ? BigInt(value) : undefined; @@ -220,6 +246,7 @@ export const walkTar = async ( let paxHeaders = 0; const retained = new Budget(TAR_RETAINED_METADATA_BYTES); let global: TarPaxRecords = new Map(); + let chargedGlobalPax = 0; let local: TarPaxRecords | undefined; let longName: Uint8Array | undefined; let longLink: Uint8Array | undefined; @@ -355,9 +382,23 @@ export const walkTar = async ( ); break; } - if (typeflag === TAR_TYPEFLAGS.paxGlobal) + if (typeflag === TAR_TYPEFLAGS.paxGlobal) { + // Charge the map that withPax is about to copy. Repeated global + // headers otherwise accumulate without reaching this budget. + const nextBytes = Math.max( + 0, + chargedGlobalPax + mergedPaxBytesDelta(global, pax.records), + ); + if (nextBytes > chargedGlobalPax) + retained.charge( + nextBytes - chargedGlobalPax, + retainedMetadataLimit, + ); + else if (nextBytes < chargedGlobalPax) + retained.refund(chargedGlobalPax - nextBytes); + chargedGlobalPax = nextBytes; global = withPax(global, pax.records); - else local = pax.records; + } else local = pax.records; } else { const end = data.indexOf(0); const value = data.subarray(0, end === -1 ? data.length : end); diff --git a/src/browser/PlaywrightElectronActiveFuses.test.ts b/src/browser/PlaywrightElectronActiveFuses.test.ts index 8cd0fdc976..e386f889aa 100644 --- a/src/browser/PlaywrightElectronActiveFuses.test.ts +++ b/src/browser/PlaywrightElectronActiveFuses.test.ts @@ -13,7 +13,7 @@ import { universalFuseImage, } from "../../tests/fixtures/electron/fuseImage.js"; import { ArtifactReaderFailure } from "../resources/ArtifactReader.js"; -import { AnalysisUnsupportedTargetError } from "../domain/analysisErrorCore.js"; +import { AnalysisTargetFailureError } from "../domain/analysisErrorCore.js"; import { assertNodeCliInspectArgumentsSupported } from "./PlaywrightElectronActiveFuses.js"; const thinWithInspectState = (state: "enabled" | "removed") => { @@ -36,10 +36,10 @@ describe("Electron inspect argument preflight", () => { await expect( assertNodeCliInspectArgumentsSupported(path), ).rejects.toMatchObject({ - _tag: "AnalysisUnsupportedTargetError", + _tag: "AnalysisTargetFailureError", operation: "capture_electron_scenario", path, - remediationAction: expect.stringContaining("inspect_electron_page"), + related: { operations: ["inspect_electron_page"] }, }); }, ); @@ -107,7 +107,7 @@ describe("Electron inspect argument preflight", () => { await expect( assertNodeCliInspectArgumentsSupported(launcherBinary), ).rejects.toMatchObject({ - _tag: "AnalysisUnsupportedTargetError", + _tag: "AnalysisTargetFailureError", operation: "capture_electron_scenario", path: launcherBinary, }); @@ -127,7 +127,7 @@ describe("Electron inspect argument preflight", () => { } else { await expect( assertNodeCliInspectArgumentsSupported(binaryPath), - ).rejects.toThrow(AnalysisUnsupportedTargetError); + ).rejects.toThrow(AnalysisTargetFailureError); } }); }); diff --git a/src/browser/PlaywrightElectronActiveFuses.ts b/src/browser/PlaywrightElectronActiveFuses.ts index e8b0665e12..df6beb1ad7 100644 --- a/src/browser/PlaywrightElectronActiveFuses.ts +++ b/src/browser/PlaywrightElectronActiveFuses.ts @@ -7,7 +7,10 @@ import { import { electronFuseFailure } from "../electron/ElectronFuseFailures.js"; import { basename, dirname } from "node:path"; -import { AnalysisUnsupportedTargetError } from "../domain/analysisErrorCore.js"; +import { + unsupportedTarget, + AnalysisTargetFailureError, +} from "../domain/analysisErrorCore.js"; import { resolveElectronFuseTarget } from "../electron/ElectronFusePath.js"; import { readElectronFuseImage } from "../electron/ElectronFuseReader.js"; @@ -39,7 +42,7 @@ const appBundleDirectoryOf = (executablePath: string): string | null => { * flags and Playwright hangs until the 60-second startup deadline expires. * * When the fuse wire is present and index 3 is explicitly disabled or removed, - * this check fast-fails with an AnalysisUnsupportedTargetError before any child + * this check fast-fails with an unsupported target failure before any child * process is launched. When the fuse state is unknown (missing sentinel, wire * version != 1, or unsupported container format), launch proceeds normally. */ @@ -90,19 +93,20 @@ export const assertNodeCliInspectArgumentsSupported = async ( entry.name === "EnableNodeCliInspectArguments", ); if (fuse?.state === "disabled" || fuse?.state === "removed") { - throw new AnalysisUnsupportedTargetError( + throw unsupportedTarget( OPERATION, executablePath, - "Target binary disables the EnableNodeCliInspectArguments fuse; Node CLI inspector arguments are ignored and active scenario capture cannot attach.", + "electron", + "Target binary disables the EnableNodeCliInspectArguments fuse; Node CLI inspector arguments are ignored and active scenario capture cannot attach. Active capture can still run against an Electron development build or a stock Electron runtime with the extracted app.", { - remediationAction: - "Use passive CDP observation tools (inspect_electron_page), or launch active capture against an Electron development build or a stock Electron runtime with the extracted app.", + field: "EnableNodeCliInspectArguments", + related: { operations: ["inspect_electron_page"] }, }, ); } } } catch (cause: unknown) { - if (cause instanceof AnalysisUnsupportedTargetError) throw cause; + if (cause instanceof AnalysisTargetFailureError) throw cause; if ( cause instanceof ArtifactReaderFailure && (cause.cleanup !== undefined || cause.reason === "cancelled") diff --git a/src/browser/PlaywrightElectronActiveProvider.test.ts b/src/browser/PlaywrightElectronActiveProvider.test.ts index 97bde974fa..db41ef2c63 100644 --- a/src/browser/PlaywrightElectronActiveProvider.test.ts +++ b/src/browser/PlaywrightElectronActiveProvider.test.ts @@ -857,11 +857,11 @@ it("rejects active capture before launch when EnableNodeCliInspectArguments fuse if (result.ok) throw new Error("Expected capture to fail"); expect(launchSpy).not.toHaveBeenCalled(); expect(result.error).toMatchObject({ - _tag: "AnalysisUnsupportedTargetError", + _tag: "AnalysisTargetFailureError", operation: "capture_electron_scenario", path: disabledBinary, message: expect.stringContaining("EnableNodeCliInspectArguments"), - remediationAction: expect.stringContaining("inspect_electron_page"), + related: { operations: ["inspect_electron_page"] }, }); }); diff --git a/src/browser/history/playwrightTrace/PlaywrightTraceDecoder.test.ts b/src/browser/history/playwrightTrace/PlaywrightTraceDecoder.test.ts index 806d224aea..5154cb5217 100644 --- a/src/browser/history/playwrightTrace/PlaywrightTraceDecoder.test.ts +++ b/src/browser/history/playwrightTrace/PlaywrightTraceDecoder.test.ts @@ -246,7 +246,10 @@ it("refuses other declared trace versions with verified archive identity", async fixture.path, ); if (result.ok) throw new Error("Expected version refusal"); - expect(result.error._tag).toBe("AnalysisUnsupportedTargetError"); + expect(result.error).toMatchObject({ + _tag: "AnalysisTargetFailureError", + failure: { kind: "unsupported", format: "playwright-trace" }, + }); expect( playwrightTraceSchema.parse(result.error.partialObservation).artifact .sha256, diff --git a/src/browser/history/playwrightTrace/PlaywrightTraceDecoder.ts b/src/browser/history/playwrightTrace/PlaywrightTraceDecoder.ts index 68c2cb1855..71ada53c2f 100644 --- a/src/browser/history/playwrightTrace/PlaywrightTraceDecoder.ts +++ b/src/browser/history/playwrightTrace/PlaywrightTraceDecoder.ts @@ -13,8 +13,8 @@ import { } from "../../../resources/index.js"; import { AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, cancelledBy, + unrecognizedTarget, } from "../../../domain/analysisErrorCore.js"; import { analysisErrorWithCancellation } from "../../../domain/analysisErrorCancellation.js"; import { fixedAllowanceOptions } from "../../../domain/fixedAllowanceRemediation.js"; @@ -185,9 +185,10 @@ class TraceArchiveRead { selected.push({ entry, member }); } if (selected.length === 0) - throw new AnalysisUnsupportedTargetError( + throw unrecognizedTarget( operation, this.path, + "playwright-trace", "Archive contains no Playwright trace or network stream members.", ); if (!selected.some((row) => row.member.path.endsWith(".network"))) diff --git a/src/browser/history/playwrightTrace/PlaywrightTraceLifecycle.test.ts b/src/browser/history/playwrightTrace/PlaywrightTraceLifecycle.test.ts index 7446fdc3a8..b2be434759 100644 --- a/src/browser/history/playwrightTrace/PlaywrightTraceLifecycle.test.ts +++ b/src/browser/history/playwrightTrace/PlaywrightTraceLifecycle.test.ts @@ -142,7 +142,10 @@ it.each([false, true])( ); if (result.ok) throw new Error("Expected version refusal"); const primary = result.error.cleanupPrimary ?? result.error; - expect(primary._tag).toBe("AnalysisUnsupportedTargetError"); + expect(primary).toMatchObject({ + _tag: "AnalysisTargetFailureError", + failure: { kind: "unsupported", format: "playwright-trace" }, + }); expect(primary.secondaryFailures).toHaveLength(1); expect(primary.secondaryFailures[0]?._tag).toBe("AnalysisCancelledError"); expect(primary.secondaryFailures[0]?.cause).toBe(reason); diff --git a/src/browser/history/playwrightTrace/TraceStream.ts b/src/browser/history/playwrightTrace/TraceStream.ts index fc5567221c..65f28d4240 100644 --- a/src/browser/history/playwrightTrace/TraceStream.ts +++ b/src/browser/history/playwrightTrace/TraceStream.ts @@ -9,7 +9,7 @@ import type { } from "../../../resources/index.js"; import { AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, + unsupportedTarget, } from "../../../domain/analysisErrorCore.js"; import { isParseLimit, @@ -143,9 +143,10 @@ class TraceStreamRead { } const version = number(raw.version); if (version !== null && version !== 10) - throw new AnalysisUnsupportedTargetError( + throw unsupportedTarget( PLAYWRIGHT_TRACE_OPERATION, inventory.artifact.path, + "playwright-trace", "Only Playwright trace version 10 is supported.", ); if (version !== 10) { diff --git a/src/domain/analysisErrorBase.ts b/src/domain/analysisErrorBase.ts index 79d4dd8d14..87be2da786 100644 --- a/src/domain/analysisErrorBase.ts +++ b/src/domain/analysisErrorBase.ts @@ -30,7 +30,6 @@ const ANALYSIS_ERROR_TAGS = [ "AnalysisArtifactChangedError", "AnalysisOutputError", "AnalysisCapabilityUnavailableError", - "AnalysisUnsupportedTargetError", "AnalysisTargetFailureError", "AnalysisCancelledError", "AnalysisTimeoutError", @@ -141,6 +140,8 @@ export interface AnalysisContinuingCallerGuidance { export interface AnalysisRelatedInputs { readonly parameters?: readonly string[]; readonly operations?: readonly string[]; + /** Providers, by ID, that offer the operation for this target. */ + readonly providers?: readonly string[]; } /** Optional provider-neutral context that must survive typed error projection. */ @@ -312,6 +313,9 @@ export abstract class AnalysisError extends Error { ...(options.related.operations === undefined ? {} : { operations: Object.freeze([...options.related.operations]) }), + ...(options.related.providers === undefined + ? {} + : { providers: Object.freeze([...options.related.providers]) }), }); this.diagnostics = options?.diagnostics === undefined diff --git a/src/domain/analysisErrorClassification.ts b/src/domain/analysisErrorClassification.ts index 08d50b0fa3..845ffb5549 100644 --- a/src/domain/analysisErrorClassification.ts +++ b/src/domain/analysisErrorClassification.ts @@ -78,10 +78,6 @@ const STATIC_ERROR_CLASSIFICATIONS = { "capability_unavailable", "unsupported_provider", ), - AnalysisUnsupportedTargetError: classified( - "unsupported_target", - "unsupported_target", - ), AnalysisCancelledError: classified("cancelled", "cancelled"), AnalysisTimeoutError: classified("provider_timeout", "timeout"), AnalysisResourceConstraintError: classified( diff --git a/src/domain/analysisErrorCore.ts b/src/domain/analysisErrorCore.ts index f910de8338..096afe1d44 100644 --- a/src/domain/analysisErrorCore.ts +++ b/src/domain/analysisErrorCore.ts @@ -5,34 +5,15 @@ import type { ArtifactIntegrityCheck } from "./artifactOperationError.js"; import { TARGET_FAILURE_PROJECTIONS, type TargetFailure, + type TargetFailureFacts, + type TargetFailureKind, + type TargetFailureOf, } from "./targetFailure.js"; import { AnalysisError, type AnalysisErrorOptions, } from "./analysisErrorBase.js"; -/** A readable supplied artifact lies outside this operation's supported target formats. */ -export class AnalysisUnsupportedTargetError extends AnalysisError { - readonly _tag = "AnalysisUnsupportedTargetError"; - /** Refusal-specific recovery, when the producer knows an available workflow. */ - readonly remediationAction: string | undefined; - /** The target holds the content, so unsupported does not make it inapplicable. */ - readonly undecodedContent: boolean; - constructor( - readonly operation: string, - readonly path: string, - readonly reason: string, - options?: AnalysisErrorOptions & { - readonly remediationAction?: string; - readonly undecodedContent?: boolean; - }, - ) { - super(`Unsupported target for ${operation} at ${path}: ${reason}`, options); - this.remediationAction = options?.remediationAction; - this.undecodedContent = options?.undecodedContent ?? false; - } -} - /** * The selected target at `path` could not be read, for the reason its owner * established. The failure's `kind` alone selects the public code, category, @@ -55,6 +36,66 @@ export class AnalysisTargetFailureError extends AnalysisError { } } +/** Where an unsupported or unrecognized target's owner located the failure. */ +type TargetFormSite = Pick; + +/** + * The target at `path` holds `format` in a form outside what `operation` + * reads. `undecodedContent` says the target holds the content in that form. + * Name the operations or providers that read it in `options.related`. + */ +export const unsupportedTarget = ( + operation: string, + path: string, + format: string, + detail: string, + { + undecodedContent = false, + offset, + field, + ...options + }: AnalysisErrorOptions & + TargetFormSite & { readonly undecodedContent?: boolean } = {}, +): AnalysisTargetFailureError => + new AnalysisTargetFailureError( + operation, + path, + { + kind: "unsupported", + format, + detail, + undecodedContent, + ...(offset === undefined ? {} : { offset }), + ...(field === undefined ? {} : { field }), + }, + options, + ); + +/** No reader of `format` claims the target at `path` for `operation`. */ +export const unrecognizedTarget = ( + operation: string, + path: string, + format: string, + detail: string, + options: AnalysisErrorOptions = {}, +): AnalysisTargetFailureError => + new AnalysisTargetFailureError( + operation, + path, + { kind: "unrecognized", format, detail }, + options, + ); + +/** The failure of `error` when it is a target failure of one of `kinds`. */ +export const targetFailureOfKind = ( + error: unknown, + ...kinds: readonly Kind[] +): TargetFailureOf | undefined => + error instanceof AnalysisTargetFailureError && + (kinds as readonly TargetFailureKind[]).includes(error.failure.kind) + ? (error.failure as TargetFailureOf) + : undefined; + /** An analysis or transport resource failure, distinct from malformed input or unsupported coverage. */ export const ANALYSIS_RESOURCE_KINDS = [ "memory", diff --git a/src/domain/analysisErrorPresentation.ts b/src/domain/analysisErrorPresentation.ts index 9ce77b72fb..2e19db932f 100644 --- a/src/domain/analysisErrorPresentation.ts +++ b/src/domain/analysisErrorPresentation.ts @@ -8,7 +8,6 @@ import { AnalysisInputError, AnalysisTargetFailureError, AnalysisOutputError, - AnalysisUnsupportedTargetError, AnalysisResourceConstraintError, AnalysisTimeoutError, } from "./analysisErrorCore.js"; @@ -129,13 +128,12 @@ export const analysisErrorRemediationAction = ( : "Open an executable analysis target before importing a binary analysis snapshot."; if (error instanceof AnalysisSnapshotMismatchError) return "Select an artifact, provider, and analysis profile matching the snapshot, or run analysis without it and save a fresh snapshot for the intended binding."; - if (error instanceof AnalysisUnsupportedTargetError) - return ( - error.remediationAction ?? - "Select a target supported by this operation or choose an operation supporting the reported target format." - ); if (error instanceof AnalysisTargetFailureError) - return targetFailureRecovery(error.operation, error.failure); + return targetFailureRecovery( + error.operation, + error.failure, + analysisErrorRelatedInputs(error), + ); if (error instanceof AnalysisResourceConstraintError) { if (error.remediationAction !== undefined) return error.remediationAction; const refusal = analysisErrorRefusal(error); @@ -418,7 +416,6 @@ export const composedCallerGuidance = (sources: { const outcomeUserMessage = (error: AnalysisError): string => { if (error instanceof AnalysisSnapshotMismatchError) return error.message; - if (error instanceof AnalysisUnsupportedTargetError) return error.message; if (error instanceof AnalysisTargetFailureError) return error.message; if (error instanceof AnalysisResourceConstraintError) return error.reason; if (error instanceof AnalysisAccessDeniedError) @@ -661,10 +658,17 @@ export const analysisErrorRelatedInputs = ( error.related?.operations, presented?.operations, ); - if (parameters === undefined && operations === undefined) return undefined; + const providers = mergeRelatedList(error.related?.providers, undefined); + if ( + parameters === undefined && + operations === undefined && + providers === undefined + ) + return undefined; return { ...(parameters === undefined ? {} : { parameters }), ...(operations === undefined ? {} : { operations }), + ...(providers === undefined ? {} : { providers }), }; }; @@ -706,7 +710,6 @@ const KNOWN_ERROR_TAGS = { AnalysisArtifactChangedError: true, AnalysisOutputError: true, AnalysisCapabilityUnavailableError: true, - AnalysisUnsupportedTargetError: true, AnalysisTargetFailureError: true, AnalysisCancelledError: true, AnalysisTimeoutError: true, diff --git a/src/domain/analysisErrorProjection.test.ts b/src/domain/analysisErrorProjection.test.ts index ae22fafa0c..b9de24bc3a 100644 --- a/src/domain/analysisErrorProjection.test.ts +++ b/src/domain/analysisErrorProjection.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from "vitest"; import { AnalysisCapabilityUnavailableError, - AnalysisUnsupportedTargetError, AnalysisInputError, AnalysisOutputError, AnalysisCancelledError, @@ -9,6 +8,7 @@ import { AnalysisResourceConstraintError, AnalysisArtifactChangedError, type AnalysisInputIssue, + unsupportedTarget, } from "./analysisErrorCore.js"; import { ArtifactOperationError } from "./artifactOperationError.js"; import { @@ -365,9 +365,10 @@ const retainedOutput = { it("distinguishes unsupported target formats from unavailable provider capabilities", () => { const projected = projectAnalysisError( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "inspect_evm_interface", "/selected/runtime.hex", + "evm-bytecode", "EOF-style EF00 container is unsupported.", { capturedOutput: retainedOutput }, ), @@ -384,7 +385,7 @@ it("distinguishes unsupported target formats from unavailable provider capabilit }, }); expect(projected.message).toContain("EF00"); - expect(projected.remediation.action).toContain("target format"); + expect(projected.remediation.action).toContain("Choose another operation"); expect(projected.remediation.action).not.toContain("doctor"); expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(true); }); diff --git a/src/domain/analysisErrorProjection.ts b/src/domain/analysisErrorProjection.ts index a0e269b992..949a3c184d 100644 --- a/src/domain/analysisErrorProjection.ts +++ b/src/domain/analysisErrorProjection.ts @@ -21,7 +21,6 @@ import { AnalysisArtifactChangedError, AnalysisCancelledError, AnalysisCapabilityUnavailableError, - AnalysisUnsupportedTargetError, AnalysisTargetFailureError, AnalysisInputError, AnalysisOutputError, @@ -84,6 +83,9 @@ const relatedInputDetails = ( ...(related?.operations === undefined || related.operations.length === 0 ? {} : { related_operations: [...related.operations] }), + ...(related?.providers === undefined || related.providers.length === 0 + ? {} + : { related_providers: [...related.providers] }), }); /** @@ -641,12 +643,6 @@ const errorDetails = ( const requestErrorDetails = ( error: AnalysisError, ): Readonly> | undefined => { - if (error instanceof AnalysisUnsupportedTargetError) - return { - operation: error.operation, - path: error.path, - reason: error.reason, - }; if (error instanceof AnalysisTargetFailureError) return { operation: error.operation, diff --git a/src/domain/analysisView/WebNetworkProjectionAccumulator.ts b/src/domain/analysisView/WebNetworkProjectionAccumulator.ts index bd83c26be2..b4ee913109 100644 --- a/src/domain/analysisView/WebNetworkProjectionAccumulator.ts +++ b/src/domain/analysisView/WebNetworkProjectionAccumulator.ts @@ -3,7 +3,7 @@ import { Budget } from "../budget.js"; import { fixedAllowanceOptions } from "../fixedAllowanceRemediation.js"; import { AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, + unsupportedTarget, } from "../analysisErrorCore.js"; import type { AnalysisError } from "../analysisErrorBase.js"; import { compareUnicodeCodePoints as compare } from "../unicodeCodePointOrder.js"; @@ -207,15 +207,8 @@ export const admitHarCaptureParent = ( ): Result => { const operation = context.operation ?? "inspect_analysis_view"; const sourceField = context.sourceField ?? "source"; - const unsupported = (reason: string, remediationAction?: string) => - err( - new AnalysisUnsupportedTargetError( - operation, - parent.evidenceId, - reason, - remediationAction === undefined ? undefined : { remediationAction }, - ), - ); + const unsupported = (reason: string) => + err(unsupportedTarget(operation, parent.evidenceId, "evidence", reason)); if (parent.operation !== "inspect_web_network_capture") return unsupported( `View ${viewKind} is unsupported for parent operation ${parent.operation}; ${viewKind} requires ${viewKind === "api-surface" ? "inspect_web_network_capture" : "inspect_web_network_capture or capture_browser_scenario"}.`, @@ -252,9 +245,14 @@ export const admitHarCaptureParent = ( .object({ sensitive_value_count: z.number().int().nonnegative() }) .safeParse(parent.parameters); if (!declarations.success || declarations.data.sensitive_value_count > 0) - return unsupported( - "sensitive_values_unretained", - "This view cannot safely project this capture because sensitivity declarations are not retained. Use a compatible capture or summary view to inspect retained observations. Do not remove sensitivity declarations to bypass this restriction.", + return err( + unsupportedTarget( + operation, + parent.evidenceId, + "evidence", + "sensitive_values_unretained: this view cannot safely project this capture because sensitivity declarations are not retained. Use a compatible capture or summary view to inspect retained observations. Do not remove sensitivity declarations to bypass this restriction.", + { field: "sensitive_value_count" }, + ), ); return ok(parsed.value); }; diff --git a/src/domain/analysisView/analysisView.test.ts b/src/domain/analysisView/analysisView.test.ts index 0332cd7b13..7aefb3cf8d 100644 --- a/src/domain/analysisView/analysisView.test.ts +++ b/src/domain/analysisView/analysisView.test.ts @@ -1731,7 +1731,7 @@ it("rejects unsupported parent operations and incompatible collections", () => { ); expect(unsupported).toMatchObject({ ok: false, - error: { _tag: "AnalysisUnsupportedTargetError" }, + error: { _tag: "AnalysisTargetFailureError" }, }); const modulesOnLayout = projectAnalysisView(layoutParent(), { kind: "page", diff --git a/src/domain/analysisView/analysisView.ts b/src/domain/analysisView/analysisView.ts index c9fd5157f2..64dd25f871 100644 --- a/src/domain/analysisView/analysisView.ts +++ b/src/domain/analysisView/analysisView.ts @@ -53,7 +53,10 @@ import { projectBrowserScenarioView } from "./browserScenarioView.js"; import { projectNativeLoadImageView } from "./nativeLoadImageView.js"; import { projectDesktopApplicationView } from "./desktopApplicationView.js"; -import { AnalysisUnsupportedTargetError } from "../analysisErrorCore.js"; +import { + unsupportedTarget, + AnalysisTargetFailureError, +} from "../analysisErrorCore.js"; import { INSPECT_ANALYSIS_VIEW_OPERATION, analysisViewInputError, @@ -155,14 +158,16 @@ const readFunctionDossierParent = createAnalysisViewResultReader( const unsupportedParent = ( parent: AnalysisViewParent, -): AnalysisUnsupportedTargetError => - new AnalysisUnsupportedTargetError( +): AnalysisTargetFailureError => + unsupportedTarget( INSPECT_ANALYSIS_VIEW_OPERATION, parentArtifactPath(parent), - `Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views.`, + "evidence", + `Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views. For an analysis view, select completed Evidence from a supported parent operation and a compatible view; for a summary receipt, use normalized_result.parent_evidence_id. To read this record, use the complete Evidence directly; complete bundle delivery may exceed the MCP response budget.`, { - remediationAction: - "For an analysis view, select completed Evidence from a supported parent operation and a compatible view. For a summary receipt, use normalized_result.parent_evidence_id. To read this record, use the original complete Evidence directly; for session-retained records, request get_evidence_bundle with detail complete or use export_evidence_bundle. Complete bundle delivery may exceed the MCP response budget.", + related: { + operations: ["get_evidence_bundle", "export_evidence_bundle"], + }, }, ); diff --git a/src/domain/analysisView/cyclonedxView.test.ts b/src/domain/analysisView/cyclonedxView.test.ts index a2fc7fc355..193e401a5c 100644 --- a/src/domain/analysisView/cyclonedxView.test.ts +++ b/src/domain/analysisView/cyclonedxView.test.ts @@ -2,7 +2,7 @@ import { expect, it } from "vitest"; import { AnalysisInputError, AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, + AnalysisTargetFailureError, } from "../analysisErrorCore.js"; import { createEvidence } from "../evidence.js"; import { unknownTarget } from "../targetIdentity.js"; @@ -912,7 +912,7 @@ it("refuses a CycloneDX view of a parent that is neither Go nor Rust", () => { ); expect(result.ok).toBe(false); if (result.ok) throw new Error("Expected an unsupported parent"); - expect(result.error).toBeInstanceOf(AnalysisUnsupportedTargetError); + expect(result.error).toBeInstanceOf(AnalysisTargetFailureError); expect(result.error.message).toContain( "inspect_go_binary or inspect_rust_binary", ); @@ -1282,9 +1282,8 @@ it("names the parent input path when CycloneDX has no artifact path", () => { ); expect(result.ok).toBe(false); if (result.ok) throw new Error("Expected an unsupported parent"); - expect(result.error).toBeInstanceOf(AnalysisUnsupportedTargetError); - if (!(result.error instanceof AnalysisUnsupportedTargetError)) - throw result.error; + expect(result.error).toBeInstanceOf(AnalysisTargetFailureError); + if (!(result.error instanceof AnalysisTargetFailureError)) throw result.error; expect(result.error.path).toBe("/artifacts/layout-input"); }); diff --git a/src/domain/analysisView/cyclonedxView.ts b/src/domain/analysisView/cyclonedxView.ts index 186510790b..5760d19fd5 100644 --- a/src/domain/analysisView/cyclonedxView.ts +++ b/src/domain/analysisView/cyclonedxView.ts @@ -2,7 +2,7 @@ import { z } from "zod"; import { digestSchema } from "../digests.js"; import { fixedCeilingConstraint, - AnalysisUnsupportedTargetError, + unsupportedTarget, } from "../analysisErrorCore.js"; import type { GoModule } from "../go/goBinary.js"; import { goBinarySchema } from "../go/goBinary.js"; @@ -750,9 +750,10 @@ export const projectCycloneDxView = ( if (parent.operation === "inspect_rust_binary") return projectRustCycloneDx(parent, view); return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( INSPECT_ANALYSIS_VIEW_OPERATION, parentArtifactPath(parent), + "evidence", `View cyclonedx is unsupported for parent operation ${parent.operation}; cyclonedx requires inspect_go_binary or inspect_rust_binary.`, ), ); diff --git a/src/domain/analysisView/environmentCoverageView.test.ts b/src/domain/analysisView/environmentCoverageView.test.ts index 715d06224f..6dfd325503 100644 --- a/src/domain/analysisView/environmentCoverageView.test.ts +++ b/src/domain/analysisView/environmentCoverageView.test.ts @@ -221,7 +221,7 @@ it("refuses a browser scenario without selected response bodies", () => { ).toMatchObject({ ok: false, error: { - _tag: "AnalysisUnsupportedTargetError", + _tag: "AnalysisTargetFailureError", message: expect.stringContaining("response_body selected"), }, }); diff --git a/src/domain/analysisView/environmentManifestView.test.ts b/src/domain/analysisView/environmentManifestView.test.ts index 7e36166122..4c029c068e 100644 --- a/src/domain/analysisView/environmentManifestView.test.ts +++ b/src/domain/analysisView/environmentManifestView.test.ts @@ -820,7 +820,7 @@ it("refuses non-HAR formats, sensitive parents, unsupported parents and malforme capture.format = format; expect(projectAnalysisView(parentOf(capture), view())).toMatchObject({ ok: false, - error: { _tag: "AnalysisUnsupportedTargetError" }, + error: { _tag: "AnalysisTargetFailureError" }, }); } for (const parameters of [{ sensitive_value_count: 1 }, {}, null]) @@ -832,8 +832,10 @@ it("refuses non-HAR formats, sensitive parents, unsupported parents and malforme ).toMatchObject({ ok: false, error: { - _tag: "AnalysisUnsupportedTargetError", - reason: "sensitive_values_unretained", + _tag: "AnalysisTargetFailureError", + failure: { + detail: expect.stringContaining("sensitive_values_unretained"), + }, }, }); const layout = analysisViewLayoutEvidence(); @@ -850,7 +852,7 @@ it("refuses non-HAR formats, sensitive parents, unsupported parents and malforme ), ).toMatchObject({ ok: false, - error: { _tag: "AnalysisUnsupportedTargetError" }, + error: { _tag: "AnalysisTargetFailureError" }, }); const cyclic: { self?: unknown } = {}; cyclic.self = cyclic; diff --git a/src/domain/analysisView/environmentManifestView.ts b/src/domain/analysisView/environmentManifestView.ts index 1c6e902aed..817b0a8a8e 100644 --- a/src/domain/analysisView/environmentManifestView.ts +++ b/src/domain/analysisView/environmentManifestView.ts @@ -1,6 +1,6 @@ import { z } from "zod"; import type { WebNetworkCaptureRecord } from "../webNetworkCapture.js"; -import { AnalysisUnsupportedTargetError } from "../analysisErrorCore.js"; +import { unsupportedTarget } from "../analysisErrorCore.js"; import type { AnalysisError } from "../analysisErrorBase.js"; import { uniqueSorted } from "../canonicalOrdering.js"; import { err, ok, type Result } from "../result.js"; @@ -161,9 +161,10 @@ export const projectEnvironmentManifestView = ( ); if (view === undefined) return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "inspect_analysis_view", parent.evidenceId, + "evidence", `View ${admitted.kind} is unsupported for parent operation ${parent.operation}; environment-manifest requires inspect_web_network_capture or capture_browser_scenario.`, ), ); diff --git a/src/domain/analysisView/environmentStateView.test.ts b/src/domain/analysisView/environmentStateView.test.ts index ed4df778ec..a2c1462522 100644 --- a/src/domain/analysisView/environmentStateView.test.ts +++ b/src/domain/analysisView/environmentStateView.test.ts @@ -768,7 +768,7 @@ it("orders a scenario capture by request order and needs its response bodies", ( ).toMatchObject({ ok: false, error: { - _tag: "AnalysisUnsupportedTargetError", + _tag: "AnalysisTargetFailureError", message: expect.stringContaining("response_body selected"), }, }); diff --git a/src/domain/analysisView/scenarioCaptureRecords.ts b/src/domain/analysisView/scenarioCaptureRecords.ts index cb6c5268b1..8d750f6bb8 100644 --- a/src/domain/analysisView/scenarioCaptureRecords.ts +++ b/src/domain/analysisView/scenarioCaptureRecords.ts @@ -1,4 +1,4 @@ -import { AnalysisUnsupportedTargetError } from "../analysisErrorCore.js"; +import { unsupportedTarget } from "../analysisErrorCore.js"; import type { AnalysisError } from "../analysisErrorBase.js"; import type { BrowserNetworkBody } from "../browserNetworkEvidence.js"; import { retainedNetworkMediaType } from "../browserNetworkMediaType.js"; @@ -346,9 +346,10 @@ export const admitScenarioCaptureParent = ( : !content.response_body && !content.header_values ) return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "inspect_analysis_view", parent.evidenceId, + "evidence", viewKind === "environment-state" ? "environment-state needs a capture_browser_scenario capture with capture.network.response_body selected." : "environment-manifest needs a capture_browser_scenario capture with capture.network.response_body or header_values selected.", diff --git a/src/domain/analysisView/webNetworkApiSurfaceView.test.ts b/src/domain/analysisView/webNetworkApiSurfaceView.test.ts index 9988747ea2..6062623b3b 100644 --- a/src/domain/analysisView/webNetworkApiSurfaceView.test.ts +++ b/src/domain/analysisView/webNetworkApiSurfaceView.test.ts @@ -351,8 +351,10 @@ it("preserves sensitive-parent refusal when query names are selected", () => { ).toMatchObject({ ok: false, error: { - _tag: "AnalysisUnsupportedTargetError", - reason: "sensitive_values_unretained", + _tag: "AnalysisTargetFailureError", + failure: { + detail: expect.stringContaining("sensitive_values_unretained"), + }, }, }); }); @@ -422,7 +424,7 @@ it("rejects native captures and malformed parents with typed errors", () => { capture.format = format; expect(project(capture)).toMatchObject({ ok: false, - error: { _tag: "AnalysisUnsupportedTargetError" }, + error: { _tag: "AnalysisTargetFailureError" }, }); } expect( @@ -553,11 +555,13 @@ it("refuses parents whose sensitive declarations it cannot check", () => { const result = project(analysisViewCaptureFixture(), 0, 50, parameters); expect(result).toMatchObject({ ok: false, - error: { _tag: "AnalysisUnsupportedTargetError" }, + error: { _tag: "AnalysisTargetFailureError" }, }); if (result.ok) continue; expect(result.error).toMatchObject({ - reason: "sensitive_values_unretained", + failure: { + detail: expect.stringContaining("sensitive_values_unretained"), + }, }); expect(result.error.message).not.toContain("path templates"); } diff --git a/src/domain/analysisView/webNetworkApiSurfaceView.ts b/src/domain/analysisView/webNetworkApiSurfaceView.ts index bac047cac6..d03dc32d38 100644 --- a/src/domain/analysisView/webNetworkApiSurfaceView.ts +++ b/src/domain/analysisView/webNetworkApiSurfaceView.ts @@ -1,5 +1,5 @@ import { z } from "zod"; -import { AnalysisUnsupportedTargetError } from "../analysisErrorCore.js"; +import { unsupportedTarget } from "../analysisErrorCore.js"; import { err, ok } from "../result.js"; import type { AnalysisViewParent } from "./analysisViewParent.js"; import { @@ -36,9 +36,10 @@ export const projectWebNetworkApiSurfaceView = ( ) => { if (view.kind !== "api-surface") return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "inspect_analysis_view", parent.evidenceId, + "evidence", `View ${view.kind} is unsupported for parent operation ${parent.operation}; api-surface requires inspect_web_network_capture.`, ), ); diff --git a/src/domain/apiContract/parseApiContract.test.ts b/src/domain/apiContract/parseApiContract.test.ts index 419576753a..839d54d3c1 100644 --- a/src/domain/apiContract/parseApiContract.test.ts +++ b/src/domain/apiContract/parseApiContract.test.ts @@ -93,7 +93,10 @@ it.each(["2.0", "3.3.0", "3.2", "3.01.0", "3.0.01", "3.2.0-beta.1"])( const value = parse(document({}, version)); expect(value.ok).toBe(false); if (!value.ok) - expect(value.error._tag).toBe("AnalysisUnsupportedTargetError"); + expect(value.error).toMatchObject({ + _tag: "AnalysisTargetFailureError", + failure: { kind: "unsupported", format: "openapi" }, + }); }, ); diff --git a/src/domain/apiContract/parseApiContract.ts b/src/domain/apiContract/parseApiContract.ts index 05b76ae383..81768a7c11 100644 --- a/src/domain/apiContract/parseApiContract.ts +++ b/src/domain/apiContract/parseApiContract.ts @@ -4,7 +4,7 @@ import { AnalysisCancelledError, AnalysisInputError, AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, + unsupportedTarget, } from "../analysisErrorCore.js"; import type { AnalysisError } from "../analysisErrorBase.js"; import { digestCanonicalValue } from "../canonicalDigest.js"; @@ -423,9 +423,10 @@ export function* parseApiContractSteps( const version = /^3\.([012])\.(?:0|[1-9][0-9]*)$/u.exec(root.openapi); if (version === null) return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( API_CONTRACT_OPERATION, artifact.path, + "openapi", "Only OpenAPI 3.0, 3.1 and 3.2 JSON documents are supported.", ), ); diff --git a/src/domain/apple/machoSliceSelection.ts b/src/domain/apple/machoSliceSelection.ts index 52a134975c..c1437c0179 100644 --- a/src/domain/apple/machoSliceSelection.ts +++ b/src/domain/apple/machoSliceSelection.ts @@ -19,7 +19,6 @@ import { import { AnalysisInputError, AnalysisTargetFailureError, - AnalysisUnsupportedTargetError, } from "../analysisErrorCore.js"; import type { AnalysisError } from "../analysisErrorBase.js"; import { ParseFailureError } from "../parseFailure.js"; @@ -139,11 +138,7 @@ const selectionError = ( ]); const parsed = failure.failure; const cause = new ParseFailureError(parsed); - return parsed.kind === "unsupported" - ? new AnalysisUnsupportedTargetError(operation, path, parsed.detail, { - cause, - }) - : new AnalysisTargetFailureError(operation, path, parsed, { cause }); + return new AnalysisTargetFailureError(operation, path, parsed, { cause }); }; interface FatSlice { diff --git a/src/domain/apple/plistScalars.test.ts b/src/domain/apple/plistScalars.test.ts index c8762a3614..222a999ab1 100644 --- a/src/domain/apple/plistScalars.test.ts +++ b/src/domain/apple/plistScalars.test.ts @@ -333,7 +333,14 @@ describe("binary plist UID widths", () => { const inexact = binaryPlistWithUid(8, BigInt(Number.MAX_SAFE_INTEGER) + 1n); expect(() => estimateBinaryPlistExpansion(inexact, 1024)).toThrow( - "binary plist UID value 9007199254740992", + expect.objectContaining({ + failure: expect.objectContaining({ + kind: "unsupported", + format: "binary-plist", + field: "uid", + undecodedContent: true, + }), + }), ); const nonzeroHighByte = binaryPlistWithUid(9, 0x1_0000_0000_0000_0000n); expect(() => estimateBinaryPlistExpansion(nonzeroHighByte, 1024)).toThrow( diff --git a/src/domain/parseFailureAnalysisError.test.ts b/src/domain/parseFailureAnalysisError.test.ts index 8a94e0d249..ffc18030be 100644 --- a/src/domain/parseFailureAnalysisError.test.ts +++ b/src/domain/parseFailureAnalysisError.test.ts @@ -3,7 +3,6 @@ import { expect, it } from "vitest"; import { AnalysisTargetFailureError, AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, } from "./analysisErrorCore.js"; import { projectAnalysisError } from "./analysisErrorProjection.js"; import { analysisErrorProjectionSchema } from "./analysisErrorProjectionSchema.js"; @@ -94,12 +93,16 @@ it("refuses an unsupported form as an unsupported target, keeping undecoded cont undecodedContent: true, }); const error = project(cause); - expect(error).toBeInstanceOf(AnalysisUnsupportedTargetError); + expect(error).toBeInstanceOf(AnalysisTargetFailureError); expect(error).toMatchObject({ cause, path: "/tmp/sample.bin", - reason: "compressed build-info section", - undecodedContent: true, + failure: { + kind: "unsupported", + format: "go", + detail: "compressed build-info section", + undecodedContent: true, + }, }); }); diff --git a/src/domain/parseFailureAnalysisError.ts b/src/domain/parseFailureAnalysisError.ts index 9a93a5d3de..47859c859a 100644 --- a/src/domain/parseFailureAnalysisError.ts +++ b/src/domain/parseFailureAnalysisError.ts @@ -2,7 +2,6 @@ import { type ANALYSIS_RESOURCE_KINDS, AnalysisTargetFailureError, AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, type ResourceConstraintRecovery, } from "./analysisErrorCore.js"; import type { AnalysisErrorOptions } from "./analysisErrorBase.js"; @@ -67,19 +66,13 @@ export const parseFailureAnalysisError = ( operation: string, path: string, cause: unknown, -): AnalysisTargetFailureError | AnalysisUnsupportedTargetError | undefined => { +): AnalysisTargetFailureError | undefined => { if (!(cause instanceof ParseFailureError)) return undefined; const { failure } = cause; switch (failure.kind) { case "limit": return undefined; case "unsupported": - return new AnalysisUnsupportedTargetError( - operation, - path, - failure.detail, - { cause, undecodedContent: failure.undecodedContent }, - ); case "malformed": case "truncated": return new AnalysisTargetFailureError(operation, path, failure, { diff --git a/src/domain/pngVisualDiff.test.ts b/src/domain/pngVisualDiff.test.ts index 2b07d5f14b..78ebc29202 100644 --- a/src/domain/pngVisualDiff.test.ts +++ b/src/domain/pngVisualDiff.test.ts @@ -6,7 +6,7 @@ import { readPngHeaderDimensions } from "./pngHeader.js"; import { comparePngScreenshots, isOneColourPng } from "./pngVisualDiff.js"; import { AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, + AnalysisTargetFailureError, } from "./analysisErrorCore.js"; import { compareWebScreenshotsInputSchema, @@ -385,7 +385,7 @@ describe("PNG chunk integrity", () => { after: grayscale, }), ), - ).toThrow(AnalysisUnsupportedTargetError); + ).toThrow(AnalysisTargetFailureError); }); }); diff --git a/src/domain/pngVisualDiff.ts b/src/domain/pngVisualDiff.ts index 1b8ca1808e..93843d30d9 100644 --- a/src/domain/pngVisualDiff.ts +++ b/src/domain/pngVisualDiff.ts @@ -7,7 +7,7 @@ import type { } from "./webScreenshot.js"; import { AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, + unsupportedTarget, } from "./analysisErrorCore.js"; import { decodeCanonicalBase64 } from "./webScreenshot.js"; import { @@ -209,15 +209,17 @@ const parsePng = ( if (header.colorType === 3 && !sawPalette) throw new TypeError("Missing PNG palette"); if (unsupportedReason !== undefined) - throw new AnalysisUnsupportedTargetError( + throw unsupportedTarget( "compare_web_screenshots", field, + "png", unsupportedReason, ); if (!header.supported) - throw new AnalysisUnsupportedTargetError( + throw unsupportedTarget( "compare_web_screenshots", field, + "png", "PNG encoding is not supported for pixel comparison.", ); const pixels = BigInt(header.width) * BigInt(header.height); diff --git a/src/domain/reconstructionVerification.ts b/src/domain/reconstructionVerification.ts index 6102da546b..11d5e04add 100644 --- a/src/domain/reconstructionVerification.ts +++ b/src/domain/reconstructionVerification.ts @@ -17,7 +17,8 @@ import { readEvidenceBundle } from "./evidenceBundle.js"; import { AnalysisInputError, AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, + targetFailureOfKind, + AnalysisTargetFailureError, } from "./analysisErrorCore.js"; import { EvidenceIntegrityError } from "./evidenceErrors.js"; import { analysisInputErrorFromIssues } from "./inputIssueProjection.js"; @@ -409,7 +410,11 @@ const assessScreenshotComparison = ( if ( !(cause instanceof TypeError) && !(cause instanceof AnalysisResourceConstraintError) && - !(cause instanceof AnalysisUnsupportedTargetError) + !( + cause instanceof AnalysisTargetFailureError && + targetFailureOfKind(cause, "unsupported", "unrecognized") !== + undefined + ) ) throw cause; replayBlocker = `Retained screenshot comparison could not be replayed: ${cause.message}`; diff --git a/src/domain/targetFailure.ts b/src/domain/targetFailure.ts index a0fb1c1585..c6b999ba87 100644 --- a/src/domain/targetFailure.ts +++ b/src/domain/targetFailure.ts @@ -296,34 +296,117 @@ export const targetFailureDetails = ( } }; -/** What a caller does next, for one failure of a known operation. */ -export const targetFailureRecovery = ( - operation: string, - failure: TargetFailure, +/** + * Operations and providers that read what the refusing operation could not. + * The owner names them by contract operation and provider ID; each adapter + * spells them its own way. + */ +export interface TargetFailureAlternatives { + readonly operations?: readonly string[]; + readonly providers?: readonly string[]; +} + +/** + * How one adapter names an operation and a provider in recovery text: MCP by + * tool name and `open_binary` argument, the CLI by command and option. + */ +export interface TargetFailureSpelling { + readonly operation: (operation: string) => string; + readonly provider: (providerId: string) => string; +} + +/** The MCP spelling, which is also the adapter-independent one in Evidence. */ +export const MCP_TARGET_FAILURE_SPELLING: TargetFailureSpelling = { + operation: (operation) => operation, + provider: (providerId) => `open_binary with provider_id "${providerId}"`, +}; + +/** The facts a recovery is rendered from, in either adapter. */ +export interface TargetFailureRecoveryFacts { + readonly operation: string; + readonly kind: TargetFailureKind; + readonly format: string; + /** The conflicting inputs' request fields, in the adapter's spelling. */ + readonly inputFields?: readonly string[]; + /** The owner's errno was transient (`retry: "backoff"` for `io`). */ + readonly transient?: boolean; + readonly alternatives?: TargetFailureAlternatives; +} + +const listed = (names: readonly string[]): string => + names.length <= 1 + ? (names[0] ?? "") + : `${names.slice(0, -1).join(", ")} or ${names.at(-1) ?? ""}`; + +/** The clause that names the alternatives, or a generic one without any. */ +const alternativeClause = ( + alternatives: TargetFailureAlternatives | undefined, + spelling: TargetFailureSpelling, ): string => { - const { recovery } = TARGET_FAILURE_PROJECTIONS[failure.kind]; + const operations = (alternatives?.operations ?? []).map(spelling.operation); + const providers = (alternatives?.providers ?? []).map(spelling.provider); + if (operations.length > 0 && providers.length > 0) + return `Use ${listed(operations)} for this target, or reopen it with ${listed(providers)}`; + if (operations.length > 0) return `Use ${listed(operations)} for this target`; + if (providers.length > 0) + return `Reopen this target with ${listed(providers)}`; + return "Choose another operation or provider for this target"; +}; + +/** + * Render what a caller does next in one adapter's spelling. This is the only + * place a target failure's recovery text is written; the CLI and MCP differ + * only in `spelling`. + */ +export const renderTargetFailureRecovery = ( + facts: TargetFailureRecoveryFacts, + spelling: TargetFailureSpelling, +): string => { + const operation = spelling.operation(facts.operation); + const { recovery } = TARGET_FAILURE_PROJECTIONS[facts.kind]; switch (recovery) { case "fix_request": return "Correct the request so it names a valid target for this operation, then retry."; case "choose_another_tool": - return `The selected target's ${failure.format} form is outside what ${operation} reads. Choose another operation or provider for this target.`; + return `The selected target's ${facts.format} form is outside what ${operation} reads. ${alternativeClause(facts.alternatives, spelling)}.`; case "choose_another_target": - return `The selected target's ${failure.format} bytes break that format's rules where ${operation} reads them. The request arguments are not at fault, so changing them will not help. Choose another operation or provider for this target, or select a well-formed copy.`; + return `The selected target's ${facts.format} bytes break that format's rules where ${operation} reads them. The request arguments are not at fault, so changing them will not help. ${alternativeClause(facts.alternatives, spelling)}, or select a well-formed copy.`; case "reacquire_complete_file": - return `The selected target's ${failure.format} bytes end before a structure they declare. The request arguments are not at fault. Re-acquire the complete file and retry; do not pad or cut the bytes.`; + return `The selected target's ${facts.format} bytes end before a structure they declare. The request arguments are not at fault. Re-acquire the complete file and retry; do not pad or cut the bytes.`; case "replace_or_record_integrity": return "The target's bytes contradict a checksum or digest they declare. Get a fresh copy, or rerun with integrity_policy=record-and-continue to keep the observed bytes as untrusted."; case "check_input_pairing": - return `The selected inputs (${failure.kind === "conflict" ? failure.inputs.map(({ field }) => field).join(", ") : "all inputs"}) each parse but disagree, so neither is reported as damaged. Select inputs from the same build. If they are from the same build, either may be damaged or its layout may be outside coverage; each input can still be read on its own.`; + return `The selected inputs (${facts.inputFields === undefined || facts.inputFields.length === 0 ? "all inputs" : facts.inputFields.join(", ")}) each parse but disagree, so neither is reported as damaged. Select inputs from the same build. If they are from the same build, either may be damaged or its layout may be outside coverage; each input can still be read on its own.`; case "retry_on_stable_copy": return "The target changed while it was read. Retry once it is stable, or copy it first."; case "fix_permissions": return "Host permissions denied the read. Grant read access to the selected path, then retry."; case "check_host": - return failure.kind === "io" && failure.transient + return facts.transient === true ? "The host reported a transient read failure. Retry with backoff." : "The host could not read the target. Check the device and file before retrying."; default: return unhandledTargetFailureCase(recovery); } }; + +/** What a caller does next, for one failure of a known operation. */ +export const targetFailureRecovery = ( + operation: string, + failure: TargetFailure, + alternatives?: TargetFailureAlternatives, + spelling: TargetFailureSpelling = MCP_TARGET_FAILURE_SPELLING, +): string => + renderTargetFailureRecovery( + { + operation, + kind: failure.kind, + format: failure.format, + ...(failure.kind === "conflict" + ? { inputFields: failure.inputs.map(({ field }) => field) } + : {}), + transient: failure.kind === "io" && failure.transient, + ...(alternatives === undefined ? {} : { alternatives }), + }, + spelling, + ); diff --git a/src/dotnet/ManagedStaticProvider.ts b/src/dotnet/ManagedStaticProvider.ts index c48106c38b..5224aa198e 100644 --- a/src/dotnet/ManagedStaticProvider.ts +++ b/src/dotnet/ManagedStaticProvider.ts @@ -24,8 +24,8 @@ import { AnalysisError } from "../domain/analysisErrorBase.js"; import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; import { AnalysisCapabilityUnavailableError, - AnalysisUnsupportedTargetError, cancelledBy, + unsupportedTarget, } from "../domain/analysisErrorCore.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; @@ -95,9 +95,10 @@ class ManagedStaticClient implements AnalysisClient { // provider capability; the unimplemented-operation refusal above is. if (this.target.format !== "pe") return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( operation, this.target.path, + this.target.format, `Managed static triage requires a PE target; observed ${this.target.format}.`, ), ); diff --git a/src/electron/ElectronFuseProvider.test.ts b/src/electron/ElectronFuseProvider.test.ts index 646c255851..0585935929 100644 --- a/src/electron/ElectronFuseProvider.test.ts +++ b/src/electron/ElectronFuseProvider.test.ts @@ -448,7 +448,7 @@ describe("Electron fuse path and container admission", () => { const result = await provider.inspect({ path }); expect(result.ok, path).toBe(false); if (!result.ok) - expect(result.error._tag).toBe("AnalysisUnsupportedTargetError"); + expect(result.error._tag).toBe("AnalysisTargetFailureError"); } }); diff --git a/src/evm/EvmoleInterfaceProvider.ts b/src/evm/EvmoleInterfaceProvider.ts index 9e066a04c3..ff66912c68 100644 --- a/src/evm/EvmoleInterfaceProvider.ts +++ b/src/evm/EvmoleInterfaceProvider.ts @@ -51,13 +51,13 @@ import { import { type AnalysisCancelledError, AnalysisCapabilityUnavailableError, - AnalysisUnsupportedTargetError, AnalysisInputError, AnalysisTargetFailureError, AnalysisOutputError, cancelledBy, carriedReason, type AbortedSignal, + unsupportedTarget, } from "../domain/analysisErrorCore.js"; import { isAbortOf } from "../process/SignalAbort.js"; import { @@ -759,9 +759,10 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort { } if (!reply.ok) { if (reply.reason === "unsupported") - throw new AnalysisUnsupportedTargetError( + throw unsupportedTarget( OPERATION, input.path, + "evm-bytecode", reply.message, { capturedOutput }, ); diff --git a/src/flutter/FlutterBuildProvider.ts b/src/flutter/FlutterBuildProvider.ts index 4e572354f2..61421f03c0 100644 --- a/src/flutter/FlutterBuildProvider.ts +++ b/src/flutter/FlutterBuildProvider.ts @@ -43,10 +43,10 @@ import { AnalysisCancelledError, AnalysisInputError, AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, AnalysisProtocolError, cancelledBy, carriedReason, + unsupportedTarget, } from "../domain/analysisErrorCore.js"; import { isAbortWithReason } from "../process/SignalAbort.js"; import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js"; @@ -1151,9 +1151,10 @@ export class FlutterBuildProvider { const candidates = libraries.filter((library) => library.kind === "libapp"); if (candidates.length === 0) return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "inspect_dart_aot", path, + "dart-aot", "No lib//libapp.so was found; the target carries no Dart AOT payload", ), ); @@ -1169,9 +1170,10 @@ export class FlutterBuildProvider { : candidates.find((candidate) => candidate.abi === abi); if (selected === undefined) return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "inspect_dart_aot", path, + "dart-aot", `No libapp.so was found for ABI ${abi ?? "(none)"}; available: ${candidates .map((candidate) => candidate.abi) .join(", ")}`, @@ -1253,9 +1255,10 @@ export class FlutterBuildProvider { const snapshotFacts = await observeDartSnapshot(bounded, signal); if (!snapshotFacts.observed) return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "inspect_dart_aot", path, + "dart-aot", `No recognizable Dart snapshot symbols were found: ${snapshotFacts.reasons.join("; ")}`, ), ); diff --git a/src/ghidra/GhidraAnalysisProfile.ts b/src/ghidra/GhidraAnalysisProfile.ts index 16bc5602ba..676a069cbe 100644 --- a/src/ghidra/GhidraAnalysisProfile.ts +++ b/src/ghidra/GhidraAnalysisProfile.ts @@ -8,10 +8,7 @@ import type { JsonValue } from "../domain/jsonValue.js"; import { createAnalysisProfile } from "../domain/analysisProfile.js"; import type { GhidraLanguageOverride } from "../config/ghidraLanguageOverride.js"; import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; -import { - AnalysisUnsupportedTargetError, - cancelledBy, -} from "../domain/analysisErrorCore.js"; +import { cancelledBy, unsupportedTarget } from "../domain/analysisErrorCore.js"; import { resolveGhidraComImport } from "./GhidraComImport.js"; import { ConfigurationError } from "../domain/configurationErrors.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; @@ -150,9 +147,10 @@ export const resolveGhidraAnalysisProfile = async ( if (mipsReason !== null) return Promise.resolve( err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "resolve_analysis_profile", target.path, + target.format, mipsReason, ), ), diff --git a/src/ghidra/GhidraMipsProfile.test.ts b/src/ghidra/GhidraMipsProfile.test.ts index 873b134326..f4f798d675 100644 --- a/src/ghidra/GhidraMipsProfile.test.ts +++ b/src/ghidra/GhidraMipsProfile.test.ts @@ -207,8 +207,8 @@ describe("bounded Ghidra MIPS admission", () => { expect(resolved).toMatchObject({ ok: false, error: { - _tag: "AnalysisUnsupportedTargetError", - reason: expect.stringContaining(reason), + _tag: "AnalysisTargetFailureError", + failure: { detail: expect.stringContaining(reason) }, }, }); }, @@ -240,8 +240,8 @@ describe("recordless legacy MIPS admission", () => { expect(resolved).toMatchObject({ ok: false, error: { - _tag: "AnalysisUnsupportedTargetError", - reason: expect.stringContaining("ET_EXEC"), + _tag: "AnalysisTargetFailureError", + failure: { detail: expect.stringContaining("ET_EXEC") }, }, }); }, diff --git a/src/ghidra/GhidraPowerPcProfile.test.ts b/src/ghidra/GhidraPowerPcProfile.test.ts index ad84a673b8..c3b485f4f3 100644 --- a/src/ghidra/GhidraPowerPcProfile.test.ts +++ b/src/ghidra/GhidraPowerPcProfile.test.ts @@ -157,8 +157,8 @@ describe("bounded Ghidra PowerPC admission", () => { expect(resolved).toMatchObject({ ok: false, error: { - _tag: "AnalysisUnsupportedTargetError", - reason: expect.stringContaining(reason), + _tag: "AnalysisTargetFailureError", + failure: { detail: expect.stringContaining(reason) }, }, }); }, diff --git a/src/ghidra/extensions/GhidraExtensions.test.ts b/src/ghidra/extensions/GhidraExtensions.test.ts index 5655634f18..3b1d2fc559 100644 --- a/src/ghidra/extensions/GhidraExtensions.test.ts +++ b/src/ghidra/extensions/GhidraExtensions.test.ts @@ -109,13 +109,13 @@ describe("optional Ghidra extension refusals", () => { if (!architecture.ok) expect(projectAnalysisError(architecture.error)).toMatchObject({ code: "unsupported_target", - remediation: { - action: expect.stringContaining("omit REA_GHIDRA_NATIVEAOT_JAR"), - }, details: { operation: "resolve_analysis_profile", path: target.path, - reason: expect.stringContaining("x86-64 ELF or native PE"), + failure_kind: "unsupported", + reason: expect.stringMatching( + /x86-64 ELF or native PE.*omit REA_GHIDRA_NATIVEAOT_JAR/su, + ), }, }); }); @@ -344,8 +344,8 @@ describe("Ghidra extension profile and producer validation", () => { if (!resolved.ok) expect(projectAnalysisError(resolved.error)).toMatchObject({ code: "unsupported_target", - remediation: { - action: expect.stringContaining("inspect_managed_artifact"), + details: { + reason: expect.stringContaining("inspect_managed_artifact"), }, }); }); diff --git a/src/ghidra/extensions/GhidraExtensions.ts b/src/ghidra/extensions/GhidraExtensions.ts index 5b4b821557..71809979d6 100644 --- a/src/ghidra/extensions/GhidraExtensions.ts +++ b/src/ghidra/extensions/GhidraExtensions.ts @@ -8,8 +8,8 @@ import type { AppConfig } from "../../config/types.js"; import type { BinaryTarget } from "../../domain/binaryTargetTypes.js"; import { AnalysisCapabilityUnavailableError, - AnalysisUnsupportedTargetError, cancelledBy, + unsupportedTarget, } from "../../domain/analysisErrorCore.js"; import { type ArtifactResourceScope, @@ -199,12 +199,12 @@ const extensionRefusalError = ( refusal.reason, { userMessage: refusal.reason }, ) - : new AnalysisUnsupportedTargetError( + : // The reason names the workflows that remain available. + unsupportedTarget( "resolve_analysis_profile", target.path, + target.format, refusal.reason, - // The reason names the workflows that remain available. - { remediationAction: refusal.reason }, ); /** Snapshot committed extension bytes into the private runtime before Java loads them. */ diff --git a/src/native/AppleDispatchMetadata.failure.test.ts b/src/native/AppleDispatchMetadata.failure.test.ts index 0483d7e266..60a2e2a8a3 100644 --- a/src/native/AppleDispatchMetadata.failure.test.ts +++ b/src/native/AppleDispatchMetadata.failure.test.ts @@ -8,9 +8,13 @@ it.each(["malformed", "unsupported"] as const)( (kind) => { const cause = new BinaryFormatFailure(kind, "metadata format refused"); expect(appleDispatchMetadataFailure(cause, "/selected")).toMatchObject({ - _tag: "AnalysisUnsupportedTargetError", + _tag: "AnalysisTargetFailureError", path: "/selected", - reason: "metadata format refused", + failure: { + kind, + format: "native-binary", + detail: "metadata format refused", + }, }); }, ); diff --git a/src/native/AppleDispatchMetadata.ts b/src/native/AppleDispatchMetadata.ts index b26ae3390d..fc05762d4f 100644 --- a/src/native/AppleDispatchMetadata.ts +++ b/src/native/AppleDispatchMetadata.ts @@ -34,9 +34,9 @@ import { AnalysisAccessDeniedError, AnalysisCapabilityUnavailableError, AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, cancelledBy, carriedReason, + AnalysisTargetFailureError, } from "../domain/analysisErrorCore.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; @@ -531,18 +531,9 @@ const appleDispatchMetadataPrimaryFailure = ( { cause }, ); if (cause instanceof BinaryFormatFailure) - return new AnalysisUnsupportedTargetError( - OPERATION, - path, - cause.message, - { - cause, - remediationAction: - cause.kind !== "unsupported" - ? "Select a Mach-O artifact with well-formed metadata sections, reopen the target, then retry." - : "Select a supported little-endian 64-bit Mach-O artifact, reopen the target, then retry.", - }, - ); + return new AnalysisTargetFailureError(OPERATION, path, cause.failure, { + cause, + }); if (cause instanceof ArtifactReaderFailure && cause.reason === "cancelled") return cancelledBy( OPERATION, diff --git a/src/native/NativeMacOSProvider.ts b/src/native/NativeMacOSProvider.ts index 01f47430ec..5c2b159e98 100644 --- a/src/native/NativeMacOSProvider.ts +++ b/src/native/NativeMacOSProvider.ts @@ -83,7 +83,7 @@ import { AnalysisCapabilityUnavailableError, AnalysisInputError, AnalysisOutputError, - AnalysisUnsupportedTargetError, + AnalysisTargetFailureError, type AnalysisResourceConstraintError, cancelledBy, } from "../domain/analysisErrorCore.js"; @@ -1266,10 +1266,10 @@ class NativeMacOSClient implements AnalysisClient { if (!parsed.ok) { if (parsed.error instanceof UnsupportedBinaryPlistUidError) return err( - new AnalysisUnsupportedTargetError( + new AnalysisTargetFailureError( "inspect_plist", fileInput.selection.path, - parsed.error.message, + parsed.error.failure, { cause: parsed.error }, ), ); diff --git a/src/native/NativeMachoInspection.test.ts b/src/native/NativeMachoInspection.test.ts index dceb1e914c..a52df90a50 100644 --- a/src/native/NativeMachoInspection.test.ts +++ b/src/native/NativeMachoInspection.test.ts @@ -927,7 +927,7 @@ describe("dSYM diagnostic admission", () => { expect(result.ok).toBe(false); if (result.ok) return; expect(result.error._tag).toBe( - accepted ? "AnalysisUnsupportedTargetError" : "AnalysisOutputError", + accepted ? "AnalysisTargetFailureError" : "AnalysisOutputError", ); expect(result.error.capturedOutput).toMatchObject({ stdout, diff --git a/src/native/NativeMachoInspection.ts b/src/native/NativeMachoInspection.ts index 06daa6976e..d5a980f161 100644 --- a/src/native/NativeMachoInspection.ts +++ b/src/native/NativeMachoInspection.ts @@ -6,7 +6,7 @@ import type { EvidenceLocation } from "../domain/evidence.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { AnalysisOutputError, - AnalysisUnsupportedTargetError, + unsupportedTarget, } from "../domain/analysisErrorCore.js"; import { inspectMachoSchema, @@ -311,14 +311,14 @@ export const inspectNativeMacho = async ( if (binary.header.fileType !== MH_DSYM) return err(unusableNativeCommandOutput(unbackedTextFailure)); return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "inspect_macho", context.target.path, - "The selected Mach-O is a dSYM companion whose unbacked text sections are unsupported by dyld_info inspection", + "macho", + "The selected Mach-O is a dSYM companion whose unbacked text sections are unsupported by dyld_info inspection; select the matching linked executable", { + field: "filetype", capturedOutput: nativeMachoCapturedOutput(unbackedTextFailure), - remediationAction: - "Select the matching linked Mach-O executable for native inspection; this operation does not inspect dSYM companions with unbacked text sections.", }, ), ); @@ -331,14 +331,14 @@ export const inspectNativeMacho = async ( return err(unusableNativeCommandOutput(fileTypeFailure)); const typeName = fileType === 4 ? "CORE" : "FVMLIB"; return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "inspect_macho", context.target.path, - `dyld_info refused the selected Mach-O file type MH_${typeName} (${fileType}): ${diagnostic}`, + "macho", + `dyld_info refused the selected Mach-O file type MH_${typeName} (${fileType}); it reads linked executables and relocatable objects: ${diagnostic}`, { + field: "filetype", capturedOutput: nativeMachoCapturedOutput(fileTypeFailure), - remediationAction: - "Select a linked Mach-O executable or relocatable object for native inspection; dyld_info refused the selected file type.", }, ), ); diff --git a/src/native/metadata/MachoSliceSelection.test.ts b/src/native/metadata/MachoSliceSelection.test.ts index 6fb0baa150..a520b9c8bc 100644 --- a/src/native/metadata/MachoSliceSelection.test.ts +++ b/src/native/metadata/MachoSliceSelection.test.ts @@ -14,7 +14,6 @@ import { import { AnalysisInputError, AnalysisTargetFailureError, - AnalysisUnsupportedTargetError, } from "../../domain/analysisErrorCore.js"; const selectNativeImage = ( @@ -400,7 +399,7 @@ describe.each(Object.entries(MAPPERS))( const file = fat([[CPU_ARM64, 0]]); file.bytes.writeUInt32BE(60, 8 + 16); const refused = await refusal(file.bytes, "arm64"); - expect(refused).toBeInstanceOf(AnalysisUnsupportedTargetError); + expect(refused).toBeInstanceOf(AnalysisTargetFailureError); expect(refused).toMatchObject({ path: "/a.dylib" }); }); }, diff --git a/src/native/pwntools/PwntoolsDecoder.ts b/src/native/pwntools/PwntoolsDecoder.ts index 49331316c1..782dbe6449 100644 --- a/src/native/pwntools/PwntoolsDecoder.ts +++ b/src/native/pwntools/PwntoolsDecoder.ts @@ -45,13 +45,13 @@ import type { import { AnalysisError } from "../../domain/analysisErrorBase.js"; import { AnalysisCapabilityUnavailableError, - AnalysisUnsupportedTargetError, AnalysisInputError, AnalysisTargetFailureError, AnalysisOutputError, AnalysisResourceConstraintError, cancelledBy, carriedReason, + unsupportedTarget, } from "../../domain/analysisErrorCore.js"; import { projectAnalysisError, @@ -580,9 +580,10 @@ export class PwntoolsDecoder< } if (!reply.ok) { if (reply.reason === "unsupported-target") - throw new AnalysisUnsupportedTargetError( + throw unsupportedTarget( OPERATION, input.path, + this.profile.targetFormat, reply.message, { capturedOutput }, ); diff --git a/src/pcap/PcapCommand.ts b/src/pcap/PcapCommand.ts index c4ad63b13a..679b79178d 100644 --- a/src/pcap/PcapCommand.ts +++ b/src/pcap/PcapCommand.ts @@ -24,9 +24,9 @@ import { createPcapDiagnosticProjection } from "./PcapDiagnosticOutput.js"; import { AnalysisCapabilityUnavailableError, AnalysisProtocolError, - AnalysisUnsupportedTargetError, cancelledBy, carriedReason, + unsupportedTarget, } from "../domain/analysisErrorCore.js"; import { OwnedCommandFailure, @@ -138,9 +138,10 @@ export const runPcapCommand = async (options: { diagnostic, ) ) - return new AnalysisUnsupportedTargetError( + return unsupportedTarget( operation, options.inputPath, + "pcap", diagnostic, details, ); diff --git a/tests/acceptance/androidBootImageCli.test.ts b/tests/acceptance/androidBootImageCli.test.ts index ad0caba910..6f16807868 100644 --- a/tests/acceptance/androidBootImageCli.test.ts +++ b/tests/acceptance/androidBootImageCli.test.ts @@ -117,8 +117,9 @@ cliTest( category: fixture.category, details: { operation: "inspect_artifact", + path, failure_kind: fixture.kind, - format: "format" in fixture ? fixture.format : "android-boot-image", + format: fixture.format, }, }); expect((await readFile(path)).equals(fixture.bytes)).toBe(true); diff --git a/tests/acceptance/managedCliOutput.test.ts b/tests/acceptance/managedCliOutput.test.ts index 6eff34d6e7..d4623ca9f9 100644 --- a/tests/acceptance/managedCliOutput.test.ts +++ b/tests/acceptance/managedCliOutput.test.ts @@ -751,13 +751,17 @@ cliTest( code: "unsupported_target", category: "unsupported_target", retryable: false, + retry: "none", remediation: { - action: - "Select a target supported by this operation or choose an operation supporting the reported target format.", + action: expect.stringContaining( + "Choose another operation or provider for this target.", + ), }, details: { operation: command.replaceAll("-", "_"), path, + failure_kind: "unsupported", + format, reason: `Managed static triage requires a PE target; observed ${format}.`, }, }); diff --git a/tests/acceptance/stableArtifactParserFailureCli.test.ts b/tests/acceptance/stableArtifactParserFailureCli.test.ts deleted file mode 100644 index 9c47c1e96d..0000000000 --- a/tests/acceptance/stableArtifactParserFailureCli.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { createHash } from "node:crypto"; -import { writeFile } from "node:fs/promises"; -import { join } from "node:path"; -import { expect } from "vitest"; -import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; -import { cliTest } from "../support/cli/cliFixture.js"; - -const fileIdentity = (path: string, bytes: Buffer) => ({ - kind: "file-snapshot-hash", - path, - bytes: bytes.length, - sha256: createHash("sha256").update(bytes).digest("hex"), -}); - -// Foreign bytes each reader refuses before it decodes any structure. The -// malformed and truncated cases live in the target-failure conformance -// registry (tests/support/targetFailure); these join it when the unsupported -// and unrecognised refusals migrate onto the TargetFailure model (#14239). -for (const command of [ - "inspect-python-pyc", - "inspect-erlang-beam", - "inspect-rust-binary", - "inspect-go-binary", - "inspect-elf-notes", - "inspect-elf-dependencies", - "inspect-elf-debug-link", - "inspect-elf-unwind-ranges", - "inspect-devicetree", - "inspect-pe-imports", - "inspect-kernel-module", - "inspect-apple-ips", - "inspect-pe-load-config", - "inspect-pe-certificates", - "inspect-pe-resources", - "inspect-native-exports", - "inspect-native-initializers", - "inspect-binary-hardening", -]) { - const isBeam = command === "inspect-erlang-beam"; - - cliTest( - `${command} retains the completed file identity after format refusal`, - async ({ cli }) => { - const root = await createTestTempDirectory("rea-format-refusal-"); - const path = join(root, "foreign.bin"); - const bytes = isBeam ? Buffer.from("FOR1") : Buffer.alloc(64, 0x7f); - await writeFile(path, bytes); - const result = await cli.run({ arguments: [command, path, "--json"] }); - expect(result.exitCode, result.stderr).toBe(1); - expect(result.json).toMatchObject({ - details: { partial_observation: fileIdentity(path, bytes) }, - }); - }, - ); -} diff --git a/tests/boundary/cli/cliHumanFailureOutput.test.ts b/tests/boundary/cli/cliHumanFailureOutput.test.ts index 0617c53695..f9d47704ba 100644 --- a/tests/boundary/cli/cliHumanFailureOutput.test.ts +++ b/tests/boundary/cli/cliHumanFailureOutput.test.ts @@ -11,7 +11,7 @@ import { registerCliCommand } from "../../../src/cli/commandRegistry.js"; import { logCliCommand } from "../../../src/cliLogging.js"; import { AnalysisInputError, - AnalysisUnsupportedTargetError, + unsupportedTarget, } from "../../../src/domain/analysisErrorCore.js"; import { projectAnalysisError, @@ -25,9 +25,10 @@ const CLI_ISSUE_REPORT_URL = "https://github.com/morluto/rea/issues"; const unsupportedTargetProjection = (): AnalysisErrorProjection => projectAnalysisError( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "inspect-target", "/tmp/sample.bin", + "fixture", "Container format is unsupported.", ), "invocation", diff --git a/tests/boundary/cli/desktopApplicationCli.test.ts b/tests/boundary/cli/desktopApplicationCli.test.ts index 154307421e..1457199f22 100644 --- a/tests/boundary/cli/desktopApplicationCli.test.ts +++ b/tests/boundary/cli/desktopApplicationCli.test.ts @@ -154,9 +154,15 @@ cliTest( }); expect(notDirectory.exitCode).toBe(1); expect(notDirectory.json).toMatchObject({ - code: "unsupported_target", - category: "unsupported_target", - details: { operation: "inspect_desktop_application", path: file }, + code: "invalid_request", + category: "invalid_input", + retry: "after_change", + details: { + operation: "inspect_desktop_application", + path: file, + failure_kind: "selection", + format: "desktop-application", + }, }); const missingPath = join(root, "missing-directory"); const missing = await cli.run({ diff --git a/tests/boundary/evm/evmoleInterfaceProvider.test.ts b/tests/boundary/evm/evmoleInterfaceProvider.test.ts index 498c32dc70..e79f395a8a 100644 --- a/tests/boundary/evm/evmoleInterfaceProvider.test.ts +++ b/tests/boundary/evm/evmoleInterfaceProvider.test.ts @@ -513,7 +513,7 @@ it scenario === "format" || scenario === "literal-replacement" ? "AnalysisTargetFailureError" : scenario === "unsupported" - ? "AnalysisUnsupportedTargetError" + ? "AnalysisTargetFailureError" : scenario === "output-limit" ? "AnalysisResourceConstraintError" : "AnalysisOutputError", diff --git a/tests/boundary/filesystem/artifactAdmittedIdentity.test.ts b/tests/boundary/filesystem/artifactAdmittedIdentity.test.ts index d9c3825a84..5613dab50b 100644 --- a/tests/boundary/filesystem/artifactAdmittedIdentity.test.ts +++ b/tests/boundary/filesystem/artifactAdmittedIdentity.test.ts @@ -353,7 +353,7 @@ it("checks embedded native packs before acceptance while preserving unsupported await session.execute("extract_artifact", { output_root: output }), ).toMatchObject({ ok: false, - error: { _tag: "AnalysisUnsupportedTargetError" }, + error: { _tag: "AnalysisTargetFailureError" }, }); await expect(access(output)).rejects.toMatchObject({ code: "ENOENT" }); } finally { diff --git a/tests/boundary/filesystem/artifactZipIntegrity.test.ts b/tests/boundary/filesystem/artifactZipIntegrity.test.ts index 87a693e8a4..2670fc6dba 100644 --- a/tests/boundary/filesystem/artifactZipIntegrity.test.ts +++ b/tests/boundary/filesystem/artifactZipIntegrity.test.ts @@ -657,8 +657,12 @@ it("preserves encrypted-member and malformed-compression observations", async () expect(extraction).toMatchObject({ ok: false, error: { - _tag: "AnalysisUnsupportedTargetError", - reason: expect.stringContaining("Archive entry secret.txt is encrypted"), + _tag: "AnalysisTargetFailureError", + failure: { + detail: expect.stringContaining( + "Archive entry secret.txt is encrypted", + ), + }, }, }); await expect(readFile(extractionRoot)).rejects.toMatchObject({ diff --git a/tests/boundary/filesystem/binaryHardening.test.ts b/tests/boundary/filesystem/binaryHardening.test.ts index aae5cc69d3..3553e874a7 100644 --- a/tests/boundary/filesystem/binaryHardening.test.ts +++ b/tests/boundary/filesystem/binaryHardening.test.ts @@ -27,7 +27,7 @@ describe("binary hardening stable filesystem boundary", () => { await writeFile(foreign, Buffer.from("not a binary")); const unsupported = await service.inspect({ path: foreign }); if (unsupported.ok) throw new Error("Expected an unsupported target"); - expect(unsupported.error._tag).toBe("AnalysisUnsupportedTargetError"); + expect(unsupported.error._tag).toBe("AnalysisTargetFailureError"); } finally { await service.close(); } diff --git a/tests/boundary/filesystem/dotnetBundleArtifacts.test.ts b/tests/boundary/filesystem/dotnetBundleArtifacts.test.ts index 5e9a1ed53c..ac8f193243 100644 --- a/tests/boundary/filesystem/dotnetBundleArtifacts.test.ts +++ b/tests/boundary/filesystem/dotnetBundleArtifacts.test.ts @@ -1126,7 +1126,7 @@ it.each(["pe", "elf"] as const)( integrityPolicy: "fail", resourceScope: new ArtifactResourceScope(), }), - ).rejects.toMatchObject({ _tag: "AnalysisUnsupportedTargetError" }); + ).rejects.toMatchObject({ _tag: "AnalysisTargetFailureError" }); await expect(access(outputRoot)).rejects.toThrow(); }, ); diff --git a/tests/boundary/filesystem/dwarfUnits.test.ts b/tests/boundary/filesystem/dwarfUnits.test.ts index c2c70230cb..caee265b1d 100644 --- a/tests/boundary/filesystem/dwarfUnits.test.ts +++ b/tests/boundary/filesystem/dwarfUnits.test.ts @@ -3,7 +3,7 @@ import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { createDwarfUnitsService } from "../../../src/composition/binaryDiagnostics/dwarfUnits.js"; import { elfImage } from "../../../src/native/dwarf/DwarfUnits.fixture.js"; -import { AnalysisUnsupportedTargetError } from "../../../src/domain/analysisErrorCore.js"; +import { AnalysisTargetFailureError } from "../../../src/domain/analysisErrorCore.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { expectFileSelectionErrors } from "../../support/expectFileSelectionErrors.js"; @@ -42,9 +42,7 @@ describe("DWARF compile-unit stable filesystem boundary", () => { }); const foreignResult = await service.inspect({ path: foreign }); if (foreignResult.ok) throw new Error("Expected an unsupported file"); - expect(foreignResult.error).toBeInstanceOf( - AnalysisUnsupportedTargetError, - ); + expect(foreignResult.error).toBeInstanceOf(AnalysisTargetFailureError); } finally { await service.close(); } diff --git a/tests/boundary/filesystem/flutterBuildProvider.test.ts b/tests/boundary/filesystem/flutterBuildProvider.test.ts index ce98c08b4a..e369afd279 100644 --- a/tests/boundary/filesystem/flutterBuildProvider.test.ts +++ b/tests/boundary/filesystem/flutterBuildProvider.test.ts @@ -1199,7 +1199,7 @@ it("refuses snapshot names without exported definitions", async () => { image[table + 2 * 24 + 4] = 0; // Local isolate data. image[table + 3 * 24 + 5] = 1; // Internal isolate instructions. await expect(analyzeImage(image, "inspect_dart_aot")).rejects.toMatchObject({ - _tag: "AnalysisUnsupportedTargetError", + _tag: "AnalysisTargetFailureError", }); }); diff --git a/tests/boundary/filesystem/ghidraPspExtension.test.ts b/tests/boundary/filesystem/ghidraPspExtension.test.ts index 4c63a1ce13..277b3f9978 100644 --- a/tests/boundary/filesystem/ghidraPspExtension.test.ts +++ b/tests/boundary/filesystem/ghidraPspExtension.test.ts @@ -450,7 +450,7 @@ describe.skipIf(process.platform === "win32")( ); const result = await provider.resolveAnalysisProfile(altered); if (result.ok) throw new Error("Invalid target was admitted"); - expect(result.error._tag).toBe("AnalysisUnsupportedTargetError"); + expect(result.error._tag).toBe("AnalysisTargetFailureError"); }, ); @@ -577,7 +577,7 @@ describe.skipIf(process.platform === "win32")( ); const result = await provider.resolveAnalysisProfile(altered); if (result.ok) throw new Error("Invalid ABI was admitted"); - expect(result.error._tag).toBe("AnalysisUnsupportedTargetError"); + expect(result.error._tag).toBe("AnalysisTargetFailureError"); expect(result.error.message).toContain( "separate MIPS ABI flags record", ); @@ -602,7 +602,7 @@ describe.skipIf(process.platform === "win32")( }; const result = await provider.resolveAnalysisProfile(altered); if (result.ok) throw new Error("Missing ABI was inferred"); - expect(result.error._tag).toBe("AnalysisUnsupportedTargetError"); + expect(result.error._tag).toBe("AnalysisTargetFailureError"); expect(result.error.message).toContain( "inspected separate MIPS ABI flags record", ); diff --git a/tests/boundary/filesystem/javascriptApplicationInputSelection.test.ts b/tests/boundary/filesystem/javascriptApplicationInputSelection.test.ts index f74c5aa69b..e235887f01 100644 --- a/tests/boundary/filesystem/javascriptApplicationInputSelection.test.ts +++ b/tests/boundary/filesystem/javascriptApplicationInputSelection.test.ts @@ -123,10 +123,12 @@ describe("JavaScript application input selection", () => { expect(await analyzeFailure({ input_path: binary })).toMatchObject({ code: "unsupported_target", category: "unsupported_target", - remediation: { action: expect.stringContaining(".asar") }, details: { operation: "analyze_javascript_application", path: binary, + failure_kind: "unsupported", + // The owner names the accepted inputs; the projection owns recovery. + reason: expect.stringContaining(".asar"), }, }); }); @@ -159,7 +161,15 @@ describe("JavaScript application input selection", () => { }, }, }); - expect(projected.remediation.action).toContain("entries_by_format"); + expect(projected).toMatchObject({ + details: { + failure_kind: "unrecognized", + reason: expect.stringContaining("entries_by_format"), + }, + }); + expect(projected.remediation.action).toContain( + "inspect_desktop_application", + ); expect(JSON.stringify(projected)).not.toContain("tool.exe"); }); diff --git a/tests/boundary/filesystem/keyedArchiveSelection.test.ts b/tests/boundary/filesystem/keyedArchiveSelection.test.ts index cdfdb9487c..a3241d3072 100644 --- a/tests/boundary/filesystem/keyedArchiveSelection.test.ts +++ b/tests/boundary/filesystem/keyedArchiveSelection.test.ts @@ -21,7 +21,7 @@ import { AnalysisError } from "../../../src/domain/analysisErrorBase.js"; import { AnalysisAccessDeniedError, AnalysisInputError, - AnalysisUnsupportedTargetError, + AnalysisTargetFailureError, } from "../../../src/domain/analysisErrorCore.js"; import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; @@ -255,7 +255,7 @@ it.each([ const rejected = await inspect(root, { path: "Contents/Resources/Other.nib", }).catch((cause: unknown) => cause); - expect(rejected).toBeInstanceOf(AnalysisUnsupportedTargetError); + expect(rejected).toBeInstanceOf(AnalysisTargetFailureError); expect(projectAnalysisError(asAnalysisError(rejected))).toMatchObject({ code: "unsupported_target", message: expect.stringContaining(reason), @@ -269,14 +269,11 @@ it.each([ ); it.each([ - ["darwin", "Inspect an ordinary property list with inspect_plist"], - [ - "linux", - "inspect_plist, which reads ordinary property lists, requires a macOS host", - ], + ["darwin", "it has no $archiver key"], + ["linux", "the ordinary property list reader requires a macOS host"], ] as const)( - "names the property-list workflow available on a %s host", - async (platform, action) => { + "names the property-list workflow and its host on a %s host", + async (platform, reason) => { const root = await createTestTempDirectory("rea-keyed-kind-"); const path = join(root, "Defaults.plist"); const bytes = Buffer.from(build({ plain: true })); @@ -292,8 +289,16 @@ it.each([ if (result.ok) throw new Error("Expected an unsupported target"); expect(projectAnalysisError(result.error)).toMatchObject({ code: "unsupported_target", - remediation: { action: expect.stringContaining(action) }, - details: { path }, + remediation: { + action: expect.stringContaining("Use inspect_plist for this target."), + }, + details: { + path, + failure_kind: "unrecognized", + format: "keyed-archive", + reason: expect.stringContaining(reason), + related_operations: ["inspect_plist"], + }, }); }, ); diff --git a/tests/boundary/filesystem/nativeExports.test.ts b/tests/boundary/filesystem/nativeExports.test.ts index 836963aff7..07bc8c68e3 100644 --- a/tests/boundary/filesystem/nativeExports.test.ts +++ b/tests/boundary/filesystem/nativeExports.test.ts @@ -495,8 +495,8 @@ describe("native export encoding and failures", () => { path: malformed, }); expect(await failure({ path: macho })).toMatchObject({ - _tag: "AnalysisUnsupportedTargetError", - reason: expect.stringContaining("inspect_macho"), + _tag: "AnalysisTargetFailureError", + failure: { detail: expect.stringContaining("inspect_macho") }, }); expect(await failure({ path, max_file_bytes: 64 })).toMatchObject({ _tag: "AnalysisResourceConstraintError", diff --git a/tests/boundary/gpu/codeObjects.test.ts b/tests/boundary/gpu/codeObjects.test.ts index 699a40dfb1..dd9f4275d6 100644 --- a/tests/boundary/gpu/codeObjects.test.ts +++ b/tests/boundary/gpu/codeObjects.test.ts @@ -1719,14 +1719,14 @@ it("does not recognize a CCOB signature after its first byte is corrupted", asyn const result = await inspect(bytes); expect(result).toMatchObject({ ok: false, - error: { _tag: "AnalysisUnsupportedTargetError" }, + error: { _tag: "AnalysisTargetFailureError" }, }); }); it("requires the PTX version directive before any module content", async () => { const result = await inspect(Buffer.from(`unexpected-prefix ${ptxFixture}`)); expect(result).toMatchObject({ ok: false, - error: { _tag: "AnalysisUnsupportedTargetError" }, + error: { _tag: "AnalysisTargetFailureError" }, }); }); it("retains an embedded CCOB with a corrupted signature as unsupported", async () => { @@ -1780,7 +1780,7 @@ it("does not dispatch a high-bit-corrupted DOS signature to the PE parser", asyn const result = await inspect(bytes); expect(result).toMatchObject({ ok: false, - error: { _tag: "AnalysisUnsupportedTargetError" }, + error: { _tag: "AnalysisTargetFailureError" }, }); }); it("preserves the PE layout refusal at the GPU provider boundary", async () => { @@ -1788,7 +1788,7 @@ it("preserves the PE layout refusal at the GPU provider boundary", async () => { expect(result).toMatchObject({ ok: false, error: { - _tag: "AnalysisUnsupportedTargetError", + _tag: "AnalysisTargetFailureError", message: expect.stringContaining("overlapping PE header"), }, }); diff --git a/tests/boundary/il2cpp/il2cppMetadataProvider.test.ts b/tests/boundary/il2cpp/il2cppMetadataProvider.test.ts index 00a10c06e8..c7107b225e 100644 --- a/tests/boundary/il2cpp/il2cppMetadataProvider.test.ts +++ b/tests/boundary/il2cpp/il2cppMetadataProvider.test.ts @@ -9,7 +9,7 @@ import { AnalysisCancelledError, AnalysisCapabilityUnavailableError, AnalysisResourceConstraintError, - AnalysisUnsupportedTargetError, + AnalysisTargetFailureError, } from "../../../src/domain/analysisErrorCore.js"; import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; import { Il2cppMetadataProvider } from "../../../src/il2cpp/Il2cppMetadataProvider.js"; @@ -195,7 +195,7 @@ it.each([ const result = await inspectMetadata(path); expect(result.ok).toBe(false); if (result.ok) return; - expect(result.error).toBeInstanceOf(AnalysisUnsupportedTargetError); + expect(result.error).toBeInstanceOf(AnalysisTargetFailureError); expect(result.error.partialObservation).toMatchObject({ normalized_result: { artifact: { path, bytes: bytes.length } }, }); @@ -873,10 +873,12 @@ it.each([false, true])( expect(result).toMatchObject({ ok: false, error: { - _tag: "AnalysisUnsupportedTargetError", - reason: expect.stringContaining( - "generic method instances are not decoded for metadata version 39", - ), + _tag: "AnalysisTargetFailureError", + failure: { + detail: expect.stringContaining( + "generic method instances are not decoded for metadata version 39", + ), + }, }, }); const ordinary = await provider.inspect({ path, binary_path }, options); diff --git a/tests/boundary/mcp/analysisViewMcp.test.ts b/tests/boundary/mcp/analysisViewMcp.test.ts index e497b605d5..ac6ba6e499 100644 --- a/tests/boundary/mcp/analysisViewMcp.test.ts +++ b/tests/boundary/mcp/analysisViewMcp.test.ts @@ -315,17 +315,14 @@ it("directs unsupported parent views to the original Evidence", async () => { expect(error).toMatchObject({ code: "unsupported_target", retryable: false, + retry: "none", details: { operation: "inspect_analysis_view", - reason: expect.stringContaining( - 'Parent Evidence operation "inspect_recorded_crash"', - ), + failure_kind: "unsupported", + format: "evidence", + related_operations: ["get_evidence_bundle", "export_evidence_bundle"], }, }); - expect(error.remediation.action).toContain("original complete Evidence"); - expect(error.remediation.action).toContain("get_evidence_bundle"); - expect(error.remediation.action).toContain("export_evidence_bundle"); - expect(error.remediation.action).not.toContain("target format"); } const complete = await client.callTool({ name: "get_evidence_bundle", @@ -1827,10 +1824,14 @@ it("extracts an environment state identically from retained, portable and file M arguments: { source: { kind: "inline", evidence: hidden }, view }, }); const hiddenError = parseMcpToolError(refused).error; - expect(hiddenError.code).toBe("unsupported_target"); - expect(hiddenError.remediation.action).toContain("sensitivity declarations"); - expect(hiddenError.remediation.action).toContain("capture or summary view"); - expect(hiddenError.remediation.action).not.toContain("target format"); + expect(hiddenError).toMatchObject({ + code: "unsupported_target", + details: { + failure_kind: "unsupported", + format: "evidence", + field: "sensitive_value_count", + }, + }); expect(JSON.stringify(refused)).not.toContain("probe folder"); await client.ping(); }); @@ -2086,10 +2087,14 @@ it("projects an environment manifest identically from retained, portable and fil arguments: { source: { kind: "inline", evidence: hidden }, view }, }); const hiddenError = parseMcpToolError(refused).error; - expect(hiddenError.code).toBe("unsupported_target"); - expect(hiddenError.remediation.action).toContain("sensitivity declarations"); - expect(hiddenError.remediation.action).toContain("capture or summary view"); - expect(hiddenError.remediation.action).not.toContain("target format"); + expect(hiddenError).toMatchObject({ + code: "unsupported_target", + details: { + failure_kind: "unsupported", + format: "evidence", + field: "sensitive_value_count", + }, + }); expect(JSON.stringify(refused)).toContain("sensitive_values_unretained"); expect(JSON.stringify(refused)).not.toContain("/api/folders"); await client.ping(); diff --git a/tests/boundary/mcp/androidBootImageMcp.test.ts b/tests/boundary/mcp/androidBootImageMcp.test.ts index cbfe32ea33..e223563182 100644 --- a/tests/boundary/mcp/androidBootImageMcp.test.ts +++ b/tests/boundary/mcp/androidBootImageMcp.test.ts @@ -132,8 +132,9 @@ it("keeps Android parser refusal kinds and recovers through compiled MCP", async category: fixture.category, details: { operation: "inspect_artifact", + path, failure_kind: fixture.kind, - format: "format" in fixture ? fixture.format : "android-boot-image", + format: fixture.format, }, }); expect((await readFile(path)).equals(fixture.bytes)).toBe(true); diff --git a/tests/boundary/mcp/errorHintExclusionMcp.test.ts b/tests/boundary/mcp/errorHintExclusionMcp.test.ts index 4cb4a55c19..437da229a5 100644 --- a/tests/boundary/mcp/errorHintExclusionMcp.test.ts +++ b/tests/boundary/mcp/errorHintExclusionMcp.test.ts @@ -1,7 +1,7 @@ import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server"; import { describe, expect, it } from "vitest"; -import { AnalysisUnsupportedTargetError } from "../../../src/domain/analysisErrorCore.js"; +import { unsupportedTarget } from "../../../src/domain/analysisErrorCore.js"; import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; import { BinaryTargetError } from "../../../src/domain/configurationErrors.js"; import { createToolResultDelivery } from "../../../src/server/toolResult.js"; @@ -14,9 +14,10 @@ describe("MCP error delivery excludes CLI-only issue hints", () => { it.each([ { name: "unsupported_target", - error: new AnalysisUnsupportedTargetError( + error: unsupportedTarget( "inspect-target", "/tmp/sample.bin", + "fixture", "Container format is unsupported.", ), expectedCode: "unsupported_target", diff --git a/tests/boundary/mcp/serverLifecycleMcp.test.ts b/tests/boundary/mcp/serverLifecycleMcp.test.ts index f534c8b3a0..8d3e372709 100644 --- a/tests/boundary/mcp/serverLifecycleMcp.test.ts +++ b/tests/boundary/mcp/serverLifecycleMcp.test.ts @@ -38,7 +38,7 @@ import { z } from "zod"; import { GoBinaryService } from "../../../src/application/go/GoBinaryService.js"; import { Il2cppMetadataService } from "../../../src/application/il2cpp/Il2cppMetadataService.js"; import { WebNetworkCaptureService } from "../../../src/application/WebNetworkCaptureService.js"; -import { AnalysisUnsupportedTargetError } from "../../../src/domain/analysisErrorCore.js"; +import { unsupportedTarget } from "../../../src/domain/analysisErrorCore.js"; import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js"; import type { JavaScriptRuntimeObservationPort } from "../../../src/ports/javascript/JavaScriptRuntimeObservationPort.js"; import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; @@ -356,9 +356,10 @@ it("closes the bound Go, IL2CPP and web-capture services and retries failed shut inspect: async ({ path }) => { goCalls += 1; return err( - new AnalysisUnsupportedTargetError( + unsupportedTarget( "inspect_go_binary", path, + "fixture", "fixture rejection", ), ); diff --git a/tests/boundary/model/modelArtifact.test.ts b/tests/boundary/model/modelArtifact.test.ts index ddad5ead24..a48f3812ae 100644 --- a/tests/boundary/model/modelArtifact.test.ts +++ b/tests/boundary/model/modelArtifact.test.ts @@ -69,8 +69,10 @@ it.each([ const result = await provider.inspect({ path, hash: "header" }); if (result.ok) throw new Error("Unknown version admitted"); expect(result.error).toMatchObject({ - _tag: "AnalysisUnsupportedTargetError", - reason: `GGUF version bytes ${versionBytes} are unsupported (little-endian ${String(little)}, big-endian ${String(big)}; byte order unknown); supported versions are 2 and 3`, + _tag: "AnalysisTargetFailureError", + failure: { + detail: `GGUF version bytes ${versionBytes} are unsupported (little-endian ${String(little)}, big-endian ${String(big)}; byte order unknown); supported versions are 2 and 3`, + }, }); }, ); @@ -1462,8 +1464,8 @@ it.each([ const result = await provider.inspect({ path, hash: "header" }); if (result.ok) throw new Error("Pickle admitted"); expect(result.error).toMatchObject({ - _tag: "AnalysisUnsupportedTargetError", - reason: expect.stringContaining("PyTorch pickle"), + _tag: "AnalysisTargetFailureError", + failure: { detail: expect.stringContaining("PyTorch pickle") }, }); }, ); @@ -1489,7 +1491,7 @@ it("admits a valid model after refusing pickle and rejects unapproved path types ); expect(await provider.inspect({ path, hash: "header" })).toMatchObject({ ok: false, - error: { _tag: "AnalysisUnsupportedTargetError" }, + error: { _tag: "AnalysisTargetFailureError" }, }); await writeFile(path, ggufFixture().bytes); expect((await provider.inspect({ path, hash: "header" })).ok).toBe(true); diff --git a/tests/boundary/pcap/pcapCommand.test.ts b/tests/boundary/pcap/pcapCommand.test.ts index f89278ba6f..7ca3182fbb 100644 --- a/tests/boundary/pcap/pcapCommand.test.ts +++ b/tests/boundary/pcap/pcapCommand.test.ts @@ -20,7 +20,7 @@ import type { ProviderProcessSupervisor } from "../../../src/process/ProviderPro import { AnalysisCancelledError, AnalysisProtocolError, - AnalysisUnsupportedTargetError, + AnalysisTargetFailureError, } from "../../../src/domain/analysisErrorCore.js"; const posixIt = test.skipIf(process.platform === "win32"); @@ -459,7 +459,7 @@ posixIt( async () => { const { limiter, capinfos } = await prlimitStandIn(); const failure = await runLimited(limiter, capinfos); - expect(failure).toBeInstanceOf(AnalysisUnsupportedTargetError); + expect(failure).toBeInstanceOf(AnalysisTargetFailureError); expect(projectAnalysisError(failure as AnalysisError)).toMatchObject({ code: "unsupported_target", }); diff --git a/tests/boundary/process/providerOutcome.test.ts b/tests/boundary/process/providerOutcome.test.ts index f8bcbb76bd..949915ece6 100644 --- a/tests/boundary/process/providerOutcome.test.ts +++ b/tests/boundary/process/providerOutcome.test.ts @@ -6,7 +6,7 @@ import { AnalysisCancelledError, AnalysisResourceConstraintError, AnalysisTimeoutError, - AnalysisUnsupportedTargetError, + AnalysisTargetFailureError, } from "../../../src/domain/analysisErrorCore.js"; import { runPcapCommand } from "../../../src/pcap/PcapCommand.js"; import { runOwnedCommand } from "../../../src/process/OwnedCommand.js"; @@ -191,7 +191,7 @@ it("leaves an exit's meaning to the provider dialect", async () => { const failure = await readCapture( 'process.stderr.write("The file is not a capture file"); process.exitCode = 2', ); - expect(failure).toBeInstanceOf(AnalysisUnsupportedTargetError); + expect(failure).toBeInstanceOf(AnalysisTargetFailureError); expect(failure).toMatchObject({ capturedOutput: { stderr: expect.stringContaining("not a capture file") }, }); diff --git a/tests/boundary/providers/adb/adbCommandFinalization.test.ts b/tests/boundary/providers/adb/adbCommandFinalization.test.ts index fc59237ff6..016b64ffaa 100644 --- a/tests/boundary/providers/adb/adbCommandFinalization.test.ts +++ b/tests/boundary/providers/adb/adbCommandFinalization.test.ts @@ -85,7 +85,7 @@ test.each([ }, { script: "process.stderr.write('device unauthorized'); process.exitCode=1", - tag: "AnalysisUnsupportedTargetError", + tag: "AnalysisTargetFailureError", }, { script: "setInterval(()=>{},1000)", diff --git a/tests/boundary/providers/managed/managedStaticProvider.test.ts b/tests/boundary/providers/managed/managedStaticProvider.test.ts index f284713773..23a72ba0e1 100644 --- a/tests/boundary/providers/managed/managedStaticProvider.test.ts +++ b/tests/boundary/providers/managed/managedStaticProvider.test.ts @@ -633,10 +633,12 @@ describe("managed static provider path boundary", () => { ).resolves.toMatchObject({ ok: false, error: { - _tag: "AnalysisUnsupportedTargetError", + _tag: "AnalysisTargetFailureError", operation: "inspect_managed_artifact", path: parsed.value.path, - reason: "Managed static triage requires a PE target; observed elf.", + failure: { + detail: "Managed static triage requires a PE target; observed elf.", + }, }, }); }); diff --git a/tests/boundary/providers/native/artifactProvider.extractionAdmission.test.ts b/tests/boundary/providers/native/artifactProvider.extractionAdmission.test.ts index 4aa85ac89d..90b2b74747 100644 --- a/tests/boundary/providers/native/artifactProvider.extractionAdmission.test.ts +++ b/tests/boundary/providers/native/artifactProvider.extractionAdmission.test.ts @@ -50,7 +50,7 @@ it("refuses an unsupported source without hashing its bytes", async () => { await client.execute("extract_artifact", { output_root: output }), ).toMatchObject({ ok: false, - error: { _tag: "AnalysisUnsupportedTargetError", path: source }, + error: { _tag: "AnalysisTargetFailureError", path: source }, }); expect(hash).not.toHaveBeenCalled(); await expect(access(output)).rejects.toMatchObject({ code: "ENOENT" }); @@ -420,7 +420,7 @@ it("keeps incidental rejected cookie signatures unsupported during native extrac await client.execute("extract_artifact", { output_root: output }), ).toMatchObject({ ok: false, - error: { _tag: "AnalysisUnsupportedTargetError", path: source }, + error: { _tag: "AnalysisTargetFailureError", path: source }, }); expect(hash).not.toHaveBeenCalled(); await expect(access(output)).rejects.toMatchObject({ code: "ENOENT" }); diff --git a/tests/boundary/providers/native/artifactProvider.extractionFormat.test.ts b/tests/boundary/providers/native/artifactProvider.extractionFormat.test.ts index 7223e4338c..b5a60be017 100644 --- a/tests/boundary/providers/native/artifactProvider.extractionFormat.test.ts +++ b/tests/boundary/providers/native/artifactProvider.extractionFormat.test.ts @@ -48,11 +48,13 @@ it.each(["plist", "pe"] as const)( expect(result).toMatchObject({ ok: false, error: { - _tag: "AnalysisUnsupportedTargetError", + _tag: "AnalysisTargetFailureError", operation: "extract_artifact", - reason: expect.stringContaining( - "Artifact format has no extraction reader:", - ), + failure: { + detail: expect.stringContaining( + "Artifact format has no extraction reader:", + ), + }, }, }); await expect(access(output)).rejects.toThrow(); @@ -139,10 +141,10 @@ describe("artifact extraction format support", () => { expect(await extract()).toMatchObject({ ok: false, error: { - _tag: "AnalysisUnsupportedTargetError", + _tag: "AnalysisTargetFailureError", operation: "extract_artifact", path: alias, - reason: "Artifact format has no extraction reader: dmg", + failure: { detail: "Artifact format has no extraction reader: dmg" }, }, }); const controller = new AbortController(); @@ -169,10 +171,10 @@ describe("artifact extraction executable formats", () => { ).toMatchObject({ ok: false, error: { - _tag: "AnalysisUnsupportedTargetError", + _tag: "AnalysisTargetFailureError", operation: "extract_artifact", path: binary, - reason: "Artifact format has no extraction reader: mach-o", + failure: { detail: "Artifact format has no extraction reader: mach-o" }, }, }); await expect(access(output)).rejects.toThrow(); diff --git a/tests/boundary/providers/native/nativeMachoUuidlessInspection.test.ts b/tests/boundary/providers/native/nativeMachoUuidlessInspection.test.ts index f2cf92f02e..cc7f88681d 100644 --- a/tests/boundary/providers/native/nativeMachoUuidlessInspection.test.ts +++ b/tests/boundary/providers/native/nativeMachoUuidlessInspection.test.ts @@ -115,10 +115,13 @@ it.each([ expect(result).toMatchObject({ ok: false, error: { - _tag: "AnalysisUnsupportedTargetError", + _tag: "AnalysisTargetFailureError", path, - reason: expect.stringContaining(fileType === 10 ? "dSYM" : diagnostic), - remediationAction: expect.stringContaining("linked Mach-O"), + failure: { + detail: expect.stringContaining( + fileType === 10 ? "dSYM" : diagnostic, + ), + }, capturedOutput: { stdout: dyldDiagnosticOutput(path, diagnostic), exit_code: 1, diff --git a/tests/support/targetFailure/readers/foreignBytes.ts b/tests/support/targetFailure/readers/foreignBytes.ts new file mode 100644 index 0000000000..55e1c18176 --- /dev/null +++ b/tests/support/targetFailure/readers/foreignBytes.ts @@ -0,0 +1,48 @@ +import type { TargetFailureKind } from "../../../../src/domain/targetFailure.js"; +import { targetFailureReaders } from "../registry.js"; + +/** Bytes no format owner of these operations claims: 64 bytes of 0x7f. */ +const foreignBytes = (): Buffer => Buffer.alloc(64, 0x7f); + +const foreign = ( + operation: string, + kind: TargetFailureKind, + format: string, +) => ({ + operation, + cases: [ + { + name: "foreign-bytes", + kind, + bytes: foreignBytes, + facts: { format }, + identity: true, + }, + ], +}); + +/** + * Selected-file readers refuse bytes no owner claims before decoding any + * structure, and keep the completed file identity they hashed. The kind is + * what each owner reports today: a magic mismatch several owners still call + * `malformed` is recorded as such until they report `unrecognized`. + */ +export default targetFailureReaders([ + foreign("inspect_python_pyc", "malformed", "python-pyc"), + foreign("inspect_rust_binary", "unsupported", "native-binary"), + foreign("inspect_go_binary", "unsupported", "native-binary"), + foreign("inspect_elf_notes", "malformed", "elf"), + foreign("inspect_elf_dependencies", "malformed", "native-binary"), + foreign("inspect_elf_debug_link", "malformed", "native-binary"), + foreign("inspect_elf_unwind_ranges", "malformed", "native-binary"), + foreign("inspect_devicetree", "unsupported", "native-binary"), + foreign("inspect_pe_imports", "malformed", "native-binary"), + foreign("inspect_kernel_module", "malformed", "native-binary"), + foreign("inspect_apple_ips", "malformed", "apple-ips"), + foreign("inspect_pe_load_config", "malformed", "native-binary"), + foreign("inspect_pe_certificates", "malformed", "native-binary"), + foreign("inspect_pe_resources", "malformed", "native-binary"), + foreign("inspect_native_exports", "unsupported", "native-binary"), + foreign("inspect_native_initializers", "malformed", "native-binary"), + foreign("inspect_binary_hardening", "unsupported", "native-binary"), +]);