From 40e9a3f1a1769f3fbb24ca226aa853f42d78c42e Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:39:15 -0500 Subject: [PATCH] feat(errors)!: add the TargetFailure model, its projection table and conformance registry (#14247) --- docs/.vitepress/documentation.ts | 5 + docs/README.md | 1 + docs/android-boot-image.md | 6 +- docs/error-contract.schema.json | 350 ++++++++++++++++-- docs/guides/managed/managed-code-analysis.md | 4 +- docs/guides/native/go-binaries.md | 6 +- docs/guides/native/native-investigation.md | 2 +- docs/il2cpp-metadata.md | 4 +- docs/maven-gradle-metadata.md | 2 +- docs/reference/target-failures.md | 67 ++++ docs/user-visible-errors.csv | 19 +- knip.json | 3 +- src/domain/analysisErrorBase.ts | 2 +- src/domain/analysisErrorClassification.ts | 51 ++- src/domain/analysisErrorCore.ts | 27 +- src/domain/analysisErrorPresentation.ts | 11 +- src/domain/analysisErrorProjection.ts | 54 +-- src/domain/analysisErrorProjectionSchema.ts | 8 +- src/domain/apple/machoContainer.ts | 2 +- src/domain/apple/machoSliceSelection.ts | 4 +- src/domain/artifactOperationError.ts | 2 +- src/domain/binaryContainer.ts | 7 +- .../managed/managedReaderFailure.test.ts | 16 +- src/domain/managed/managedReaderFailure.ts | 9 +- src/domain/parseFailure.ts | 54 +-- src/domain/parseFailureAnalysisError.test.ts | 14 +- src/domain/parseFailureAnalysisError.ts | 9 +- src/domain/targetFailure.test.ts | 132 +++++++ src/domain/targetFailure.ts | 324 ++++++++++++++++ src/electron/ElectronFuseProvider.test.ts | 2 +- src/native/NativeMachoSourceProvider.test.ts | 2 +- src/native/dwarf/DwarfUnitsProvider.test.ts | 6 +- src/native/elf/ElfNotesProvider.test.ts | 2 +- .../metadata/MachoSliceSelection.test.ts | 6 +- src/native/pe/PeCertificatesProvider.test.ts | 4 +- src/native/pe/PeResourcesProvider.test.ts | 2 +- src/native/pe/PeUnwindRangesProvider.test.ts | 12 +- .../ArtifactOperationFailure.test.ts | 15 +- src/resources/ArtifactReader.ts | 2 +- src/resources/StableArtifactFailure.ts | 11 +- src/server/EvidenceMcpServerCore.ts | 17 +- tests/acceptance/androidBootImageCli.test.ts | 2 +- tests/acceptance/appleIpsCli.test.ts | 18 - .../nativeExportsDynamicSegment.test.ts | 2 +- .../applications/peResources.test.ts | 2 +- .../applications/peUnsupportedTargets.test.ts | 2 +- .../artifactReaderLimitsCli.test.ts | 6 +- tests/acceptance/bunPathBudgetCli.test.ts | 2 +- tests/acceptance/bunStandaloneCli.test.ts | 2 +- tests/acceptance/denoStandaloneCli.test.ts | 2 +- tests/acceptance/dotnetBundleJourney.test.ts | 4 +- tests/acceptance/dwarfUnitsCli.test.ts | 2 +- tests/acceptance/elfNotesCli.test.ts | 2 +- tests/acceptance/erlangBeamCli.test.ts | 4 +- tests/acceptance/fitImageCli.test.ts | 2 +- tests/acceptance/goBinaryCli.test.ts | 8 +- .../goBinaryPointerMappingsCli.test.ts | 2 +- tests/acceptance/godotPck.test.ts | 2 +- tests/acceptance/gpuCodeObjectsCli.test.ts | 2 +- tests/acceptance/il2cppMetadataCli.test.ts | 12 +- .../il2cppStructuralExtentsCli.test.ts | 2 +- .../acceptance/mavenGradleMetadataCli.test.ts | 2 +- tests/acceptance/modelArtifactCli.test.ts | 4 +- .../acceptance/nativeInitializersCli.test.ts | 2 +- tests/acceptance/nodeSeaCli.test.ts | 2 +- tests/acceptance/nugetNupkgCli.test.ts | 2 +- tests/acceptance/peCertificatesCli.test.ts | 12 +- tests/acceptance/peImportsCli.test.ts | 30 +- tests/acceptance/peLoadConfigCli.test.ts | 30 +- tests/acceptance/pyinstallerArchive.test.ts | 2 +- tests/acceptance/pythonPycCli.test.ts | 2 +- tests/acceptance/rustBinaryCli.test.ts | 4 +- .../stableArtifactParserFailureCli.test.ts | 202 +--------- .../targetFailureConformance.test.ts | 68 ++++ tests/acceptance/webSourceLocationCli.test.ts | 4 +- tests/acceptance/windowsShortcutCli.test.ts | 2 +- .../cli/artifactZstandardWindow.test.ts | 2 +- .../cli/keyedArchiveXmlNestingCli.test.ts | 4 +- .../cli/managedMemberComparisonCli.test.ts | 2 +- tests/boundary/cli/nodeSeaHashWork.test.ts | 2 +- tests/boundary/filesystem/appleIps.test.ts | 2 +- .../filesystem/asarHeaderAdmission.test.ts | 4 +- tests/boundary/filesystem/dwarfUnits.test.ts | 2 +- tests/boundary/filesystem/erlangBeam.test.ts | 2 +- .../filesystem/mavenGradleMetadata.test.ts | 6 +- .../boundary/filesystem/nativeExports.test.ts | 2 +- .../nativeExportsSectionless.test.ts | 2 +- .../filesystem/peCertificates.test.ts | 2 +- .../filesystem/windowsShortcut.test.ts | 2 +- tests/boundary/go/goBinaryProvider.test.ts | 8 +- tests/boundary/gpu/codeObjects.test.ts | 6 +- .../boundary/il2cpp/il2cppBinaryFile.test.ts | 4 +- .../il2cpp/il2cppMetadataProvider.test.ts | 8 +- .../boundary/mcp/androidBootImageMcp.test.ts | 2 +- .../mcp/asarListingAdmissionMcp.test.ts | 4 +- tests/boundary/mcp/bunStandaloneMcp.test.ts | 2 +- tests/boundary/mcp/elfNotesMcp.test.ts | 2 +- tests/boundary/mcp/erlangBeamMcp.test.ts | 4 +- tests/boundary/mcp/goBinaryMcp.test.ts | 6 +- tests/boundary/mcp/nodeSeaMcp.test.ts | 4 +- tests/boundary/mcp/pythonPycMcp.test.ts | 4 +- tests/boundary/mcp/rustBinaryMcp.test.ts | 2 +- .../mcp/targetFailureToolResult.test.ts | 58 +++ tests/boundary/mcp/universalSliceMcp.test.ts | 8 +- tests/boundary/mcp/v8CodeCacheMcp.test.ts | 2 +- tests/boundary/model/modelArtifact.test.ts | 2 +- .../native/artifactProvider.capacity.test.ts | 2 +- .../native/nativeSelectedArchitecture.test.ts | 2 +- tests/fixtures/androidBootImage.ts | 4 +- tests/support/targetFailure/contract.ts | 69 ++++ .../targetFailure/readers/peHeaders.ts | 31 ++ .../readers/selectedFileFormats.ts | 163 ++++++++ tests/support/targetFailure/registry.ts | 67 ++++ 113 files changed, 1639 insertions(+), 583 deletions(-) create mode 100644 docs/reference/target-failures.md create mode 100644 src/domain/targetFailure.test.ts create mode 100644 src/domain/targetFailure.ts create mode 100644 tests/acceptance/targetFailureConformance.test.ts create mode 100644 tests/boundary/mcp/targetFailureToolResult.test.ts create mode 100644 tests/support/targetFailure/contract.ts create mode 100644 tests/support/targetFailure/readers/peHeaders.ts create mode 100644 tests/support/targetFailure/readers/selectedFileFormats.ts create mode 100644 tests/support/targetFailure/registry.ts diff --git a/docs/.vitepress/documentation.ts b/docs/.vitepress/documentation.ts index f388c0463c..d64dad9486 100644 --- a/docs/.vitepress/documentation.ts +++ b/docs/.vitepress/documentation.ts @@ -673,6 +673,11 @@ export const documentationSections = [ source: "reference/mcp-contracts.md", route: "/mcp-contracts", }, + { + text: "Target failures", + source: "reference/target-failures.md", + route: "/target-failures", + }, { text: "Directory identity", source: "reference/directory-identity.md", diff --git a/docs/README.md b/docs/README.md index 5bab491d28..d70acf9750 100644 --- a/docs/README.md +++ b/docs/README.md @@ -175,6 +175,7 @@ The [REA website](https://rea.tools/) has worked examples and product pages. ## Contracts and evidence - [MCP runtime contracts](reference/mcp-contracts.md) +- [Target failures](reference/target-failures.md) - [Directory identity](reference/directory-identity.md) - [Reconstruction obligation ledgers](reference/reconstruction-obligation-ledgers.md) - [Reconstruction coverage](reconstruction-coverage.md) diff --git a/docs/android-boot-image.md b/docs/android-boot-image.md index 7121812efe..cdc4cf76de 100644 --- a/docs/android-boot-image.md +++ b/docs/android-boot-image.md @@ -82,9 +82,9 @@ The reader admits at most 4,096 vendor ramdisk table entries and an entry size of at most 4,096 bytes. It verifies that the table dimensions agree and the declared bytes fit in the image before applying those limits and reading the table. A vendor `header_size` above 1 MiB also exceeds a capacity limit. Unsupported -header revisions return `unsupported_target`; truncated declared structures -return `truncated`; malformed layouts return `unsupported_target`. Truncated and -malformed refusals also carry `details.format_failure`, `details.format` +header revisions, truncated declared structures and malformed layouts all +return `unsupported_target`. Truncated and malformed refusals carry +`details.failure_kind` (`truncated` or `malformed`), `details.format` (`android-boot-image`) and, when the parser names them, `details.offset` and `details.field`. The page padding after the last component carries no data and may be absent. These refusals diff --git a/docs/error-contract.schema.json b/docs/error-contract.schema.json index fb915ce379..0084246680 100644 --- a/docs/error-contract.schema.json +++ b/docs/error-contract.schema.json @@ -12,7 +12,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -22,6 +22,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -84,7 +88,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -94,6 +98,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -156,7 +164,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -166,6 +174,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -228,7 +240,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -238,6 +250,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -300,7 +316,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -310,6 +326,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -372,7 +392,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -382,6 +402,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -444,7 +468,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -454,6 +478,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -516,7 +544,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -526,6 +554,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -588,7 +620,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -598,6 +630,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -660,7 +696,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -670,6 +706,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -732,7 +772,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -742,6 +782,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -881,7 +925,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -891,6 +935,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -953,7 +1001,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -963,6 +1011,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -1017,7 +1069,7 @@ { "type": "object", "properties": { - "code": { "type": "string", "const": "truncated" }, + "code": { "type": "string", "const": "partial" }, "category": { "type": "string", "enum": [ @@ -1025,7 +1077,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -1035,6 +1087,238 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, + "remediation": { + "type": "object", + "properties": { "action": { "type": "string", "minLength": 1 } }, + "required": ["action"], + "additionalProperties": false + }, + "recovery": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { "type": "string", "const": "inspect_input_contract" }, + "operation": { "type": "string", "minLength": 1 } + }, + "required": ["kind", "operation"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "const": "inspect_timeout_state" }, + "operation": { "type": "string", "minLength": 1 }, + "timeout_ms": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": ["kind", "operation", "timeout_ms"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "const": "retry_cleanup" }, + "operation": { "type": "string", "minLength": 1 } + }, + "required": ["kind", "operation"], + "additionalProperties": false + } + ] + }, + "details": { + "type": "object", + "propertyNames": { "type": "string" }, + "additionalProperties": {} + } + }, + "required": ["code", "category", "message", "retryable", "remediation"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "code": { "type": "string", "const": "target_integrity_mismatch" }, + "category": { + "type": "string", + "enum": [ + "invalid_input", + "unsupported_provider", + "unsupported_target", + "integrity_mismatch", + "partial", + "cancelled", + "timeout", + "resource_constraint", + "unavailable", + "execution_failure" + ] + }, + "message": { "type": "string", "minLength": 1 }, + "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, + "remediation": { + "type": "object", + "properties": { "action": { "type": "string", "minLength": 1 } }, + "required": ["action"], + "additionalProperties": false + }, + "recovery": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { "type": "string", "const": "inspect_input_contract" }, + "operation": { "type": "string", "minLength": 1 } + }, + "required": ["kind", "operation"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "const": "inspect_timeout_state" }, + "operation": { "type": "string", "minLength": 1 }, + "timeout_ms": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": ["kind", "operation", "timeout_ms"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "const": "retry_cleanup" }, + "operation": { "type": "string", "minLength": 1 } + }, + "required": ["kind", "operation"], + "additionalProperties": false + } + ] + }, + "details": { + "type": "object", + "propertyNames": { "type": "string" }, + "additionalProperties": {} + } + }, + "required": ["code", "category", "message", "retryable", "remediation"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "code": { "type": "string", "const": "input_conflict" }, + "category": { + "type": "string", + "enum": [ + "invalid_input", + "unsupported_provider", + "unsupported_target", + "integrity_mismatch", + "partial", + "cancelled", + "timeout", + "resource_constraint", + "unavailable", + "execution_failure" + ] + }, + "message": { "type": "string", "minLength": 1 }, + "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, + "remediation": { + "type": "object", + "properties": { "action": { "type": "string", "minLength": 1 } }, + "required": ["action"], + "additionalProperties": false + }, + "recovery": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { "type": "string", "const": "inspect_input_contract" }, + "operation": { "type": "string", "minLength": 1 } + }, + "required": ["kind", "operation"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "const": "inspect_timeout_state" }, + "operation": { "type": "string", "minLength": 1 }, + "timeout_ms": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": ["kind", "operation", "timeout_ms"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "const": "retry_cleanup" }, + "operation": { "type": "string", "minLength": 1 } + }, + "required": ["kind", "operation"], + "additionalProperties": false + } + ] + }, + "details": { + "type": "object", + "propertyNames": { "type": "string" }, + "additionalProperties": {} + } + }, + "required": ["code", "category", "message", "retryable", "remediation"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "code": { "type": "string", "const": "host_io_failed" }, + "category": { + "type": "string", + "enum": [ + "invalid_input", + "unsupported_provider", + "unsupported_target", + "integrity_mismatch", + "partial", + "cancelled", + "timeout", + "resource_constraint", + "unavailable", + "execution_failure" + ] + }, + "message": { "type": "string", "minLength": 1 }, + "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -1097,7 +1381,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -1107,6 +1391,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -1169,7 +1457,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -1179,6 +1467,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -1241,7 +1533,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -1251,6 +1543,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -1313,7 +1609,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -1323,6 +1619,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -1385,7 +1685,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -1395,6 +1695,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, @@ -1457,7 +1761,7 @@ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -1467,6 +1771,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry": { + "type": "string", + "enum": ["none", "backoff", "after_change"] + }, "remediation": { "type": "object", "properties": { "action": { "type": "string", "minLength": 1 } }, diff --git a/docs/guides/managed/managed-code-analysis.md b/docs/guides/managed/managed-code-analysis.md index 3d881066a8..c438eaeab2 100644 --- a/docs/guides/managed/managed-code-analysis.md +++ b/docs/guides/managed/managed-code-analysis.md @@ -525,12 +525,12 @@ any completed hash retains the observed digest and byte count. Retry against a stable source. This differs from corrupted retained Evidence, which remains an Evidence-integrity failure. Malformed selected PE/CLI bytes are a target refusal, not an input error, in inspection and comparison: `unsupported_target` with -`details.format` `pe-cli`, `details.format_failure` `malformed`, and +`details.format` `pe-cli`, `details.failure_kind` `malformed`, and `details.path` naming the file whose bytes are at fault, so a comparison names the malformed side by its own path. `details.field` and `details.offset` give the reader's structure and byte offset when known. The arguments are not at fault, so no input recovery is offered. A metadata layout or signature form -outside decoder coverage is `unsupported_target` without `format_failure`. +outside decoder coverage is `unsupported_target` without `failure_kind`. Inventory status follows the same split: when a reader stops on such a form (`unsupported-metadata` or `unsupported-signature`), `metadata.status` is `partial` and an artifact's `classification.status` stays `managed`; only a diff --git a/docs/guides/native/go-binaries.md b/docs/guides/native/go-binaries.md index d745abdfb8..6fa3279366 100644 --- a/docs/guides/native/go-binaries.md +++ b/docs/guides/native/go-binaries.md @@ -198,17 +198,17 @@ than ignored. A damaged universal file is a target refusal, not a request to correct: overlapping slices, a slice range outside the file, or a selected slice whose header disagrees with its FAT entry return `unsupported_target` with -`details.format` `macho`, `details.format_failure` `malformed` (`truncated` +`details.format` `macho`, `details.failure_kind` `malformed` (`truncated` when the selected slice ends inside its Mach-O header), and `details.path` naming the universal file. A file that ends inside its FAT header or -architecture table was cut short rather than corrupted: `format_failure` is +architecture table was cut short rather than corrupted: `details.failure_kind` is `truncated`, `details.available_bytes` is the file's size and `details.required_bytes` is the length that header or table needs, so acquire the complete file again. A CAFEBABE file whose architecture count reads as a Java class-file version is not read as a truncated universal file. A FAT form outside REA's coverage, such as an alignment exponent above 52, is `unsupported_target` without -`format_failure`. The same rules apply to `inspect_rust_binary`, +`failure_kind`. The same rules apply to `inspect_rust_binary`, `inspect_dwarf_units` and `inspect_native_initializers`. For ELF images without a named build-info section, discovery checks each diff --git a/docs/guides/native/native-investigation.md b/docs/guides/native/native-investigation.md index 029680f81c..8498f90ad4 100644 --- a/docs/guides/native/native-investigation.md +++ b/docs/guides/native/native-investigation.md @@ -967,7 +967,7 @@ complete observation. malformed/unresolved/nil references. Missing fields stay absent; unknown classes are preserved. Select `root`, `offset` and `limit` explicitly. Named parser limits report the exhausted bound and its maximum in - `details.reported_limits` on a `truncated` error. + `details.reported_limits` on a `partial` error. Binary references retain their serialized type-8 UID identity; ordinary dictionaries with `UID` or `CF$UID` keys remain authored data. XML uses Foundation's single numeric `CF$UID` dictionary convention for references; diff --git a/docs/il2cpp-metadata.md b/docs/il2cpp-metadata.md index eccc1415a9..1210ee1914 100644 --- a/docs/il2cpp-metadata.md +++ b/docs/il2cpp-metadata.md @@ -482,7 +482,7 @@ Each category says which selected file is at fault: - **unsupported**: an `unsupported_target` refusal whose `details.path` is `binary_path`. The binary's form is outside coverage. -- **malformed**: an `unsupported_target` refusal with `details.format_failure` +- **malformed**: an `unsupported_target` refusal with `details.failure_kind` `malformed` or `truncated`, whose `details.path` is `binary_path`. The binary's own bytes are damaged. A damaged universal Mach-O container, including a slice that ends inside its header or disagrees with its FAT @@ -561,7 +561,7 @@ A version other than 24, 27, 29, 31 or 39 fails as an unsupported target with Damaged metadata is refused as a malformed target: an `unsupported_target` refusal whose `details.path` is the metadata file, `details.format` is -`il2cpp-metadata`, `details.format_failure` is `truncated` for +`il2cpp-metadata`, `details.failure_kind` is `truncated` for `truncated-header` and `malformed` otherwise, and `details.reason` names one reason. The request is not at fault, so no input recovery is offered: diff --git a/docs/maven-gradle-metadata.md b/docs/maven-gradle-metadata.md index df67aafd4c..94027538c2 100644 --- a/docs/maven-gradle-metadata.md +++ b/docs/maven-gradle-metadata.md @@ -96,7 +96,7 @@ unknowns, not guesses. The selected file is limited to 1 MiB by default (16 MiB maximum). Exceeding the budget fails without partial success. Malformed XML or JSON is also -`unsupported_target`, with `details.format_failure` set to `malformed`. A +`unsupported_target`, with `details.failure_kind` set to `malformed`. A well-formed document that is not a Maven project or Gradle module metadata file is `unsupported_target` without that field. Document type declarations are unsupported. External entities are not resolved. diff --git a/docs/reference/target-failures.md b/docs/reference/target-failures.md new file mode 100644 index 0000000000..5b839ebba4 --- /dev/null +++ b/docs/reference/target-failures.md @@ -0,0 +1,67 @@ +# Target failures + +When REA cannot read a target, `details.failure_kind` identifies why. It is the primary machine identifier, in the sense of an RFC 9457 problem type. `code` is a coarse class derived from it, and `retry` says whether repeating the request can help. Clients should branch on `failure_kind` and must not parse `message`, `remediation.action` or `details.reason`. + +## Kinds + +| `failure_kind` | Meaning | `code` | `category` | `retry` | What to do | +| -------------- | -------------------------------------------------------------------------------- | --------------------------- | -------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------- | +| `selection` | The request names something that is not a valid target for this operation. | `invalid_request` | `invalid_input` | `after_change` | Fix the request. | +| `unrecognized` | No reader for this operation recognizes the bytes. | `unsupported_target` | `unsupported_target` | `none` | Choose another operation or provider. | +| `unsupported` | A recognized format, but in a version or variant this reader does not implement. | `unsupported_target` | `unsupported_target` | `none` | Choose another operation or provider. | +| `malformed` | The bytes break the format's own rules. | `unsupported_target` | `unsupported_target` | `none` | Choose another target, or a well-formed copy. | +| `truncated` | The bytes end before a structure they declare. | `unsupported_target` | `unsupported_target` | `none` | Re-acquire the complete file. | +| `integrity` | The bytes contradict a digest or checksum they declare. | `target_integrity_mismatch` | `integrity_mismatch` | `none` | Get a fresh copy, or keep the observed bytes with `integrity_policy=record-and-continue` where it is offered. | +| `conflict` | Two or more inputs each parse, but disagree. None is blamed. | `input_conflict` | `invalid_input` | `after_change` | Select inputs that belong together. | +| `changed` | The file changed while it was read. | `artifact_changed` | `integrity_mismatch` | `backoff` | Retry once it is stable. | +| `access` | Host permissions denied the read. | `access_denied` | `unavailable` | `after_change` | Grant read access. | +| `io` | The host could not read the file. | `host_io_failed` | `execution_failure` | `backoff` (transient errno) or `none` | Retry with backoff for a transient error. Otherwise check the device and file. | + +The four target refusals share `unsupported_target` because the caller cannot use the target as it stands, and each needs a different target or tool. `failure_kind` says which. No other code covers more than one kind. + +The list of kinds can grow. Handle the kinds you know, and treat any other kind by its `code`. + +A caller's cancellation (`cancelled`) and an admission limit (`resource_constraint`) describe the operation, not the target, so they keep their own error shapes. A result cut short by a delivery or decode limit reports code `partial`. `truncated` names only a target whose bytes end early. + +## Retry + +| `retry` | Meaning | +| -------------- | ----------------------------------------------------------------- | +| `none` | Repeating the request cannot help. The target itself must change. | +| `backoff` | The unchanged request may succeed later. Retry with backoff. | +| `after_change` | Only a changed request, input or host permission can succeed. | + +`retryable` keeps the meaning it has across all REA errors: the unchanged request may succeed. For a target failure, it is `true` exactly when `retry` is `backoff`. + +## Details + +Every target failure reports: + +- `operation`: the operation that refused the target. +- `path`: the exact file at fault. For a composite request, this is the input whose bytes failed. For a conflict, it is the primary input, and `inputs` lists all of them. +- `failure_kind`: the kind. +- `format`: the format whose owner established the failure, such as `elf`, `macho` or `pe-cli`. +- `reason`: the owner's description, for people. +- `offset` and `field`: where the failure is, when the owner knows. +- `partial_observation`: the file's size and SHA-256, when the operation hashed the file before it refused it. + +Some kinds add facts: + +- `truncated` reports `available_bytes` and `required_bytes` when the owner measured them. +- `conflict` reports `inputs`, a list of `{ field, path }` entries, one for each input that disagrees. The CLI spells each `field` the way the command spells its option. + +## MCP delivery + +A target failure is always a `tools/call` result with `isError: true`, and its projection is the JSON text block. It is never a JSON-RPC error. A provider that throws a target failure inside a tool handler still produces this result. + +## Migration + +This model replaces `details.format_failure` with `failure_kind`. It also changes these codes: + +- the `truncated` code to `partial`; +- `artifact_operation_failed` to `target_integrity_mismatch` or `host_io_failed`; +- `invalid_request` to `input_conflict`, for a pair of inputs that disagree. + +The remaining operations move to this vocabulary area by area, and each release note lists the operations whose `code` changes. The plan is tracked in [#14239](https://github.com/morluto/rea/issues/14239). + +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 c6c3f73c3a..2f91c5802d 100644 --- a/docs/user-visible-errors.csv +++ b/docs/user-visible-errors.csv @@ -6,7 +6,6 @@ AnalysisAccessDeniedError,,access_denied,unavailable,false AnalysisArtifactChangedError,,artifact_changed,integrity_mismatch,true AnalysisCapabilityUnavailableError,,capability_unavailable,unsupported_provider,false AnalysisUnsupportedTargetError,,unsupported_target,unsupported_target,false -AnalysisMalformedTargetError,,unsupported_target,unsupported_target,false AnalysisCancelledError,,cancelled,cancelled,true AnalysisTimeoutError,,provider_timeout,timeout,true AnalysisResourceConstraintError,,resource_constraint,resource_constraint,false @@ -15,13 +14,23 @@ NoBinaryOpenError,,target_unavailable,unavailable,false EvidenceIntegrityError,,evidence_integrity_mismatch,integrity_mismatch,false ProviderAdapterError,,execution_failure,execution_failure,false AnalysisCapabilityUnavailableError,retryable=true,capability_unavailable,unavailable,true +AnalysisTargetFailureError,kind=selection,invalid_request,invalid_input,false +AnalysisTargetFailureError,kind=unrecognized,unsupported_target,unsupported_target,false +AnalysisTargetFailureError,kind=unsupported,unsupported_target,unsupported_target,false +AnalysisTargetFailureError,kind=malformed,unsupported_target,unsupported_target,false +AnalysisTargetFailureError,kind=truncated,unsupported_target,unsupported_target,false +AnalysisTargetFailureError,kind=integrity,target_integrity_mismatch,integrity_mismatch,false +AnalysisTargetFailureError,kind=conflict,input_conflict,invalid_input,false +AnalysisTargetFailureError,kind=changed,artifact_changed,integrity_mismatch,true +AnalysisTargetFailureError,kind=access,access_denied,unavailable,false +AnalysisTargetFailureError,kind=io,host_io_failed,execution_failure,false ArtifactOperationError,reason=cancelled,cancelled,cancelled,true ArtifactOperationError,reason=malformed,unsupported_target,unsupported_target,false -ArtifactOperationError,reason=truncated,truncated,truncated,false +ArtifactOperationError,reason=truncated,unsupported_target,unsupported_target,false ArtifactOperationError,reason=unsupported,unsupported_target,unsupported_target,false ArtifactOperationError,reason=format,artifact_operation_failed,execution_failure,false ArtifactOperationError,reason=integrity,artifact_operation_failed,integrity_mismatch,false -ArtifactOperationError,reason=limit,truncated,truncated,false +ArtifactOperationError,reason=limit,partial,partial,false ArtifactOperationError,reason=path,artifact_operation_failed,execution_failure,false ArtifactOperationError,reason=unavailable,artifact_operation_failed,unavailable,false ArtifactOperationError,reason=io,artifact_operation_failed,execution_failure,false @@ -61,7 +70,7 @@ BrowserObservationError,reason=target_changed,target_unavailable,unavailable,fal BrowserObservationError,reason=target_session_detached,target_unavailable,unavailable,false BrowserObservationError,reason=protocol_error,unreadable_output,execution_failure,false BrowserObservationError,reason=disconnected,provider_unavailable,unavailable,true -BrowserObservationError,reason=payload_limit,truncated,truncated,false +BrowserObservationError,reason=payload_limit,partial,partial,false BrowserObservationError,reason=window_not_found,unreadable_output,execution_failure,false BrowserObservationError,reason=window_metadata_missing,unreadable_output,execution_failure,false BrowserObservationError,reason=process_ownership_unavailable,unreadable_output,execution_failure,false @@ -90,7 +99,7 @@ UnknownRegistryError,reason=already-exists,invalid_request,invalid_input,false UnknownRegistryError,reason=revision-conflict,revision_conflict,execution_failure,true UnknownRegistryError,reason=invalid-transition,execution_failure,execution_failure,false UnknownRegistryError,reason=integrity,evidence_integrity_mismatch,execution_failure,false -UnknownRegistryError,reason=limit,truncated,execution_failure,false +UnknownRegistryError,reason=limit,partial,execution_failure,false UnknownRegistryError,reason=constraint,invalid_request,invalid_input,false HopperTimeoutError,,provider_timeout,timeout,true HopperCancelledError,,cancelled,cancelled,true diff --git a/knip.json b/knip.json index 66dae4e189..74b29dd39c 100644 --- a/knip.json +++ b/knip.json @@ -18,7 +18,8 @@ "scripts/verify-real-ghidra-decompiler-failure.mjs", "scripts/verify-real-ghidra-decompile-timeout.mjs", "scripts/verify-real-ghidra-function-bundle.mjs", - "tests/processOwnershipRunner.ts" + "tests/processOwnershipRunner.ts", + "tests/support/targetFailure/readers/*.ts" ], "project": ["src/**/*.ts", "tests/**/*.ts", "scripts/**/*.mjs"], "vitepress": { diff --git a/src/domain/analysisErrorBase.ts b/src/domain/analysisErrorBase.ts index 879cfa7298..79d4dd8d14 100644 --- a/src/domain/analysisErrorBase.ts +++ b/src/domain/analysisErrorBase.ts @@ -31,7 +31,7 @@ const ANALYSIS_ERROR_TAGS = [ "AnalysisOutputError", "AnalysisCapabilityUnavailableError", "AnalysisUnsupportedTargetError", - "AnalysisMalformedTargetError", + "AnalysisTargetFailureError", "AnalysisCancelledError", "AnalysisTimeoutError", "AnalysisResourceConstraintError", diff --git a/src/domain/analysisErrorClassification.ts b/src/domain/analysisErrorClassification.ts index 957f6fe73e..76bcadb1f4 100644 --- a/src/domain/analysisErrorClassification.ts +++ b/src/domain/analysisErrorClassification.ts @@ -1,4 +1,12 @@ -import { AnalysisCapabilityUnavailableError } from "./analysisErrorCore.js"; +import { + AnalysisCapabilityUnavailableError, + AnalysisTargetFailureError, +} from "./analysisErrorCore.js"; +import { + TARGET_FAILURE_KINDS, + TARGET_FAILURE_PROJECTIONS, + type TargetFailureKind, +} from "./targetFailure.js"; import { domainErrorTag, type AnalysisError, @@ -40,6 +48,7 @@ export const RETRYABLE_CODES: ReadonlySet = new Set([ /** Domain tags whose classification depends on the error's own facts. */ type SpecializedErrorTag = + | "AnalysisTargetFailureError" | "ArtifactOperationError" | "BinaryTargetError" | "BrowserObservationError" @@ -70,10 +79,6 @@ const STATIC_ERROR_CLASSIFICATIONS = { "unsupported_target", "unsupported_target", ), - AnalysisMalformedTargetError: classified( - "unsupported_target", - "unsupported_target", - ), AnalysisCancelledError: classified("cancelled", "cancelled"), AnalysisTimeoutError: classified("provider_timeout", "timeout"), AnalysisResourceConstraintError: classified( @@ -100,15 +105,25 @@ const RETRYABLE_CAPABILITY_UNAVAILABLE = classified( "unavailable", ); +/** The code and category the projection table gives one target failure kind. */ +const kindClassification = ( + kind: TargetFailureKind, +): AnalysisErrorClassification => { + const { code, category } = TARGET_FAILURE_PROJECTIONS[kind]; + return { code, category }; +}; + const ARTIFACT_OPERATION_CLASSIFICATIONS = { cancelled: classified("cancelled", "cancelled"), - // The artifact's bytes are at fault, not the request: a target refusal. - malformed: classified("unsupported_target", "unsupported_target"), - truncated: classified("truncated", "truncated"), - unsupported: classified("unsupported_target", "unsupported_target"), + // Reasons that name a target failure kind take that kind's projection, so + // an inventory refusal and a selected-file refusal of the same bytes report + // the same code. `limit` reports `partial`: the result was cut short. + malformed: kindClassification("malformed"), + truncated: kindClassification("truncated"), + unsupported: kindClassification("unsupported"), format: classified("artifact_operation_failed", "execution_failure"), integrity: classified("artifact_operation_failed", "integrity_mismatch"), - limit: classified("truncated", "truncated"), + limit: classified("partial", "partial"), path: classified("artifact_operation_failed", "execution_failure"), unavailable: classified("artifact_operation_failed", "unavailable"), io: classified("artifact_operation_failed", "execution_failure"), @@ -146,7 +161,7 @@ const UNKNOWN_REGISTRY_CLASSIFICATIONS = { "revision-conflict": classified("revision_conflict", "execution_failure"), "invalid-transition": classified("execution_failure", "execution_failure"), integrity: classified("evidence_integrity_mismatch", "execution_failure"), - limit: classified("truncated", "execution_failure"), + limit: classified("partial", "execution_failure"), constraint: classified("invalid_request", "invalid_input"), } as const satisfies Readonly< Record @@ -227,7 +242,7 @@ const BROWSER_OBSERVATION_CLASSIFICATIONS = { target_session_detached: classified("target_unavailable", "unavailable"), protocol_error: classified("unreadable_output", "execution_failure"), disconnected: classified("provider_unavailable", "unavailable"), - payload_limit: classified("truncated", "truncated"), + payload_limit: classified("partial", "partial"), window_not_found: classified("unreadable_output", "execution_failure"), window_metadata_missing: classified("unreadable_output", "execution_failure"), process_ownership_unavailable: classified( @@ -257,6 +272,7 @@ const staticClassification = ( if (tag === undefined) throw new TypeError(`Unpresented provider error: ${error._tag}`); switch (tag) { + case "AnalysisTargetFailureError": case "ArtifactOperationError": case "BinaryTargetError": case "BrowserObservationError": @@ -283,6 +299,8 @@ export const classifyAnalysisError = ( return { code: owned.code, category: owned.category }; if (error instanceof AnalysisCapabilityUnavailableError && error.retryable) return RETRYABLE_CAPABILITY_UNAVAILABLE; + if (error instanceof AnalysisTargetFailureError) + return kindClassification(error.failure.kind); if (error instanceof ProviderSelectionError) return PROVIDER_SELECTION_CLASSIFICATIONS[error.reason]; if (error instanceof BrowserObservationError) @@ -363,6 +381,15 @@ export const analysisErrorCatalogue = RETRYABLE_CAPABILITY_UNAVAILABLE, true, ), + ...TARGET_FAILURE_KINDS.map((kind) => { + const { code, category, retry } = TARGET_FAILURE_PROJECTIONS[kind]; + return catalogueRow( + "AnalysisTargetFailureError", + `kind=${kind}`, + { code, category }, + retry === "backoff", + ); + }), ...reasonRows("ArtifactOperationError", ARTIFACT_OPERATION_CLASSIFICATIONS), catalogueRow( "ArtifactOperationError", diff --git a/src/domain/analysisErrorCore.ts b/src/domain/analysisErrorCore.ts index 1a8c92a8a2..f910de8338 100644 --- a/src/domain/analysisErrorCore.ts +++ b/src/domain/analysisErrorCore.ts @@ -2,7 +2,10 @@ import type { JsonValue } from "./jsonValue.js"; import type { FixedAllowance } from "./fixedAllowanceRemediation.js"; import type { AmbiguousSelector } from "./analysisRefusal.js"; import type { ArtifactIntegrityCheck } from "./artifactOperationError.js"; -import type { ParseFailure } from "./parseFailure.js"; +import { + TARGET_FAILURE_PROJECTIONS, + type TargetFailure, +} from "./targetFailure.js"; import { AnalysisError, type AnalysisErrorOptions, @@ -30,28 +33,22 @@ export class AnalysisUnsupportedTargetError extends AnalysisError { } } -/** What a byte-format parser established about the selected target's bytes. */ -export type MalformedTargetFailure = Extract< - ParseFailure, - { readonly kind: "malformed" | "truncated" } ->; - /** - * The selected target's bytes violate, or end inside, a structure of the - * format this operation reads. The request's arguments are not at fault, so - * this is a target refusal rather than invalid input. + * 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, + * retryability and recovery; see {@link TARGET_FAILURE_PROJECTIONS}. */ -export class AnalysisMalformedTargetError extends AnalysisError { - readonly _tag = "AnalysisMalformedTargetError"; - readonly failure: MalformedTargetFailure; +export class AnalysisTargetFailureError extends AnalysisError { + readonly _tag = "AnalysisTargetFailureError"; + readonly failure: TargetFailure; constructor( readonly operation: string, readonly path: string, - failure: MalformedTargetFailure, + failure: TargetFailure, options?: AnalysisErrorOptions, ) { super( - `${failure.kind === "truncated" ? "Truncated" : "Malformed"} ${failure.format} target for ${operation} at ${path}: ${failure.detail}`, + `${TARGET_FAILURE_PROJECTIONS[failure.kind].title} ${failure.format} target for ${operation} at ${path}: ${failure.detail}`, options, ); this.failure = Object.freeze({ ...failure }); diff --git a/src/domain/analysisErrorPresentation.ts b/src/domain/analysisErrorPresentation.ts index 3fca18532e..e61a36f304 100644 --- a/src/domain/analysisErrorPresentation.ts +++ b/src/domain/analysisErrorPresentation.ts @@ -6,12 +6,13 @@ import { AnalysisArtifactChangedError, AnalysisCapabilityUnavailableError, AnalysisInputError, - AnalysisMalformedTargetError, + AnalysisTargetFailureError, AnalysisOutputError, AnalysisUnsupportedTargetError, AnalysisResourceConstraintError, AnalysisTimeoutError, } from "./analysisErrorCore.js"; +import { targetFailureRecovery } from "./targetFailure.js"; import { ArtifactOperationError } from "./artifactOperationError.js"; import { INFO_PLIST_DECODE_MIB, @@ -133,8 +134,8 @@ export const analysisErrorRemediationAction = ( error.remediationAction ?? "Select a target supported by this operation or choose an operation supporting the reported target format." ); - if (error instanceof AnalysisMalformedTargetError) - return `The selected target's ${error.failure.format} bytes are ${error.failure.kind} where ${error.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 complete, well-formed copy of it.`; + if (error instanceof AnalysisTargetFailureError) + return targetFailureRecovery(error.operation, error.failure); if (error instanceof AnalysisResourceConstraintError) { if (error.remediationAction !== undefined) return error.remediationAction; const refusal = analysisErrorRefusal(error); @@ -418,7 +419,7 @@ 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 AnalysisMalformedTargetError) return error.message; + if (error instanceof AnalysisTargetFailureError) return error.message; if (error instanceof AnalysisResourceConstraintError) return error.reason; if (error instanceof AnalysisAccessDeniedError) return "Host filesystem permissions denied read access to the selected path."; @@ -712,7 +713,7 @@ const KNOWN_ERROR_TAGS = { AnalysisOutputError: true, AnalysisCapabilityUnavailableError: true, AnalysisUnsupportedTargetError: true, - AnalysisMalformedTargetError: true, + AnalysisTargetFailureError: true, AnalysisCancelledError: true, AnalysisTimeoutError: true, AnalysisResourceConstraintError: true, diff --git a/src/domain/analysisErrorProjection.ts b/src/domain/analysisErrorProjection.ts index 071375c432..32ad4fe5cd 100644 --- a/src/domain/analysisErrorProjection.ts +++ b/src/domain/analysisErrorProjection.ts @@ -22,13 +22,17 @@ import { AnalysisCancelledError, AnalysisCapabilityUnavailableError, AnalysisUnsupportedTargetError, - AnalysisMalformedTargetError, + AnalysisTargetFailureError, AnalysisInputError, AnalysisOutputError, AnalysisTimeoutError, AnalysisResourceConstraintError, - type MalformedTargetFailure, } from "./analysisErrorCore.js"; +import { + targetFailureDetails, + targetFailureRetry, + type TargetFailureRetry, +} from "./targetFailure.js"; import { ArtifactOperationError } from "./artifactOperationError.js"; import { BinaryTargetError, @@ -560,7 +564,13 @@ const projectError = ( category: analysisErrorCategory(error), message: analysisErrorUserMessage(error, callerLifetime), retryable: - (RETRYABLE_CODES.has(code) && + // `retryable` keeps its contract meaning: the unchanged request may + // succeed. For a target failure that is exactly a `backoff` hint. + (error instanceof AnalysisTargetFailureError && + code !== "cleanup_incomplete" && + targetFailureRetry(error.failure) === "backoff") || + (!(error instanceof AnalysisTargetFailureError) && + RETRYABLE_CODES.has(code) && error.ownPresentation()?.retryable !== false) || (error instanceof AnalysisCapabilityUnavailableError && error.retryable) || @@ -579,6 +589,10 @@ const projectError = ( ? `${remediation}${retentionGuidance}${publicationRemediation}` : `${remediation}${retentionGuidance} ${cleanupRetryRemediation(cleanupRetry)}${publicationRemediation}`, }, + ...(error instanceof AnalysisTargetFailureError && + code !== "cleanup_incomplete" + ? { retry: targetFailureRetry(error.failure) } + : {}), ...(recovery === undefined ? {} : { recovery }), ...(Object.keys(details).length === 0 ? {} : { details }), }; @@ -617,25 +631,6 @@ const errorDetails = ( providerErrorDetails(error) ?? lifecycleErrorDetails(error); -/** The public facts of a format owner's malformed or truncated parse. */ -const parseFailureDetails = (failure: MalformedTargetFailure) => { - const { kind, format, offset, field } = failure; - const extent = kind === "truncated" ? failure.extent : undefined; - return { - format_failure: kind, - format, - ...(offset === undefined ? {} : { offset }), - ...(field === undefined ? {} : { field }), - // The reader's measured end of the input and the length it needed. - ...(extent === undefined - ? {} - : { - available_bytes: extent.availableBytes, - required_bytes: extent.requiredBytes, - }), - }; -}; - const requestErrorDetails = ( error: AnalysisError, ): Readonly> | undefined => { @@ -645,12 +640,12 @@ const requestErrorDetails = ( path: error.path, reason: error.reason, }; - if (error instanceof AnalysisMalformedTargetError) + if (error instanceof AnalysisTargetFailureError) return { operation: error.operation, path: error.path, reason: error.failure.detail, - ...parseFailureDetails(error.failure), + ...targetFailureDetails(error.failure), }; if (error instanceof AnalysisResourceConstraintError) return { @@ -759,7 +754,7 @@ const artifactStateErrorDetails = ( : { integrity_check: error.integrityCheck }), ...(error.parseFailure === undefined ? {} - : parseFailureDetails(error.parseFailure)), + : targetFailureDetails(error.parseFailure)), ...(error.readerLimit === undefined ? {} : { reader_limit: { ...error.readerLimit } }), @@ -999,7 +994,10 @@ export interface AnalysisErrorProjection extends Readonly< | "artifact_integrity_mismatch" | "artifact_operation_failed" | "evidence_integrity_mismatch" - | "truncated" + | "partial" + | "target_integrity_mismatch" + | "input_conflict" + | "host_io_failed" | "process_capture_failed" | "cleanup_incomplete" | "revision_conflict" @@ -1011,7 +1009,7 @@ export interface AnalysisErrorProjection extends Readonly< | "unsupported_provider" | "unsupported_target" | "integrity_mismatch" - | "truncated" + | "partial" | "cancelled" | "timeout" | "resource_constraint" @@ -1019,6 +1017,8 @@ export interface AnalysisErrorProjection extends Readonly< | "execution_failure"; readonly message: string; readonly retryable: boolean; + /** A target failure's retry hint, derived from its kind. */ + readonly retry?: TargetFailureRetry; readonly remediation: Readonly<{ action: string; }>; diff --git a/src/domain/analysisErrorProjectionSchema.ts b/src/domain/analysisErrorProjectionSchema.ts index 1fa056d118..3863869587 100644 --- a/src/domain/analysisErrorProjectionSchema.ts +++ b/src/domain/analysisErrorProjectionSchema.ts @@ -9,7 +9,7 @@ const categorySchema = z.enum([ "unsupported_provider", "unsupported_target", "integrity_mismatch", - "truncated", + "partial", "cancelled", "timeout", "resource_constraint", @@ -25,6 +25,7 @@ const common = { category: categorySchema, message: z.string().min(1), retryable: z.boolean(), + retry: z.enum(["none", "backoff", "after_change"]).optional(), remediation: remediationSchema, recovery: analysisErrorRecoverySchema.optional(), }; @@ -99,7 +100,10 @@ export const analysisErrorProjectionSchema = z.discriminatedUnion("code", [ .strict(), generic("artifact_operation_failed"), evidenceIntegrityErrorProjectionSchema, - generic("truncated"), + generic("partial"), + generic("target_integrity_mismatch"), + generic("input_conflict"), + generic("host_io_failed"), generic("process_capture_failed"), generic("cleanup_incomplete"), generic("revision_conflict"), diff --git a/src/domain/apple/machoContainer.ts b/src/domain/apple/machoContainer.ts index 772c3ee61d..a095a10ea8 100644 --- a/src/domain/apple/machoContainer.ts +++ b/src/domain/apple/machoContainer.ts @@ -1,5 +1,5 @@ import { BinaryReader } from "../binaryContainer.js"; -import type { TruncatedExtent } from "../parseFailure.js"; +import type { TruncatedExtent } from "../targetFailure.js"; import { hasJvmClassHeader, isJvmClassFile, diff --git a/src/domain/apple/machoSliceSelection.ts b/src/domain/apple/machoSliceSelection.ts index 2fcaf454c6..52a134975c 100644 --- a/src/domain/apple/machoSliceSelection.ts +++ b/src/domain/apple/machoSliceSelection.ts @@ -18,7 +18,7 @@ import { } from "./machoTargetSelection.js"; import { AnalysisInputError, - AnalysisMalformedTargetError, + AnalysisTargetFailureError, AnalysisUnsupportedTargetError, } from "../analysisErrorCore.js"; import type { AnalysisError } from "../analysisErrorBase.js"; @@ -143,7 +143,7 @@ const selectionError = ( ? new AnalysisUnsupportedTargetError(operation, path, parsed.detail, { cause, }) - : new AnalysisMalformedTargetError(operation, path, parsed, { cause }); + : new AnalysisTargetFailureError(operation, path, parsed, { cause }); }; interface FatSlice { diff --git a/src/domain/artifactOperationError.ts b/src/domain/artifactOperationError.ts index 76bca3cd7f..582221e4bb 100644 --- a/src/domain/artifactOperationError.ts +++ b/src/domain/artifactOperationError.ts @@ -9,7 +9,7 @@ import { import type { ArtifactReaderLimitFact } from "./artifactReaderLimits.js"; import type { FixedAllowance } from "./fixedAllowanceRemediation.js"; import type { LimitRef, ParseFailureKind } from "./parseFailure.js"; -import type { MalformedTargetFailure } from "./analysisErrorCore.js"; +import type { MalformedTargetFailure } from "./targetFailure.js"; /** The resource class that refused an artifact operation. */ export type ArtifactLimitBoundary = "file-size" | "capacity" | "memory"; diff --git a/src/domain/binaryContainer.ts b/src/domain/binaryContainer.ts index 43887bd947..a64b581c3e 100644 --- a/src/domain/binaryContainer.ts +++ b/src/domain/binaryContainer.ts @@ -6,11 +6,8 @@ import { type ZeroFillMapping, } from "./virtualFileMapping.js"; import type { PeDataDirectory } from "./peOptionalHeader.js"; -import { - decodeLimit, - ParseFailureError, - type TruncatedExtent, -} from "./parseFailure.js"; +import { decodeLimit, ParseFailureError } from "./parseFailure.js"; +import type { TruncatedExtent } from "./targetFailure.js"; /** Return whether the leading bytes begin with the 4-byte ELF magic (`\x7fELF`). */ export const hasElfMagic = (bytes: Uint8Array): boolean => diff --git a/src/domain/managed/managedReaderFailure.test.ts b/src/domain/managed/managedReaderFailure.test.ts index 967611a625..ba5ded54d6 100644 --- a/src/domain/managed/managedReaderFailure.test.ts +++ b/src/domain/managed/managedReaderFailure.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { - AnalysisMalformedTargetError, + AnalysisTargetFailureError, AnalysisUnsupportedTargetError, } from "../analysisErrorCore.js"; import { projectAnalysisError } from "../analysisErrorProjection.js"; @@ -28,14 +28,14 @@ describe("managedInspectionTargetFailure", () => { 0x2000, ), ); - expect(failure).toBeInstanceOf(AnalysisMalformedTargetError); + expect(failure).toBeInstanceOf(AnalysisTargetFailureError); expect(projectAnalysisError(failure!)).toMatchObject({ code: "unsupported_target", retryable: false, details: { operation: OPERATION, path: PATH, - format_failure: "malformed", + failure_kind: "malformed", format: "pe-cli", field: "pe.section-data", offset: 0x2000, @@ -51,10 +51,10 @@ describe("managedInspectionTargetFailure", () => { PATH, managedFailure("invalid-tables", "metadata.tables", "bad table"), ); - expect(failure).toBeInstanceOf(AnalysisMalformedTargetError); - expect( - (failure as AnalysisMalformedTargetError).failure, - ).not.toHaveProperty("offset"); + expect(failure).toBeInstanceOf(AnalysisTargetFailureError); + expect((failure as AnalysisTargetFailureError).failure).not.toHaveProperty( + "offset", + ); }); it.each(["unsupported-metadata", "unsupported-signature"] as const)( @@ -88,7 +88,7 @@ describe("managedInspectionTargetFailure", () => { managedFailure(code, "metadata.tables", "detail"), ); // Only a broken rule is malformed in both the inventory and a refusal. - expect(refusal instanceof AnalysisMalformedTargetError).toBe( + expect(refusal instanceof AnalysisTargetFailureError).toBe( status === "malformed", ); }, diff --git a/src/domain/managed/managedReaderFailure.ts b/src/domain/managed/managedReaderFailure.ts index 644c4f236c..4237d7ead0 100644 --- a/src/domain/managed/managedReaderFailure.ts +++ b/src/domain/managed/managedReaderFailure.ts @@ -1,5 +1,5 @@ import { - AnalysisMalformedTargetError, + AnalysisTargetFailureError, AnalysisUnsupportedTargetError, } from "../analysisErrorCore.js"; import type { ManagedParseIssue } from "./managedArtifact.js"; @@ -64,10 +64,7 @@ export const managedInspectionTargetFailure = ( operation: string, path: string, cause: unknown, -): - | AnalysisMalformedTargetError - | AnalysisUnsupportedTargetError - | undefined => { +): AnalysisTargetFailureError | AnalysisUnsupportedTargetError | undefined => { if (!(cause instanceof ManagedReaderFailure)) return undefined; const { code, scope, offset, detail } = cause.issue; if (code === "resource-limit") return undefined; @@ -75,7 +72,7 @@ export const managedInspectionTargetFailure = ( return new AnalysisUnsupportedTargetError(operation, path, detail, { cause, }); - return new AnalysisMalformedTargetError( + return new AnalysisTargetFailureError( operation, path, { diff --git a/src/domain/parseFailure.ts b/src/domain/parseFailure.ts index 3b47bf39e0..cb14be3c94 100644 --- a/src/domain/parseFailure.ts +++ b/src/domain/parseFailure.ts @@ -1,7 +1,13 @@ +import type { + TargetFailureFacts, + TargetFailureOf, + TruncatedExtent, +} from "./targetFailure.js"; + /** - * How a byte-format parser failed. One algebra for every format, so the - * public category depends on what the parser established, not on which error - * class it happened to throw. + * How a byte-format parser failed. The byte-structure outcomes are the + * {@link TargetFailureOf} variants themselves, so a parser's fact is the + * target failure every projection reads; only `limit` is parser-specific. * * - `malformed`: the bytes violate the format's structure. * - `truncated`: a declared structure starts in the bytes but ends past them. @@ -15,16 +21,6 @@ export type ParseFailureKind = | "unsupported" | "limit"; -interface ParseFailureFacts { - /** The format being decoded, such as `elf` or `windows-shortcut`. */ - readonly format: string; - readonly detail: string; - /** Byte offset of the structure that failed, when the parser knows it. */ - readonly offset?: number; - /** The structure or field that failed, when the parser names it. */ - readonly field?: string; -} - /** * The limit a parse stopped at: its stable name, the maximum in force, and, * when the parser measured it, the smallest value that would admit the input. @@ -45,31 +41,13 @@ export const reportedParseLimit = ({ name, maximum, required }: LimitRef) => ({ : { required: typeof required === "bigint" ? String(required) : required }), }); -/** - * How far the input reached when a declared structure ran past it: the - * measured end of the input and the length the structure needs. Only a - * reader that measured the input's end reports it. - */ -export interface TruncatedExtent { - readonly availableBytes: number; - readonly requiredBytes: number; -} - /** A parse outcome the parser established, carried with its facts. */ -export type ParseFailure = ParseFailureFacts & - ( - | { readonly kind: "malformed" } - | { readonly kind: "truncated"; readonly extent?: TruncatedExtent } - | { - readonly kind: "unsupported"; - /** The input holds the content, in a form this decoder cannot read. */ - readonly undecodedContent: boolean; - } - | { - readonly kind: "limit"; - readonly limit: LimitRef; - } - ); +export type ParseFailure = + | TargetFailureOf<"malformed" | "truncated" | "unsupported"> + | (TargetFailureFacts & { + readonly kind: "limit"; + readonly limit: LimitRef; + }); /** The one throwable carrier for a {@link ParseFailure}. */ export class ParseFailureError< @@ -91,7 +69,7 @@ export class ParseFailureError< } /** Where the failure was found, and the failure that revealed it. */ -type ParseFailureSite = Pick & { +type ParseFailureSite = Pick & { readonly cause?: unknown; }; diff --git a/src/domain/parseFailureAnalysisError.test.ts b/src/domain/parseFailureAnalysisError.test.ts index 05c92453dc..8a94e0d249 100644 --- a/src/domain/parseFailureAnalysisError.test.ts +++ b/src/domain/parseFailureAnalysisError.test.ts @@ -1,7 +1,7 @@ import { expect, it } from "vitest"; import { - AnalysisMalformedTargetError, + AnalysisTargetFailureError, AnalysisResourceConstraintError, AnalysisUnsupportedTargetError, } from "./analysisErrorCore.js"; @@ -36,16 +36,14 @@ it.each([ "refuses $failure.kind bytes as a malformed target, not invalid input", (cause) => { const error = project(cause); - expect(error).toBeInstanceOf(AnalysisMalformedTargetError); + expect(error).toBeInstanceOf(AnalysisTargetFailureError); expect(error).toMatchObject({ cause, operation: "inspect_example", path: "/tmp/sample.bin", failure: cause.failure, }); - const projected = projectAnalysisError( - error as AnalysisMalformedTargetError, - ); + const projected = projectAnalysisError(error as AnalysisTargetFailureError); expect(projected).toMatchObject({ code: "unsupported_target", category: "unsupported_target", @@ -58,7 +56,7 @@ it.each([ operation: "inspect_example", path: "/tmp/sample.bin", reason: cause.message, - format_failure: cause.failure.kind, + failure_kind: cause.failure.kind, format: "elf", }, }); @@ -81,10 +79,10 @@ it("keeps the parser's structure and offset on a malformed target", () => { field: "tensor data", }); const error = project(cause); - if (!(error instanceof AnalysisMalformedTargetError)) + if (!(error instanceof AnalysisTargetFailureError)) throw new Error("Expected a malformed target"); expect(projectAnalysisError(error).details).toMatchObject({ - format_failure: "truncated", + failure_kind: "truncated", format: "gguf", offset: 64, field: "tensor data", diff --git a/src/domain/parseFailureAnalysisError.ts b/src/domain/parseFailureAnalysisError.ts index 00ad01cd89..9a93a5d3de 100644 --- a/src/domain/parseFailureAnalysisError.ts +++ b/src/domain/parseFailureAnalysisError.ts @@ -1,6 +1,6 @@ import { type ANALYSIS_RESOURCE_KINDS, - AnalysisMalformedTargetError, + AnalysisTargetFailureError, AnalysisResourceConstraintError, AnalysisUnsupportedTargetError, type ResourceConstraintRecovery, @@ -67,10 +67,7 @@ export const parseFailureAnalysisError = ( operation: string, path: string, cause: unknown, -): - | AnalysisMalformedTargetError - | AnalysisUnsupportedTargetError - | undefined => { +): AnalysisTargetFailureError | AnalysisUnsupportedTargetError | undefined => { if (!(cause instanceof ParseFailureError)) return undefined; const { failure } = cause; switch (failure.kind) { @@ -85,7 +82,7 @@ export const parseFailureAnalysisError = ( ); case "malformed": case "truncated": - return new AnalysisMalformedTargetError(operation, path, failure, { + return new AnalysisTargetFailureError(operation, path, failure, { cause, }); } diff --git a/src/domain/targetFailure.test.ts b/src/domain/targetFailure.test.ts new file mode 100644 index 0000000000..e6d6540331 --- /dev/null +++ b/src/domain/targetFailure.test.ts @@ -0,0 +1,132 @@ +import { describe, expect, it } from "vitest"; + +import { AnalysisTargetFailureError } from "./analysisErrorCore.js"; +import { projectAnalysisError } from "./analysisErrorProjection.js"; +import { analysisErrorProjectionSchema } from "./analysisErrorProjectionSchema.js"; +import { + TARGET_FAILURE_KINDS, + targetFailureDetails, + targetFailureRecovery, + type TargetFailure, + type TargetFailureKind, +} from "./targetFailure.js"; +import { TARGET_FAILURE_CONTRACT } from "../../tests/support/targetFailure/contract.js"; + +const failureOf = (kind: TargetFailureKind): TargetFailure => { + const facts = { format: "elf", detail: `${kind} detail`, offset: 4 }; + switch (kind) { + case "unsupported": + return { ...facts, kind, undecodedContent: false }; + case "truncated": + return { + ...facts, + kind, + extent: { availableBytes: 4, requiredBytes: 64 }, + }; + case "conflict": + return { + ...facts, + kind, + inputs: [ + { field: "path", path: "/tmp/a" }, + { field: "binary_path", path: "/tmp/b" }, + ], + }; + case "io": + return { ...facts, kind, transient: false }; + default: + return { ...facts, kind }; + } +}; + +const project = (failure: TargetFailure) => + projectAnalysisError( + new AnalysisTargetFailureError("inspect_elf_notes", "/tmp/t", failure), + ); + +describe("target failure projection", () => { + it.each(TARGET_FAILURE_KINDS)( + "derives the public contract of %s from its kind", + (kind) => { + const { code, category, retry } = TARGET_FAILURE_CONTRACT[kind]; + const failure = failureOf(kind); + const projected = project(failure); + expect(projected).toMatchObject({ + code, + category, + retry, + // `retryable` keeps its contract meaning: the unchanged request may succeed. + retryable: retry === "backoff", + remediation: { + action: targetFailureRecovery("inspect_elf_notes", failure), + }, + details: { + operation: "inspect_elf_notes", + path: "/tmp/t", + reason: failure.detail, + failure_kind: kind, + format: "elf", + offset: 4, + }, + }); + expect(projected).not.toHaveProperty("recovery"); + expect(projected).not.toHaveProperty("details.format_failure"); + // Every kind's projection satisfies the schema CLI and MCP advertise. + expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe( + true, + ); + }, + ); + + it("gives no two kinds with unrelated caller actions one code", () => { + const actions = new Map>(); + for (const kind of TARGET_FAILURE_KINDS) { + const { code } = TARGET_FAILURE_CONTRACT[kind]; + actions.set(code, (actions.get(code) ?? new Set()).add(kind)); + } + // Only the four target refusals share a code; `failure_kind` says which. + expect( + [...actions.values()] + .filter((kinds) => kinds.size > 1) + .map((k) => [...k]), + ).toEqual([["unrecognized", "unsupported", "malformed", "truncated"]]); + }); + + it("refines an io failure's retry hint from its errno fact", () => { + expect(project(failureOf("io"))).toMatchObject({ + retry: "none", + retryable: false, + }); + expect( + project({ ...failureOf("io"), kind: "io", transient: true }), + ).toMatchObject({ retry: "backoff", retryable: true }); + }); + + it("reports measured extents for a truncated structure", () => { + expect(targetFailureDetails(failureOf("truncated"))).toEqual({ + failure_kind: "truncated", + format: "elf", + offset: 4, + available_bytes: 4, + required_bytes: 64, + }); + }); + + it("lists every input of a conflict and blames none", () => { + expect(targetFailureDetails(failureOf("conflict"))).toMatchObject({ + failure_kind: "conflict", + inputs: [ + { field: "path", path: "/tmp/a" }, + { field: "binary_path", path: "/tmp/b" }, + ], + }); + }); + + it("gives each caller action its own recovery", () => { + const malformed = targetFailureRecovery("op", failureOf("malformed")); + const truncated = targetFailureRecovery("op", failureOf("truncated")); + expect(malformed).toContain("request arguments are not at fault"); + expect(truncated).toContain("Re-acquire the complete file"); + expect(truncated).not.toBe(malformed); + }); +}); diff --git a/src/domain/targetFailure.ts b/src/domain/targetFailure.ts new file mode 100644 index 0000000000..aeb02b6ee7 --- /dev/null +++ b/src/domain/targetFailure.ts @@ -0,0 +1,324 @@ +/** + * Why a target could not be read: one owned fact, raised once by the format + * or filesystem owner that established it. Wrappers carry it unchanged. + * + * `failure_kind` is the primary machine identifier (RFC 9457's problem type). + * The coarse `code`, its `category`, the `retry` hint, the recovery and the + * `details` are all derived from the kind by {@link TARGET_FAILURE_PROJECTIONS} + * and {@link targetFailureDetails}. See `docs/reference/target-failures.md`. + * + * The model describes the target. A caller's cancellation and an admission + * limit describe the operation, so they keep their own error types + * (`AnalysisCancelledError`, `AnalysisResourceConstraintError`). + * + * Identifiers are lower-case ASCII in American spelling. + * + * Areas migrate onto this model one at a time (#14239). The declarative + * conformance registry under `tests/support/targetFailure/` lists every + * migrated reader with a fixture per kind. When the last area has migrated, + * a guard script rejects any other reason vocabulary. + */ + +/** Every kind, in the order the error reference lists them. */ +export const TARGET_FAILURE_KINDS = [ + "selection", + "unrecognized", + "unsupported", + "malformed", + "truncated", + "integrity", + "conflict", + "changed", + "access", + "io", +] as const; +export type TargetFailureKind = (typeof TARGET_FAILURE_KINDS)[number]; + +/** Facts every kind may carry. `detail` is for people; never parse it. */ +export interface TargetFailureFacts { + /** The format whose owner established the failure, such as `elf`. */ + readonly format: string; + readonly detail: string; + /** Byte offset of the structure that failed, when the owner knows it. */ + readonly offset?: number; + /** The structure or field that failed, when the owner names it. */ + readonly field?: string; +} + +/** + * Where a truncated structure stopped: the bytes the input holds from the + * structure's start, and the bytes the structure declares. Only a reader that + * measured the input's end reports it. + */ +export interface TruncatedExtent { + readonly availableBytes: number; + readonly requiredBytes: number; +} + +/** One input of a composite request, named by the request field that chose it. */ +export interface TargetFailureInput { + readonly field: string; + readonly path: string; +} + +/** One target failure. A variant adds only the facts its caller action needs. */ +export type TargetFailure = TargetFailureFacts & + ( + | { readonly kind: "selection" } + | { readonly kind: "unrecognized" } + | { + readonly kind: "unsupported"; + /** The input holds the content, in a form this decoder cannot read. */ + readonly undecodedContent: boolean; + } + | { readonly kind: "malformed" } + | { + readonly kind: "truncated"; + /** The measured end and the length needed, when the owner measured them. */ + readonly extent?: TruncatedExtent; + } + | { readonly kind: "integrity" } + | { + readonly kind: "conflict"; + /** Two or more inputs that each parse but disagree. None is blamed. */ + readonly inputs: readonly TargetFailureInput[]; + } + | { readonly kind: "changed" } + | { readonly kind: "access" } + | { + readonly kind: "io"; + /** + * The host reported a transient condition (EAGAIN, EINTR, a timeout) + * rather than a persistent device error. Set from the owner's errno. + */ + readonly transient: boolean; + } + ); + +/** The variant of one kind. */ +export type TargetFailureOf = Extract< + TargetFailure, + { readonly kind: Kind } +>; + +/** Bytes that break, or end inside, a structure of the format being read. */ +export type MalformedTargetFailure = TargetFailureOf<"malformed" | "truncated">; + +/** + * When repeating the request can help, after gRPC's status semantics: + * `none` (never, the target itself must change), `backoff` (the unchanged + * request may succeed later), `after_change` (only once the caller changes + * the request or a control). + */ +export type TargetFailureRetry = "none" | "backoff" | "after_change"; + +/** What a caller should do next. Each adapter renders it in its own words. */ +export type TargetFailureRecovery = + | "fix_request" + | "choose_another_tool" + | "choose_another_target" + | "reacquire_complete_file" + | "replace_or_record_integrity" + | "check_input_pairing" + | "retry_on_stable_copy" + | "fix_permissions" + | "check_host"; + +/** The public projection of one kind. */ +export interface TargetFailureProjection { + /** A short summary of the kind that does not change per occurrence (RFC 9457 `title`). */ + readonly title: string; + /** A coarse class derived from the kind; `failure_kind` identifies the failure. */ + readonly code: + | "invalid_request" + | "unsupported_target" + | "target_integrity_mismatch" + | "input_conflict" + | "artifact_changed" + | "access_denied" + | "host_io_failed"; + readonly category: + | "invalid_input" + | "unsupported_target" + | "integrity_mismatch" + | "unavailable" + | "execution_failure"; + /** The kind's retry hint; `io` refines it from its errno fact. */ + readonly retry: TargetFailureRetry; + readonly recovery: TargetFailureRecovery; +} + +/** + * The single projection table. No two codes cover unrelated caller actions: + * the four target refusals share `unsupported_target` because each needs a + * different target or tool, and their `failure_kind` says which. + */ +export const TARGET_FAILURE_PROJECTIONS = { + selection: { + title: "Unselectable", + code: "invalid_request", + category: "invalid_input", + retry: "after_change", + recovery: "fix_request", + }, + unrecognized: { + title: "Unrecognized", + code: "unsupported_target", + category: "unsupported_target", + retry: "none", + recovery: "choose_another_tool", + }, + unsupported: { + title: "Unsupported", + code: "unsupported_target", + category: "unsupported_target", + retry: "none", + recovery: "choose_another_tool", + }, + malformed: { + title: "Malformed", + code: "unsupported_target", + category: "unsupported_target", + retry: "none", + recovery: "choose_another_target", + }, + truncated: { + title: "Truncated", + code: "unsupported_target", + category: "unsupported_target", + retry: "none", + recovery: "reacquire_complete_file", + }, + integrity: { + title: "Integrity-mismatched", + code: "target_integrity_mismatch", + category: "integrity_mismatch", + retry: "none", + recovery: "replace_or_record_integrity", + }, + conflict: { + title: "Conflicting", + code: "input_conflict", + category: "invalid_input", + retry: "after_change", + recovery: "check_input_pairing", + }, + changed: { + title: "Changed", + code: "artifact_changed", + category: "integrity_mismatch", + retry: "backoff", + recovery: "retry_on_stable_copy", + }, + access: { + title: "Inaccessible", + code: "access_denied", + category: "unavailable", + retry: "after_change", + recovery: "fix_permissions", + }, + io: { + title: "Unreadable", + code: "host_io_failed", + category: "execution_failure", + retry: "none", + recovery: "check_host", + }, +} as const satisfies Readonly< + Record +>; + +/** Reports a case a switch did not handle; unreachable when the switch is total. */ +export const unhandledTargetFailureCase = (value: never): never => { + throw new TypeError( + `Unhandled target failure case: ${JSON.stringify(value)}`, + ); +}; + +/** The retry hint of one failure: its kind's, refined by an `io` errno fact. */ +export const targetFailureRetry = ( + failure: TargetFailure, +): TargetFailureRetry => + failure.kind === "io" && failure.transient + ? "backoff" + : TARGET_FAILURE_PROJECTIONS[failure.kind].retry; + +type DetailValue = + | string + | number + | readonly Readonly>[]; + +/** + * The machine-readable facts of a failure, in the public spelling. Every kind + * reports `failure_kind` and `format`; a variant adds its own facts. + */ +export const targetFailureDetails = ( + failure: TargetFailure, +): Readonly> => { + const common = { + failure_kind: failure.kind, + format: failure.format, + ...(failure.offset === undefined ? {} : { offset: failure.offset }), + ...(failure.field === undefined ? {} : { field: failure.field }), + }; + switch (failure.kind) { + case "truncated": + return { + ...common, + ...(failure.extent === undefined + ? {} + : { + available_bytes: failure.extent.availableBytes, + required_bytes: failure.extent.requiredBytes, + }), + }; + case "conflict": + return { + ...common, + inputs: failure.inputs.map(({ field, path }) => ({ field, path })), + }; + case "selection": + case "unrecognized": + case "unsupported": + case "malformed": + case "integrity": + case "changed": + case "access": + case "io": + return common; + default: + return unhandledTargetFailureCase(failure); + } +}; + +/** What a caller does next, for one failure of a known operation. */ +export const targetFailureRecovery = ( + operation: string, + failure: TargetFailure, +): string => { + const { recovery } = TARGET_FAILURE_PROJECTIONS[failure.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.`; + 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.`; + 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.`; + 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.`; + 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 + ? "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); + } +}; diff --git a/src/electron/ElectronFuseProvider.test.ts b/src/electron/ElectronFuseProvider.test.ts index bf3a1a3332..646c255851 100644 --- a/src/electron/ElectronFuseProvider.test.ts +++ b/src/electron/ElectronFuseProvider.test.ts @@ -310,7 +310,7 @@ describe("Electron fuse reader resource boundaries", () => { expect(result.ok).toBe(false); if (!result.ok) expect(result.error).toMatchObject({ - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", path, failure: { kind: "malformed", diff --git a/src/native/NativeMachoSourceProvider.test.ts b/src/native/NativeMachoSourceProvider.test.ts index b9e61ef6c5..2b0b7b1e8a 100644 --- a/src/native/NativeMachoSourceProvider.test.ts +++ b/src/native/NativeMachoSourceProvider.test.ts @@ -539,7 +539,7 @@ it.each([ const result = await client.execute("inspect_macho", {}); if (result.ok) throw new Error("Expected malformed target refusal"); expect(result.error).toMatchObject({ - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", operation: "inspect_macho", path, failure: { kind: "malformed", detail: reason }, diff --git a/src/native/dwarf/DwarfUnitsProvider.test.ts b/src/native/dwarf/DwarfUnitsProvider.test.ts index 2592010efa..60f431eb12 100644 --- a/src/native/dwarf/DwarfUnitsProvider.test.ts +++ b/src/native/dwarf/DwarfUnitsProvider.test.ts @@ -5,7 +5,7 @@ import { expect, it, vi } from "vitest"; import { AnalysisCancelledError, AnalysisInputError, - AnalysisMalformedTargetError, + AnalysisTargetFailureError, AnalysisResourceConstraintError, } from "../../domain/analysisErrorCore.js"; import { readMachoImageFromReader } from "../../domain/apple/machoImage.js"; @@ -354,7 +354,7 @@ it("rejects an unterminated PE long name within the decoding allowance", async ( const read = await inspect(image); expect(read.ok).toBe(false); if (!read.ok) { - expect(read.error).toBeInstanceOf(AnalysisMalformedTargetError); + expect(read.error).toBeInstanceOf(AnalysisTargetFailureError); expect(read.error).toMatchObject({ failure: { detail: expect.stringContaining("could not be resolved") }, }); @@ -397,7 +397,7 @@ it("rejects PE long section names when PointerToSymbolTable is zero", async () = }).toEqual({ zeroCountOk: false, nonZeroCountOk: false }); for (const rejected of [readZeroCount, readNonZeroCount]) { if (rejected.ok) continue; - expect(rejected.error).toBeInstanceOf(AnalysisMalformedTargetError); + expect(rejected.error).toBeInstanceOf(AnalysisTargetFailureError); expect(rejected.error).toMatchObject({ failure: { detail: expect.stringContaining( diff --git a/src/native/elf/ElfNotesProvider.test.ts b/src/native/elf/ElfNotesProvider.test.ts index e4e3c5a949..8daae0007b 100644 --- a/src/native/elf/ElfNotesProvider.test.ts +++ b/src/native/elf/ElfNotesProvider.test.ts @@ -139,7 +139,7 @@ describe("ELF note provider failures", () => { if (result.ok) throw new Error("Expected a malformed target"); // The image's bytes, not the request, are at fault. expect(result.error).toMatchObject({ - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", operation: "inspect_elf_notes", path, failure: { kind: "malformed", format: "elf" }, diff --git a/src/native/metadata/MachoSliceSelection.test.ts b/src/native/metadata/MachoSliceSelection.test.ts index dd3fcc8f01..6fb0baa150 100644 --- a/src/native/metadata/MachoSliceSelection.test.ts +++ b/src/native/metadata/MachoSliceSelection.test.ts @@ -13,7 +13,7 @@ import { } from "../../domain/apple/machoSliceSelection.js"; import { AnalysisInputError, - AnalysisMalformedTargetError, + AnalysisTargetFailureError, AnalysisUnsupportedTargetError, } from "../../domain/analysisErrorCore.js"; @@ -372,7 +372,7 @@ describe.each(Object.entries(MAPPERS))( ]); file.bytes.writeUInt32BE(8, 8 + 20 + 12); const refused = await refusal(file.bytes, "arm64e"); - expect(refused).toBeInstanceOf(AnalysisMalformedTargetError); + expect(refused).toBeInstanceOf(AnalysisTargetFailureError); expect(refused).toMatchObject({ path: "/a.dylib", failure: { @@ -389,7 +389,7 @@ describe.each(Object.entries(MAPPERS))( [CPU_ARM64, 2, 0], ]); const refused = await refusal(file.bytes, "arm64e"); - expect(refused).toBeInstanceOf(AnalysisMalformedTargetError); + expect(refused).toBeInstanceOf(AnalysisTargetFailureError); expect(refused).toMatchObject({ path: "/a.dylib", failure: { kind: "malformed", format: "macho" }, diff --git a/src/native/pe/PeCertificatesProvider.test.ts b/src/native/pe/PeCertificatesProvider.test.ts index 45f219d8de..1ae5cf0995 100644 --- a/src/native/pe/PeCertificatesProvider.test.ts +++ b/src/native/pe/PeCertificatesProvider.test.ts @@ -12,7 +12,7 @@ import { } from "../../../tests/fixtures/apkSignature/v1SignatureBlock.js"; import { inspectPeCertificatesInputSchema } from "../../domain/native/peCertificates.js"; import { - AnalysisMalformedTargetError, + AnalysisTargetFailureError, AnalysisResourceConstraintError, } from "../../domain/analysisErrorCore.js"; import { peCertificateFixture } from "./PeCertificates.fixture.js"; @@ -89,7 +89,7 @@ it("accepts shallower valid BER and refuses malformed BER as a malformed target" const malformed = await inspect(Buffer.from([0x30, 0x03, 0x05])); expect(malformed.ok).toBe(false); if (malformed.ok) throw new Error("Expected malformed target refusal"); - expect(malformed.error).toBeInstanceOf(AnalysisMalformedTargetError); + expect(malformed.error).toBeInstanceOf(AnalysisTargetFailureError); expect(malformed.error).toMatchObject({ failure: { kind: "malformed", format: "pe-certificate-table" }, }); diff --git a/src/native/pe/PeResourcesProvider.test.ts b/src/native/pe/PeResourcesProvider.test.ts index 09f78f7cf4..2ffb02512f 100644 --- a/src/native/pe/PeResourcesProvider.test.ts +++ b/src/native/pe/PeResourcesProvider.test.ts @@ -165,7 +165,7 @@ describe("PE resource provider budget reporting", () => { }); if (result.ok) throw new Error("Expected malformed table refusal"); expect(result.error).toMatchObject({ - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", }); }); }); diff --git a/src/native/pe/PeUnwindRangesProvider.test.ts b/src/native/pe/PeUnwindRangesProvider.test.ts index 26d23ca272..5d4e122ff5 100644 --- a/src/native/pe/PeUnwindRangesProvider.test.ts +++ b/src/native/pe/PeUnwindRangesProvider.test.ts @@ -3,7 +3,7 @@ import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; -import { AnalysisMalformedTargetError } from "../../domain/analysisErrorCore.js"; +import { AnalysisTargetFailureError } from "../../domain/analysisErrorCore.js"; import { inspectPeUnwindRangesInputSchema, type PeUnwindRanges, @@ -364,12 +364,18 @@ describe("x64 PE exception directory refusals and absence", () => { { entries: [primary], truncateTo: 0x2400 + 6 }, ], ] satisfies [string, PeUnwindFixtureOptions][])( - "refuses %s as a malformed target", + "refuses %s as a damaged target", async (_name, options) => { const result = await inspect(options); expect(result.ok).toBe(false); if (result.ok) return; - expect(result.error).toBeInstanceOf(AnalysisMalformedTargetError); + expect(result.error).toBeInstanceOf(AnalysisTargetFailureError); + if (!(result.error instanceof AnalysisTargetFailureError)) + throw result.error; + // A file cut inside the directory is truncated; the rest are malformed. + expect(result.error.failure.kind).toBe( + "truncateTo" in options ? "truncated" : "malformed", + ); }, ); }); diff --git a/src/resources/ArtifactOperationFailure.test.ts b/src/resources/ArtifactOperationFailure.test.ts index a96a98eac6..7170022bd2 100644 --- a/src/resources/ArtifactOperationFailure.test.ts +++ b/src/resources/ArtifactOperationFailure.test.ts @@ -98,7 +98,10 @@ it.each([ cause: malformedInput("pe", "bad field"), genericCode: "unsupported_target", }, - { cause: truncatedInput("pe", "short field"), genericCode: "truncated" }, + { + cause: truncatedInput("pe", "short field"), + genericCode: "unsupported_target", + }, { cause: unsupportedInput("pe", "unsupported image"), genericCode: "unsupported_target", @@ -174,7 +177,7 @@ it.each([ reason: cause.message, ...(cause.kind === "unsupported" ? {} - : { format_failure: cause.kind, format: "pe" }), + : { failure_kind: cause.kind, format: "pe" }), partial_observation: observation, }, }); @@ -188,7 +191,7 @@ it.each([ detail: cause.message, ...(cause.kind === "unsupported" ? {} - : { format_failure: cause.kind, format: "pe" }), + : { failure_kind: cause.kind, format: "pe" }), }, }); }, @@ -266,7 +269,7 @@ it("preserves adjustable reader admission facts and gives cleanup priority", () translateArtifactFailure("inspect_artifact", failure), ); expect(adjustable).toMatchObject({ - code: "truncated", + code: "partial", retryable: true, details: { reader_limit: { @@ -310,7 +313,7 @@ it.each(["capacity", "file-size", "memory"] as const)( translateArtifactFailure("inventory_artifact", failure), ); expect(result).toMatchObject({ - code: "truncated", + code: "partial", retryable: false, message: failure.message, details: { boundary, detail: failure.message }, @@ -373,7 +376,7 @@ it("keeps a fixed reader ceiling's refusal through cleanup wrapping and public p expect( projectAnalysisError(translateArtifactFailure("inspect_artifact", failure)), ).toMatchObject({ - code: "truncated", + code: "partial", retryable: false, message: failure.message, details: { refusal }, diff --git a/src/resources/ArtifactReader.ts b/src/resources/ArtifactReader.ts index c9c860ee06..3723677af5 100644 --- a/src/resources/ArtifactReader.ts +++ b/src/resources/ArtifactReader.ts @@ -28,7 +28,7 @@ import type { } from "../domain/analysisErrorBase.js"; import { errorMessage } from "../kernel/errorMessage.js"; import type { LimitRef } from "../domain/parseFailure.js"; -import type { MalformedTargetFailure } from "../domain/analysisErrorCore.js"; +import type { MalformedTargetFailure } from "../domain/targetFailure.js"; export interface ArtifactReaderFailureOptions extends ErrorOptions { /** Recovery guidance established by the producing adapter, separate from diagnostics. */ diff --git a/src/resources/StableArtifactFailure.ts b/src/resources/StableArtifactFailure.ts index 07761b6b03..4acd75a314 100644 --- a/src/resources/StableArtifactFailure.ts +++ b/src/resources/StableArtifactFailure.ts @@ -20,7 +20,7 @@ import { AnalysisAccessDeniedError, AnalysisArtifactChangedError, AnalysisInputError, - AnalysisMalformedTargetError, + AnalysisTargetFailureError, AnalysisUnsupportedTargetError, cancelledBy, carriedReason, @@ -90,12 +90,9 @@ export const projectOwnedArtifactInputFailure = ( // truncated reason, so a cancelled read whose opaque abort reason happens to // be a parser failure stays a cancellation. if (cause.parseFailure !== undefined) - return new AnalysisMalformedTargetError( - operation, - path, - cause.parseFailure, - { cause }, - ); + return new AnalysisTargetFailureError(operation, path, cause.parseFailure, { + cause, + }); // Only a path-kind refusal (a symlink, directory or other non-regular file) // is the caller's selection. Byte faults without parsed facts are left to // the reader's own artifact-operation classification. diff --git a/src/server/EvidenceMcpServerCore.ts b/src/server/EvidenceMcpServerCore.ts index b82819404e..5abf067da8 100644 --- a/src/server/EvidenceMcpServerCore.ts +++ b/src/server/EvidenceMcpServerCore.ts @@ -32,6 +32,7 @@ import { type ToolResultDelivery, } from "./ToolResultDelivery.js"; import { RequestTrackingMcpServer } from "./RequestTrackingMcpServer.js"; +import { AnalysisTargetFailureError } from "../domain/analysisErrorCore.js"; import { DISCOVER_TOOLS } from "../contracts/catalog/catalogDiscovery.js"; import { ProgressiveToolCatalog } from "./ProgressiveToolCatalog.js"; import type { WithAdmittedAnalysis } from "./analysisAdmission.js"; @@ -403,9 +404,19 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer { input, normalized(context as ServerContext), ); - const result = await (this.analysisSettings === undefined - ? invoke() - : this.analysisSettings.run(invoke)); + let result: Awaited>; + try { + result = await (this.analysisSettings === undefined + ? invoke() + : this.analysisSettings.run(invoke)); + } catch (cause: unknown) { + // The SDK flattens a thrown handler failure into one text block and + // JSON-RPC errors are for protocol faults, so a target failure that + // escapes a handler is still returned as a projected tool result. + // Its message can name target bytes, so it is marked as such. + if (!(cause instanceof AnalysisTargetFailureError)) throw cause; + result = this.delivery.toErrorToolResult(cause, true); + } if (request !== undefined) request.projectedErrorEncoding = projectedErrorEncoding(result); return result; diff --git a/tests/acceptance/androidBootImageCli.test.ts b/tests/acceptance/androidBootImageCli.test.ts index 508d3fc83e..dacf0bf82c 100644 --- a/tests/acceptance/androidBootImageCli.test.ts +++ b/tests/acceptance/androidBootImageCli.test.ts @@ -119,7 +119,7 @@ cliTest( operation: "inspect_artifact", reason: fixture.kind, ...("format" in fixture - ? { format_failure: fixture.kind, format: fixture.format } + ? { failure_kind: fixture.kind, format: fixture.format } : {}), }, }); diff --git a/tests/acceptance/appleIpsCli.test.ts b/tests/acceptance/appleIpsCli.test.ts index 38588e4681..f46ea3b725 100644 --- a/tests/acceptance/appleIpsCli.test.ts +++ b/tests/acceptance/appleIpsCli.test.ts @@ -209,21 +209,3 @@ cliTest( expect(evidence.subject?.local_path).toBe(join(root, "report.ips")); }, ); - -cliTest("reports a truncated IPS as a malformed target", async ({ cli }) => { - const root = await createTestTempDirectory("rea-apple-ips-cli-bad-"); - const path = join(root, "broken.ips"); - await writeFile(path, appleIpsBytes({ truncateBody: true })); - const result = await cli.run({ - arguments: ["inspect-apple-ips", path, "--json"], - }); - expect(result.exitCode).toBe(1); - expect(result.json).toMatchObject({ - code: "unsupported_target", - details: { - operation: "inspect_apple_ips", - path, - format_failure: "malformed", - }, - }); -}); diff --git a/tests/acceptance/applications/nativeExportsDynamicSegment.test.ts b/tests/acceptance/applications/nativeExportsDynamicSegment.test.ts index 9f9a63f7e9..9ef28dd75b 100644 --- a/tests/acceptance/applications/nativeExportsDynamicSegment.test.ts +++ b/tests/acceptance/applications/nativeExportsDynamicSegment.test.ts @@ -103,7 +103,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)( expect(error).toMatchObject({ code: "unsupported_target", details: { - format_failure: "malformed", + failure_kind: "malformed", reason: expect.stringContaining("null entry"), }, }); diff --git a/tests/acceptance/applications/peResources.test.ts b/tests/acceptance/applications/peResources.test.ts index 0c9a13d84c..73d132ddcd 100644 --- a/tests/acceptance/applications/peResources.test.ts +++ b/tests/acceptance/applications/peResources.test.ts @@ -46,7 +46,7 @@ const expectPeInputFailureAcrossAdapters = async (input: { details: { operation: "inspect_pe_resources", path, - format_failure: expect.stringMatching(/^(?:malformed|truncated)$/u), + failure_kind: expect.stringMatching(/^(?:malformed|truncated)$/u), }, }, ); diff --git a/tests/acceptance/applications/peUnsupportedTargets.test.ts b/tests/acceptance/applications/peUnsupportedTargets.test.ts index 856b5c64c8..24a73383e3 100644 --- a/tests/acceptance/applications/peUnsupportedTargets.test.ts +++ b/tests/acceptance/applications/peUnsupportedTargets.test.ts @@ -65,7 +65,7 @@ cliTest.for(cases)( expect(error).toMatchObject({ details: { path, - format_failure: expect.stringMatching(/^(?:malformed|truncated)$/u), + failure_kind: expect.stringMatching(/^(?:malformed|truncated)$/u), }, }); } else { diff --git a/tests/acceptance/artifactReaderLimitsCli.test.ts b/tests/acceptance/artifactReaderLimitsCli.test.ts index 478a922920..b785f712ee 100644 --- a/tests/acceptance/artifactReaderLimitsCli.test.ts +++ b/tests/acceptance/artifactReaderLimitsCli.test.ts @@ -178,7 +178,7 @@ for (const reader of readers) }); expect(refused.exitCode).toBe(1); expect(refused.json).toMatchObject({ - code: "truncated", + code: "partial", retryable: true, details: { reader_limit: { @@ -229,7 +229,7 @@ test("admits the same SEA carrier above the legacy 4096-argument ceiling", async const refused = await cli.run({ arguments: command }); expect(refused.exitCode).toBe(1); expect(refused.json).toMatchObject({ - code: "truncated", + code: "partial", details: { reader_limit: { parameter: "artifact_limits.node_sea.argument_count", @@ -273,7 +273,7 @@ test("applies the selected reader budget before extraction and preserves its out }); expect(refused.exitCode).toBe(1); expect(refused.json).toMatchObject({ - code: "truncated", + code: "partial", details: { reader_limit: { parameter: "artifact_limits.dotnet_bundle.entry_count" }, }, diff --git a/tests/acceptance/bunPathBudgetCli.test.ts b/tests/acceptance/bunPathBudgetCli.test.ts index e8ece793ba..e780b38ea8 100644 --- a/tests/acceptance/bunPathBudgetCli.test.ts +++ b/tests/acceptance/bunPathBudgetCli.test.ts @@ -31,7 +31,7 @@ for (const shared of [false, true]) if (!shared) { expect(result.exitCode).toBe(1); expect(result.json).toMatchObject({ - code: "truncated", + code: "partial", retryable: true, details: { reason: "limit", diff --git a/tests/acceptance/bunStandaloneCli.test.ts b/tests/acceptance/bunStandaloneCli.test.ts index bbcbdb8ad0..3752a46781 100644 --- a/tests/acceptance/bunStandaloneCli.test.ts +++ b/tests/acceptance/bunStandaloneCli.test.ts @@ -47,7 +47,7 @@ cliTest( }); expect(result.exitCode).toBe(1); expect(result.json).toMatchObject({ - code: moduleCount < 13 ? "truncated" : "artifact_operation_failed", + code: moduleCount < 13 ? "partial" : "artifact_operation_failed", retryable: moduleCount < 13, details: moduleCount < 13 diff --git a/tests/acceptance/denoStandaloneCli.test.ts b/tests/acceptance/denoStandaloneCli.test.ts index d86198e903..2c15d824dd 100644 --- a/tests/acceptance/denoStandaloneCli.test.ts +++ b/tests/acceptance/denoStandaloneCli.test.ts @@ -107,7 +107,7 @@ cliTest( }); expect(capped.exitCode).toBe(1); expect(capped.json).toMatchObject({ - code: "truncated", + code: "partial", details: { reason: "limit", boundary: "capacity", diff --git a/tests/acceptance/dotnetBundleJourney.test.ts b/tests/acceptance/dotnetBundleJourney.test.ts index 7006a5e801..b0b4703a16 100644 --- a/tests/acceptance/dotnetBundleJourney.test.ts +++ b/tests/acceptance/dotnetBundleJourney.test.ts @@ -246,8 +246,8 @@ test("reports excessive bundle path depth as a public CLI limit", async ({ }); expect(result.exitCode, result.stderr).toBe(1); expect(result.json).toMatchObject({ - code: "truncated", - category: "truncated", + code: "partial", + category: "partial", retryable: true, details: { reason: "limit", diff --git a/tests/acceptance/dwarfUnitsCli.test.ts b/tests/acceptance/dwarfUnitsCli.test.ts index b6ba6e35ed..98beee2fa9 100644 --- a/tests/acceptance/dwarfUnitsCli.test.ts +++ b/tests/acceptance/dwarfUnitsCli.test.ts @@ -111,7 +111,7 @@ cliTest( code: "unsupported_target", details: { operation: "inspect_dwarf_units", - format_failure: "malformed", + failure_kind: "malformed", reason: expect.stringContaining( "PE long section name string table is unavailable", ), diff --git a/tests/acceptance/elfNotesCli.test.ts b/tests/acceptance/elfNotesCli.test.ts index 48848fda9a..47c6ca355d 100644 --- a/tests/acceptance/elfNotesCli.test.ts +++ b/tests/acceptance/elfNotesCli.test.ts @@ -201,7 +201,7 @@ cliTest( details: { operation: "inspect_elf_notes", path, - format_failure: "malformed", + failure_kind: "malformed", format: "elf", }, }); diff --git a/tests/acceptance/erlangBeamCli.test.ts b/tests/acceptance/erlangBeamCli.test.ts index 14170b6f4c..a78d1a17e6 100644 --- a/tests/acceptance/erlangBeamCli.test.ts +++ b/tests/acceptance/erlangBeamCli.test.ts @@ -470,7 +470,7 @@ cliTest( code: "unsupported_target", details: { operation: "inspect_erlang_beam", - format_failure: "malformed", + failure_kind: "malformed", format: "beam", }, }); @@ -512,7 +512,7 @@ cliTest( code: "unsupported_target", details: { operation: "inspect_erlang_beam", - format_failure: "malformed", + failure_kind: "malformed", format: "beam", reason: "BEAM chunk payload exceeds the form.", }, diff --git a/tests/acceptance/fitImageCli.test.ts b/tests/acceptance/fitImageCli.test.ts index 57f9992175..93c93877ac 100644 --- a/tests/acceptance/fitImageCli.test.ts +++ b/tests/acceptance/fitImageCli.test.ts @@ -122,7 +122,7 @@ cliTest("reports the fixed FIT devicetree depth limit", async ({ cli }) => { const refused = await inspect(65); expect(refused.json).toMatchObject({ - code: "truncated", + code: "partial", retryable: false, details: { boundary: "capacity", diff --git a/tests/acceptance/goBinaryCli.test.ts b/tests/acceptance/goBinaryCli.test.ts index f743690473..91a149aebd 100644 --- a/tests/acceptance/goBinaryCli.test.ts +++ b/tests/acceptance/goBinaryCli.test.ts @@ -73,7 +73,7 @@ cliTest( code: "unsupported_target", details: { operation: "inspect_go_binary", - format_failure: expect.stringMatching(/^(?:malformed|truncated)$/u), + failure_kind: expect.stringMatching(/^(?:malformed|truncated)$/u), }, }; expect(result.exitCode).toBe(1); @@ -173,7 +173,7 @@ cliTest( }, } : { - format_failure: expect.stringMatching( + failure_kind: expect.stringMatching( /^(?:malformed|truncated)$/u, ), }), @@ -192,7 +192,7 @@ cliTest( }, } : { - format_failure: expect.stringMatching( + failure_kind: expect.stringMatching( /^(?:malformed|truncated)$/u, ), }), @@ -366,7 +366,7 @@ cliTest( code: "unsupported_target", details: { operation: "inspect_go_binary", - format_failure: expect.stringMatching(/^(?:malformed|truncated)$/u), + failure_kind: expect.stringMatching(/^(?:malformed|truncated)$/u), }, }; diff --git a/tests/acceptance/goBinaryPointerMappingsCli.test.ts b/tests/acceptance/goBinaryPointerMappingsCli.test.ts index 031fbebef2..6505c5b36c 100644 --- a/tests/acceptance/goBinaryPointerMappingsCli.test.ts +++ b/tests/acceptance/goBinaryPointerMappingsCli.test.ts @@ -58,7 +58,7 @@ cliTest( expect(rejected.json).toMatchObject({ code: "unsupported_target", details: { - format_failure: expect.stringMatching(/^(?:malformed|truncated)$/u), + failure_kind: expect.stringMatching(/^(?:malformed|truncated)$/u), }, }); const response = await call("inspect_go_binary", { path }); diff --git a/tests/acceptance/godotPck.test.ts b/tests/acceptance/godotPck.test.ts index 3f0ad3d6cc..f8c39f40a7 100644 --- a/tests/acceptance/godotPck.test.ts +++ b/tests/acceptance/godotPck.test.ts @@ -424,7 +424,7 @@ cliTest( }); expect(reply.exitCode, reply.stdout + reply.stderr).toBe(1); expect(reply.json).toMatchObject({ - code: "truncated", + code: "partial", retryable: true, details: { reason: "limit", diff --git a/tests/acceptance/gpuCodeObjectsCli.test.ts b/tests/acceptance/gpuCodeObjectsCli.test.ts index f10f278f8f..82b613a2df 100644 --- a/tests/acceptance/gpuCodeObjectsCli.test.ts +++ b/tests/acceptance/gpuCodeObjectsCli.test.ts @@ -1180,7 +1180,7 @@ cliTest( category: "unsupported_target", details: { operation: "inspect_gpu_code_objects", - format_failure: "malformed", + failure_kind: "malformed", reason: expect.stringContaining( "MZ header does not declare a PE image", ), diff --git a/tests/acceptance/il2cppMetadataCli.test.ts b/tests/acceptance/il2cppMetadataCli.test.ts index d1e9ae9fde..9a368d81f4 100644 --- a/tests/acceptance/il2cppMetadataCli.test.ts +++ b/tests/acceptance/il2cppMetadataCli.test.ts @@ -336,7 +336,7 @@ cliTest( details: { operation: "inspect_il2cpp_metadata", path, - format_failure: "malformed", + failure_kind: "malformed", format: "il2cpp-metadata", reason: expect.stringContaining("record-size-mismatch"), }, @@ -501,7 +501,7 @@ cliTest( code: "unsupported_target", details: { operation: "inspect_il2cpp_metadata", - format_failure: "malformed", + failure_kind: "malformed", format: "il2cpp-metadata", reason: expect.stringContaining("section-overlap"), }, @@ -537,7 +537,7 @@ cliTest( details: { operation: "inspect_il2cpp_metadata", path, - format_failure: "truncated", + failure_kind: "truncated", format: "il2cpp-metadata", reason: expect.stringContaining("truncated-header"), partial_observation: { @@ -1133,7 +1133,7 @@ cliTest( code: "unsupported_target", details: { path, - format_failure: "malformed", + failure_kind: "malformed", format: "il2cpp-metadata", reason: expect.stringContaining("section-overlap"), }, @@ -1147,7 +1147,7 @@ cliTest( code: "unsupported_target", details: { path: binaryPath, - format_failure: "truncated", + failure_kind: "truncated", format: "macho", }, }), @@ -1169,7 +1169,7 @@ cliTest( code: "unsupported_target", details: { path, - format_failure: "malformed", + failure_kind: "malformed", format: "il2cpp-metadata", reason: expect.stringMatching(/^invalid-method-definition-token:/u), }, diff --git a/tests/acceptance/il2cppStructuralExtentsCli.test.ts b/tests/acceptance/il2cppStructuralExtentsCli.test.ts index 6247342afb..68433c8b82 100644 --- a/tests/acceptance/il2cppStructuralExtentsCli.test.ts +++ b/tests/acceptance/il2cppStructuralExtentsCli.test.ts @@ -50,7 +50,7 @@ cliTest( code: "unsupported_target", details: { path, - format_failure: "malformed", + failure_kind: "malformed", format: "il2cpp-metadata", reason: expect.stringContaining( `record-size-mismatch: section ${name}`, diff --git a/tests/acceptance/mavenGradleMetadataCli.test.ts b/tests/acceptance/mavenGradleMetadataCli.test.ts index 2986d0a698..90aefbb29e 100644 --- a/tests/acceptance/mavenGradleMetadataCli.test.ts +++ b/tests/acceptance/mavenGradleMetadataCli.test.ts @@ -570,7 +570,7 @@ cliTest.for([ code: "unsupported_target", details: { operation: "inspect_maven_gradle_metadata", - format_failure: "malformed", + failure_kind: "malformed", reason: expect.stringContaining(issue), partial_observation: { kind: "file-snapshot-hash", diff --git a/tests/acceptance/modelArtifactCli.test.ts b/tests/acceptance/modelArtifactCli.test.ts index 406cb25051..9416930964 100644 --- a/tests/acceptance/modelArtifactCli.test.ts +++ b/tests/acceptance/modelArtifactCli.test.ts @@ -32,7 +32,7 @@ const MALFORMED_MODEL = { category: "unsupported_target", details: { operation: "inspect_model_artifact", - format_failure: expect.stringMatching(/^(?:malformed|truncated)$/u), + failure_kind: expect.stringMatching(/^(?:malformed|truncated)$/u), }, } as const; @@ -540,7 +540,7 @@ cliTest( operation: "inspect_model_artifact", path, reason: "Declared extent is outside the file", - format_failure: "malformed", + failure_kind: "malformed", }, }); expect(offsetFailure.error).not.toHaveProperty("recovery"); diff --git a/tests/acceptance/nativeInitializersCli.test.ts b/tests/acceptance/nativeInitializersCli.test.ts index 49f1424019..292f25da11 100644 --- a/tests/acceptance/nativeInitializersCli.test.ts +++ b/tests/acceptance/nativeInitializersCli.test.ts @@ -222,7 +222,7 @@ cliTest.for([ details: { operation: "inspect_native_initializers", ...(code === "unsupported_target" - ? { path, format_failure: "malformed" } + ? { path, failure_kind: "malformed" } : { reported_limits: { boundary: "structure", diff --git a/tests/acceptance/nodeSeaCli.test.ts b/tests/acceptance/nodeSeaCli.test.ts index dc744fff7c..c4d1661b77 100644 --- a/tests/acceptance/nodeSeaCli.test.ts +++ b/tests/acceptance/nodeSeaCli.test.ts @@ -344,7 +344,7 @@ cliTest( }); expect(result.exitCode).not.toBe(0); expect(result.json).toMatchObject({ - code: "truncated", + code: "partial", retryable: true, details: { reason: "limit", diff --git a/tests/acceptance/nugetNupkgCli.test.ts b/tests/acceptance/nugetNupkgCli.test.ts index 0629849fa1..5fe36f6a45 100644 --- a/tests/acceptance/nugetNupkgCli.test.ts +++ b/tests/acceptance/nugetNupkgCli.test.ts @@ -199,7 +199,7 @@ cliTest("refuses a non-ZIP file through the public CLI", async ({ cli }) => { category: "unsupported_target", details: { operation: "inspect_nuget_nupkg", - format_failure: "malformed", + failure_kind: "malformed", reason: expect.stringContaining("not a ZIP"), }, }); diff --git a/tests/acceptance/peCertificatesCli.test.ts b/tests/acceptance/peCertificatesCli.test.ts index c1e05f31b2..7af12d0e9b 100644 --- a/tests/acceptance/peCertificatesCli.test.ts +++ b/tests/acceptance/peCertificatesCli.test.ts @@ -56,7 +56,7 @@ cliTest( : { code: "unsupported_target", details: { - format_failure: kind, + failure_kind: kind, format: "pe-certificate-table", reason: expect.stringContaining(message), }, @@ -105,7 +105,7 @@ cliTest.for([false, true])( code: "unsupported_target", details: { operation: "inspect_pe_certificates", - format_failure: "truncated", + failure_kind: "truncated", format: "pe-certificate-table", }, }; @@ -189,7 +189,7 @@ cliTest.for([0x00, 0xff, null])( code: "unsupported_target", details: { operation: "inspect_pe_certificates", - format_failure: "malformed", + failure_kind: "malformed", format: "pe-certificate-table", reason: expect.stringContaining("critical"), }, @@ -224,7 +224,7 @@ cliTest( code: "unsupported_target", details: { operation: "inspect_pe_certificates", - format_failure: "malformed", + failure_kind: "malformed", format: "pe-certificate-table", reason: expect.stringContaining("Name RDN"), }, @@ -260,7 +260,7 @@ cliTest( code: "unsupported_target", details: { operation: "inspect_pe_certificates", - format_failure: "malformed", + failure_kind: "malformed", format: "pe-certificate-table", reason: expect.stringContaining("padding"), }, @@ -437,7 +437,7 @@ cliTest( code: "unsupported_target", details: { operation: "inspect_pe_certificates", - format_failure: "malformed", + failure_kind: "malformed", format: "pe-certificate-table", }, }); diff --git a/tests/acceptance/peImportsCli.test.ts b/tests/acceptance/peImportsCli.test.ts index b3469c8aa0..fba0a1a015 100644 --- a/tests/acceptance/peImportsCli.test.ts +++ b/tests/acceptance/peImportsCli.test.ts @@ -13,40 +13,14 @@ import { peWithoutImportTableFixture, } from "../fixtures/binaryDiagnostics/peImports.js"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; -import { parseMcpToolError } from "../fixtures/mcpToolError.js"; import { cliTest } from "../support/cli/cliFixture.js"; for (const bits of [32, 64] as const) { cliTest( - `rejects non-MZ PE${String(bits)} imports across CLI and MCP`, + `reads a valid PE${String(bits)} imports across CLI and MCP`, async ({ cli }) => { - const root = await createTestTempDirectory("rea-pe-imports-signature-"); + const root = await createTestTempDirectory("rea-pe-imports-valid-"); const call = await cli.sharedMcpCall!(); - for (const [name, prefix] of [ - ["zz", Buffer.from("ZZ")], - ["high-bit", Buffer.from([0xcd, 0xda])], - ] as const) { - const bytes = peImportImage({ bits }); - prefix.copy(bytes); - const path = join(root, `${name}.exe`); - await writeFile(path, bytes); - const result = await cli.run({ - arguments: ["inspect-pe-imports", path, "--json"], - }); - expect(result.exitCode).toBe(1); - expect(result.json).toMatchObject({ - code: "unsupported_target", - details: { - operation: "inspect_pe_imports", - path, - format_failure: "malformed", - }, - }); - const response = await call("inspect_pe_imports", { path }); - expect(response.isError).toBe(true); - expect(parseMcpToolError(response)).toEqual({ error: result.json }); - expect((await readFile(path)).equals(bytes)).toBe(true); - } const path = join(root, "valid.exe"); const bytes = peImportImage({ bits }); await writeFile(path, bytes); diff --git a/tests/acceptance/peLoadConfigCli.test.ts b/tests/acceptance/peLoadConfigCli.test.ts index e701cd9422..11dee2fa9d 100644 --- a/tests/acceptance/peLoadConfigCli.test.ts +++ b/tests/acceptance/peLoadConfigCli.test.ts @@ -7,40 +7,14 @@ import { peLoadConfigImage, } from "../../src/native/pe/PeLoadConfig.fixture.js"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; -import { parseMcpToolError } from "../fixtures/mcpToolError.js"; import { cliTest } from "../support/cli/cliFixture.js"; for (const bits of [32, 64] as const) { cliTest( - `rejects non-MZ PE${String(bits)} load config across CLI and MCP`, + `reads a valid PE${String(bits)} load config across CLI and MCP`, async ({ cli }) => { - const root = await createTestTempDirectory("rea-pe-config-signature-"); + const root = await createTestTempDirectory("rea-pe-config-valid-"); const call = await cli.sharedMcpCall!(); - for (const [name, prefix] of [ - ["zz", Buffer.from("ZZ")], - ["high-bit", Buffer.from([0xcd, 0xda])], - ] as const) { - const bytes = peLoadConfigImage({ bits }); - prefix.copy(bytes); - const path = join(root, `${name}.exe`); - await writeFile(path, bytes); - const result = await cli.run({ - arguments: ["inspect-pe-load-config", path, "--json"], - }); - expect(result.exitCode).toBe(1); - expect(result.json).toMatchObject({ - code: "unsupported_target", - details: { - operation: "inspect_pe_load_config", - path, - format_failure: "malformed", - }, - }); - const response = await call("inspect_pe_load_config", { path }); - expect(response.isError).toBe(true); - expect(parseMcpToolError(response)).toEqual({ error: result.json }); - expect((await readFile(path)).equals(bytes)).toBe(true); - } const path = join(root, "valid.exe"); const bytes = peLoadConfigImage({ bits }); await writeFile(path, bytes); diff --git a/tests/acceptance/pyinstallerArchive.test.ts b/tests/acceptance/pyinstallerArchive.test.ts index e0905b9f2d..80ec219ff5 100644 --- a/tests/acceptance/pyinstallerArchive.test.ts +++ b/tests/acceptance/pyinstallerArchive.test.ts @@ -707,7 +707,7 @@ cliTest( }); expect(result.exitCode).toBe(1); expect(result.json).toMatchObject({ - code: "truncated", + code: "partial", details: { reason: "limit", detail: expect.stringContaining( diff --git a/tests/acceptance/pythonPycCli.test.ts b/tests/acceptance/pythonPycCli.test.ts index 2cf9394e5d..9567c381b9 100644 --- a/tests/acceptance/pythonPycCli.test.ts +++ b/tests/acceptance/pythonPycCli.test.ts @@ -569,7 +569,7 @@ cliTest( code: "unsupported_target", details: { operation: "inspect_python_pyc", - format_failure: "malformed", + failure_kind: "malformed", reason: expect.stringContaining("shorter than a 16-byte CPython"), }, }); diff --git a/tests/acceptance/rustBinaryCli.test.ts b/tests/acceptance/rustBinaryCli.test.ts index 829ef4fb82..5132472cc3 100644 --- a/tests/acceptance/rustBinaryCli.test.ts +++ b/tests/acceptance/rustBinaryCli.test.ts @@ -34,7 +34,7 @@ cliTest( code: "unsupported_target", details: { operation: "inspect_rust_binary", - format_failure: expect.stringMatching(/^(?:malformed|truncated)$/u), + failure_kind: expect.stringMatching(/^(?:malformed|truncated)$/u), }, }; @@ -547,7 +547,7 @@ cliTest( code: "unsupported_target", details: { operation: "inspect_go_binary", - format_failure: expect.stringMatching(/^(?:malformed|truncated)$/u), + failure_kind: expect.stringMatching(/^(?:malformed|truncated)$/u), reason: expect.stringContaining( "Virtual address or string range is not file mapped", ), diff --git a/tests/acceptance/stableArtifactParserFailureCli.test.ts b/tests/acceptance/stableArtifactParserFailureCli.test.ts index 07c4f4b5eb..9c47c1e96d 100644 --- a/tests/acceptance/stableArtifactParserFailureCli.test.ts +++ b/tests/acceptance/stableArtifactParserFailureCli.test.ts @@ -2,14 +2,8 @@ import { createHash } from "node:crypto"; import { writeFile } from "node:fs/promises"; import { join } from "node:path"; import { expect } from "vitest"; -import { - fatImage, - machoImage, -} from "../../src/artifacts/apple/MachoImage.fixture.js"; -import { buildManagedPeFixture } from "../../src/dotnet/ManagedPe.fixture.js"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; import { cliTest } from "../support/cli/cliFixture.js"; -import { peCertificateFixture } from "../../src/native/pe/PeCertificates.fixture.js"; const fileIdentity = (path: string, bytes: Buffer) => ({ kind: "file-snapshot-hash", @@ -18,6 +12,10 @@ const fileIdentity = (path: string, bytes: Buffer) => ({ 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", @@ -38,7 +36,6 @@ for (const command of [ "inspect-native-initializers", "inspect-binary-hardening", ]) { - const operation = command.replaceAll("-", "_"); const isBeam = command === "inspect-erlang-beam"; cliTest( @@ -55,195 +52,4 @@ for (const command of [ }); }, ); - - // One public owner for the byte readers' malformed-target projection: the - // bytes, not the request, are at fault, so no argument recovery is offered. - // Format-specific structure (an IPS body, a shortcut CLSID) keeps its own - // command test. A BEAM reader sees the ELF magic as a foreign container. - cliTest( - `${command} refuses a truncated ELF header as a malformed target`, - async ({ cli }) => { - const root = await createTestTempDirectory("rea-malformed-target-"); - const path = join(root, "truncated.bin"); - const bytes = Buffer.from("\x7fELF"); - await writeFile(path, bytes); - const result = await cli.run({ arguments: [command, path, "--json"] }); - expect(result.exitCode, result.stderr).toBe(1); - expect(result.json).toMatchObject({ - code: "unsupported_target", - category: "unsupported_target", - details: { - operation, - path, - format_failure: "malformed", - partial_observation: fileIdentity(path, bytes), - }, - }); - expect(result.json).not.toHaveProperty("recovery"); - }, - ); } - -/** A managed PE whose first section's raw data starts past the end of the file. */ -const managedSectionPastEof = () => { - const bytes = buildManagedPeFixture(); - const pe = bytes.readUInt32LE(0x3c); - const sections = pe + 24 + bytes.readUInt16LE(pe + 20); - bytes.writeUInt32LE(bytes.length + 0x1000, sections + 20); - return bytes; -}; - -/** A universal Mach-O whose first declared slice runs into the second. */ -const overlappingUniversalMacho = () => { - const slice = (type: number, subtype: number) => ({ - cpu: { type, subtype }, - bytes: machoImage({ cpu: { type, subtype }, wide: true }), - }); - const bytes = Buffer.from( - fatImage([slice(0x01000007, 3), slice(0x0100000c, 0)]), - ); - const first = bytes.readUInt32BE(8 + 8); - const second = bytes.readUInt32BE(8 + 20 + 8); - bytes.writeUInt32BE(second - first + 16, 8 + 12); - return bytes; -}; - -/** A universal Mach-O cut off inside its FAT table: 20 of its 48 table bytes. */ -const truncatedUniversalMacho = () => { - const slice = (type: number, subtype: number) => ({ - cpu: { type, subtype }, - bytes: machoImage({ cpu: { type, subtype }, wide: true }), - }); - return Buffer.from( - fatImage([slice(0x01000007, 3), slice(0x0100000c, 0)]), - ).subarray(0, 20); -}; - -const nativeUniversalCommands = [ - "inspect-go-binary", - "inspect-rust-binary", - "inspect-dwarf-units", - "inspect-native-initializers", -]; - -// Format owners with their own mappers: a managed PE/CLI reader and the -// universal Mach-O container read before slice selection. The selected file's -// bytes are at fault, so each is a malformed or truncated target at that -// file's path; a truncated one carries the measured and needed lengths. -interface FormatOwnerRow { - readonly command: string; - readonly bytes: () => Buffer; - readonly failure: "malformed" | "truncated"; - readonly format: { readonly format: string } & Record; - readonly extra: readonly string[]; - readonly identity: boolean; -} - -for (const { command, bytes, failure, format, extra, identity } of [ - ...[ - "inspect-managed-artifact", - "inspect-managed-members", - "inspect-managed-native-boundaries", - ].map((command): FormatOwnerRow => ({ - command, - bytes: managedSectionPastEof, - failure: "malformed", - format: { format: "pe-cli", field: "pe.section-data" }, - extra: [], - identity: false, - })), - ...nativeUniversalCommands.map((command): FormatOwnerRow => ({ - command, - bytes: overlappingUniversalMacho, - failure: "malformed", - format: { format: "macho", reason: "Mach-O slices 0 and 1 overlap." }, - extra: ["--architecture", "arm64"], - identity: true, - })), - ...nativeUniversalCommands.map((command): FormatOwnerRow => ({ - command, - bytes: truncatedUniversalMacho, - failure: "truncated", - format: { format: "macho", available_bytes: 20, required_bytes: 48 }, - extra: ["--architecture", "arm64"], - identity: true, - })), -]) { - cliTest( - `${command} refuses ${failure} ${format.format} bytes as a ${failure} target`, - async ({ cli }) => { - const root = await createTestTempDirectory("rea-format-owner-"); - const path = join(root, "malformed.bin"); - const written = bytes(); - await writeFile(path, written); - const result = await cli.run({ - arguments: [command, path, ...extra, "--json"], - }); - expect(result.exitCode, result.stderr).toBe(1); - expect(result.json).toMatchObject({ - code: "unsupported_target", - category: "unsupported_target", - retryable: false, - details: { - operation: command.replaceAll("-", "_"), - path, - format_failure: failure, - ...format, - ...(identity - ? { partial_observation: fileIdentity(path, written) } - : {}), - }, - }); - expect(result.json).not.toHaveProperty("details.issues"); - expect(result.json).not.toHaveProperty("recovery"); - }, - ); -} - -/** A PE image whose first WIN_CERTIFICATE declares less than its own header. */ -const shortCertificateHeader = (): Buffer => { - const bytes = peCertificateFixture(); - bytes.writeUInt32LE(4, bytes.readUInt32LE(0x98 + 96 + 4 * 8)); - return bytes; -}; - -// Structure past the shared headers is refused by each format's own parser, -// which names its format and failure kind once for every adapter. -for (const { command, bytes, formatFailure, format } of [ - { - command: "inspect-erlang-beam", - bytes: () => Buffer.from("FOR1"), - formatFailure: "truncated", - format: "beam", - }, - { - command: "inspect-pe-certificates", - bytes: shortCertificateHeader, - formatFailure: "malformed", - format: "pe-certificate-table", - }, -] as const) - cliTest( - `${command} refuses ${formatFailure} ${format} structure as the target's`, - async ({ cli }) => { - const root = await createTestTempDirectory("rea-format-body-"); - const path = join(root, "target.bin"); - const selected = bytes(); - await writeFile(path, selected); - const result = await cli.run({ arguments: [command, path, "--json"] }); - expect(result.exitCode, result.stderr).toBe(1); - expect(result.json).toMatchObject({ - code: "unsupported_target", - category: "unsupported_target", - retryable: false, - details: { - operation: command.replaceAll("-", "_"), - path, - format_failure: formatFailure, - format, - partial_observation: fileIdentity(path, selected), - }, - }); - expect(result.json).not.toHaveProperty("recovery"); - }, - ); diff --git a/tests/acceptance/targetFailureConformance.test.ts b/tests/acceptance/targetFailureConformance.test.ts new file mode 100644 index 0000000000..0e95925b83 --- /dev/null +++ b/tests/acceptance/targetFailureConformance.test.ts @@ -0,0 +1,68 @@ +import { createHash } from "node:crypto"; +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { expect } from "vitest"; + +import { parseMcpToolError } from "../fixtures/mcpToolError.js"; +import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; +import { cliTest } from "../support/cli/cliFixture.js"; +import { TARGET_FAILURE_CONTRACT } from "../support/targetFailure/contract.js"; +import { loadTargetFailureReaders } from "../support/targetFailure/registry.js"; + +const fileIdentity = (path: string, bytes: Buffer) => ({ + kind: "file-snapshot-hash", + path, + bytes: bytes.length, + sha256: createHash("sha256").update(bytes).digest("hex"), +}); + +// One generated suite for every registered reader: each case runs through +// the CLI and the MCP adapter, and both must report the kind's contract and +// the owner's facts. +for (const { operation, cases } of await loadTargetFailureReaders()) { + const command = operation.replaceAll("_", "-"); + for (const testCase of cases) { + cliTest( + `${operation} refuses ${testCase.name} as ${testCase.kind} through CLI and MCP`, + async ({ cli }) => { + const root = await createTestTempDirectory("rea-target-failure-"); + const path = join(root, `${testCase.name}.bin`); + const bytes = testCase.bytes(); + await writeFile(path, bytes); + const expected = { + ...TARGET_FAILURE_CONTRACT[testCase.kind], + details: { + operation, + path, + failure_kind: testCase.kind, + ...testCase.facts, + ...(testCase.identity + ? { partial_observation: fileIdentity(path, bytes) } + : {}), + }, + }; + + const result = await cli.run({ + arguments: [command, path, ...(testCase.cli ?? []), "--json"], + }); + expect(result.exitCode, result.stderr).toBe(1); + expect(result.json).toMatchObject(expected); + expect(result.json).not.toHaveProperty("recovery"); + expect(result.json).not.toHaveProperty("details.issues"); + expect(result.json).not.toHaveProperty("details.format_failure"); + + const call = await cli.sharedMcpCall!(); + const response = await call(operation, { path, ...testCase.mcp }); + // A target failure is an isError tool result carrying the projected + // diagnostic as JSON text, never a JSON-RPC error. The transport + // removes the private structured carrier before sending errors. + expect(response.isError).toBe(true); + const { error } = parseMcpToolError(response); + expect(error).toMatchObject(expected); + expect(error).not.toHaveProperty("recovery"); + // A refusal never alters the caller's selected file. + expect((await readFile(path)).equals(bytes)).toBe(true); + }, + ); + } +} diff --git a/tests/acceptance/webSourceLocationCli.test.ts b/tests/acceptance/webSourceLocationCli.test.ts index 02df0973e9..90b0c75512 100644 --- a/tests/acceptance/webSourceLocationCli.test.ts +++ b/tests/acceptance/webSourceLocationCli.test.ts @@ -716,9 +716,9 @@ cliTest( environment: silentCliEnv, }); expect(refused.exitCode).toBe(1); - expect((refused.json as { code?: unknown }).code).toBe("truncated"); + expect((refused.json as { code?: unknown }).code).toBe("partial"); expect(refused.json).toMatchObject({ - code: "truncated", + code: "partial", details: { detail: expect.stringContaining("source_map_limits.map_bytes"), }, diff --git a/tests/acceptance/windowsShortcutCli.test.ts b/tests/acceptance/windowsShortcutCli.test.ts index 0799da839f..384247c1f6 100644 --- a/tests/acceptance/windowsShortcutCli.test.ts +++ b/tests/acceptance/windowsShortcutCli.test.ts @@ -280,7 +280,7 @@ cliTest("reports a wrong CLSID as a malformed target", async ({ cli }) => { details: { operation: "inspect_windows_shortcut", path, - format_failure: "malformed", + failure_kind: "malformed", }, }); }); diff --git a/tests/boundary/cli/artifactZstandardWindow.test.ts b/tests/boundary/cli/artifactZstandardWindow.test.ts index 9d6b243d41..b0bc49c7bd 100644 --- a/tests/boundary/cli/artifactZstandardWindow.test.ts +++ b/tests/boundary/cli/artifactZstandardWindow.test.ts @@ -16,7 +16,7 @@ import { ZIP_ZSTANDARD_WINDOW_CEILING } from "../../../src/resources/ZipArtifact const expectRefusal = (diagnostic: unknown, large: boolean): void => { expect(diagnostic).toMatchObject({ - code: large ? "truncated" : "artifact_operation_failed", + code: large ? "partial" : "artifact_operation_failed", details: { reason: large ? "limit" : "format", ...(large ? { boundary: "memory", truncated: true } : {}), diff --git a/tests/boundary/cli/keyedArchiveXmlNestingCli.test.ts b/tests/boundary/cli/keyedArchiveXmlNestingCli.test.ts index 0f0463686a..817655762d 100644 --- a/tests/boundary/cli/keyedArchiveXmlNestingCli.test.ts +++ b/tests/boundary/cli/keyedArchiveXmlNestingCli.test.ts @@ -32,8 +32,8 @@ for (const [name, xml] of [ }); expect(output.exitCode, output.stderr).toBe(1); expect(output.json).toMatchObject({ - code: "truncated", - category: "truncated", + code: "partial", + category: "partial", details: { reason: "limit", truncated: true, diff --git a/tests/boundary/cli/managedMemberComparisonCli.test.ts b/tests/boundary/cli/managedMemberComparisonCli.test.ts index df29c8117f..28e26c48a3 100644 --- a/tests/boundary/cli/managedMemberComparisonCli.test.ts +++ b/tests/boundary/cli/managedMemberComparisonCli.test.ts @@ -191,7 +191,7 @@ cliTest( details: { operation: "inspect_managed_members", path: side, - format_failure: "malformed", + failure_kind: "malformed", format: "pe-cli", reason: "PE section count must be positive", }, diff --git a/tests/boundary/cli/nodeSeaHashWork.test.ts b/tests/boundary/cli/nodeSeaHashWork.test.ts index fbd0344581..b915847704 100644 --- a/tests/boundary/cli/nodeSeaHashWork.test.ts +++ b/tests/boundary/cli/nodeSeaHashWork.test.ts @@ -17,7 +17,7 @@ cliTest( }); expect(result.exitCode).toBe(1); expect(result.json).toMatchObject({ - code: "truncated", + code: "partial", details: { reason: "limit", boundary: "capacity" }, }); expect((await readFile(path)).equals(bytes)).toBe(true); diff --git a/tests/boundary/filesystem/appleIps.test.ts b/tests/boundary/filesystem/appleIps.test.ts index d845578e0f..2f99b45528 100644 --- a/tests/boundary/filesystem/appleIps.test.ts +++ b/tests/boundary/filesystem/appleIps.test.ts @@ -78,7 +78,7 @@ describe("Apple IPS stable filesystem boundary", () => { const invalid = await service.inspect({ path: corrupt }); if (invalid.ok) throw new Error("Expected invalid UTF-8 failure"); expect(invalid.error).toMatchObject({ - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", failure: { detail: expect.stringContaining("UTF-8") }, }); diff --git a/tests/boundary/filesystem/asarHeaderAdmission.test.ts b/tests/boundary/filesystem/asarHeaderAdmission.test.ts index ac0f802ff4..182047c59c 100644 --- a/tests/boundary/filesystem/asarHeaderAdmission.test.ts +++ b/tests/boundary/filesystem/asarHeaderAdmission.test.ts @@ -186,7 +186,7 @@ it("names the default header admission budget and its setting when source select translateArtifactFailure("inventory_artifact", inventoryFailure), ); expect(inventory).toMatchObject({ - code: "truncated", + code: "partial", message: recovery, remediation: { action: recovery }, details: { @@ -272,7 +272,7 @@ it("applies the caller-selected environment, not the ambient one, to inventory a .runProviderAnalysis(archive, operation, {}) .then(projectCliAnalysisResult), ).resolves.toMatchObject({ - code: "truncated", + code: "partial", message: recovery, details: { maximum_header_bytes: headerBytes - 1, diff --git a/tests/boundary/filesystem/dwarfUnits.test.ts b/tests/boundary/filesystem/dwarfUnits.test.ts index 6d6f057703..c2c70230cb 100644 --- a/tests/boundary/filesystem/dwarfUnits.test.ts +++ b/tests/boundary/filesystem/dwarfUnits.test.ts @@ -29,7 +29,7 @@ describe("DWARF compile-unit stable filesystem boundary", () => { const malformedResult = await service.inspect({ path: malformed }); if (malformedResult.ok) throw new Error("Expected a malformed target"); expect(malformedResult.error).toMatchObject({ - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", operation: "inspect_dwarf_units", path: malformed, }); diff --git a/tests/boundary/filesystem/erlangBeam.test.ts b/tests/boundary/filesystem/erlangBeam.test.ts index dd9a201110..bdbb5cd3ad 100644 --- a/tests/boundary/filesystem/erlangBeam.test.ts +++ b/tests/boundary/filesystem/erlangBeam.test.ts @@ -25,7 +25,7 @@ describe("Erlang BEAM stable filesystem boundary", () => { const refused = await service.inspect({ path: malformed }); if (refused.ok) throw new Error("Expected malformed target refusal"); expect(refused.error).toMatchObject({ - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", operation: "inspect_erlang_beam", path: malformed, failure: { diff --git a/tests/boundary/filesystem/mavenGradleMetadata.test.ts b/tests/boundary/filesystem/mavenGradleMetadata.test.ts index 9e20a4886e..526ff1c69a 100644 --- a/tests/boundary/filesystem/mavenGradleMetadata.test.ts +++ b/tests/boundary/filesystem/mavenGradleMetadata.test.ts @@ -40,7 +40,7 @@ describe("Maven POM and Gradle module metadata stable filesystem boundary", () = const result = await inspect(invalid); expect(result).toMatchObject({ ok: false, - error: { _tag: "AnalysisMalformedTargetError" }, + error: { _tag: "AnalysisTargetFailureError" }, }); } const unfamiliar = await inspect( @@ -108,7 +108,7 @@ describe("Maven POM and Gradle module metadata stable filesystem boundary", () = expect(await inspect(["runtime", "runtime"])).toMatchObject({ ok: false, error: { - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", failure: { detail: expect.stringContaining("duplicate variant name"), }, @@ -117,7 +117,7 @@ describe("Maven POM and Gradle module metadata stable filesystem boundary", () = expect(await inspect([false])).toMatchObject({ ok: false, error: { - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", failure: { detail: expect.stringContaining("variant.name") }, }, }); diff --git a/tests/boundary/filesystem/nativeExports.test.ts b/tests/boundary/filesystem/nativeExports.test.ts index 28ef92ab8c..836963aff7 100644 --- a/tests/boundary/filesystem/nativeExports.test.ts +++ b/tests/boundary/filesystem/nativeExports.test.ts @@ -490,7 +490,7 @@ describe("native export encoding and failures", () => { }); // Malformed bytes are a target refusal, not a request-field error. expect(await failure({ path: malformed })).toMatchObject({ - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", operation: "inspect_native_exports", path: malformed, }); diff --git a/tests/boundary/filesystem/nativeExportsSectionless.test.ts b/tests/boundary/filesystem/nativeExportsSectionless.test.ts index a9d68a9548..75b0e4d808 100644 --- a/tests/boundary/filesystem/nativeExportsSectionless.test.ts +++ b/tests/boundary/filesystem/nativeExportsSectionless.test.ts @@ -26,7 +26,7 @@ describe("sectionless ELF export filesystem boundary", () => { expect(rejected).toMatchObject({ ok: false, error: { - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", operation: "inspect_native_exports", path: malformedPath, }, diff --git a/tests/boundary/filesystem/peCertificates.test.ts b/tests/boundary/filesystem/peCertificates.test.ts index b59b7e994b..b53ea1e6d9 100644 --- a/tests/boundary/filesystem/peCertificates.test.ts +++ b/tests/boundary/filesystem/peCertificates.test.ts @@ -35,7 +35,7 @@ describe("PE certificate stable filesystem boundary", () => { const result = await createPeCertificatesService().inspect({ path }); if (result.ok) throw new Error("Expected malformed target refusal"); expect(result.error).toMatchObject({ - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", operation: "inspect_pe_certificates", path, failure: { kind: "malformed", format: "pe-certificate-table" }, diff --git a/tests/boundary/filesystem/windowsShortcut.test.ts b/tests/boundary/filesystem/windowsShortcut.test.ts index 47029e6d71..6a75df0c82 100644 --- a/tests/boundary/filesystem/windowsShortcut.test.ts +++ b/tests/boundary/filesystem/windowsShortcut.test.ts @@ -73,7 +73,7 @@ describe("Windows shortcut stable filesystem boundary", () => { const malformedResult = await service.inspect({ path: malformed }); if (malformedResult.ok) throw new Error("Expected a malformed target"); expect(malformedResult.error).toMatchObject({ - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", operation: "inspect_windows_shortcut", path: malformed, }); diff --git a/tests/boundary/go/goBinaryProvider.test.ts b/tests/boundary/go/goBinaryProvider.test.ts index f4635fe488..76f70ddc18 100644 --- a/tests/boundary/go/goBinaryProvider.test.ts +++ b/tests/boundary/go/goBinaryProvider.test.ts @@ -6,7 +6,7 @@ import { GoBinaryService } from "../../../src/application/go/GoBinaryService.js" import { GoBinaryProvider } from "../../../src/go/GoBinaryProvider.js"; import { GO_ANALYSIS_BUDGET_DEFAULTS } from "../../../src/domain/go/goBinary.js"; import { - AnalysisMalformedTargetError, + AnalysisTargetFailureError, AnalysisResourceConstraintError, } from "../../../src/domain/analysisErrorCore.js"; import { BinaryFormatFailure } from "../../../src/domain/binaryContainer.js"; @@ -69,8 +69,8 @@ it.each([false, true])( }, }); else { - expect(result.error).toBeInstanceOf(AnalysisMalformedTargetError); - if (!(result.error instanceof AnalysisMalformedTargetError)) + expect(result.error).toBeInstanceOf(AnalysisTargetFailureError); + if (!(result.error instanceof AnalysisTargetFailureError)) throw result.error; expect(result.error.cause).toBeInstanceOf(BinaryFormatFailure); if (!(result.error.cause instanceof BinaryFormatFailure)) @@ -84,7 +84,7 @@ it.each([false, true])( expect(projected).toMatchObject({ code: "unsupported_target", details: { - format_failure: "truncated", + failure_kind: "truncated", format: "macho", field: "Mach-O load commands", offset: 32, diff --git a/tests/boundary/gpu/codeObjects.test.ts b/tests/boundary/gpu/codeObjects.test.ts index 3ed7e59ba8..699a40dfb1 100644 --- a/tests/boundary/gpu/codeObjects.test.ts +++ b/tests/boundary/gpu/codeObjects.test.ts @@ -1680,7 +1680,7 @@ it("rejects out-of-range bundle entries without guessing a payload", async () => const result = await inspect(bytes); expect(result).toMatchObject({ ok: false, - error: { _tag: "AnalysisMalformedTargetError" }, + error: { _tag: "AnalysisTargetFailureError" }, }); }); @@ -1955,7 +1955,7 @@ it("distinguishes impossible Clang bundle counts from a framed over-capacity dir const result = await inspect(bytes, { analysis: "inventory" }); if (result.ok) throw new Error("Expected malformed directory"); expect(result.error).toMatchObject({ - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", }); } const framed = Buffer.alloc(32 + 65537 * 25); @@ -2013,7 +2013,7 @@ it("checks Clang bundle ID bounds before the retained directory allowance", asyn const result = await inspect(bytes, { analysis: "inventory" }); if (result.ok) throw new Error("Expected a malformed bundle directory"); expect(result.error).toMatchObject({ - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", }); } }); diff --git a/tests/boundary/il2cpp/il2cppBinaryFile.test.ts b/tests/boundary/il2cpp/il2cppBinaryFile.test.ts index 0309d18992..148a6fabab 100644 --- a/tests/boundary/il2cpp/il2cppBinaryFile.test.ts +++ b/tests/boundary/il2cpp/il2cppBinaryFile.test.ts @@ -8,7 +8,7 @@ import { } from "../../../src/il2cpp/Il2cppBinaryImage.js"; import { AnalysisInputError, - AnalysisMalformedTargetError, + AnalysisTargetFailureError, } from "../../../src/domain/analysisErrorCore.js"; import type { Il2cppBinaryArchitecture } from "../../../src/domain/il2cpp/il2cppMetadata.js"; import { describe, expect, it } from "vitest"; @@ -145,7 +145,7 @@ const containerFailure = ( try { link(bytes, architecture); } catch (cause) { - if (cause instanceof AnalysisMalformedTargetError) + if (cause instanceof AnalysisTargetFailureError) return { path: cause.path, ...cause.failure }; throw cause; } diff --git a/tests/boundary/il2cpp/il2cppMetadataProvider.test.ts b/tests/boundary/il2cpp/il2cppMetadataProvider.test.ts index db04b5a476..a1bf904550 100644 --- a/tests/boundary/il2cpp/il2cppMetadataProvider.test.ts +++ b/tests/boundary/il2cpp/il2cppMetadataProvider.test.ts @@ -669,7 +669,7 @@ it("retains the exact source when recognized magic has no complete version", asy if (result.ok) throw new Error("Expected truncated metadata prefix"); expect(result.error).toMatchObject({ - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", path, failure: { kind: "truncated", @@ -880,7 +880,7 @@ it.each([false, true])( expect(ordinary).toMatchObject({ ok: false, error: { - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", path: binary_path, failure: { kind: "malformed", @@ -929,7 +929,7 @@ it("refuses duplicate MethodDef tokens before publishing linked Evidence or Ghid details: { path, format: "il2cpp-metadata", - format_failure: "malformed", + failure_kind: "malformed", reason: expect.stringMatching(/^invalid-method-definition-token:/u), }, }); @@ -1179,7 +1179,7 @@ it("names the metadata, not the binary, when linking reads a malformed metadata const result = await provider.inspect({ path, binary_path: binaryPath }); if (result.ok) throw new Error("Expected the metadata name to be refused"); expect(result.error).toMatchObject({ - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", path, failure: { kind: "malformed", diff --git a/tests/boundary/mcp/androidBootImageMcp.test.ts b/tests/boundary/mcp/androidBootImageMcp.test.ts index c9d37b8541..8d08b223e1 100644 --- a/tests/boundary/mcp/androidBootImageMcp.test.ts +++ b/tests/boundary/mcp/androidBootImageMcp.test.ts @@ -134,7 +134,7 @@ it("keeps Android parser refusal kinds and recovers through compiled MCP", async operation: "inspect_artifact", reason: fixture.kind, ...("format" in fixture - ? { format_failure: fixture.kind, format: fixture.format } + ? { failure_kind: fixture.kind, format: fixture.format } : {}), }, }); diff --git a/tests/boundary/mcp/asarListingAdmissionMcp.test.ts b/tests/boundary/mcp/asarListingAdmissionMcp.test.ts index 9179da2a84..90e5655e0c 100644 --- a/tests/boundary/mcp/asarListingAdmissionMcp.test.ts +++ b/tests/boundary/mcp/asarListingAdmissionMcp.test.ts @@ -22,8 +22,8 @@ mcpTest( client.callTool({ name: "inspect_artifact", arguments: {} }); const refused = await inspect(); expect(parseMcpToolError(refused).error).toMatchObject({ - code: "truncated", - category: "truncated", + code: "partial", + category: "partial", details: { admission: "asar-listing", limit: { setting: "asar.max_listing_bytes", unit: "bytes" }, diff --git a/tests/boundary/mcp/bunStandaloneMcp.test.ts b/tests/boundary/mcp/bunStandaloneMcp.test.ts index a019373761..3f032f43d7 100644 --- a/tests/boundary/mcp/bunStandaloneMcp.test.ts +++ b/tests/boundary/mcp/bunStandaloneMcp.test.ts @@ -91,7 +91,7 @@ it("keeps a budget-limited Bun layout unresolved through MCP", async () => { }); expect(reply.isError).toBe(true); expect(parseMcpToolError(reply).error).toMatchObject({ - code: moduleCount < 13 ? "truncated" : "artifact_operation_failed", + code: moduleCount < 13 ? "partial" : "artifact_operation_failed", retryable: moduleCount < 13, details: moduleCount < 13 diff --git a/tests/boundary/mcp/elfNotesMcp.test.ts b/tests/boundary/mcp/elfNotesMcp.test.ts index a930531f1a..9090824bd8 100644 --- a/tests/boundary/mcp/elfNotesMcp.test.ts +++ b/tests/boundary/mcp/elfNotesMcp.test.ts @@ -177,7 +177,7 @@ mcpTest( details: { operation: "inspect_elf_notes", path, - format_failure: "malformed", + failure_kind: "malformed", format: "elf", }, }); diff --git a/tests/boundary/mcp/erlangBeamMcp.test.ts b/tests/boundary/mcp/erlangBeamMcp.test.ts index b03bd72428..32595ff727 100644 --- a/tests/boundary/mcp/erlangBeamMcp.test.ts +++ b/tests/boundary/mcp/erlangBeamMcp.test.ts @@ -163,7 +163,7 @@ mcpTest( }); expect(parseMcpToolError(response).error).toMatchObject({ code: "unsupported_target", - details: { format_failure: "truncated", format: "beam" }, + details: { failure_kind: "truncated", format: "beam" }, }); } finally { await session.close(); @@ -240,7 +240,7 @@ mcpTest( expect(parseMcpToolError(response).error).toMatchObject({ code: "unsupported_target", details: { - format_failure: "truncated", + failure_kind: "truncated", format: "beam", reason: expect.stringContaining("lambda table is truncated"), }, diff --git a/tests/boundary/mcp/goBinaryMcp.test.ts b/tests/boundary/mcp/goBinaryMcp.test.ts index 7aac6ffa1c..17101522e9 100644 --- a/tests/boundary/mcp/goBinaryMcp.test.ts +++ b/tests/boundary/mcp/goBinaryMcp.test.ts @@ -279,7 +279,11 @@ goMcpTest( name: "inspect_go_binary", arguments: { path }, }); - expect(parseMcpToolError(response)).toMatchObject({ + expect( + response.isError, + `${fixture.name} returned a non-error result: ${JSON.stringify(response).slice(0, 2000)}`, + ).toBe(true); + expect(parseMcpToolError(response), fixture.name).toMatchObject({ error: { code: fixture.code, details: { diff --git a/tests/boundary/mcp/nodeSeaMcp.test.ts b/tests/boundary/mcp/nodeSeaMcp.test.ts index 0a25dd1f8f..4024282a81 100644 --- a/tests/boundary/mcp/nodeSeaMcp.test.ts +++ b/tests/boundary/mcp/nodeSeaMcp.test.ts @@ -71,7 +71,7 @@ it.each(["compact"] as const)( artifact_limits: { node_sea: { asset_count: 1 } }, }); expect(parseMcpToolError(assetRefusal).error).toMatchObject({ - code: "truncated", + code: "partial", retryable: true, details: { operation: "inspect_artifact", @@ -205,7 +205,7 @@ it("reports the PE parser budget when Node SEA inventory exhausts it", async () expect(opened.isError, JSON.stringify(opened)).not.toBe(true); const reply = await call("inspect_artifact", {}); expect(parseMcpToolError(reply).error).toMatchObject({ - code: "truncated", + code: "partial", retryable: false, details: { operation: "inspect_artifact", diff --git a/tests/boundary/mcp/pythonPycMcp.test.ts b/tests/boundary/mcp/pythonPycMcp.test.ts index eeffa627df..009843bac1 100644 --- a/tests/boundary/mcp/pythonPycMcp.test.ts +++ b/tests/boundary/mcp/pythonPycMcp.test.ts @@ -103,7 +103,7 @@ it("reads signed TYPE_INT64 constants and rejects a truncated payload", async () code: "unsupported_target", details: { operation: "inspect_python_pyc", - format_failure: expect.stringMatching(/^(?:malformed|truncated)$/u), + failure_kind: expect.stringMatching(/^(?:malformed|truncated)$/u), reason: expect.stringContaining("64-bit integer"), }, }); @@ -233,7 +233,7 @@ it("rejects negative code fields for magics after constructor validation was add code: "unsupported_target", details: { operation: "inspect_python_pyc", - format_failure: expect.stringMatching(/^(?:malformed|truncated)$/u), + failure_kind: expect.stringMatching(/^(?:malformed|truncated)$/u), reason: expect.stringContaining("co_flags is negative"), }, }); diff --git a/tests/boundary/mcp/rustBinaryMcp.test.ts b/tests/boundary/mcp/rustBinaryMcp.test.ts index b759513390..31dc2a5ed4 100644 --- a/tests/boundary/mcp/rustBinaryMcp.test.ts +++ b/tests/boundary/mcp/rustBinaryMcp.test.ts @@ -171,7 +171,7 @@ mcpTest( code: "unsupported_target", details: { operation: "inspect_rust_binary", - format_failure: expect.stringMatching(/^(?:malformed|truncated)$/u), + failure_kind: expect.stringMatching(/^(?:malformed|truncated)$/u), }, }); } finally { diff --git a/tests/boundary/mcp/targetFailureToolResult.test.ts b/tests/boundary/mcp/targetFailureToolResult.test.ts new file mode 100644 index 0000000000..e142b021b7 --- /dev/null +++ b/tests/boundary/mcp/targetFailureToolResult.test.ts @@ -0,0 +1,58 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { expect } from "vitest"; + +import { machoImage } from "../../../src/artifacts/apple/MachoImage.fixture.js"; +import { AnalysisTargetFailureError } from "../../../src/domain/analysisErrorCore.js"; +import { createServer } from "../../../src/server/createServer.js"; +import { createTestBinarySession } from "../../fixtures/binarySession.js"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { mcpTest } from "../../support/mcp/mcpFixture.js"; + +// The SDK flattens anything a handler throws into one text block, and JSON-RPC +// errors are for protocol faults. A target failure a provider throws must +// still reach the client as an `isError` tool result carrying the projection. +mcpTest( + "returns a thrown target failure as a tool result, not a JSON-RPC error", + async ({ mcp }) => { + const root = await createTestTempDirectory("rea-target-failure-mcp-"); + const path = join(root, "target.bin"); + await writeFile( + path, + machoImage({ cpu: { type: 0x0100000c, subtype: 0 }, wide: true }), + ); + const session = createTestBinarySession(() => { + throw new AnalysisTargetFailureError("open_binary", path, { + kind: "malformed", + format: "macho", + detail: "load command runs past the image", + offset: 32, + }); + }); + try { + const client = await mcp.connect( + createServer({ kind: "session", session }), + ); + // A JSON-RPC error would reject this call. + const response = await client.callTool({ + name: "open_binary", + arguments: { path }, + }); + expect(parseMcpToolError(response).error).toMatchObject({ + code: "unsupported_target", + retry: "none", + details: { + path, + failure_kind: "malformed", + format: "macho", + offset: 32, + }, + }); + // The session survives the refusal and keeps answering requests. + await expect(client.ping()).resolves.toBeDefined(); + } finally { + await session.close(); + } + }, +); diff --git a/tests/boundary/mcp/universalSliceMcp.test.ts b/tests/boundary/mcp/universalSliceMcp.test.ts index fb30a81618..7ddc86b111 100644 --- a/tests/boundary/mcp/universalSliceMcp.test.ts +++ b/tests/boundary/mcp/universalSliceMcp.test.ts @@ -270,7 +270,7 @@ sliceTest( code: "unsupported_target", details: { path: damaged, - format_failure: "malformed", + failure_kind: "malformed", format: "macho", reason: "FAT architecture 0 slice range extends beyond the file", }, @@ -290,7 +290,7 @@ sliceTest( code: "unsupported_target", details: { path: cutOff, - format_failure: "truncated", + failure_kind: "truncated", format: "macho", available_bytes: 20, required_bytes: 28, @@ -320,7 +320,7 @@ sliceTest( code: "unsupported_target", details: { path: disagreeing, - format_failure: "malformed", + failure_kind: "malformed", format: "macho", reason: "FAT architecture 0 CPU type/subtype disagrees with its Mach-O header", @@ -451,7 +451,7 @@ sliceTest( code: "unsupported_target", details: { path, - format_failure: "malformed", + failure_kind: "malformed", format: "macho", reason: "Mach-O slices 0 and 1 overlap.", }, diff --git a/tests/boundary/mcp/v8CodeCacheMcp.test.ts b/tests/boundary/mcp/v8CodeCacheMcp.test.ts index c66869e022..4b610ec4f5 100644 --- a/tests/boundary/mcp/v8CodeCacheMcp.test.ts +++ b/tests/boundary/mcp/v8CodeCacheMcp.test.ts @@ -107,7 +107,7 @@ mcpTest( code: "unsupported_target", details: { operation: "inspect_v8_code_cache", - format_failure: expect.stringMatching(/^(?:malformed|truncated)$/u), + failure_kind: expect.stringMatching(/^(?:malformed|truncated)$/u), partial_observation: { kind: "file-snapshot-hash", path, diff --git a/tests/boundary/model/modelArtifact.test.ts b/tests/boundary/model/modelArtifact.test.ts index c4138ce22d..ddad5ead24 100644 --- a/tests/boundary/model/modelArtifact.test.ts +++ b/tests/boundary/model/modelArtifact.test.ts @@ -29,7 +29,7 @@ import { /** A malformed model header is a malformed target, like every format failure. */ const MALFORMED_TARGET = { - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", operation: "inspect_model_artifact", } as const; diff --git a/tests/boundary/providers/native/artifactProvider.capacity.test.ts b/tests/boundary/providers/native/artifactProvider.capacity.test.ts index a989bdfb73..df2300f352 100644 --- a/tests/boundary/providers/native/artifactProvider.capacity.test.ts +++ b/tests/boundary/providers/native/artifactProvider.capacity.test.ts @@ -42,7 +42,7 @@ it.each([1, 129])( expect(bytes.length).toBeLessThan(16_384); const projected = projectAnalysisError(result.error); expect(projected).toMatchObject({ - code: "truncated", + code: "partial", retryable: false, message: expect.stringMatching(/PyInstaller.*PYZ.*128.file.*budget/iu), details: { boundary: "capacity" }, diff --git a/tests/boundary/providers/native/nativeSelectedArchitecture.test.ts b/tests/boundary/providers/native/nativeSelectedArchitecture.test.ts index 3adec20769..125a801f6b 100644 --- a/tests/boundary/providers/native/nativeSelectedArchitecture.test.ts +++ b/tests/boundary/providers/native/nativeSelectedArchitecture.test.ts @@ -344,7 +344,7 @@ it.each([ expect(result.ok).toBe(false); if (result.ok) throw new Error("Mismatched FAT slice was admitted"); expect(result.error).toMatchObject({ - _tag: "AnalysisMalformedTargetError", + _tag: "AnalysisTargetFailureError", failure: { detail: expect.stringContaining( "Selected lipo slice does not identify exactly one FAT entry", diff --git a/tests/fixtures/androidBootImage.ts b/tests/fixtures/androidBootImage.ts index 1c913cfc25..7258d4016c 100644 --- a/tests/fixtures/androidBootImage.ts +++ b/tests/fixtures/androidBootImage.ts @@ -418,8 +418,8 @@ export const androidBootImageRefusals = () => { name: "short-image", bytes: truncateImage(buildBootImage({ version: 0 })), kind: "truncated", - code: "truncated", - category: "truncated", + code: "unsupported_target", + category: "unsupported_target", format: "android-boot-image", }, { diff --git a/tests/support/targetFailure/contract.ts b/tests/support/targetFailure/contract.ts new file mode 100644 index 0000000000..fb0dd21561 --- /dev/null +++ b/tests/support/targetFailure/contract.ts @@ -0,0 +1,69 @@ +import type { + TargetFailureKind, + TargetFailureRetry, +} from "../../../src/domain/targetFailure.js"; + +/** + * The public target-failure contract, spelled out independently of the + * projection table so a change to the table fails its tests. It matches + * `docs/reference/target-failures.md`. + */ +export const TARGET_FAILURE_CONTRACT = { + selection: { + code: "invalid_request", + category: "invalid_input", + retry: "after_change", + }, + unrecognized: { + code: "unsupported_target", + category: "unsupported_target", + retry: "none", + }, + unsupported: { + code: "unsupported_target", + category: "unsupported_target", + retry: "none", + }, + malformed: { + code: "unsupported_target", + category: "unsupported_target", + retry: "none", + }, + truncated: { + code: "unsupported_target", + category: "unsupported_target", + retry: "none", + }, + integrity: { + code: "target_integrity_mismatch", + category: "integrity_mismatch", + retry: "none", + }, + conflict: { + code: "input_conflict", + category: "invalid_input", + retry: "after_change", + }, + changed: { + code: "artifact_changed", + category: "integrity_mismatch", + retry: "backoff", + }, + access: { + code: "access_denied", + category: "unavailable", + retry: "after_change", + }, + io: { + code: "host_io_failed", + category: "execution_failure", + retry: "none", + }, +} as const satisfies Record< + TargetFailureKind, + { + readonly code: string; + readonly category: string; + readonly retry: TargetFailureRetry; + } +>; diff --git a/tests/support/targetFailure/readers/peHeaders.ts b/tests/support/targetFailure/readers/peHeaders.ts new file mode 100644 index 0000000000..37fc703765 --- /dev/null +++ b/tests/support/targetFailure/readers/peHeaders.ts @@ -0,0 +1,31 @@ +import { peImportImage } from "../../../fixtures/binaryDiagnostics/peImports.js"; +import { peLoadConfigImage } from "../../../../src/native/pe/PeLoadConfig.fixture.js"; +import { targetFailureReaders, type TargetFailureCase } from "../registry.js"; + +/** A valid image whose DOS signature is replaced, so the PE owner refuses it. */ +const withoutMz = ( + image: (options: { readonly bits: 32 | 64 }) => Buffer, +): TargetFailureCase[] => + ([32, 64] as const).flatMap((bits) => + ( + [ + ["zz", Buffer.from("ZZ")], + ["high-bit", Buffer.from([0xcd, 0xda])], + ] as const + ).map(([name, prefix]) => ({ + name: `pe${String(bits)}-${name}-dos-signature`, + kind: "malformed" as const, + bytes: () => { + const bytes = image({ bits }); + prefix.copy(bytes); + return bytes; + }, + identity: false, + })), + ); + +/** PE readers that refuse a corrupt DOS header before reading their tables. */ +export default targetFailureReaders([ + { operation: "inspect_pe_imports", cases: withoutMz(peImportImage) }, + { operation: "inspect_pe_load_config", cases: withoutMz(peLoadConfigImage) }, +]); diff --git a/tests/support/targetFailure/readers/selectedFileFormats.ts b/tests/support/targetFailure/readers/selectedFileFormats.ts new file mode 100644 index 0000000000..7125fa0df7 --- /dev/null +++ b/tests/support/targetFailure/readers/selectedFileFormats.ts @@ -0,0 +1,163 @@ +import { + fatImage, + machoImage, +} from "../../../../src/artifacts/apple/MachoImage.fixture.js"; +import { buildManagedPeFixture } from "../../../../src/dotnet/ManagedPe.fixture.js"; +import { peCertificateFixture } from "../../../../src/native/pe/PeCertificates.fixture.js"; +import { appleIpsBytes } from "../../../fixtures/binaryDiagnostics/appleIps.js"; +import { targetFailureReaders, type TargetFailureCase } from "../registry.js"; + +/** An ELF magic with nothing after it: every ELF-reading owner refuses it. */ +const truncatedElfHeader: TargetFailureCase = { + name: "elf-magic-only", + kind: "malformed", + bytes: () => Buffer.from("\x7fELF"), + identity: true, +}; + +/** A managed PE whose first section's raw data starts past the end of the file. */ +const managedSectionPastEof = (): Buffer => { + const bytes = buildManagedPeFixture(); + const pe = bytes.readUInt32LE(0x3c); + const sections = pe + 24 + bytes.readUInt16LE(pe + 20); + bytes.writeUInt32LE(bytes.length + 0x1000, sections + 20); + return bytes; +}; + +/** A universal Mach-O whose first declared slice runs into the second. */ +const overlappingUniversalMacho = (): Buffer => { + const slice = (type: number, subtype: number) => ({ + cpu: { type, subtype }, + bytes: machoImage({ cpu: { type, subtype }, wide: true }), + }); + const bytes = Buffer.from( + fatImage([slice(0x01000007, 3), slice(0x0100000c, 0)]), + ); + const first = bytes.readUInt32BE(8 + 8); + const second = bytes.readUInt32BE(8 + 20 + 8); + bytes.writeUInt32BE(second - first + 16, 8 + 12); + return bytes; +}; + +/** A universal Mach-O cut off inside its FAT table: 20 of its 48 table bytes. */ +const truncatedUniversalMacho = (): Buffer => { + const slice = (type: number, subtype: number) => ({ + cpu: { type, subtype }, + bytes: machoImage({ cpu: { type, subtype }, wide: true }), + }); + return Buffer.from( + fatImage([slice(0x01000007, 3), slice(0x0100000c, 0)]), + ).subarray(0, 20); +}; + +/** A PE image whose first WIN_CERTIFICATE declares less than its own header. */ +const shortCertificateHeader = (): Buffer => { + const bytes = peCertificateFixture(); + bytes.writeUInt32LE(4, bytes.readUInt32LE(0x98 + 96 + 4 * 8)); + return bytes; +}; + +const truncatedSlices: TargetFailureCase = { + name: "macho-fat-table-cut-off", + kind: "truncated", + bytes: truncatedUniversalMacho, + facts: { format: "macho", available_bytes: 20, required_bytes: 48 }, + cli: ["--architecture", "arm64"], + mcp: { architecture: "arm64" }, + identity: true, +}; + +const managedCase: TargetFailureCase = { + name: "pe-cli-section-past-eof", + kind: "malformed", + bytes: managedSectionPastEof, + facts: { format: "pe-cli", field: "pe.section-data" }, + identity: false, +}; + +const overlappingSlices: TargetFailureCase = { + name: "macho-overlapping-slices", + kind: "malformed", + bytes: overlappingUniversalMacho, + facts: { format: "macho", reason: "Mach-O slices 0 and 1 overlap." }, + cli: ["--architecture", "arm64"], + mcp: { architecture: "arm64" }, + identity: true, +}; + +/** + * Selected-file readers whose format owner raises its parse failure once. + * The selected file's bytes are at fault, not the request. + */ +export default targetFailureReaders([ + ...[ + "inspect_python_pyc", + "inspect_elf_notes", + "inspect_elf_dependencies", + "inspect_elf_debug_link", + "inspect_elf_unwind_ranges", + "inspect_devicetree", + "inspect_pe_imports", + "inspect_kernel_module", + "inspect_pe_load_config", + "inspect_pe_resources", + "inspect_native_exports", + "inspect_binary_hardening", + ].map((operation) => ({ operation, cases: [truncatedElfHeader] })), + ...[ + "inspect_go_binary", + "inspect_rust_binary", + "inspect_native_initializers", + ].map((operation) => ({ + operation, + cases: [truncatedElfHeader, overlappingSlices, truncatedSlices], + })), + { + operation: "inspect_dwarf_units", + cases: [overlappingSlices, truncatedSlices], + }, + { + operation: "inspect_apple_ips", + cases: [ + truncatedElfHeader, + { + // The JSON body ends inside its declared report object. + name: "ips-truncated-body", + kind: "malformed", + bytes: () => appleIpsBytes({ truncateBody: true }), + identity: true, + }, + ], + }, + { + operation: "inspect_erlang_beam", + cases: [ + truncatedElfHeader, + { + name: "beam-form-header-only", + kind: "truncated", + bytes: () => Buffer.from("FOR1"), + facts: { format: "beam" }, + identity: true, + }, + ], + }, + { + operation: "inspect_pe_certificates", + cases: [ + truncatedElfHeader, + { + name: "short-certificate-header", + kind: "malformed", + bytes: shortCertificateHeader, + facts: { format: "pe-certificate-table" }, + identity: true, + }, + ], + }, + ...[ + "inspect_managed_artifact", + "inspect_managed_members", + "inspect_managed_native_boundaries", + ].map((operation) => ({ operation, cases: [managedCase] })), +]); diff --git a/tests/support/targetFailure/registry.ts b/tests/support/targetFailure/registry.ts new file mode 100644 index 0000000000..6a3a9c7e67 --- /dev/null +++ b/tests/support/targetFailure/registry.ts @@ -0,0 +1,67 @@ +import { readdir } from "node:fs/promises"; + +import type { TargetFailureKind } from "../../../src/domain/targetFailure.js"; + +/** + * One case of a reader's target-failure contract: bytes the reader must + * refuse with `kind`, and the owner facts the refusal must carry. + */ +export interface TargetFailureCase { + /** A short name that is unique within its reader entry. */ + readonly name: string; + readonly kind: TargetFailureKind; + readonly bytes: () => Buffer; + /** Owner facts the refusal reports, such as `format`, `offset` or `field`. */ + readonly facts?: Readonly>; + /** Extra arguments after the path, as CLI flags and as MCP arguments. */ + readonly cli?: readonly string[]; + readonly mcp?: Readonly>; + /** + * Whether the refusal keeps the completed file identity. Readers that + * refuse before they hash the file report none. + */ + readonly identity: boolean; +} + +/** Every case one public operation must pass, through both adapters. */ +export interface TargetFailureReader { + /** The MCP tool name; the CLI command is its kebab-case spelling. */ + readonly operation: string; + readonly cases: readonly TargetFailureCase[]; +} + +/** + * Register readers from one area. Each area owns a module in `readers/`, so + * adding a reader never edits a shared table. + */ +export const targetFailureReaders = ( + readers: readonly TargetFailureReader[], +): readonly TargetFailureReader[] => readers; + +const READERS = new URL("./readers/", import.meta.url); + +/** Every registered reader, from every area module, in a stable order. */ +export const loadTargetFailureReaders = async (): Promise< + readonly TargetFailureReader[] +> => { + const modules = (await readdir(READERS)) + .filter((name) => name.endsWith(".ts")) + .sort(); + const readers: TargetFailureReader[] = []; + for (const name of modules) { + const module = (await import(new URL(name, READERS).href)) as { + readonly default?: readonly TargetFailureReader[]; + }; + if (module.default === undefined) + throw new Error(`Target failure module ${name} has no default export`); + readers.push(...module.default); + } + const seen = new Set(); + for (const { operation, cases } of readers) + for (const { name } of cases) { + const key = `${operation}/${name}`; + if (seen.has(key)) throw new Error(`Duplicate conformance case ${key}`); + seen.add(key); + } + return readers; +};