diff --git a/docs/error-contract.schema.json b/docs/error-contract.schema.json index aed6718305e..ded55f8acac 100644 --- a/docs/error-contract.schema.json +++ b/docs/error-contract.schema.json @@ -22,6 +22,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -98,6 +102,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -174,6 +182,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -250,6 +262,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -326,6 +342,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -402,6 +422,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -478,6 +502,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -554,6 +582,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -630,6 +662,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -706,6 +742,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -782,6 +822,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -971,6 +1015,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -1047,6 +1095,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -1123,6 +1175,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -1199,6 +1255,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -1275,6 +1335,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -1351,6 +1415,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -1427,6 +1495,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -1503,6 +1575,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -1579,6 +1655,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -1655,6 +1735,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -1731,6 +1815,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] @@ -1807,6 +1895,10 @@ }, "message": { "type": "string", "minLength": 1 }, "retryable": { "type": "boolean" }, + "retry_class": { + "type": "string", + "enum": ["same_call", "change_first", "never", "unknown_outcome"] + }, "retry": { "type": "string", "enum": ["none", "backoff", "after_change"] diff --git a/docs/reference/mcp-contracts.md b/docs/reference/mcp-contracts.md index d168a687aea..434f627665b 100644 --- a/docs/reference/mcp-contracts.md +++ b/docs/reference/mcp-contracts.md @@ -252,7 +252,14 @@ metadata in the supported JSON payloads (`parameters`, `raw_result`, Tool execution failures return `isError: true` and the complete canonical `{ "error": ... }` diagnostic as JSON in text `content`. Read that diagnostic for the error code, target details, partial observations, remediation, and the -optional bounded `recovery` next step. `recovery.kind=inspect_input_contract` +optional bounded `recovery` next step. `retry_class` says what must happen +before the request can succeed, as the failure's producer declared it: +`same_call` (the unchanged request may succeed later), `change_first` (change +the request or the state it reads first, as `remediation.action` says), +`never` (no change to this request clears it) or `unknown_outcome` (the +request may have taken effect; reconcile state before repeating it). +`retryable` is true exactly when `retry_class` is `same_call`. Errors retained +in Evidence by earlier releases may omit `retry_class`. `recovery.kind=inspect_input_contract` names the rejected operation: re-read that operation's advertised input schema (call `tools/list` if the catalog may be stale), correct the listed fields, and do not repeat the unchanged call. A well-formed request the selected target @@ -546,8 +553,9 @@ unproven verified resolutions with nonretryable `invalid_request` diagnostics. missing `evidence_id` or `related_unknown_id` where applicable. Correct the reported input or supply the required retained Evidence; unchanged retries do not repair these constraints. Rejected mutations leave retained state unchanged. -Revision conflicts remain retryable `revision_conflict`; broken revision histories -remain `evidence_integrity_mismatch`. +A revision conflict is a nonretryable `revision_conflict`: `details.current_revision` +names the stored revision to update from. Broken revision histories remain +`evidence_integrity_mismatch`. `list_unknowns` returns every matching current head by default. For a smaller inline response, supply `offset` and `limit`, then follow `next_offset` until it @@ -572,9 +580,11 @@ contributes to the stable unknown ID, so the same question can have different IDs under different scopes. Check the active target before recording a target-scoped unknown; creating one in a target-free session does not infer a target from its supporting Evidence. -Duplicate creation is a nonretryable `invalid_request`; use the existing head -or update it with its current `expected_revision`. A stale update remains a -retryable `revision_conflict`. An `update_unknown` revision keeps the unknown’s +Duplicate creation is a nonretryable `invalid_request` whose +`details.existing_unknown_id` names the existing head; use it or update it with +its current `expected_revision`. A stale update is a nonretryable +`revision_conflict` that reports `details.current_revision`; review that state +and retry with it as `expected_revision`. An `update_unknown` revision keeps the unknown’s original `scope_digest`. Its mutation Evidence subject is the active binary analysis target, or null without one, so it can differ from the unknown’s scope. diff --git a/docs/reference/target-failures.md b/docs/reference/target-failures.md index 87b5eedecb3..d84683f5106 100644 --- a/docs/reference/target-failures.md +++ b/docs/reference/target-failures.md @@ -33,7 +33,7 @@ A caller's cancellation (`cancelled`) and an admission limit (`resource_constrai | `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`. +`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`, and `retry_class` maps `backoff`, `after_change` and `none` to `same_call`, `change_first` and `never`. ## Details diff --git a/docs/user-visible-errors.csv b/docs/user-visible-errors.csv index b88a0eb2b47..980f862ae68 100644 --- a/docs/user-visible-errors.csv +++ b/docs/user-visible-errors.csv @@ -1,111 +1,117 @@ -tag,discriminant,code,category,retryable_by_default -AnalysisProtocolError,,unreadable_output,execution_failure,false -AnalysisOutputError,,unreadable_output,execution_failure,false -AnalysisInputError,,invalid_request,invalid_input,false -AnalysisAccessDeniedError,,access_denied,unavailable,false -AnalysisArtifactChangedError,,artifact_changed,integrity_mismatch,true -AnalysisCapabilityUnavailableError,,capability_unavailable,unsupported_provider,false -AnalysisCancelledError,,cancelled,cancelled,true -AnalysisTimeoutError,,provider_timeout,timeout,true -AnalysisResourceConstraintError,,resource_constraint,resource_constraint,false -ConfigurationError,,configuration_invalid,invalid_input,false -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=integrity,artifact_operation_failed,integrity_mismatch,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 -ArtifactOperationError,reason=integrity; artifact identity reported,artifact_integrity_mismatch,integrity_mismatch,false -ArtifactOperationError,reason=integrity; target changed during the read,artifact_changed,integrity_mismatch,true -BinaryTargetError,constraint=unconstrained,target_unavailable,unavailable,false -BinaryTargetError,constraint=unconstrained; read permission denied,access_denied,unavailable,false -BinaryTargetError,constraint=directory_requires_file,target_unavailable,unavailable,false -BinaryTargetError,constraint=directory_requires_file; read permission denied,access_denied,unavailable,false -BinaryTargetError,constraint=wasm_requires_static_inspection,target_unavailable,unsupported_target,false -BinaryTargetError,constraint=wasm_requires_static_inspection; read permission denied,access_denied,unsupported_target,false -BinaryTargetError,constraint=file_format_rejected,target_unavailable,unsupported_target,false -BinaryTargetError,constraint=file_format_rejected; read permission denied,access_denied,unsupported_target,false -BinaryTargetError,constraint=load_selection_rejected,invalid_request,invalid_input,false -BinaryTargetError,constraint=bundle_type_unsupported,target_unavailable,unsupported_target,false -BinaryTargetError,constraint=bundle_type_unsupported; read permission denied,access_denied,unsupported_target,false -BinaryTargetError,constraint=bundle_info_plist_decode_budget_exceeded,target_unavailable,unavailable,false -BinaryTargetError,constraint=bundle_info_plist_decode_budget_exceeded; read permission denied,access_denied,unavailable,false -BinaryTargetError,constraint=bundle_info_plist_missing,target_unavailable,unavailable,false -BinaryTargetError,constraint=bundle_info_plist_missing; read permission denied,access_denied,unavailable,false -BinaryTargetError,constraint=bundle_layout_ambiguous,target_unavailable,unavailable,false -BinaryTargetError,constraint=bundle_layout_ambiguous; read permission denied,access_denied,unavailable,false -BinaryTargetError,constraint=bundle_executable_undeclared,target_unavailable,unavailable,false -BinaryTargetError,constraint=bundle_executable_undeclared; read permission denied,access_denied,unavailable,false -BinaryTargetError,constraint=bundle_program_missing,target_unavailable,unavailable,false -BinaryTargetError,constraint=bundle_program_missing; read permission denied,access_denied,unavailable,false -BinaryTargetError,constraint=bundle_current_version_missing,target_unavailable,unavailable,false -BinaryTargetError,constraint=bundle_current_version_missing; read permission denied,access_denied,unavailable,false -BinaryTargetError,constraint=bundle_path_escapes,target_unavailable,unavailable,false -BinaryTargetError,constraint=bundle_path_escapes; read permission denied,access_denied,unavailable,false -BrowserObservationError,reason=endpoint_unreachable,provider_unavailable,unavailable,true -BrowserObservationError,reason=invalid_endpoint_response,unreadable_output,execution_failure,false -BrowserObservationError,reason=target_not_found,target_unavailable,unavailable,false -BrowserObservationError,reason=target_not_allowed,target_unavailable,unavailable,false -BrowserObservationError,reason=application_already_running,target_unavailable,unavailable,false -BrowserObservationError,reason=service_worker_blocked,target_unavailable,unavailable,false -BrowserObservationError,reason=target_changed,target_unavailable,unavailable,false -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,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 -BrowserObservationError,reason=cleanup_failed,execution_failure,execution_failure,false -BrowserObservationError,reason=cancelled,cancelled,cancelled,true -BrowserObservationError,reason=timeout,provider_timeout,timeout,true -BrowserObservationError,caused by cancellation,cancelled,cancelled,true -EvidenceFileError,reason=not-file,invalid_request,invalid_input,false -EvidenceFileError,reason=exists,invalid_request,invalid_input,false -EvidenceFileError,reason=wrong-kind,invalid_request,invalid_input,false -EvidenceFileError,reason=missing,invalid_request,invalid_input,false -EvidenceFileError,reason=symlink-traversal,invalid_request,invalid_input,false -EvidenceFileError,reason=invalid-json,evidence_integrity_mismatch,execution_failure,false -EvidenceFileError,reason=path-limit,resource_constraint,resource_constraint,false -EvidenceFileError,reason=storage-limit,resource_constraint,resource_constraint,false -EvidenceFileError,reason=io,execution_failure,execution_failure,false -ProcessCaptureError,,process_capture_failed,execution_failure,false -ProcessCaptureError,caused by cancellation,cancelled,cancelled,true -ProviderSelectionError,reason=unknown_provider,capability_unavailable,unsupported_provider,false -ProviderSelectionError,reason=provider_unavailable,provider_unavailable,unavailable,true -ProviderSelectionError,reason=target_unsupported,capability_unavailable,unsupported_provider,false -ProviderSelectionError,reason=ambiguous,capability_unavailable,unsupported_provider,false -ProviderSelectionError,reason=invalid_options,capability_unavailable,unsupported_provider,false -UnknownRegistryError,reason=not-found,execution_failure,execution_failure,false -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,partial,execution_failure,false -UnknownRegistryError,reason=constraint,invalid_request,invalid_input,false -HopperTimeoutError,,provider_timeout,timeout,true -HopperCancelledError,,cancelled,cancelled,true -HopperProtocolError,,unreadable_output,execution_failure,false -HopperRemoteError,diagnostic_type=remote,execution_failure,execution_failure,false -HopperRemoteError,diagnostic_type=authorization,execution_failure,unavailable,false -HopperRemoteError,diagnostic_type=invalid_request,invalid_request,invalid_input,false -HopperRemoteError,diagnostic_type=selector_not_found,invalid_request,invalid_input,false -HopperRemoteError,diagnostic_type=capability_unavailable,execution_failure,execution_failure,false -HopperRemoteError,diagnostic_type=bridge_exception,execution_failure,execution_failure,false -HopperProcessError,,provider_unavailable,unavailable,true -HopperStartError,,provider_unavailable,unavailable,true -HopperStartError,Apple Events authorization denied,provider_unavailable,unavailable,false +tag,discriminant,code,category,retry,retryable_by_default +AnalysisProtocolError,,unreadable_output,execution_failure,never,false +AnalysisOutputError,,unreadable_output,execution_failure,never,false +AnalysisInputError,,invalid_request,invalid_input,change_first,false +AnalysisAccessDeniedError,,access_denied,unavailable,change_first,false +AnalysisArtifactChangedError,,artifact_changed,integrity_mismatch,same_call,true +AnalysisCapabilityUnavailableError,,capability_unavailable,unsupported_provider,never,false +AnalysisCancelledError,,cancelled,cancelled,same_call,true +AnalysisTimeoutError,,provider_timeout,timeout,same_call,true +AnalysisResourceConstraintError,,resource_constraint,resource_constraint,change_first,false +ConfigurationError,,configuration_invalid,invalid_input,change_first,false +NoBinaryOpenError,,target_unavailable,unavailable,change_first,false +EvidenceIntegrityError,,evidence_integrity_mismatch,integrity_mismatch,never,false +ProviderAdapterError,,execution_failure,execution_failure,never,false +AnalysisCapabilityUnavailableError,retry=same_call,capability_unavailable,unavailable,same_call,true +AnalysisCapabilityUnavailableError,retry=change_first,capability_unavailable,unavailable,change_first,false +AnalysisTargetFailureError,kind=selection,invalid_request,invalid_input,change_first,false +AnalysisTargetFailureError,kind=unrecognized,unsupported_target,unsupported_target,never,false +AnalysisTargetFailureError,kind=unsupported,unsupported_target,unsupported_target,never,false +AnalysisTargetFailureError,kind=malformed,unsupported_target,unsupported_target,never,false +AnalysisTargetFailureError,kind=truncated,unsupported_target,unsupported_target,never,false +AnalysisTargetFailureError,kind=integrity,target_integrity_mismatch,integrity_mismatch,never,false +AnalysisTargetFailureError,kind=conflict,input_conflict,invalid_input,change_first,false +AnalysisTargetFailureError,kind=changed,artifact_changed,integrity_mismatch,same_call,true +AnalysisTargetFailureError,kind=access,access_denied,unavailable,change_first,false +AnalysisTargetFailureError,kind=io,host_io_failed,execution_failure,never,false +ArtifactOperationError,reason=cancelled,cancelled,cancelled,same_call,true +ArtifactOperationError,reason=integrity,artifact_operation_failed,integrity_mismatch,never,false +ArtifactOperationError,reason=limit,partial,partial,change_first,false +ArtifactOperationError,reason=path,artifact_operation_failed,execution_failure,never,false +ArtifactOperationError,reason=unavailable,artifact_operation_failed,unavailable,change_first,false +ArtifactOperationError,reason=io,artifact_operation_failed,execution_failure,never,false +ArtifactOperationError,reason=integrity; artifact identity reported,artifact_integrity_mismatch,integrity_mismatch,never,false +ArtifactOperationError,reason=limit; release-fixed allowance,partial,partial,never,false +ArtifactOperationError,reason=integrity; the session's admitted identity no longer matches,artifact_operation_failed,integrity_mismatch,change_first,false +ArtifactOperationError,reason=integrity; target changed during the read,artifact_changed,integrity_mismatch,same_call,true +BinaryTargetError,constraint=unconstrained,target_unavailable,unavailable,change_first,false +BinaryTargetError,constraint=unconstrained; read permission denied,access_denied,unavailable,change_first,false +BinaryTargetError,constraint=directory_requires_file,target_unavailable,unavailable,change_first,false +BinaryTargetError,constraint=directory_requires_file; read permission denied,access_denied,unavailable,change_first,false +BinaryTargetError,constraint=wasm_requires_static_inspection,target_unavailable,unsupported_target,change_first,false +BinaryTargetError,constraint=wasm_requires_static_inspection; read permission denied,access_denied,unsupported_target,change_first,false +BinaryTargetError,constraint=file_format_rejected,target_unavailable,unsupported_target,change_first,false +BinaryTargetError,constraint=file_format_rejected; read permission denied,access_denied,unsupported_target,change_first,false +BinaryTargetError,constraint=load_selection_rejected,invalid_request,invalid_input,change_first,false +BinaryTargetError,constraint=bundle_type_unsupported,target_unavailable,unsupported_target,change_first,false +BinaryTargetError,constraint=bundle_type_unsupported; read permission denied,access_denied,unsupported_target,change_first,false +BinaryTargetError,constraint=bundle_info_plist_decode_budget_exceeded,target_unavailable,unavailable,change_first,false +BinaryTargetError,constraint=bundle_info_plist_decode_budget_exceeded; read permission denied,access_denied,unavailable,change_first,false +BinaryTargetError,constraint=bundle_info_plist_missing,target_unavailable,unavailable,change_first,false +BinaryTargetError,constraint=bundle_info_plist_missing; read permission denied,access_denied,unavailable,change_first,false +BinaryTargetError,constraint=bundle_layout_ambiguous,target_unavailable,unavailable,change_first,false +BinaryTargetError,constraint=bundle_layout_ambiguous; read permission denied,access_denied,unavailable,change_first,false +BinaryTargetError,constraint=bundle_executable_undeclared,target_unavailable,unavailable,change_first,false +BinaryTargetError,constraint=bundle_executable_undeclared; read permission denied,access_denied,unavailable,change_first,false +BinaryTargetError,constraint=bundle_program_missing,target_unavailable,unavailable,change_first,false +BinaryTargetError,constraint=bundle_program_missing; read permission denied,access_denied,unavailable,change_first,false +BinaryTargetError,constraint=bundle_current_version_missing,target_unavailable,unavailable,change_first,false +BinaryTargetError,constraint=bundle_current_version_missing; read permission denied,access_denied,unavailable,change_first,false +BinaryTargetError,constraint=bundle_path_escapes,target_unavailable,unavailable,change_first,false +BinaryTargetError,constraint=bundle_path_escapes; read permission denied,access_denied,unavailable,change_first,false +BrowserObservationError,reason=endpoint_unreachable,provider_unavailable,unavailable,same_call,true +BrowserObservationError,reason=invalid_endpoint_response,unreadable_output,execution_failure,never,false +BrowserObservationError,reason=target_not_found,target_unavailable,unavailable,change_first,false +BrowserObservationError,reason=target_not_allowed,target_unavailable,unavailable,change_first,false +BrowserObservationError,reason=application_already_running,target_unavailable,unavailable,change_first,false +BrowserObservationError,reason=service_worker_blocked,target_unavailable,unavailable,change_first,false +BrowserObservationError,reason=target_changed,target_unavailable,unavailable,change_first,false +BrowserObservationError,reason=target_session_detached,target_unavailable,unavailable,change_first,false +BrowserObservationError,reason=protocol_error,unreadable_output,execution_failure,never,false +BrowserObservationError,reason=disconnected,provider_unavailable,unavailable,same_call,true +BrowserObservationError,reason=payload_limit,partial,partial,change_first,false +BrowserObservationError,reason=window_not_found,unreadable_output,execution_failure,never,false +BrowserObservationError,reason=window_metadata_missing,unreadable_output,execution_failure,never,false +BrowserObservationError,reason=process_ownership_unavailable,unreadable_output,execution_failure,never,false +BrowserObservationError,reason=cleanup_failed,execution_failure,execution_failure,never,false +BrowserObservationError,reason=cancelled,cancelled,cancelled,same_call,true +BrowserObservationError,reason=timeout,provider_timeout,timeout,same_call,true +BrowserObservationError,caused by cancellation,cancelled,cancelled,same_call,true +EvidenceFileError,reason=not-file,invalid_request,invalid_input,change_first,false +EvidenceFileError,reason=exists,invalid_request,invalid_input,change_first,false +EvidenceFileError,reason=wrong-kind,invalid_request,invalid_input,change_first,false +EvidenceFileError,reason=missing,invalid_request,invalid_input,change_first,false +EvidenceFileError,reason=symlink-traversal,invalid_request,invalid_input,change_first,false +EvidenceFileError,reason=invalid-json,evidence_integrity_mismatch,execution_failure,never,false +EvidenceFileError,reason=path-limit,resource_constraint,resource_constraint,change_first,false +EvidenceFileError,reason=storage-limit,resource_constraint,resource_constraint,change_first,false +EvidenceFileError,reason=io,execution_failure,execution_failure,never,false +EvidenceIntegrityError,analysis snapshot selected for a resource-only session,invalid_request,invalid_input,change_first,false +EvidenceIntegrityError,referenced Evidence missing from this session,evidence_integrity_mismatch,integrity_mismatch,change_first,false +ProcessCaptureError,,process_capture_failed,execution_failure,never,false +ProcessCaptureError,caused by cancellation,cancelled,cancelled,same_call,true +ProviderSelectionError,reason=unknown_provider,capability_unavailable,unsupported_provider,change_first,false +ProviderSelectionError,reason=provider_unavailable,provider_unavailable,unavailable,same_call,true +ProviderSelectionError,reason=target_unsupported,capability_unavailable,unsupported_provider,never,false +ProviderSelectionError,reason=ambiguous,capability_unavailable,unsupported_provider,change_first,false +ProviderSelectionError,reason=invalid_options,capability_unavailable,unsupported_provider,change_first,false +UnknownRegistryError,reason=not-found,invalid_request,invalid_input,change_first,false +UnknownRegistryError,reason=already-exists,invalid_request,invalid_input,change_first,false +UnknownRegistryError,reason=revision-conflict,revision_conflict,execution_failure,change_first,false +UnknownRegistryError,reason=invalid-transition,execution_failure,execution_failure,change_first,false +UnknownRegistryError,reason=integrity,evidence_integrity_mismatch,execution_failure,never,false +UnknownRegistryError,reason=limit,partial,execution_failure,change_first,false +UnknownRegistryError,reason=constraint,invalid_request,invalid_input,change_first,false +HopperTimeoutError,,provider_timeout,timeout,same_call,true +HopperCancelledError,,cancelled,cancelled,same_call,true +HopperCancelledError,request sent to Hopper,cancelled,cancelled,unknown_outcome,false +HopperProtocolError,,unreadable_output,execution_failure,never,false +HopperRemoteError,diagnostic_type=remote,execution_failure,execution_failure,never,false +HopperRemoteError,diagnostic_type=authorization,execution_failure,unavailable,change_first,false +HopperRemoteError,diagnostic_type=invalid_request,invalid_request,invalid_input,change_first,false +HopperRemoteError,diagnostic_type=selector_not_found,invalid_request,invalid_input,change_first,false +HopperRemoteError,diagnostic_type=capability_unavailable,execution_failure,execution_failure,never,false +HopperRemoteError,diagnostic_type=bridge_exception,execution_failure,execution_failure,never,false +HopperProcessError,,provider_unavailable,unavailable,change_first,false +HopperStartError,,provider_unavailable,unavailable,same_call,true +HopperStartError,"Apple Events authorization denied, launch arguments not encodable, or another REA session owns the target",provider_unavailable,unavailable,change_first,false diff --git a/scripts/generate-error-schema.mjs b/scripts/generate-error-schema.mjs index d6b41a43b1f..d2b5445c81d 100644 --- a/scripts/generate-error-schema.mjs +++ b/scripts/generate-error-schema.mjs @@ -34,6 +34,7 @@ const columns = { discriminant: "discriminant", code: "code", category: "category", + retry: "retry", retryable_by_default: "retryableByDefault", }; await ensureGeneratedFile({ diff --git a/src/adb/AdbFileStaging.ts b/src/adb/AdbFileStaging.ts index 741cb47e036..6fc843c2b98 100644 --- a/src/adb/AdbFileStaging.ts +++ b/src/adb/AdbFileStaging.ts @@ -310,9 +310,23 @@ export const refuseExistingTarget = async ( () => false, ) ) - return new AnalysisOutputError( + // The caller's output_directory selected an occupied name; nothing the + // device or adb returned is at fault. + return new AnalysisInputError( operation, - `The output file already exists: ${path}`, + { + userMessage: `The output file already exists: ${path}`, + remediationAction: + "Choose an output_directory that does not already contain this file, or remove the file if it is yours, then retry. REA does not overwrite local files.", + conformsToInputContract: true, + }, + [ + { + path: ["output_directory"], + reason: "invalid_value", + message: `The output file already exists: ${path}`, + }, + ], ); return undefined; }; diff --git a/src/adb/AdbProvider.test.ts b/src/adb/AdbProvider.test.ts index 97510ce4a5e..8e62d93b860 100644 --- a/src/adb/AdbProvider.test.ts +++ b/src/adb/AdbProvider.test.ts @@ -662,10 +662,16 @@ it("refuses to reuse an existing package output directory", async () => { }); expect(result.ok).toBe(false); if (result.ok) return; - expect(projectAnalysisError(result.error)).toMatchObject({ - code: "unreadable_output", + // An occupied output_directory is the caller's selection, not output + // REA could not read. + const projected = projectAnalysisError(result.error); + expect(projected).toMatchObject({ + code: "invalid_request", + category: "invalid_input", + message: expect.stringContaining("already exists"), + remediation: { action: expect.stringContaining("output_directory") }, }); - expect(result.error.message).toContain("already exists"); + expect(projected).not.toHaveProperty("recovery"); }); it.each([ @@ -1884,14 +1890,20 @@ exit 1`, }); expect(result.ok).toBe(false); if (result.ok) return; - expect(projectAnalysisError(result.error)).toMatchObject({ - code: "unreadable_output", - details: { - operation: "push_adb_file", - reason: expect.stringContaining("/data/local/tmp/exists.bin/payload.bin"), + // The caller's overwrite choice refused the push; nothing adb returned + // is unreadable. + const projected = projectAnalysisError(result.error); + expect(projected).toMatchObject({ + code: "invalid_request", + category: "invalid_input", + retryable: false, + message: expect.stringContaining("overwrite was not requested"), + remediation: { + action: + "Pass overwrite: true to replace the device file, or choose another device_path.", }, }); - expect(result.error.message).toContain("overwrite"); + expect(projected).not.toHaveProperty("recovery"); // The refusal ends at the existence probes; no push reaches the device. expect(await readFile(join(root, "calls"), "utf8")).toBe( [ diff --git a/src/adb/AdbProvider.ts b/src/adb/AdbProvider.ts index 427dd279221..666ce8f81ba 100644 --- a/src/adb/AdbProvider.ts +++ b/src/adb/AdbProvider.ts @@ -978,16 +978,33 @@ export class AdbProvider { const packageDirectory = appendCallerPath(directory.value, packageName); let packageDirectoryCreated = false; let packageDirectoryIdentity: OutputDirectoryIdentity | undefined; - try { - if ( - await lstat(packageDirectory).then( - () => true, - () => false, - ) + // The caller's output_directory already holds this package: refuse the + // selection before creating anything, as for an existing output file. + if ( + await lstat(packageDirectory).then( + () => true, + () => false, ) - throw new Error( - `The package output directory already exists: ${packageDirectory}`, - ); + ) + return err( + new AnalysisInputError( + operation, + { + userMessage: `The package output directory already exists: ${packageDirectory}`, + remediationAction: + "Choose an output_directory that does not already contain this package, or remove that directory if it is yours, then retry. REA does not overwrite local files.", + conformsToInputContract: true, + }, + [ + { + path: ["output_directory"], + reason: "invalid_value", + message: `The package output directory already exists: ${packageDirectory}`, + }, + ], + ), + ); + try { await mkdir(packageDirectory); packageDirectoryCreated = true; const created = await lstat(packageDirectory); @@ -1476,9 +1493,22 @@ export class AdbProvider { const deviceExists = existsProbe.value.matches; if (deviceExists && !input.overwrite) return err( - new AnalysisOutputError( + new AnalysisInputError( operation, - `The device path already exists and overwrite was not requested: ${devicePath}`, + { + userMessage: `The device path already exists and overwrite was not requested: ${devicePath}`, + remediationAction: + "Pass overwrite: true to replace the device file, or choose another device_path.", + conformsToInputContract: true, + related: { parameters: ["overwrite", "device_path"] }, + }, + [ + { + path: ["device_path"], + reason: "invalid_value", + message: `The device path already exists and overwrite was not requested: ${devicePath}`, + }, + ], ), ); const pushed = await runAdb( diff --git a/src/android/AndroidMappingFile.ts b/src/android/AndroidMappingFile.ts index 1650726fe97..06ae35e53c7 100644 --- a/src/android/AndroidMappingFile.ts +++ b/src/android/AndroidMappingFile.ts @@ -3,7 +3,7 @@ import { artifactFilePrimaryFacts, ArtifactReaderFailure, projectStableArtifactFailure, - stableArtifactInputRecovery, + stableArtifactInputOptions, readerIntegrityFailure, type ArtifactResourceScope, readStableArtifact, @@ -121,10 +121,12 @@ const readFailurePrimary = ( if (owned?.reason === "integrity") return readerIntegrityFailure(read.operation, read.path, owned); if (owned?.reason === "path") - return invalidMapping(read, "invalid_value", owned.message, { - cause: owned, - ...stableArtifactInputRecovery(owned), - }); + return invalidMapping( + read, + "invalid_value", + owned.message, + stableArtifactInputOptions(owned), + ); if (primary instanceof Error && "code" in primary) { if (primary.code === "EACCES" || primary.code === "EPERM") return new AnalysisAccessDeniedError( diff --git a/src/apkSignature/ApkSignatureProvider.test.ts b/src/apkSignature/ApkSignatureProvider.test.ts index 3514a5bbba8..397d1521a1e 100644 --- a/src/apkSignature/ApkSignatureProvider.test.ts +++ b/src/apkSignature/ApkSignatureProvider.test.ts @@ -427,7 +427,7 @@ const registerSignatureInputAdmissionCases = () => { expect(result.error._tag).toBe("AnalysisTargetFailureError"); }); - it("reports a damaged supported Zip64 end record as input failure while accepting the intact and restored controls", async () => { + it("reports a damaged supported Zip64 end record as a malformed target while accepting the intact and restored controls", async () => { const classic = Buffer.from(await zipOf(["entry.txt"])); const endOffset = classic.length - 22; expect(classic.readUInt32LE(endOffset)).toBe(0x06054b50); @@ -482,7 +482,7 @@ const registerSignatureInputAdmissionCases = () => { }); expect(damaged.ok).toBe(false); if (!damaged.ok) { - expect(damaged.error._tag).toBe("AnalysisInputError"); + expect(damaged.error._tag).toBe("AnalysisTargetFailureError"); expect(JSON.stringify(damaged.error)).toContain( "invalid Zip64 EOCD signature", ); @@ -491,7 +491,7 @@ const registerSignatureInputAdmissionCases = () => { }; const registerSigningStructureFailureCases = () => { - it("reports a malformed signing block as an input error", async () => { + it("reports a malformed signing block as a malformed target", async () => { const result = await provider.inspect({ path: await write( "bad.apk", @@ -502,7 +502,7 @@ const registerSigningStructureFailureCases = () => { }); expect(result.ok).toBe(false); if (result.ok) return; - expect(result.error._tag).toBe("AnalysisInputError"); + expect(result.error._tag).toBe("AnalysisTargetFailureError"); }); it("reports a malformed declared lineage instead of dropping it", async () => { @@ -545,7 +545,7 @@ const registerSigningStructureFailureCases = () => { }); expect(result.ok).toBe(false); if (result.ok) return; - expect(result.error._tag).toBe("AnalysisInputError"); + expect(result.error._tag).toBe("AnalysisTargetFailureError"); expect(JSON.stringify(result.error)).toContain( "Malformed ZIP central directory", ); @@ -566,7 +566,7 @@ const registerSigningStructureFailureCases = () => { }); expect(result.ok).toBe(false); if (result.ok) return; - expect(result.error._tag).toBe("AnalysisInputError"); + expect(result.error._tag).toBe("AnalysisTargetFailureError"); }); it("says why the digest was not recomputed when the EOCD does not follow the directory", async () => { diff --git a/src/apkSignature/ApkSignatureProvider.ts b/src/apkSignature/ApkSignatureProvider.ts index 175ae1ea09b..509caaca094 100644 --- a/src/apkSignature/ApkSignatureProvider.ts +++ b/src/apkSignature/ApkSignatureProvider.ts @@ -436,15 +436,36 @@ export class ApkSignatureProvider implements ApkSignaturePort { tail.centralDirectoryOffset, tail.centralDirectorySize, ); - const v1Read = await readV1(handle, centralDirectory, tail, block.value); + const v1Read = await readV1( + handle, + centralDirectory, + tail, + block.value, + artifact.path, + ); if (!v1Read.ok) return v1Read; const { v1, decoded: v1Decoded, duplicates } = v1Read.value; - const v2 = decodeScheme(block.value, APK_BLOCK_ID.signatureV2, "v2"); + const v2 = decodeScheme( + block.value, + APK_BLOCK_ID.signatureV2, + "v2", + artifact.path, + ); if (!v2.ok) return v2; - const v3 = decodeScheme(block.value, APK_BLOCK_ID.signatureV3, "v3"); + const v3 = decodeScheme( + block.value, + APK_BLOCK_ID.signatureV3, + "v3", + artifact.path, + ); if (!v3.ok) return v3; - const v31 = decodeScheme(block.value, APK_BLOCK_ID.signatureV31, "v3.1"); + const v31 = decodeScheme( + block.value, + APK_BLOCK_ID.signatureV31, + "v3.1", + artifact.path, + ); if (!v31.ok) return v31; // Account for representation expansion before allocating the report. @@ -568,6 +589,7 @@ const readV1 = async ( centralDirectory: Uint8Array, tail: ZipTail, block: ApkSigningBlock | null, + path: string, ): Promise< Result< { @@ -586,7 +608,7 @@ const readV1 = async ( tail.classicEntryCount, tail.centralDirectoryOffset, ); - if (!entries.ok) return err(mapCentralDirectoryError(entries.error)); + if (!entries.ok) return err(mapCentralDirectoryError(entries.error, path)); const v1 = detectV1Signature(entries.value.entries); if (v1.signers.length > MAX_V1_SIGNERS) return err(v1SignerCapacityError(MAX_V1_SIGNERS)); @@ -632,19 +654,21 @@ const decodeScheme = ( block: ApkSigningBlock | null, id: number, version: ApkSchemeVersion, + path: string, ): Result => { const pair = block?.pairs.find((p) => p.id === id); if (pair === undefined) return ok({ present: false, signers: [], uninterpretedBytes: 0 }); const signers = decodeSigners(pair.value, version); - if (!signers.ok) return err(mapApkSchemeError(signers.error, version)); + if (!signers.ok) return err(mapApkSchemeError(signers.error, version, path)); const decoded: DecodedSigner[] = []; for (const signer of signers.value.signers) { const rotation = version === "v2" ? ok({ present: false } as const) : lineageOf(signer, version); - if (!rotation.ok) return err(mapApkSchemeError(rotation.error, version)); + if (!rotation.ok) + return err(mapApkSchemeError(rotation.error, version, path)); decoded.push({ signer, rotation: rotation.value }); } return ok({ diff --git a/src/apkSignature/apkSignatureFailures.ts b/src/apkSignature/apkSignatureFailures.ts index 1f00ca861db..bf6d548bf66 100644 --- a/src/apkSignature/apkSignatureFailures.ts +++ b/src/apkSignature/apkSignatureFailures.ts @@ -16,6 +16,7 @@ import { AnalysisAccessDeniedError, AnalysisInputError, AnalysisResourceConstraintError, + AnalysisTargetFailureError, unsupportedTarget, unrecognizedTarget, } from "../domain/analysisErrorCore.js"; @@ -32,10 +33,21 @@ import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "inspect_apk_signature"; -const inputError = (message: string): AnalysisInputError => - new AnalysisInputError(OPERATION, undefined, [ - { path: ["path"], reason: "invalid_value", message }, - ]); +/** + * Damaged archive or signing structures are the selected target's bytes, not + * the request: a malformed target, at the offset where decoding failed. + */ +const malformedApk = ( + path: string, + detail: string, + offset?: number, +): AnalysisTargetFailureError => + new AnalysisTargetFailureError(OPERATION, path, { + kind: "malformed", + format: "zip", + detail, + ...(offset === undefined ? {} : { offset }), + }); /** Map a tagged signing-block framing failure to the shared analysis error algebra. */ export const mapApkBlockError = ( @@ -66,12 +78,16 @@ export const mapApkBlockError = ( `The selected archive declares an unsupported multi-disk ZIP layout (${error.detail}). Select a complete single-disk APK/ZIP archive.`, ); case "malformed-zip": - return inputError( + return malformedApk( + path, `Damaged ZIP/APK at byte ${String(error.offset)}: ${error.detail}.`, + error.offset, ); case "malformed-block": - return inputError( + return malformedApk( + path, `Malformed APK Signing Block at byte ${String(error.offset)}: ${error.detail}.`, + error.offset, ); case "limit": { const { name, maximum } = error.failure.limit; @@ -90,9 +106,11 @@ export const mapApkBlockError = ( export const mapApkSchemeError = ( error: ApkSchemeError, scheme: string, + path: string, ): AnalysisError => { if (error.kind === "malformed-signer") - return inputError( + return malformedApk( + path, `Malformed APK Signature Scheme ${scheme} block: ${error.detail}.`, ); const { name, maximum } = error.failure.limit; @@ -108,10 +126,13 @@ export const mapApkSchemeError = ( /** A central directory that cannot be walked leaves v1 presence unknown: refuse. */ export const mapCentralDirectoryError = ( error: ApkCentralDirectoryError, + path: string, ): AnalysisError => { if (error.kind !== "limit") - return inputError( + return malformedApk( + path, `Malformed ZIP central directory at byte ${String(error.offset)}: ${error.detail}.`, + error.offset, ); const { name, maximum } = error.failure.limit; return parseLimitConstraint(OPERATION, "capacity", error, { diff --git a/src/apktool/ApktoolProvider.test.ts b/src/apktool/ApktoolProvider.test.ts index 2be682f7b16..faf33aaf201 100644 --- a/src/apktool/ApktoolProvider.test.ts +++ b/src/apktool/ApktoolProvider.test.ts @@ -811,7 +811,9 @@ it("rejects a target that is not a readable file", async () => { operation: "decode_android_resources", input: { path: join(root, "absent.apk"), include_strings: true }, }); - expect(projected).toMatchObject({ code: "invalid_request" }); + // A missing APK is the selected target's state, not a schema violation. + expect(projected).toMatchObject({ code: "target_unavailable" }); + expect(projected).not.toHaveProperty("recovery"); }); it("cancels before spawning anything", async () => { diff --git a/src/apktool/ApktoolProvider.ts b/src/apktool/ApktoolProvider.ts index 2c79414388d..203d6f3e763 100644 --- a/src/apktool/ApktoolProvider.ts +++ b/src/apktool/ApktoolProvider.ts @@ -254,10 +254,21 @@ const apktoolCommandFailure = ( }, runtimeExhaustion: ({ area }) => ({ limits: null, - recovery: { - retryable: false, - remediationAction: `${externalJvmExhaustionRecovery(area, APKTOOL_JVM)} Repeating the unchanged request is expected to fail the same way.`, - }, + // Native threads are host capacity that frees when other work ends, as + // in the shared default; every other area is the JVM's own setting. + recovery: + area === "native-thread" + ? { + retryable: true, + remediationAction: externalJvmExhaustionRecovery( + area, + APKTOOL_JVM, + ), + } + : { + retryable: false, + remediationAction: `${externalJvmExhaustionRecovery(area, APKTOOL_JVM)} Repeating the unchanged request is expected to fail the same way.`, + }, }), dialect: (exit, details, unclassified) => { // A physical launcher/capture failure does not establish target refusal. diff --git a/src/apktool/ApktoolWorkspace.lifecycle.test.ts b/src/apktool/ApktoolWorkspace.lifecycle.test.ts index 4643603d9a9..891663f5091 100644 --- a/src/apktool/ApktoolWorkspace.lifecycle.test.ts +++ b/src/apktool/ApktoolWorkspace.lifecycle.test.ts @@ -481,15 +481,17 @@ it.each(["EACCES", "EPERM", "EIO", "ENOENT"] as const)( .snapshotInput(input, "decode_android_resources") .catch((cause: unknown) => cause); if (code === "EIO") expect(result).toBe(failure); + // A missing selected APK is the target's state, as for every other + // selected-file reader. + else if (code === "ENOENT") + expect(result).toMatchObject({ _tag: "BinaryTargetError" }); else expect(result).toMatchObject({ - _tag: - code === "ENOENT" - ? "AnalysisInputError" - : "AnalysisAccessDeniedError", + _tag: "AnalysisAccessDeniedError", operation: "decode_android_resources", cause: failure, - ...(code === "ENOENT" ? {} : { path: input, systemCode: code }), + path: input, + systemCode: code, }); expect(workspace.snapshot).toBeUndefined(); await expect(fs.stat(join(root.path, "input.apk"))).rejects.toMatchObject( diff --git a/src/apktool/ApktoolWorkspace.ts b/src/apktool/ApktoolWorkspace.ts index 8f7034c6b40..c46cf5f5d8a 100644 --- a/src/apktool/ApktoolWorkspace.ts +++ b/src/apktool/ApktoolWorkspace.ts @@ -9,12 +9,12 @@ import { withArtifactFileHandle, withArtifactRegularFile, DirectoryArtifactReader, + selectedFileTargetError, } from "../resources/index.js"; import { createHash } from "node:crypto"; import { chmod, open } from "node:fs/promises"; import { join } from "node:path"; import { - AnalysisInputError, AnalysisAccessDeniedError, AnalysisArtifactChangedError, AnalysisProtocolError, @@ -145,17 +145,21 @@ export class ApktoolWorkspace { return new AnalysisAccessDeniedError(operation, path, physical.code, { cause: physical, }); + // A missing or non-regular selected APK is the target's state, as + // for every other selected-file reader, not a malformed argument. if ( physical instanceof NonRegularFileReadError || artifactSelectedPathErrno(physical) !== undefined ) - return new AnalysisInputError(operation, { cause: physical }, [ - { - path: ["path"], - reason: "invalid_value", - message: "APK input must resolve to an accessible regular file", - }, - ]); + return selectedFileTargetError( + path, + physical instanceof Error + ? physical + : new Error( + "APK input must resolve to an accessible regular file", + ), + physical, + ); return physical; }); } diff --git a/src/application/DirectAnalysisCleanup.ts b/src/application/DirectAnalysisCleanup.ts index e5b4cfd7639..72f6ad30c2c 100644 --- a/src/application/DirectAnalysisCleanup.ts +++ b/src/application/DirectAnalysisCleanup.ts @@ -3,6 +3,7 @@ import { type AnalysisError, } from "../domain/analysisErrorBase.js"; import { + analysisErrorRetry, childFailureDiagnostics, projectAnalysisError, } from "../domain/analysisErrorProjection.js"; @@ -112,6 +113,15 @@ export const withSessionCleanup = async ( }; /** Project typed one-shot outcomes only after execution and cleanup settle. */ +/** + * The retry class of a reply that reports `cleanup_incomplete`, read from the + * typed failure it reports: work may repeat only after cleanup settles. + */ +const cleanupIncompleteRetry = (failure: AnalysisError) => { + const retry = analysisErrorRetry(failure); + return retry === "same_call" ? "change_first" : retry; +}; + export const directAnalysisCleanupFailure = ( result: Result, error: AnalysisError, @@ -130,6 +140,7 @@ export const directAnalysisCleanupFailure = ( ...primary, code: "cleanup_incomplete", retryable: false, + retry_class: cleanupIncompleteRetry(combined), remediation: cleanup.remediation, details: { ...primary.details, @@ -147,6 +158,7 @@ export const directAnalysisCleanupFailure = ( ...cleanup, code: "cleanup_incomplete", retryable: false, + retry_class: cleanupIncompleteRetry(error), details: { ...cleanup.details, cleanup: "incomplete", diff --git a/src/application/NativeSymbolSelection.test.ts b/src/application/NativeSymbolSelection.test.ts index d312a662dc7..1a84f4fd43b 100644 --- a/src/application/NativeSymbolSelection.test.ts +++ b/src/application/NativeSymbolSelection.test.ts @@ -17,9 +17,16 @@ const names = (rows: JsonValue): AnalysisOperationPort => ({ operation === "list_names" ? ok(createAnalysisExecution(rows, PROVIDER)) : err( - new AnalysisInputError(operation, { conformsToInputContract: true }, [ - { path: ["procedure"], reason: "invalid_value" }, - ]), + new AnalysisInputError( + operation, + { + conformsToInputContract: true, + userMessage: "No procedure matches the selector.", + remediationAction: + "Select an observed procedure name or address.", + }, + [{ path: ["procedure"], reason: "invalid_value" }], + ), ), }); diff --git a/src/application/NativeSymbolSelection.ts b/src/application/NativeSymbolSelection.ts index cd0ded6283c..afe0da40b76 100644 --- a/src/application/NativeSymbolSelection.ts +++ b/src/application/NativeSymbolSelection.ts @@ -214,6 +214,10 @@ const unresolvedNameError = ( ...(candidates.length > 0 ? {} : { related: { operations: ["search_procedures", "list_names"] } }), + userMessage: + candidates.length > 0 + ? `No observed name equals ${JSON.stringify(selector)}.` + : `No analyzed symbol is named ${JSON.stringify(selector)}.`, remediationAction: candidates.length > 0 ? `Retry with one of the observed names or addresses: ${candidates.map(({ address, name }) => `${name} at ${address}`).join(", ")}. The provider does not report which library each name is imported from.` diff --git a/src/application/apiContract/ApiContractRead.ts b/src/application/apiContract/ApiContractRead.ts index dfceb0f07c4..62c12c93770 100644 --- a/src/application/apiContract/ApiContractRead.ts +++ b/src/application/apiContract/ApiContractRead.ts @@ -5,7 +5,7 @@ import { type ArtifactResourceScope, readStableArtifact, projectStableArtifactFailure, - stableArtifactInputRecovery, + stableArtifactInputOptions, readerIntegrityFailure, } from "../../resources/index.js"; import type { AnalysisError } from "../../domain/analysisErrorBase.js"; @@ -34,22 +34,13 @@ const inputFailure = ( message: string, parameter = "path", ) => - new AnalysisInputError( - operation, + new AnalysisInputError(operation, stableArtifactInputOptions(cause), [ { - cause, - ...(cause instanceof ArtifactReaderFailure - ? stableArtifactInputRecovery(cause) - : {}), + path: [parameter], + reason: "invalid_format", + message: `${message} (${path})`, }, - [ - { - path: [parameter], - reason: "invalid_format", - message: `${message} (${path})`, - }, - ], - ); + ]); const readFailure = ( failure: unknown, diff --git a/src/application/binary/BinarySessionBundleResources.test.ts b/src/application/binary/BinarySessionBundleResources.test.ts index b029c551c82..6077939f84a 100644 --- a/src/application/binary/BinarySessionBundleResources.test.ts +++ b/src/application/binary/BinarySessionBundleResources.test.ts @@ -17,7 +17,6 @@ import { BinarySession } from "./BinarySession.js"; import { SessionProviderRouter } from "./SessionProviderRouter.js"; import { bundleResourceRootSchema } from "../../domain/apple/bundleResourceRoot.js"; import type { AnalysisError } from "../../domain/analysisErrorBase.js"; -import { analysisErrorRemediationAction } from "../../domain/analysisErrorPresentation.js"; import { projectAnalysisError } from "../../domain/analysisErrorProjection.js"; import { ResourceSnapshotMismatchError } from "../../domain/evidenceErrors.js"; import type { AnalysisSnapshot } from "../../domain/analysisSnapshot.js"; @@ -46,12 +45,17 @@ const expectResourceSnapshotRefusal = ( _tag: "EvidenceIntegrityError", operation, }); + // A snapshot does not apply to a resource-only session: the caller's + // selection, not a changed or forged snapshot. const projected = projectAnalysisError(error); - expect(projected.code).toBe("evidence_integrity_mismatch"); - expect(projected.category).toBe("integrity_mismatch"); + expect(projected.code).toBe("invalid_request"); + expect(projected.category).toBe("invalid_input"); expect(projected.retryable).toBe(false); expect(projected.remediation).toEqual({ - action: analysisErrorRemediationAction(error), + action: + operation === "export" + ? "Call close_binary without snapshot_path to close this resource-only session." + : "Open an executable analysis target before importing a binary analysis snapshot.", }); }; diff --git a/src/application/binary/BinarySessionRefusalAlternatives.test.ts b/src/application/binary/BinarySessionRefusalAlternatives.test.ts index 3637afaa29f..0ac1ff99675 100644 --- a/src/application/binary/BinarySessionRefusalAlternatives.test.ts +++ b/src/application/binary/BinarySessionRefusalAlternatives.test.ts @@ -21,8 +21,9 @@ import { buildCapabilityInventory } from "../CapabilityInventory.js"; import { offeredOperationAlternatives } from "../OperationAlternatives.js"; const IDENTITY = createFixtureProviderIdentity(); -const GENERIC = - "This analysis is unavailable for the current target. Choose another analysis or target."; +// A declared reason without its own recovery points to the session inventory. +const DECLARED_UNAVAILABLE = + "Review details.reason, which names why the provider cannot run this operation. In a binary-analysis session, binary_session lists the operations available for the open target and provider; select one of those, or open a target that supports this analysis. Otherwise resolve the condition the reason names."; /** The owning formatter's remediation for exactly these offered tools. */ const remediationFor = (operation: string, offered: readonly string[]) => @@ -188,7 +189,7 @@ describe("undeclared navigation refusals", () => { const declared = await refusal(session, "next_address"); expect(declared).toMatchObject({ code: "capability_unavailable", - remediation: { action: GENERIC }, + remediation: { action: DECLARED_UNAVAILABLE }, details: { reason: "next_address needs a loaded listing" }, }); expect(declared.details).not.toHaveProperty("alternatives"); diff --git a/src/application/binary/NativeProviderSelection.test.ts b/src/application/binary/NativeProviderSelection.test.ts index 084acbab8b6..6849124e1f4 100644 --- a/src/application/binary/NativeProviderSelection.test.ts +++ b/src/application/binary/NativeProviderSelection.test.ts @@ -107,7 +107,12 @@ const fixture = ( : err( new AnalysisInputError( operation, - { conformsToInputContract: true }, + { + conformsToInputContract: true, + userMessage: "No procedure matches the selector.", + remediationAction: + "Select an observed procedure name or address.", + }, [{ path: ["address"], reason: "invalid_value" }], ), ); diff --git a/src/application/binary/SessionRuntimeAvailability.test.ts b/src/application/binary/SessionRuntimeAvailability.test.ts index ef4a1eb0690..09a263fbbd6 100644 --- a/src/application/binary/SessionRuntimeAvailability.test.ts +++ b/src/application/binary/SessionRuntimeAvailability.test.ts @@ -33,6 +33,7 @@ it.each([undefined, "Restore the fixture runtime."])( return { code: "provider_unavailable", category: "unavailable", + retry: "same_call", ...(remediation === undefined ? {} : { remediation }), continuing: { remediationAction: "Use the current fixture session." }, }; @@ -100,11 +101,7 @@ it.each([ "kuna", "list_strings", "first refusal", - { - ...(activeRepair === undefined - ? {} - : { remediationAction: activeRepair }), - }, + activeRepair === undefined ? {} : { remediationAction: activeRepair }, ), ), ); diff --git a/src/application/decompileDirectory/exportTree.ts b/src/application/decompileDirectory/exportTree.ts index 5d56a9323b7..01d066faa29 100644 --- a/src/application/decompileDirectory/exportTree.ts +++ b/src/application/decompileDirectory/exportTree.ts @@ -88,6 +88,7 @@ export const classifyOutputPath = async ( decompileInputError( "output_directory", "Resume requires an existing export directory. Omit resume to start a new export.", + "Omit resume to start a new export, or name the existing export directory.", ), ); return missingOrRejected(stripped, listed); @@ -97,6 +98,7 @@ export const classifyOutputPath = async ( decompileInputError( "output_directory", "Output directory already exists. Pass resume to continue an export that matches this target and analysis profile.", + "Pass resume to continue the export, or choose a new output_directory.", ), ); const root = await realpath(stripped).catch((cause: unknown) => cause); @@ -445,6 +447,7 @@ const openResumedJournal = async ( decompileInputError( "output_directory", "The decompile journal could not be repaired after an interrupted write.", + "Choose a new output_directory to start a fresh export.", ), ); } @@ -550,6 +553,7 @@ const missingOrRejected = async ( decompileInputError( "output_directory", "The output directory must be a real directory, not a symlink.", + "Select the real directory instead of the symlink, or choose a new output_directory.", ), ); if (isStat(listed)) @@ -557,6 +561,7 @@ const missingOrRejected = async ( decompileInputError( "output_directory", "The output path exists and is not a directory.", + "Choose an output_directory that does not exist or is an export directory.", ), ); if (reportedSystemCode(listed) !== "ENOENT") @@ -564,6 +569,7 @@ const missingOrRejected = async ( decompileInputError( "output_directory", "The output directory could not be inspected.", + "Check that this user can create, inspect and write the output directory on the host, then retry; or choose another output_directory.", ), ); const parent = await realpath(dirname(stripped)).catch( @@ -574,6 +580,7 @@ const missingOrRejected = async ( decompileInputError( "output_directory", "The output directory's parent does not exist.", + "Create the parent directory, or choose an output_directory whose parent exists.", ), ); return ok({ mode: "create", root: join(parent, basename(stripped)) }); @@ -591,10 +598,12 @@ const createPrivateDirectory = async ( ? decompileInputError( "output_directory", "Output directory already exists. Pass resume to continue an export that matches this target and analysis profile.", + "Pass resume to continue the export, or choose a new output_directory.", ) : decompileInputError( "output_directory", "The output directory could not be created.", + "Check that this user can create, inspect and write the output directory on the host, then retry; or choose another output_directory.", ), ); // This call created the directory, so it owns removing it when the @@ -614,7 +623,10 @@ const createPrivateDirectory = async ( "output_directory", removed ? "The output directory could not be secured." - : "The output directory could not be secured, and the directory this call created could not be removed. Remove it before retrying.", + : "The output directory could not be secured, and the directory this call created could not be removed.", + removed + ? "Check that this user can make the output directory private on the host, then retry; or choose another output_directory." + : "Remove the directory this call created, then retry; or choose another output_directory.", ), ); }; @@ -632,6 +644,7 @@ const prepareFunctionsDirectory = async ( decompileInputError( "output_directory", "The functions directory could not be created.", + "Check that this user can create, inspect and write the output directory on the host, then retry; or choose another output_directory.", ), ); const stat = await lstat(directory, { bigint: true }).catch( @@ -642,6 +655,7 @@ const prepareFunctionsDirectory = async ( decompileInputError( "output_directory", "The functions directory is not a real directory.", + "Choose a new output_directory to start a fresh export.", ), ); resources.ownFunctionsDirectory(stat); @@ -660,6 +674,7 @@ const prepareFunctionsDirectory = async ( decompileInputError( "output_directory", "The functions directory could not be secured.", + "Check that this user can create, inspect and write the output directory on the host, then retry; or choose another output_directory.", ), ); const repaired = await lstat(directory, { bigint: true }).catch( @@ -674,6 +689,7 @@ const prepareFunctionsDirectory = async ( decompileInputError( "output_directory", "The functions directory is not a real directory.", + "Choose a new output_directory to start a fresh export.", ), ); resources.ownFunctionsDirectory(repaired); @@ -720,6 +736,7 @@ const seedJournal = async ( decompileInputError( "output_directory", "The decompile journal could not be created.", + "Check that this user can create, inspect and write the output directory on the host, then retry; or choose another output_directory.", ), ); }; @@ -748,6 +765,7 @@ const openJournal = async ( decompileInputError( "output_directory", "The decompile journal could not be opened.", + "Check that this user can create, inspect and write the output directory on the host, then retry; or choose another output_directory.", ), ); }; @@ -769,10 +787,12 @@ const journalReadError = (cause: unknown): AnalysisInputError => ? decompileInputError( "output_directory", "Resume requires decompile-journal.jsonl in the output directory. An export stopped before its journal was written has no functions to keep; choose a new output directory, or remove this one if it is yours.", + "Choose a new output_directory, or remove this one if it is yours, then retry.", ) : decompileInputError( "output_directory", "The decompile journal could not be read.", + "Check that this user can create, inspect and write the output directory on the host, then retry; or choose another output_directory.", ); const readJournal = async ( @@ -901,6 +921,7 @@ const unknownIdentity = ( return decompileInputError( "output_directory", "Resume requires an observed target SHA-256 for both the journal and this target.", + "Choose a new output_directory to start a fresh export; the existing files were left unchanged.", ); if ( header.analysis_profile_digest === null || @@ -909,6 +930,7 @@ const unknownIdentity = ( return decompileInputError( "output_directory", "Resume requires an analysis profile digest for both the journal and this provider.", + "Choose a new output_directory to start a fresh export; the existing files were left unchanged.", ); return undefined; }; @@ -1069,6 +1091,7 @@ const acquireExportLease = async ( decompileInputError( "output_directory", "The output directory could not be inspected.", + "Check that this user can create, inspect and write the output directory on the host, then retry; or choose another output_directory.", ), ); const leaseResources = new ArtifactResourceScope(); diff --git a/src/application/decompileDirectory/inputError.ts b/src/application/decompileDirectory/inputError.ts index 88fb1436ef0..38d9faa5e6e 100644 --- a/src/application/decompileDirectory/inputError.ts +++ b/src/application/decompileDirectory/inputError.ts @@ -1,10 +1,23 @@ import { AnalysisInputError } from "../../domain/analysisErrorCore.js"; -/** Caller-facing rejection for one decompile-directory argument. */ +/** + * Caller-facing rejection for one decompile-directory argument. With a next + * step, the argument conforms to the input contract and the refusal is about + * the selected directory's state, so it names its own recovery. + */ export const decompileInputError = ( path: string, message: string, + nextStep?: string, ): AnalysisInputError => - new AnalysisInputError("decompile_all", { userMessage: message }, [ - { path: [path], reason: "invalid_value", message }, - ]); + new AnalysisInputError( + "decompile_all", + nextStep === undefined + ? { userMessage: message } + : { + userMessage: message, + remediationAction: nextStep, + conformsToInputContract: true, + }, + [{ path: [path], reason: "invalid_value", message }], + ); diff --git a/src/application/desktop/DesktopBuildBundle.ts b/src/application/desktop/DesktopBuildBundle.ts index da8b7d11b3f..6f49d246c33 100644 --- a/src/application/desktop/DesktopBuildBundle.ts +++ b/src/application/desktop/DesktopBuildBundle.ts @@ -63,6 +63,8 @@ const readAptKey = async (path: string): Promise => { const refuse = (reason: string, cause?: unknown) => new AnalysisInputError(START, { userMessage: `The apt key file ${path} ${reason}.`, + remediationAction: + "Name an apt key file that is a readable regular file of a signing key's size, then start the build computer again.", conformsToInputContract: true, ...(cause === undefined ? {} : { cause }), }); diff --git a/src/application/desktop/DesktopBuildComputers.ts b/src/application/desktop/DesktopBuildComputers.ts index 127863bc1b1..2ff1d276b02 100644 --- a/src/application/desktop/DesktopBuildComputers.ts +++ b/src/application/desktop/DesktopBuildComputers.ts @@ -134,10 +134,11 @@ export interface BuildComputerSteps { readonly turns: DesktopBuildTurns; } -const unknownComputer = (operation: string) => +/** A computer_id that names no build computer this REA server holds. */ +export const unknownComputer = (operation: string): AnalysisInputError => new AnalysisInputError(operation, { - userMessage: - "No build computer has this id in this REA server; start one with start_build_computer.", + userMessage: "No build computer has this id in this REA server.", + remediationAction: "Start one with start_build_computer.", conformsToInputContract: true, }); diff --git a/src/application/desktop/DesktopBuildSteps.ts b/src/application/desktop/DesktopBuildSteps.ts index c6014a61d9e..60d3cf5dbb9 100644 --- a/src/application/desktop/DesktopBuildSteps.ts +++ b/src/application/desktop/DesktopBuildSteps.ts @@ -7,10 +7,11 @@ import type { JsonValue } from "../../domain/jsonValue.js"; import { err, ok, type Result } from "../../domain/result.js"; import type { ProgressReporter } from "../../ports/ProgressReporter.js"; import type { StoppedCapture } from "./DesktopBuildSummary.js"; -import type { - BuildComputerSteps, - DesktopBuildComputers, - ForwardedResult, +import { + unknownComputer, + type BuildComputerSteps, + type DesktopBuildComputers, + type ForwardedResult, } from "./DesktopBuildComputers.js"; import type { ExportedBuild } from "./DesktopBuildExport.js"; import type { @@ -18,14 +19,6 @@ import type { DesktopBuildWitness, } from "./DesktopBuildWitness.js"; -const unknownComputer = (operation: string) => - new AnalysisInputError(operation, { - userMessage: - "No build computer has this id in this REA server; start one with start_build_computer.", - remediationAction: "Start one with start_build_computer.", - conformsToInputContract: true, - }); - type Identified = { readonly computer_id: string } & Value; /** diff --git a/src/application/desktop/DesktopCaptureFailure.test.ts b/src/application/desktop/DesktopCaptureFailure.test.ts index e2ea6dd7b62..7bdd58e2102 100644 --- a/src/application/desktop/DesktopCaptureFailure.test.ts +++ b/src/application/desktop/DesktopCaptureFailure.test.ts @@ -222,7 +222,11 @@ describe("failedCaptureError", () => { it("keeps a typed failure as the cleanup primary", () => { const failure = new AnalysisInputError( "capture_desktop_application", - { userMessage: "bad input", conformsToInputContract: true }, + { + userMessage: "bad input", + remediationAction: "Correct the input.", + conformsToInputContract: true, + }, [], ); const error = failedCaptureError(failure, [ diff --git a/src/application/desktop/DesktopTaskDraft.ts b/src/application/desktop/DesktopTaskDraft.ts index 656507e6aa4..a645234ebae 100644 --- a/src/application/desktop/DesktopTaskDraft.ts +++ b/src/application/desktop/DesktopTaskDraft.ts @@ -90,6 +90,8 @@ const draft = async ( if (!withheld.ok) throw new AnalysisInputError(OPERATION, { userMessage: `REA cannot withhold the sign-in state: ${withheld.error}.`, + remediationAction: + "Take the step the refusal names: mark the missing or misordered sign-in checkpoint, capture again when a walk may have missed a file, or name only captured paths under the app's home directory. Then draft the task again.", conformsToInputContract: true, }); const held = (home: string) => isWithinAny(home, withheld.value); diff --git a/src/application/investigation/EvidenceLedger.ts b/src/application/investigation/EvidenceLedger.ts index 68213d66121..ce905e1588b 100644 --- a/src/application/investigation/EvidenceLedger.ts +++ b/src/application/investigation/EvidenceLedger.ts @@ -392,7 +392,11 @@ export class EvidenceLedger { ); } if (this.#unknownHeads.has(unknown.unknown_id)) - return err(new UnknownRegistryError("already-exists")); + return err( + new UnknownRegistryError("already-exists", { + existingUnknownId: unknown.unknown_id, + }), + ); return this.#appendUnknown(unknown, parsedMutation); } @@ -437,7 +441,11 @@ export class EvidenceLedger { ); if (creationUnknown !== undefined) { if (creationUnknown.revision_digest !== unknown.revision_digest) - return err(new UnknownRegistryError("already-exists")); + return err( + new UnknownRegistryError("already-exists", { + existingUnknownId: unknown.unknown_id, + }), + ); const checked = this.#appendIncremental([evidence]); if (!checked.ok) return err(this.#exposeRefusedEvidence(checked.error, evidence)); @@ -480,7 +488,11 @@ export class EvidenceLedger { if (current === undefined) return err(new UnknownRegistryError("not-found")); if (current.revision !== input.expected_revision) - return err(new UnknownRegistryError("revision-conflict")); + return err( + new UnknownRegistryError("revision-conflict", { + currentRevision: current.revision, + }), + ); const headroom = admitInvestigationAuthentication( input, "update_unknown", diff --git a/src/application/javascript/JavaScriptApplicationService.ts b/src/application/javascript/JavaScriptApplicationService.ts index d7b38a9d6a0..b6126a9ccdd 100644 --- a/src/application/javascript/JavaScriptApplicationService.ts +++ b/src/application/javascript/JavaScriptApplicationService.ts @@ -10,6 +10,7 @@ import { z } from "zod"; import { ArtifactReaderFailure, + bindArtifactFileCleanup, type ArtifactResourceScope, translateArtifactFailure, } from "../../resources/index.js"; @@ -22,6 +23,7 @@ import { AnalysisAccessDeniedError, AnalysisOutputError, } from "../../domain/analysisErrorCore.js"; +import { hostDescriptorPressure } from "../../process/hostDescriptorPressure.js"; import { ArtifactOperationError } from "../../domain/artifactOperationError.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; import type { Evidence } from "../../domain/evidence.js"; @@ -197,8 +199,22 @@ export const analyzeJavaScriptApplicationValidated = async ( } // Preserve execution constraints and their completed partial Evidence. if (cause instanceof AnalysisError) return err(cause); - if (cause instanceof ArtifactReaderFailure) + if (cause instanceof ArtifactReaderFailure) { + // The directory reader reports an opendir refused for descriptor + // exhaustion as I/O; it clears when descriptors are released. The + // reader's cleanup leases stay bound to the reported failure. + const pressure = + cause.reason === "io" && cause.cleanup === undefined + ? hostDescriptorPressure(OPERATION, cause.cause, { + input_path: input.input_path, + }) + : undefined; + if (pressure !== undefined) { + bindArtifactFileCleanup(cause, pressure); + return err(pressure); + } return err(translateArtifactFailure(OPERATION, input.input_path, cause)); + } if (cause instanceof z.ZodError) return err( new AnalysisOutputError(OPERATION, describeResultSchemaFailure(cause), { @@ -220,20 +236,21 @@ export const analyzeJavaScriptApplicationValidated = async ( ...(typeof syscall === "string" ? { syscall } : {}), }; return err( - cause.code === "EACCES" || cause.code === "EPERM" - ? new AnalysisAccessDeniedError( - OPERATION, - input.input_path, - cause.code, - { cause, diagnostics }, - ) - : new ArtifactOperationError( - OPERATION, - "io", - undefined, - cause.message, - { cause, diagnostics }, - ), + hostDescriptorPressure(OPERATION, cause, diagnostics) ?? + (cause.code === "EACCES" || cause.code === "EPERM" + ? new AnalysisAccessDeniedError( + OPERATION, + input.input_path, + cause.code, + { cause, diagnostics }, + ) + : new ArtifactOperationError( + OPERATION, + "io", + undefined, + cause.message, + { cause, diagnostics }, + )), ); } return err( diff --git a/src/application/javascript/SourceToBundleReference.ts b/src/application/javascript/SourceToBundleReference.ts index 3581cd8804b..ff138c9f602 100644 --- a/src/application/javascript/SourceToBundleReference.ts +++ b/src/application/javascript/SourceToBundleReference.ts @@ -3,9 +3,11 @@ import { setImmediate } from "node:timers/promises"; import type { z } from "zod"; import type { compareSourceToBundleRequestSchema } from "../../contracts/javascript/applicationWorkflowInputContracts.js"; import { - historicalSourceGraphSchema, + historicalSourceGraphCommitmentHolds, + historicalSourceGraphStructureSchema, type HistoricalSourceGraph, } from "../../domain/referenceSourceGraph.js"; +import { EvidenceIntegrityError } from "../../domain/evidenceErrors.js"; import type { ArtifactResourceScope } from "../../resources/index.js"; import { cancelledBy, isAborted } from "../../domain/analysisErrorCore.js"; import type { AnalysisError } from "../../domain/analysisErrorBase.js"; @@ -51,7 +53,11 @@ export const resolveSourceToBundleReference = async ( "Insufficient heap headroom to authenticate the historical source graph", }); if (!headroom.ok) return headroom; - const parsed = historicalSourceGraphSchema.safeParse(read.value.data); + const parsed = historicalSourceGraphStructureSchema.safeParse( + read.value.data, + ); + const commitmentHolds = + parsed.success && historicalSourceGraphCommitmentHolds(parsed.data); // Dispatch aborts queued while synchronous validation and commitment hashing ran. await setImmediate(); if (isAborted(signal)) @@ -68,6 +74,19 @@ export const resolveSourceToBundleReference = async ( { cause: parsed.error }, ), ); + // A well-formed graph whose entries disagree with its root commitment is + // an integrity failure of the selected file, like a snapshot whose + // binding does not match, not a request error. + if (!commitmentHolds) + return err( + new EvidenceIntegrityError( + `Historical source graph ${read.value.path} does not match its root_sha256 commitment.`, + { + userMessage: + "The selected historical source graph's entries do not match its root_sha256 commitment.", + }, + ), + ); return ok({ reference: parsed.data, reference_source: { diff --git a/src/application/ntfs/NtfsJournalService.ts b/src/application/ntfs/NtfsJournalService.ts index 4a714edaa8b..60801ac25c7 100644 --- a/src/application/ntfs/NtfsJournalService.ts +++ b/src/application/ntfs/NtfsJournalService.ts @@ -13,7 +13,7 @@ import { readStableArtifact, assertStableArtifactState, projectStableArtifactFailure, - stableArtifactInputRecovery, + stableArtifactInputOptions, readerIntegrityFailure, } from "../../resources/index.js"; import { @@ -55,16 +55,9 @@ const inputFailure = ( message: string, cause?: Error, ) => - new AnalysisInputError( - operation, - { - cause, - ...(cause instanceof ArtifactReaderFailure - ? stableArtifactInputRecovery(cause) - : {}), - }, - [{ path: [parameter], reason: "invalid_format", message }], - ); + new AnalysisInputError(operation, stableArtifactInputOptions(cause), [ + { path: [parameter], reason: "invalid_format", message }, + ]); /** * An acquisition the call could not hold: above the caller's diff --git a/src/application/reverse/ReverseEngineeringService.ts b/src/application/reverse/ReverseEngineeringService.ts index 113f6964455..6edeb11c183 100644 --- a/src/application/reverse/ReverseEngineeringService.ts +++ b/src/application/reverse/ReverseEngineeringService.ts @@ -837,7 +837,7 @@ export class ReverseEngineeringService { ...(cause.capabilityError.userMessage === undefined ? {} : { userMessage: cause.capabilityError.userMessage }), - retryable: cause.capabilityError.retryable, + retry: cause.capabilityError.retry, ...ownedCleanupOptions(cause), }, ); @@ -958,7 +958,9 @@ export class ReverseEngineeringService { controlFailure.message, { cause, - retryable: controlFailure.retryable, + ...(controlFailure.retryable + ? { retry: "same_call" as const } + : {}), userMessage: controlFailure.message, remediationAction: remediation, diagnostics: { diff --git a/src/browser/assets/WebArtifactReads.ts b/src/browser/assets/WebArtifactReads.ts index 35939922911..3bc48008523 100644 --- a/src/browser/assets/WebArtifactReads.ts +++ b/src/browser/assets/WebArtifactReads.ts @@ -5,7 +5,7 @@ import { z } from "zod"; import { artifactFileCleanupError, ArtifactReaderFailure, - stableArtifactInputRecovery, + stableArtifactInputOptions, artifactFileCancellationError, artifactFilePrimaryFacts, type ArtifactFilePrimaryFacts, @@ -279,12 +279,7 @@ const selectedFileError = ( const selected = (message: string) => new AnalysisInputError( context.operation, - { - cause, - ...(cause instanceof ArtifactReaderFailure - ? stableArtifactInputRecovery(cause) - : {}), - }, + stableArtifactInputOptions(cause), [{ path: context.field, reason: "invalid_value", message }], ); if ( diff --git a/src/browser/history/CaptureFailures.ts b/src/browser/history/CaptureFailures.ts index 507b8c60484..d1a29a01ba5 100644 --- a/src/browser/history/CaptureFailures.ts +++ b/src/browser/history/CaptureFailures.ts @@ -11,7 +11,7 @@ import { type ArtifactResourceScope, ArtifactFileCleanupFailure, ArtifactReaderFailure, - stableArtifactInputRecovery, + stableArtifactInputOptions, readerIntegrityFailure, bindArtifactFileCleanup, artifactFileCancellationError, @@ -464,20 +464,18 @@ export const historicalCaptureFailure = ( ) return new AnalysisInputError( OPERATION, - { - cause, - ...(cause.reason === "limit" - ? { - diagnostics: { - budget: webNetworkCaptureBudgetFacts(input, "max_input_bytes"), - }, - remediationAction: webNetworkCaptureBudgetRecovery( - input, - "max_input_bytes", - ), - } - : stableArtifactInputRecovery(cause)), - }, + cause.reason === "limit" + ? { + cause, + diagnostics: { + budget: webNetworkCaptureBudgetFacts(input, "max_input_bytes"), + }, + remediationAction: webNetworkCaptureBudgetRecovery( + input, + "max_input_bytes", + ), + } + : stableArtifactInputOptions(cause), [ { path: inputPath, diff --git a/src/cli/analysisEvidenceDelivery.ts b/src/cli/analysisEvidenceDelivery.ts index de98edcc7c4..6b9781cf62d 100644 --- a/src/cli/analysisEvidenceDelivery.ts +++ b/src/cli/analysisEvidenceDelivery.ts @@ -1080,7 +1080,12 @@ const refusedPartialPublication = ( ...(cleanupIncomplete ? { code: "cleanup_incomplete", - retryable: false, + // Both retry fields describe the unreleased cleanup, not the + // original failure. + retryable: refusal.retryable, + ...(refusal.retry_class === undefined + ? {} + : { retry_class: refusal.retry_class }), remediation: refusal.remediation, } : {}), diff --git a/src/cutter/CutterBridgeClient.ts b/src/cutter/CutterBridgeClient.ts index 39913092830..bedc25104bd 100644 --- a/src/cutter/CutterBridgeClient.ts +++ b/src/cutter/CutterBridgeClient.ts @@ -855,14 +855,23 @@ export class CutterBridgeClient { (candidate) => candidate.session_id === sessionId, ); if (descriptor === undefined) - throw new AnalysisInputError("cutter_command", undefined, [ + throw new AnalysisInputError( + "cutter_command", { - path: ["session_id"], - reason: "invalid_value", - message: - "Cutter bridge session is unavailable or stale; list sessions again and select an available session.", + userMessage: "This Cutter bridge session is unavailable or stale.", + remediationAction: + "Call list_cutter_sessions and retry with an available session_id.", + conformsToInputContract: true, }, - ]); + [ + { + path: ["session_id"], + reason: "invalid_value", + message: + "Cutter bridge session is unavailable or stale; list sessions again and select an available session.", + }, + ], + ); return descriptor; } diff --git a/src/domain/analysisErrorBase.ts b/src/domain/analysisErrorBase.ts index 61eb5578e47..d2129d908fe 100644 --- a/src/domain/analysisErrorBase.ts +++ b/src/domain/analysisErrorBase.ts @@ -255,8 +255,8 @@ export interface AnalysisErrorOwnPresentation { readonly continuing?: AnalysisContinuingCallerGuidance; /** The next step; absent keeps the shared fallback. */ readonly remediation?: string; - /** False when the failure cannot clear on retry whatever its code. */ - readonly retryable?: false; + /** What the caller must do before the request can succeed. */ + readonly retry: AnalysisRetryClass; readonly details?: Readonly>; } @@ -671,6 +671,7 @@ import type { FileOffsetPartialObservation } from "./native/fileOffsetPartialObs import type { NativeCallPartialObservation } from "./native/nativeCallPartialObservation.js"; import type { HopperCallerReconciliationPartial } from "./native/hopperCallerReconciliation.js"; import type { AnalysisErrorProjection } from "./analysisErrorProjection.js"; +import type { AnalysisRetryClass } from "./analysisErrorClassification.js"; import type { ElectronActiveObservationResult, ElectronActivePartialObservation, diff --git a/src/domain/analysisErrorClassification.test.ts b/src/domain/analysisErrorClassification.test.ts index 5c77df2d5bc..cfebc9d49b9 100644 --- a/src/domain/analysisErrorClassification.test.ts +++ b/src/domain/analysisErrorClassification.test.ts @@ -4,7 +4,7 @@ import { analysisErrorCatalogue } from "./analysisErrorClassification.js"; import { projectAnalysisError } from "./analysisErrorProjection.js"; import { ArtifactOperationError } from "./artifactOperationError.js"; import { BinaryTargetError } from "./configurationErrors.js"; -import { EvidenceFileError } from "./evidenceErrors.js"; +import { EvidenceFileError, EvidenceReferenceError } from "./evidenceErrors.js"; const catalogue = analysisErrorCatalogue(); const entry = (tag: string, discriminant: string) => @@ -35,6 +35,7 @@ it.each([ expect(entry("EvidenceFileError", `reason=${reason}`)).toMatchObject({ code: projected.code, category: projected.category, + retry: projected.retry_class, retryableByDefault: projected.retryable, }); }, @@ -106,3 +107,72 @@ it("reports a budget-exceeded bundle target as its catalogue row", () => { ), ).toMatchObject({ code: denied.code, category: denied.category }); }); + +it("reports missing referenced Evidence as recoverable by importing it", () => { + const missing = projectAnalysisError( + new EvidenceReferenceError("evidence-1", "missing", { + expected: "retained Evidence", + actual: null, + }), + ); + expect(missing).toMatchObject({ + code: "evidence_integrity_mismatch", + category: "integrity_mismatch", + retryable: false, + retry_class: "change_first", + }); + expect( + entry( + "EvidenceIntegrityError", + "referenced Evidence missing from this session", + ), + ).toMatchObject({ retry: "change_first" }); + // Evidence that names another identity cannot be repaired by importing. + expect( + projectAnalysisError( + new EvidenceReferenceError("evidence-1", "identity_mismatch", { + expected: "sha256:a", + actual: "sha256:b", + }), + ), + ).toMatchObject({ retry_class: "never" }); +}); + +it("reports a release-fixed artifact ceiling as never retryable", () => { + const projected = projectAnalysisError( + new ArtifactOperationError( + "inspect_artifact", + "limit", + undefined, + undefined, + { + fixedAllowance: { name: "The fixture integer ceiling", kind: "count" }, + }, + ), + ); + expect(projected).toMatchObject({ code: "partial", retry_class: "never" }); +}); + +it("reports a stale admitted identity as recoverable by reopening", () => { + const projected = projectAnalysisError( + new ArtifactOperationError( + "inspect_keyed_archive", + "integrity", + undefined, + undefined, + { integrityCheck: "admitted-identity" }, + ), + ); + expect(projected).toMatchObject({ + code: "artifact_operation_failed", + category: "integrity_mismatch", + retryable: false, + retry_class: "change_first", + }); + expect( + entry( + "ArtifactOperationError", + "reason=integrity; the session's admitted identity no longer matches", + ), + ).toMatchObject({ retry: "change_first" }); +}); diff --git a/src/domain/analysisErrorClassification.ts b/src/domain/analysisErrorClassification.ts index 845ffb5549d..1b5b6164e48 100644 --- a/src/domain/analysisErrorClassification.ts +++ b/src/domain/analysisErrorClassification.ts @@ -1,11 +1,14 @@ import { AnalysisCapabilityUnavailableError, + AnalysisResourceConstraintError, AnalysisTargetFailureError, } from "./analysisErrorCore.js"; import { TARGET_FAILURE_KINDS, TARGET_FAILURE_PROJECTIONS, + targetFailureRetry, type TargetFailureKind, + type TargetFailureRetry, } from "./targetFailure.js"; import { domainErrorTag, @@ -24,7 +27,11 @@ import { BinaryTargetError, type BinaryTargetErrorOptions, } from "./configurationErrors.js"; -import { EvidenceFileError } from "./evidenceErrors.js"; +import { + EvidenceFileError, + EvidenceReferenceError, + ResourceSnapshotMismatchError, +} from "./evidenceErrors.js"; import { ProviderSelectionError, type ProviderSelectionFailureReason, @@ -34,20 +41,36 @@ import { UnknownRegistryError } from "./unknownRegistryError.js"; type ErrorCode = AnalysisErrorProjection["code"]; type ErrorCategory = AnalysisErrorProjection["category"]; -/** The caller-facing code and category of one domain error case. */ +/** + * What the caller must do before the failed request can succeed. Only the + * failure's producer knows this, so every classification declares it: + * - `same_call`: the unchanged request may succeed later (a transient fault, + * occupied capacity, a cancellation or a deadline). + * - `change_first`: the caller must change the request or the state it reads + * first (re-read a revision, raise a limit, settle a disposition). + * - `never`: no change the caller can make to this request clears it. + * - `unknown_outcome`: the request may have taken effect; reconcile the + * resulting state before deciding to repeat it. + */ +export type AnalysisRetryClass = + | "same_call" + | "change_first" + | "never" + | "unknown_outcome"; + +/** The caller-facing code, category and retry class of one error case. */ export interface AnalysisErrorClassification { readonly code: ErrorCode; readonly category: ErrorCategory; + readonly retry: AnalysisRetryClass; } -/** Codes whose failures may succeed when the unchanged request is repeated. */ -export const RETRYABLE_CODES: ReadonlySet = new Set([ - "artifact_changed", - "provider_timeout", - "cancelled", - "revision_conflict", - "provider_unavailable", -]); +/** A target failure kind's public retry hint, as the shared retry class. */ +const TARGET_FAILURE_RETRY_CLASSES = { + backoff: "same_call", + after_change: "change_first", + none: "never", +} as const satisfies Readonly>; /** Domain tags whose classification depends on the error's own facts. */ type SpecializedErrorTag = @@ -63,34 +86,67 @@ type SpecializedErrorTag = const classified = ( code: ErrorCode, category: ErrorCategory, -): AnalysisErrorClassification => ({ code, category }); + retry: AnalysisRetryClass, +): AnalysisErrorClassification => ({ code, category, retry }); const STATIC_ERROR_CLASSIFICATIONS = { - AnalysisProtocolError: classified("unreadable_output", "execution_failure"), - AnalysisOutputError: classified("unreadable_output", "execution_failure"), - AnalysisInputError: classified("invalid_request", "invalid_input"), - AnalysisAccessDeniedError: classified("access_denied", "unavailable"), + AnalysisProtocolError: classified( + "unreadable_output", + "execution_failure", + "never", + ), + AnalysisOutputError: classified( + "unreadable_output", + "execution_failure", + "never", + ), + AnalysisInputError: classified( + "invalid_request", + "invalid_input", + "change_first", + ), + AnalysisAccessDeniedError: classified( + "access_denied", + "unavailable", + "change_first", + ), AnalysisArtifactChangedError: classified( "artifact_changed", "integrity_mismatch", + "same_call", ), AnalysisCapabilityUnavailableError: classified( "capability_unavailable", "unsupported_provider", + "never", ), - AnalysisCancelledError: classified("cancelled", "cancelled"), - AnalysisTimeoutError: classified("provider_timeout", "timeout"), + AnalysisCancelledError: classified("cancelled", "cancelled", "same_call"), + AnalysisTimeoutError: classified("provider_timeout", "timeout", "same_call"), AnalysisResourceConstraintError: classified( "resource_constraint", "resource_constraint", + "change_first", + ), + ConfigurationError: classified( + "configuration_invalid", + "invalid_input", + "change_first", + ), + NoBinaryOpenError: classified( + "target_unavailable", + "unavailable", + "change_first", ), - ConfigurationError: classified("configuration_invalid", "invalid_input"), - NoBinaryOpenError: classified("target_unavailable", "unavailable"), EvidenceIntegrityError: classified( "evidence_integrity_mismatch", "integrity_mismatch", + "never", + ), + ProviderAdapterError: classified( + "execution_failure", + "execution_failure", + "never", ), - ProviderAdapterError: classified("execution_failure", "execution_failure"), } as const satisfies Readonly< Record< Exclude, @@ -98,28 +154,39 @@ const STATIC_ERROR_CLASSIFICATIONS = { > >; -/** A capability the caller may wait for is unavailable, not unsupported. */ -const RETRYABLE_CAPABILITY_UNAVAILABLE = classified( - "capability_unavailable", - "unavailable", -); +/** + * A capability the caller may wait for, or make available, is unavailable, + * not unsupported. Its producer says which. + */ +const availableLaterCapability = ( + retry: "same_call" | "change_first", +): AnalysisErrorClassification => + classified("capability_unavailable", "unavailable", retry); -/** The code and category the projection table gives one target failure kind. */ +/** The classification the projection table gives one target failure kind. */ const kindClassification = ( kind: TargetFailureKind, ): AnalysisErrorClassification => { - const { code, category } = TARGET_FAILURE_PROJECTIONS[kind]; - return { code, category }; + const { code, category, retry } = TARGET_FAILURE_PROJECTIONS[kind]; + return { code, category, retry: TARGET_FAILURE_RETRY_CLASSES[retry] }; }; const ARTIFACT_OPERATION_CLASSIFICATIONS = { - cancelled: classified("cancelled", "cancelled"), + cancelled: classified("cancelled", "cancelled", "same_call"), // `limit` reports `partial`: the result was cut short. - integrity: classified("artifact_operation_failed", "integrity_mismatch"), - limit: classified("partial", "partial"), - path: classified("artifact_operation_failed", "execution_failure"), - unavailable: classified("artifact_operation_failed", "unavailable"), - io: classified("artifact_operation_failed", "execution_failure"), + integrity: classified( + "artifact_operation_failed", + "integrity_mismatch", + "never", + ), + limit: classified("partial", "partial", "change_first"), + path: classified("artifact_operation_failed", "execution_failure", "never"), + unavailable: classified( + "artifact_operation_failed", + "unavailable", + "change_first", + ), + io: classified("artifact_operation_failed", "execution_failure", "never"), } as const satisfies Readonly< Record >; @@ -128,34 +195,75 @@ const ARTIFACT_OPERATION_CLASSIFICATIONS = { const ARTIFACT_IDENTITY_MISMATCH = classified( "artifact_integrity_mismatch", "integrity_mismatch", + "never", +); + +/** + * The session's opened target no longer matches its bytes: reopening the + * artifact, then retrying, recovers. + */ +const ARTIFACT_ADMITTED_IDENTITY_STALE = classified( + "artifact_operation_failed", + "integrity_mismatch", + "change_first", ); const EVIDENCE_FILE_CLASSIFICATIONS = { // A missing, non-file or already-existing path is the caller's selection. - "not-file": classified("invalid_request", "invalid_input"), - exists: classified("invalid_request", "invalid_input"), - "wrong-kind": classified("invalid_request", "invalid_input"), - missing: classified("invalid_request", "invalid_input"), - "symlink-traversal": classified("invalid_request", "invalid_input"), + "not-file": classified("invalid_request", "invalid_input", "change_first"), + exists: classified("invalid_request", "invalid_input", "change_first"), + "wrong-kind": classified("invalid_request", "invalid_input", "change_first"), + missing: classified("invalid_request", "invalid_input", "change_first"), + "symlink-traversal": classified( + "invalid_request", + "invalid_input", + "change_first", + ), "invalid-json": classified( "evidence_integrity_mismatch", "execution_failure", + "never", ), - "path-limit": classified("resource_constraint", "resource_constraint"), - "storage-limit": classified("resource_constraint", "resource_constraint"), - io: classified("execution_failure", "execution_failure"), + "path-limit": classified( + "resource_constraint", + "resource_constraint", + "change_first", + ), + "storage-limit": classified( + "resource_constraint", + "resource_constraint", + "change_first", + ), + io: classified("execution_failure", "execution_failure", "never"), } as const satisfies Readonly< Record >; const UNKNOWN_REGISTRY_CLASSIFICATIONS = { - "not-found": classified("execution_failure", "execution_failure"), - "already-exists": classified("invalid_request", "invalid_input"), - "revision-conflict": classified("revision_conflict", "execution_failure"), - "invalid-transition": classified("execution_failure", "execution_failure"), - integrity: classified("evidence_integrity_mismatch", "execution_failure"), - limit: classified("partial", "execution_failure"), - constraint: classified("invalid_request", "invalid_input"), + // An unknown_id this session does not hold is the caller's selection. + "not-found": classified("invalid_request", "invalid_input", "change_first"), + "already-exists": classified( + "invalid_request", + "invalid_input", + "change_first", + ), + "revision-conflict": classified( + "revision_conflict", + "execution_failure", + "change_first", + ), + "invalid-transition": classified( + "execution_failure", + "execution_failure", + "change_first", + ), + integrity: classified( + "evidence_integrity_mismatch", + "execution_failure", + "never", + ), + limit: classified("partial", "execution_failure", "change_first"), + constraint: classified("invalid_request", "invalid_input", "change_first"), } as const satisfies Readonly< Record >; @@ -164,14 +272,28 @@ const PROVIDER_SELECTION_CLASSIFICATIONS = { unknown_provider: classified( "capability_unavailable", "unsupported_provider", + "change_first", + ), + provider_unavailable: classified( + "provider_unavailable", + "unavailable", + "same_call", ), - provider_unavailable: classified("provider_unavailable", "unavailable"), target_unsupported: classified( "capability_unavailable", "unsupported_provider", + "never", + ), + ambiguous: classified( + "capability_unavailable", + "unsupported_provider", + "change_first", + ), + invalid_options: classified( + "capability_unavailable", + "unsupported_provider", + "change_first", ), - ambiguous: classified("capability_unavailable", "unsupported_provider"), - invalid_options: classified("capability_unavailable", "unsupported_provider"), } as const satisfies Readonly< Record >; @@ -181,31 +303,71 @@ type BinaryTargetConstraintKey = | "unconstrained"; const BINARY_TARGET_CLASSIFICATIONS = { - unconstrained: classified("target_unavailable", "unavailable"), - directory_requires_file: classified("target_unavailable", "unavailable"), + unconstrained: classified( + "target_unavailable", + "unavailable", + "change_first", + ), + directory_requires_file: classified( + "target_unavailable", + "unavailable", + "change_first", + ), wasm_requires_static_inspection: classified( "target_unavailable", "unsupported_target", + "change_first", + ), + file_format_rejected: classified( + "target_unavailable", + "unsupported_target", + "change_first", + ), + load_selection_rejected: classified( + "invalid_request", + "invalid_input", + "change_first", ), - file_format_rejected: classified("target_unavailable", "unsupported_target"), - load_selection_rejected: classified("invalid_request", "invalid_input"), bundle_type_unsupported: classified( "target_unavailable", "unsupported_target", + "change_first", ), bundle_info_plist_decode_budget_exceeded: classified( "target_unavailable", "unavailable", + "change_first", + ), + bundle_info_plist_missing: classified( + "target_unavailable", + "unavailable", + "change_first", + ), + bundle_layout_ambiguous: classified( + "target_unavailable", + "unavailable", + "change_first", + ), + bundle_executable_undeclared: classified( + "target_unavailable", + "unavailable", + "change_first", + ), + bundle_program_missing: classified( + "target_unavailable", + "unavailable", + "change_first", ), - bundle_info_plist_missing: classified("target_unavailable", "unavailable"), - bundle_layout_ambiguous: classified("target_unavailable", "unavailable"), - bundle_executable_undeclared: classified("target_unavailable", "unavailable"), - bundle_program_missing: classified("target_unavailable", "unavailable"), bundle_current_version_missing: classified( "target_unavailable", "unavailable", + "change_first", + ), + bundle_path_escapes: classified( + "target_unavailable", + "unavailable", + "change_first", ), - bundle_path_escapes: classified("target_unavailable", "unavailable"), } as const satisfies Readonly< Record >; @@ -222,39 +384,101 @@ const binaryTargetClassification = ( }; const BROWSER_OBSERVATION_CLASSIFICATIONS = { - endpoint_unreachable: classified("provider_unavailable", "unavailable"), + endpoint_unreachable: classified( + "provider_unavailable", + "unavailable", + "same_call", + ), invalid_endpoint_response: classified( "unreadable_output", "execution_failure", + "never", + ), + target_not_found: classified( + "target_unavailable", + "unavailable", + "change_first", + ), + target_not_allowed: classified( + "target_unavailable", + "unavailable", + "change_first", + ), + application_already_running: classified( + "target_unavailable", + "unavailable", + "change_first", + ), + service_worker_blocked: classified( + "target_unavailable", + "unavailable", + "change_first", + ), + target_changed: classified( + "target_unavailable", + "unavailable", + "change_first", + ), + target_session_detached: classified( + "target_unavailable", + "unavailable", + "change_first", + ), + protocol_error: classified("unreadable_output", "execution_failure", "never"), + disconnected: classified("provider_unavailable", "unavailable", "same_call"), + payload_limit: classified("partial", "partial", "change_first"), + window_not_found: classified( + "unreadable_output", + "execution_failure", + "never", + ), + window_metadata_missing: classified( + "unreadable_output", + "execution_failure", + "never", ), - target_not_found: classified("target_unavailable", "unavailable"), - target_not_allowed: classified("target_unavailable", "unavailable"), - application_already_running: classified("target_unavailable", "unavailable"), - service_worker_blocked: classified("target_unavailable", "unavailable"), - target_changed: classified("target_unavailable", "unavailable"), - target_session_detached: classified("target_unavailable", "unavailable"), - protocol_error: classified("unreadable_output", "execution_failure"), - disconnected: classified("provider_unavailable", "unavailable"), - 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( "unreadable_output", "execution_failure", + "never", ), - cleanup_failed: classified("execution_failure", "execution_failure"), - cancelled: classified("cancelled", "cancelled"), - timeout: classified("provider_timeout", "timeout"), + cleanup_failed: classified("execution_failure", "execution_failure", "never"), + cancelled: classified("cancelled", "cancelled", "same_call"), + timeout: classified("provider_timeout", "timeout", "same_call"), } as const satisfies Readonly< Record >; +/** + * A snapshot path given to a resource-only session, which has no executable + * binding: the caller's selection, not changed or forged Evidence. A missing + * Evidence reference stays an integrity failure, because the same reason + * reports a retained source or closure member that the supplied Evidence + * itself should have held. + */ +const RESOURCE_SNAPSHOT_NOT_APPLICABLE = classified( + "invalid_request", + "invalid_input", + "change_first", +); + +/** + * Referenced Evidence this session does not hold: importing the missing + * records lets the same request succeed. + */ +const EVIDENCE_REFERENCE_MISSING = classified( + "evidence_integrity_mismatch", + "integrity_mismatch", + "change_first", +); + /** Any error the caller's cancellation caused reports as that cancellation. */ -const CANCELLED = classified("cancelled", "cancelled"); +const CANCELLED = classified("cancelled", "cancelled", "same_call"); const PROCESS_CAPTURE_FAILED = classified( "process_capture_failed", "execution_failure", + "never", ); /** A tag whose code and category do not depend on the error's facts. */ @@ -280,20 +504,27 @@ const staticClassification = ( }; /** - * The code and category of a domain-presented error. A provider-owned error - * supplies its own through `ownPresentation()`. Cleanup state is applied by - * the projection, which reports `cleanup_incomplete` above this code. + * The code, category and retry class of a domain-presented error. A + * provider-owned error supplies its own through `ownPresentation()`. Cleanup + * state is applied by the projection, which reports `cleanup_incomplete` + * above this code. */ export const classifyAnalysisError = ( error: AnalysisError, ): AnalysisErrorClassification => { const owned = error.ownPresentation(); if (owned !== undefined) - return { code: owned.code, category: owned.category }; - if (error instanceof AnalysisCapabilityUnavailableError && error.retryable) - return RETRYABLE_CAPABILITY_UNAVAILABLE; + return { code: owned.code, category: owned.category, retry: owned.retry }; + if ( + error instanceof AnalysisCapabilityUnavailableError && + error.retry !== "never" + ) + return availableLaterCapability(error.retry); if (error instanceof AnalysisTargetFailureError) - return kindClassification(error.failure.kind); + return { + ...kindClassification(error.failure.kind), + retry: TARGET_FAILURE_RETRY_CLASSES[targetFailureRetry(error.failure)], + }; if (error instanceof ProviderSelectionError) return PROVIDER_SELECTION_CLASSIFICATIONS[error.reason]; if (error instanceof BrowserObservationError) @@ -301,9 +532,23 @@ export const classifyAnalysisError = ( ? CANCELLED : BROWSER_OBSERVATION_CLASSIFICATIONS[error.reason]; if (error instanceof ArtifactOperationError) { + // A reader limit says whether the caller can raise it; a release-fixed + // allowance cannot change. + if (error.reason !== "integrity" && error.fixedAllowance !== undefined) + return { + ...ARTIFACT_OPERATION_CLASSIFICATIONS[error.reason], + retry: "never", + }; + if (error.readerLimit !== undefined && error.reason !== "integrity") + return { + ...ARTIFACT_OPERATION_CLASSIFICATIONS[error.reason], + retry: error.readerLimit.can_increase ? "change_first" : "never", + }; if (error.reason !== "integrity") return ARTIFACT_OPERATION_CLASSIFICATIONS[error.reason]; if (error.artifactDetails !== undefined) return ARTIFACT_IDENTITY_MISMATCH; + if (error.integrityCheck === "admitted-identity") + return ARTIFACT_ADMITTED_IDENTITY_STALE; // A target that changed during the read is the model's `changed` kind. return integrityCheckMeansChanged(error.integrityCheck) ? kindClassification("changed") @@ -316,24 +561,50 @@ export const classifyAnalysisError = ( ); if (error instanceof EvidenceFileError) return EVIDENCE_FILE_CLASSIFICATIONS[error.reason]; + if (error instanceof ResourceSnapshotMismatchError) + return RESOURCE_SNAPSHOT_NOT_APPLICABLE; + if (error instanceof EvidenceReferenceError && error.reason === "missing") + return EVIDENCE_REFERENCE_MISSING; if (error instanceof UnknownRegistryError) return UNKNOWN_REGISTRY_CLASSIFICATIONS[error.reason]; if (error._tag === "ProcessCaptureError") return error.userCategory === "cancelled" ? CANCELLED - : PROCESS_CAPTURE_FAILED; + : "retryable" in error && error.retryable === true + ? { ...PROCESS_CAPTURE_FAILED, retry: "same_call" } + : PROCESS_CAPTURE_FAILED; + if (error instanceof AnalysisResourceConstraintError) + return { + ...STATIC_ERROR_CLASSIFICATIONS.AnalysisResourceConstraintError, + retry: resourceConstraintRetry(error), + }; return staticClassification(error); }; +/** + * A resource refusal's producer declares whether the same request can be + * admitted later. Occupied capacity can; a fixed allowance cannot change; + * any other bound needs a changed request or limit first. + */ +const resourceConstraintRetry = ( + error: AnalysisResourceConstraintError, +): AnalysisRetryClass => + (error.retryable ?? error.resource === "capacity") + ? "same_call" + : error.fixedAllowance === undefined + ? "change_first" + : "never"; + /** One row of the generated error catalogue. */ export interface AnalysisErrorCatalogueEntry extends AnalysisErrorClassification { readonly tag: AnalysisErrorTag | ProviderErrorTag; /** The fact that selects this row; empty when the tag alone does. */ readonly discriminant: string; /** - * Whether the projection reports the case as retryable. An error's own - * recovery facts can still change it: a resource constraint's recovery, a - * raisable reader limit, a capture's retry flag, or a provider's opt-out. + * Whether the projection reports the case as retryable: its retry class is + * `same_call`. An error's own facts can still change the class: a resource + * constraint's recovery, a reader limit, a capture's retry flag, or a + * capability's declared availability. */ readonly retryableByDefault: boolean; } @@ -346,12 +617,11 @@ export const catalogueRow = ( tag: AnalysisErrorTag | ProviderErrorTag, discriminant: string, classification: AnalysisErrorClassification, - retryableByDefault = RETRYABLE_CODES.has(classification.code), ): AnalysisErrorCatalogueEntry => ({ tag, discriminant, ...classification, - retryableByDefault, + retryableByDefault: classification.retry === "same_call", }); const reasonRows = ( @@ -375,25 +645,37 @@ export const analysisErrorCatalogue = ), catalogueRow( "AnalysisCapabilityUnavailableError", - "retryable=true", - RETRYABLE_CAPABILITY_UNAVAILABLE, - true, + "retry=same_call", + availableLaterCapability("same_call"), ), - ...TARGET_FAILURE_KINDS.map((kind) => { - const { code, category, retry } = TARGET_FAILURE_PROJECTIONS[kind]; - return catalogueRow( + catalogueRow( + "AnalysisCapabilityUnavailableError", + "retry=change_first", + availableLaterCapability("change_first"), + ), + ...TARGET_FAILURE_KINDS.map((kind) => + catalogueRow( "AnalysisTargetFailureError", `kind=${kind}`, - { code, category }, - retry === "backoff", - ); - }), + kindClassification(kind), + ), + ), ...reasonRows("ArtifactOperationError", ARTIFACT_OPERATION_CLASSIFICATIONS), catalogueRow( "ArtifactOperationError", "reason=integrity; artifact identity reported", ARTIFACT_IDENTITY_MISMATCH, ), + catalogueRow( + "ArtifactOperationError", + "reason=limit; release-fixed allowance", + { ...ARTIFACT_OPERATION_CLASSIFICATIONS.limit, retry: "never" }, + ), + catalogueRow( + "ArtifactOperationError", + "reason=integrity; the session's admitted identity no longer matches", + ARTIFACT_ADMITTED_IDENTITY_STALE, + ), catalogueRow( "ArtifactOperationError", "reason=integrity; target changed during the read", @@ -426,6 +708,16 @@ export const analysisErrorCatalogue = CANCELLED, ), ...reasonRows("EvidenceFileError", EVIDENCE_FILE_CLASSIFICATIONS), + catalogueRow( + "EvidenceIntegrityError", + "analysis snapshot selected for a resource-only session", + RESOURCE_SNAPSHOT_NOT_APPLICABLE, + ), + catalogueRow( + "EvidenceIntegrityError", + "referenced Evidence missing from this session", + EVIDENCE_REFERENCE_MISSING, + ), catalogueRow("ProcessCaptureError", "", PROCESS_CAPTURE_FAILED), catalogueRow("ProcessCaptureError", "caused by cancellation", CANCELLED), ...reasonRows("ProviderSelectionError", PROVIDER_SELECTION_CLASSIFICATIONS), diff --git a/src/domain/analysisErrorCleanup.test.ts b/src/domain/analysisErrorCleanup.test.ts index 902533e766d..cd607d9da9c 100644 --- a/src/domain/analysisErrorCleanup.test.ts +++ b/src/domain/analysisErrorCleanup.test.ts @@ -519,7 +519,7 @@ it.each(["primary", "cleanup", "default", "cleanup-continuing"] as const)( owner === "cleanup" ? cleanupAction : owner === "default" - ? "This analysis is unavailable for the current target. Choose another analysis or target." + ? "Review details.reason, which names why the provider cannot run this operation. In a binary-analysis session, binary_session lists the operations available for the open target and provider; select one of those, or open a target that supports this analysis. Otherwise resolve the condition the reason names." : primaryAction; expect(projectAnalysisError(composed).remediation.action).toBe( owner === "cleanup-continuing" ? cleanupAction : expected, @@ -650,7 +650,7 @@ it("reports a capability refusal as retryable once its cleanup settles", () => { "inspect", "the selected provider is unavailable", { - retryable: true, + retry: "same_call", cleanup: { reason: "close denied", resources: ["owned-worker"] }, }, ); diff --git a/src/domain/analysisErrorCore.ts b/src/domain/analysisErrorCore.ts index 4db370c3271..df0bc728aee 100644 --- a/src/domain/analysisErrorCore.ts +++ b/src/domain/analysisErrorCore.ts @@ -280,6 +280,25 @@ export const parameterFileSizeConstraint = ( ); }; +/** + * Refuse while shared host capacity, such as open file descriptors, is + * occupied. It clears when other work releases it, so the unchanged request + * is retryable; the producer names how to free it. + */ +export const occupiedHostCapacityConstraint = ( + operation: string, + reason: string, + reportedLimits: Readonly>, + options: AnalysisErrorOptions & { readonly remediationAction: string }, +): AnalysisResourceConstraintError => + new AnalysisResourceConstraintError( + operation, + "capacity", + reason, + reportedLimits, + { ...options, retryable: true, measuredExhaustion: true }, + ); + /** * Refuse at a session setting the caller can change. The structured limit is * that setting. A parser limit still goes through `parseLimitConstraint`. @@ -358,6 +377,38 @@ export class AnalysisProtocolError extends AnalysisError { readonly _tag = "AnalysisProtocolError"; } +/** + * How an input refusal relates to the advertised input contract. + * + * A contract violation (missing, unknown, mistyped or malformed arguments) + * may leave recovery to the shared schema guidance. A refusal whose arguments + * conform cannot be corrected by re-reading the schema, so its producer must + * name the outcome and the next step; an ambiguous selection's refusal names + * its own recovery. + */ +export type AnalysisInputErrorOptions = AnalysisErrorOptions & + ( + | { + readonly conformsToInputContract?: false; + readonly userMessage?: string; + /** Refusal-specific correction beside the input-contract advice. */ + readonly remediationAction?: string; + readonly ambiguousSelector?: never; + } + | { + readonly conformsToInputContract: true; + readonly userMessage: string; + readonly remediationAction: string; + readonly ambiguousSelector?: never; + } + | { + readonly conformsToInputContract?: true; + readonly userMessage?: string; + readonly remediationAction?: string; + readonly ambiguousSelector: AmbiguousSelector; + } + ); + /** Caller input failed provider-neutral application parsing. */ export class AnalysisInputError extends AnalysisError { readonly _tag = "AnalysisInputError"; @@ -375,12 +426,7 @@ export class AnalysisInputError extends AnalysisError { constructor( readonly operation: string, - options?: AnalysisErrorOptions & { - readonly userMessage?: string; - readonly remediationAction?: string; - readonly conformsToInputContract?: boolean; - readonly ambiguousSelector?: AmbiguousSelector; - }, + options?: AnalysisInputErrorOptions, readonly issues: readonly AnalysisInputIssue[] = [], ) { super(`Invalid analysis input for ${operation}`, options); @@ -450,19 +496,22 @@ export class AnalysisCapabilityUnavailableError extends AnalysisError { readonly siblingOperations: readonly string[] | undefined; readonly siblingReasons: Readonly> | undefined; /** - * Incomplete cleanup must settle before the operation can be retried, so this - * follows the live cleanup state: an error built while cleanup was pending - * reports retryable once that owner releases. + * Whether the capability can become available: `same_call` when the + * condition may clear by itself, `change_first` when the caller must act + * first (such as settling a debugger inferior), `never` when the provider + * does not support the operation. Incomplete cleanup is applied once, by + * the projection. */ + readonly retry: "same_call" | "change_first" | "never"; + /** The unchanged request may succeed once the condition clears. */ get retryable(): boolean { - return this.#requestedRetryable && !this.cleanupIncomplete; + return this.retry === "same_call" && !this.cleanupIncomplete; } /** * Operations the caller can run now that observe part of what this one * would answer; the remediation states what they do not establish. */ readonly alternatives: readonly string[]; - readonly #requestedRetryable: boolean; constructor( readonly providerId: string, @@ -474,7 +523,7 @@ export class AnalysisCapabilityUnavailableError extends AnalysisError { readonly fallbackRemediationAction?: string; readonly siblingOperations?: readonly string[]; readonly siblingReasons?: Readonly>; - readonly retryable?: boolean; + readonly retry?: "same_call" | "change_first" | "never"; readonly alternatives?: readonly string[]; }, ) { @@ -487,7 +536,7 @@ export class AnalysisCapabilityUnavailableError extends AnalysisError { this.fallbackRemediationAction = options?.fallbackRemediationAction; this.siblingOperations = options?.siblingOperations; this.siblingReasons = options?.siblingReasons; - this.#requestedRetryable = options?.retryable === true; + this.retry = options?.retry ?? "never"; this.alternatives = Object.freeze([...(options?.alternatives ?? [])]); } } diff --git a/src/domain/analysisErrorPresentation.ts b/src/domain/analysisErrorPresentation.ts index 5e27365a3df..e1f32dd5977 100644 --- a/src/domain/analysisErrorPresentation.ts +++ b/src/domain/analysisErrorPresentation.ts @@ -274,6 +274,10 @@ export const analysisErrorRemediationAction = ( const refusal = analysisErrorRefusal(error); if (error.remediationAction === undefined && refusal !== undefined) return analysisRefusalRemediation(refusal, callerLifetime); + // A conforming refusal's producer always names its next step; the schema + // guidance below is only for arguments that violate the contract. + if (error.conformsToInputContract && error.remediationAction !== undefined) + return error.remediationAction; const mistakeRemediation = knownArgumentMistakeRemediation( error.operation, error.issues, @@ -329,14 +333,37 @@ export const analysisErrorRemediationAction = ( } if (error instanceof UnknownRegistryError && error.reason === "not-found") return "Check that the unknown_id belongs to this session, then retry."; + if ( + error instanceof UnknownRegistryError && + error.reason === "revision-conflict" + ) + return error.facts.currentRevision === undefined + ? "Read the unknown's current revision with list_unknowns, then retry update_unknown with that expected_revision." + : `Retry update_unknown with expected_revision ${String(error.facts.currentRevision)} after reviewing the current state with list_unknowns.`; if ( error instanceof NoBinaryOpenError && error.remediationAction !== undefined ) return error.remediationAction; + // A provider's own message names its repair (an unset REA_* command, an + // unsupported host); only a bare declared reason needs the inventory. + if ( + error instanceof AnalysisCapabilityUnavailableError && + error.userMessage === undefined + ) + return UNAVAILABLE_OPERATION_REMEDIATION; return analysisErrorUserMessage(error); }; +/** + * Recovery for an operation a provider declared unavailable without naming + * its own. The declared reason is in details. Only a binary-analysis + * session's inventory lists what its provider supports; a standalone + * provider such as a debugger bridge repairs the condition its reason names. + */ +const UNAVAILABLE_OPERATION_REMEDIATION = + "Review details.reason, which names why the provider cannot run this operation. In a binary-analysis session, binary_session lists the operations available for the open target and provider; select one of those, or open a target that supports this analysis. Otherwise resolve the condition the reason names."; + /** * Recovery for a measured exhaustion or occupied admission. A typed refusal * never reaches this: its own variant names the recovery. @@ -498,6 +525,13 @@ const outcomeUserMessage = (error: AnalysisError): string => { return "The requested residual unknown does not exist in this session. Check the unknown_id and try again."; if (error instanceof UnknownRegistryError && error.constraint !== undefined) return describeResidualUnknownGraphConstraint(error.constraint); + if ( + error instanceof UnknownRegistryError && + error.reason === "revision-conflict" + ) + return error.facts.currentRevision === undefined + ? "The unknown's stored revision does not match expected_revision." + : `The unknown's stored revision is ${String(error.facts.currentRevision)}, which does not match expected_revision.`; if (error instanceof UnknownRegistryError) return "Evidence state changed before the update completed. Refresh the current state and try again."; if (error instanceof ConfigurationError) @@ -549,7 +583,7 @@ const standardErrorMessage = (error: AnalysisError): string | undefined => { if (UNREADABLE_OUTPUT_TAGS.has(tag) || code === "unreadable_output") return "Analysis returned a result REA could not read. Review the reported details; repeating the unchanged request is not expected to succeed."; if (UNSUPPORTED_PROVIDER_TAGS.has(tag)) - return "This analysis is unavailable for the current target. Choose another analysis or target."; + return "This analysis is unavailable for the current target."; if (CANCELLED_TAGS.has(tag) || code === "cancelled") return "Analysis was cancelled. Start it again when ready."; return undefined; diff --git a/src/domain/analysisErrorProjection.test.ts b/src/domain/analysisErrorProjection.test.ts index 2f7c909fc47..28df86859b9 100644 --- a/src/domain/analysisErrorProjection.test.ts +++ b/src/domain/analysisErrorProjection.test.ts @@ -30,6 +30,7 @@ import { analysisErrorUserMessage, } from "./analysisErrorPresentation.js"; import { ProviderSelectionError } from "./providerSelectionError.js"; +import { unknownFridaSession } from "./fridaInputErrors.js"; import { analysisErrorProjectionSchema } from "./analysisErrorProjectionSchema.js"; import { nativeCallPartialObservationSchema } from "./native/nativeCallPartialObservation.js"; import { analysisSettingLimit } from "./analysisSettingDefinitions.js"; @@ -97,19 +98,36 @@ it("projects nested workflow-publication recovery for the actual caller lifetime describe("agent recovery metadata", () => { it("distinguishes deterministic duplicate identities from stale update revisions", () => { + const unknownId = `unk_${"1".repeat(64)}`; const duplicate = projectAnalysisError( - new UnknownRegistryError("already-exists"), + new UnknownRegistryError("already-exists", { + existingUnknownId: unknownId, + }), ); expect(duplicate).toMatchObject({ code: "invalid_request", category: "invalid_input", retryable: false, - details: { reason: "already-exists" }, + details: { reason: "already-exists", existing_unknown_id: unknownId }, }); expect(analysisErrorProjectionSchema.parse(duplicate)).toEqual(duplicate); - expect( - projectAnalysisError(new UnknownRegistryError("revision-conflict")), - ).toMatchObject({ code: "revision_conflict", retryable: true }); + // A stale expected_revision cannot succeed unchanged: the caller re-reads + // the reported revision first. + const conflict = projectAnalysisError( + new UnknownRegistryError("revision-conflict", { currentRevision: 3 }), + ); + expect(conflict).toMatchObject({ + code: "revision_conflict", + retryable: false, + message: + "The unknown's stored revision is 3, which does not match expected_revision.", + remediation: { + action: + "Retry update_unknown with expected_revision 3 after reviewing the current state with list_unknowns.", + }, + details: { reason: "revision-conflict", current_revision: 3 }, + }); + expect(analysisErrorProjectionSchema.parse(conflict)).toEqual(conflict); }); it.each(["history_gap", "revision_chain"] as const)( @@ -182,6 +200,7 @@ describe("agent recovery metadata", () => { category: "invalid_input", message: "No exact original-file offset exists.", retryable: false, + retry_class: "change_first", remediation: { action: "Select an address inside a file-backed mapping.", }, @@ -190,6 +209,22 @@ describe("agent recovery metadata", () => { expect(analysisErrorProjectionSchema.parse(projected)).toEqual(projected); }); + it("keeps a conforming refusal's own recovery through redaction, never the schema's", () => { + const refusal = unknownFridaSession("load_frida_script", "fixture-session"); + for (const error of [ + refusal, + redactExplicitFailure(refusal, ["fixture-session"]), + ]) { + const projected = projectAnalysisError(error); + expect(projected).not.toHaveProperty("recovery"); + expect(projected.remediation.action).toMatch( + /^Use a session_id that start_frida_session returned/u, + ); + expect(projected.remediation.action).not.toMatch(/schema|tools\/list/u); + expect(projected.message).not.toContain("Analysis input is invalid"); + } + }); + it("separates timeout-state inspection from client deadline recovery", () => { const projected = projectAnalysisError( new AnalysisTimeoutError("inspect_binary_layout", 2_500), @@ -221,7 +256,6 @@ describe("capability failure retry disposition", () => { { name: "an explicit refusal keeps its producer guidance", options: { - retryable: false, remediationAction: "Use the documented host workflow.", userMessage: "Host capability unavailable.", }, @@ -232,22 +266,22 @@ describe("capability failure retry disposition", () => { }, { name: "a transient failure can retry without switching targets", - options: { retryable: true }, + options: { retry: "same_call" }, category: "unavailable", retryable: true, action: expect.stringContaining("retry the same analysis"), message: "Required runtime controls are unavailable for this attempt.", }, { - name: "a transient refusal keeps its producer's recovery steps", + name: "a refusal the caller must act on first is not retryable unchanged", options: { - retryable: true, + retry: "change_first", remediationAction: "Choose an explicit disposition, then retry closing.", userMessage: "Close requires an explicit disposition.", }, category: "unavailable", - retryable: true, + retryable: false, action: "Choose an explicit disposition, then retry closing.", message: "Close requires an explicit disposition.", }, @@ -281,7 +315,7 @@ describe("capability failure retry disposition", () => { "inspect", "temporary failure", { - retryable: true, + retry: "same_call", cleanup: { reason: "owned handle is still live", resources: ["native-owner"], @@ -608,7 +642,63 @@ it("retains native partial observations and cleanup uncertainty on provider fail expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(true); }); +describe("analysis error projection: artifact reader limits", () => { + const limited = (canIncrease: boolean) => + new ArtifactOperationError("inventory_artifact", "limit", undefined, "", { + readerLimit: { + parameter: "max_entries", + effective_value: 10, + unit: "count", + minimum: 1, + maximum: canIncrease ? 100 : 10, + applies_at: "next_operation", + agent_editable: true, + can_increase: canIncrease, + update_mode: "parameter", + pending_restart: false, + }, + }); + + it("asks for a raised limit first, and never a same-call retry", () => { + expect(projectAnalysisError(limited(true))).toMatchObject({ + retryable: false, + retry_class: "change_first", + }); + expect(projectAnalysisError(limited(false))).toMatchObject({ + retryable: false, + retry_class: "never", + }); + const composed = analysisErrorWithCleanupFailure( + limited(true), + new ProviderCleanupError( + "artifact", + ["/tmp/reader"], + { reason: "close failed" }, + { operation: "inventory_artifact" }, + ), + "inventory_artifact", + ); + expect(projectAnalysisError(composed)).toMatchObject({ + code: "cleanup_incomplete", + retryable: false, + }); + releaseOwnedCleanup(composed); + }); +}); + describe("analysis error projection: browser provider failures", () => { + it("reports a protocol failure the caller's cancellation caused as cancelled", () => { + expect( + projectAnalysisError( + new BrowserObservationError( + "capture_browser_scenario", + "protocol_error", + { cause: new AnalysisCancelledError("capture_browser_scenario") }, + ), + ), + ).toMatchObject({ code: "cancelled", category: "cancelled" }); + }); + it("explains the service-worker policy refusal and names its recovery", () => { const projected = projectAnalysisError( new BrowserObservationError( @@ -932,11 +1022,27 @@ describe("analysis error projection: caller contract", () => { }); }); + it("describes a debugging-protocol failure instead of an unclassified one", () => { + const projected = projectAnalysisError( + new BrowserObservationError("inspect_web_page", "protocol_error"), + ); + expect(projected).toMatchObject({ + code: "unreadable_output", + details: { reason: "protocol_error" }, + }); + expect(projected.message).toMatch(/debugging-protocol exchange/u); + // The reason also covers REA's own protocol handling. + expect(projected.message).not.toMatch(/endpoint/u); + expect(projected.message).not.toContain("did not classify"); + }); + it("gives missing residual unknowns lookup-specific remediation", () => { expect( projectAnalysisError(new UnknownRegistryError("not-found")), ).toMatchObject({ - code: "execution_failure", + // An unknown_id the session does not hold is the caller's selection. + code: "invalid_request", + category: "invalid_input", message: expect.stringMatching( /residual unknown.*does not exist.*unknown_id/iu, ), @@ -1356,6 +1462,7 @@ describe("analysis error projection: provider-owned errors", () => { return { code: "provider_unavailable", category: "unavailable", + retry: "same_call", message: "The example provider stopped.", remediation: "Restart the example provider, then retry.", details: { stage: "launch" }, diff --git a/src/domain/analysisErrorProjection.ts b/src/domain/analysisErrorProjection.ts index f3fb6ff2a02..2e8cfe34e5d 100644 --- a/src/domain/analysisErrorProjection.ts +++ b/src/domain/analysisErrorProjection.ts @@ -65,7 +65,7 @@ import { analysisErrorRefusal } from "./analysisErrorRefusal.js"; import { analysisRefusalDetails } from "./analysisRefusal.js"; import { classifyAnalysisError, - RETRYABLE_CODES, + type AnalysisRetryClass, } from "./analysisErrorClassification.js"; import { isRecord } from "../kernel/isRecord.js"; import { reportedParseLimit } from "./parseFailure.js"; @@ -545,6 +545,7 @@ const projectError = ( ? errorRecovery(error) : cleanupRetryRecovery(cleanupRetry); const remediation = analysisErrorRemediationAction(error, callerLifetime); + const retryClass = analysisErrorRetry(error); const includesUnretainedEvidence = options.partialObservation && [partialObservation, completedSourceObservation].some( @@ -569,26 +570,10 @@ const projectError = ( code, category: analysisErrorCategory(error), message: analysisErrorUserMessage(error, callerLifetime), - retryable: - // `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) || - (error._tag === "ProcessCaptureError" && - "retryable" in error && - error.retryable === true) || - (error instanceof ArtifactOperationError && - error.readerLimit?.can_increase === true && - !error.cleanupIncomplete) || - (code === "resource_constraint" && - error instanceof AnalysisResourceConstraintError && - (error.retryable ?? error.resource === "capacity")), + // `retryable` keeps its contract meaning: the unchanged request may + // succeed. Only the producer's retry class says so. + retryable: retryClass === "same_call", + retry_class: retryClass, remediation: { action: cleanupRetry === undefined @@ -609,6 +594,20 @@ const projectError = ( }; }; +/** + * The retry class the failure's producer declared. Owned resources that are + * still unreleased must settle before the request can run again, so no + * failure with incomplete cleanup is `same_call`. + */ +export const analysisErrorRetry = ( + error: AnalysisError, +): AnalysisRetryClass => { + const { retry } = classifyAnalysisError(primaryAnalysisError(error)); + return retry === "same_call" && error.cleanupIncomplete + ? "change_first" + : retry; +}; + const errorRecovery = ( error: AnalysisError, ): AnalysisErrorRecovery | undefined => { @@ -790,6 +789,12 @@ const artifactStateErrorDetails = ( ...(error.constraint === undefined ? {} : { constraint: error.constraint }), + ...(error.facts.currentRevision === undefined + ? {} + : { current_revision: error.facts.currentRevision }), + ...(error.facts.existingUnknownId === undefined + ? {} + : { existing_unknown_id: error.facts.existingUnknownId }), }; if (error instanceof EvidenceFileError) return { @@ -1025,7 +1030,14 @@ export interface AnalysisErrorProjection extends Readonly< | "unavailable" | "execution_failure"; readonly message: string; + /** True exactly when `retry_class` is `same_call`. */ readonly retryable: boolean; + /** + * What the caller must do before the request can succeed, as its producer + * declared. Every projection this release builds sets it; an error retained + * by an earlier release may lack it. + */ + readonly retry_class?: AnalysisRetryClass; /** A target failure's retry hint, derived from its kind. */ readonly retry?: TargetFailureRetry; readonly remediation: Readonly<{ diff --git a/src/domain/analysisErrorProjectionSchema.ts b/src/domain/analysisErrorProjectionSchema.ts index 166cdc33b8f..ab89e694f21 100644 --- a/src/domain/analysisErrorProjectionSchema.ts +++ b/src/domain/analysisErrorProjectionSchema.ts @@ -26,6 +26,10 @@ const common = { category: categorySchema, message: z.string().min(1), retryable: z.boolean(), + // Always produced; optional when reading errors retained by earlier releases. + retry_class: z + .enum(["same_call", "change_first", "never", "unknown_outcome"]) + .optional(), retry: z.enum(["none", "backoff", "after_change"]).optional(), remediation: remediationSchema, recovery: analysisErrorRecoverySchema.optional(), diff --git a/src/domain/apple/machoSliceSelection.ts b/src/domain/apple/machoSliceSelection.ts index 9ec4afe7ac1..a093c37e443 100644 --- a/src/domain/apple/machoSliceSelection.ts +++ b/src/domain/apple/machoSliceSelection.ts @@ -129,14 +129,27 @@ const selectionError = ( failure: MachoSliceSelectionFailure, input: SliceSelectionInput, ): AnalysisError => { + // The selector is well formed; the file's slices decide whether it + // matches, so the refusal names the slices instead of the schema. if (failure.kind !== "target") - return new AnalysisInputError(operation, undefined, [ + return new AnalysisInputError( + operation, { - path: [input.architectureField], - reason: "invalid_value", - message: failure.message, + userMessage: failure.message, + remediationAction: + failure.kind === "ambiguous_architecture" + ? `Retry with ${input.architectureField} set to one of the architectures this file lists.` + : `Retry with ${input.architectureField} naming a slice this file contains, or omit it for a file that is not a universal Mach-O.`, + conformsToInputContract: true, }, - ]); + [ + { + path: [input.architectureField], + reason: "invalid_value", + message: failure.message, + }, + ], + ); return new AnalysisTargetFailureError(operation, path, failure.failure); }; diff --git a/src/domain/browserObservationError.ts b/src/domain/browserObservationError.ts index 144eb3874af..e3e9f30a547 100644 --- a/src/domain/browserObservationError.ts +++ b/src/domain/browserObservationError.ts @@ -125,5 +125,9 @@ const observationFailureMessage = ( return `${operation} refused the selected page because it is controlled by or has a registered service worker while the service-worker policy is block. Set environment.service_workers to allow to permit observation, or remove the service worker registration through the browser.`; if (reason === "disconnected") return `${operation} lost its debugging connection. Verify that the target process is still running, refresh target discovery, and retry the observation.`; + if (reason === "protocol_error") + // Covers an unreadable endpoint reply and a failure inside REA's own + // protocol handling, so it does not blame the endpoint. + return `${operation} could not complete a debugging-protocol exchange. Review the reported details; repeating the unchanged request is not expected to succeed.`; return undefined; }; diff --git a/src/domain/explicitSensitiveFailure.test.ts b/src/domain/explicitSensitiveFailure.test.ts index a14205cf1e4..1ace963e4af 100644 --- a/src/domain/explicitSensitiveFailure.test.ts +++ b/src/domain/explicitSensitiveFailure.test.ts @@ -284,7 +284,7 @@ it("preserves a retryable capability failure through explicit-value redaction", "mitmproxy", "inspect_web_network_capture", "Runtime admission for /targets/private/capture failed transiently", - { retryable: true }, + { retry: "same_call" }, ); expect(projectAnalysisError(error).retryable).toBe(true); const result = redactExplicitFailure(error, ["private"]); @@ -347,6 +347,23 @@ it("coarsens format issue pointers without creating replacement coordinates", () expect(result.issues[0]?.path).toEqual(["capture_path", "/metadata"]); }); +it("redacts excluded values inside ambiguous selector candidates", () => { + const error = new AnalysisInputError("inspect", { + ambiguousSelector: { + field: ["name"], + candidates: ["explicit-secret", { name: "explicit-secret-two" }, 3], + }, + }); + const result = redactExplicitFailure(error, ["explicit-secret"]); + if (!(result instanceof AnalysisInputError)) + throw new Error("Input error required"); + expect(result.ambiguousSelector?.field).toEqual(["name"]); + expect(result.ambiguousSelector?.candidates).toHaveLength(3); + expect(JSON.stringify(result.ambiguousSelector)).not.toContain( + "explicit-secret", + ); +}); + it("excludes a marked permission-denied path without losing its host error code", () => { const error = redactExplicitFailure( new AnalysisAccessDeniedError( diff --git a/src/domain/explicitSensitiveFailure.ts b/src/domain/explicitSensitiveFailure.ts index b264f4a08a6..c91eebc9cbf 100644 --- a/src/domain/explicitSensitiveFailure.ts +++ b/src/domain/explicitSensitiveFailure.ts @@ -6,6 +6,7 @@ import { AnalysisAccessDeniedError, AnalysisArtifactChangedError, AnalysisInputError, + type AnalysisInputErrorOptions, type AnalysisInputIssue, AnalysisOutputError, AnalysisCapabilityUnavailableError, @@ -92,6 +93,41 @@ export const redactSensitiveFailure = ( return redacted === error ? error : mirrorCleanup(error, redacted, text); }; +/** An input refusal's own text and contract side, with sensitive values redacted. */ +const inputRefusalText = ( + error: AnalysisInputError, + text: (value: string) => string, + json: (value: JsonValue) => JsonValue, +): AnalysisInputErrorOptions => { + const userMessage = + error.userMessage === undefined ? undefined : text(error.userMessage); + const remediationAction = + error.remediationAction === undefined + ? undefined + : text(error.remediationAction); + if (error.ambiguousSelector !== undefined) + return { + // Candidates are target values and may hold an excluded one. + ambiguousSelector: { + field: error.ambiguousSelector.field, + candidates: error.ambiguousSelector.candidates.map(json), + }, + ...(userMessage === undefined ? {} : { userMessage }), + ...(remediationAction === undefined ? {} : { remediationAction }), + }; + // A conforming refusal always carries both; the constructor requires them. + if ( + error.conformsToInputContract && + userMessage !== undefined && + remediationAction !== undefined + ) + return { conformsToInputContract: true, userMessage, remediationAction }; + return { + ...(userMessage === undefined ? {} : { userMessage }), + ...(remediationAction === undefined ? {} : { remediationAction }), + }; +}; + const redactFailure = ( error: AnalysisError, text: (value: string) => string, @@ -270,13 +306,7 @@ const redactFailure = ( error.operation, { ...context, - ...(error.userMessage === undefined - ? {} - : { userMessage: text(error.userMessage) }), - ...(error.remediationAction === undefined - ? {} - : { remediationAction: text(error.remediationAction) }), - conformsToInputContract: error.conformsToInputContract, + ...inputRefusalText(error, text, visit), }, error.issues.map(issueProjection), ); @@ -322,7 +352,7 @@ const redactFailure = ( ]), ), }), - ...(error.retryable ? { retryable: true } : {}), + retry: error.retry, }, ); if (error instanceof AnalysisResourceConstraintError) diff --git a/src/domain/referenceSourceGraph.ts b/src/domain/referenceSourceGraph.ts index 6c98bcf491f..fc2eba54311 100644 --- a/src/domain/referenceSourceGraph.ts +++ b/src/domain/referenceSourceGraph.ts @@ -197,15 +197,20 @@ const graphShape = { limitations: z.array(nonEmptyTextSchema), }; -const historicalSourceGraphStructureSchema = z +/** A graph whose fields and invariants hold, before its commitment is checked. */ +export const historicalSourceGraphStructureSchema = z .strictObject(graphShape) .superRefine(checkGraphInvariants); +/** Whether a structurally valid graph's root commitment matches its entries. */ +export const historicalSourceGraphCommitmentHolds = ( + graph: z.infer, +): boolean => + computeRootSha256(graph.entries, graph.exclusions) === graph.root_sha256; + export const historicalSourceGraphSchema = historicalSourceGraphStructureSchema.superRefine((graph, context) => { - if ( - computeRootSha256(graph.entries, graph.exclusions) !== graph.root_sha256 - ) + if (!historicalSourceGraphCommitmentHolds(graph)) context.addIssue({ code: "custom", message: "Historical source root commitment does not match entries", diff --git a/src/domain/runtimeControlUnavailableError.ts b/src/domain/runtimeControlUnavailableError.ts index 70c644eba4b..9b0336c67a4 100644 --- a/src/domain/runtimeControlUnavailableError.ts +++ b/src/domain/runtimeControlUnavailableError.ts @@ -33,7 +33,7 @@ export const runtimeControlCapabilityError = ( ): AnalysisCapabilityUnavailableError => new AnalysisCapabilityUnavailableError(providerId, operation, cause.message, { cause, - retryable: cause.retryable, + ...(cause.retryable ? { retry: "same_call" as const } : {}), ...(cause.remediationAction === undefined ? {} : { diff --git a/src/domain/targetFailure.test.ts b/src/domain/targetFailure.test.ts index 393bc9ed02e..5a5ae0949c5 100644 --- a/src/domain/targetFailure.test.ts +++ b/src/domain/targetFailure.test.ts @@ -3,6 +3,10 @@ import { describe, expect, it } from "vitest"; import { AnalysisTargetFailureError } from "./analysisErrorCore.js"; import { projectAnalysisError } from "./analysisErrorProjection.js"; import { analysisErrorProjectionSchema } from "./analysisErrorProjectionSchema.js"; +import { analysisErrorCatalogue } from "./analysisErrorClassification.js"; +import { analysisErrorWithCleanupFailure } from "./analysisErrorCleanup.js"; +import { ProviderCleanupError } from "./providerCleanupError.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; import { TARGET_FAILURE_KINDS, targetFailureDetails, @@ -70,6 +74,19 @@ describe("target failure projection", () => { }, }); expect(projected).not.toHaveProperty("recovery"); + // The generated catalogue row states the same retry contract. + expect( + analysisErrorCatalogue().find( + (row) => + row.tag === "AnalysisTargetFailureError" && + row.discriminant === `kind=${kind}`, + ), + ).toMatchObject({ + code, + category, + retry: projected.retry_class, + retryableByDefault: projected.retryable, + }); // Every kind's projection satisfies the schema CLI and MCP advertise. expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe( true, @@ -77,6 +94,31 @@ describe("target failure projection", () => { }, ); + it("does not invite a retry while a changed target's cleanup is incomplete", () => { + const composed = analysisErrorWithCleanupFailure( + new AnalysisTargetFailureError( + "inspect_elf_notes", + "/tmp/t", + failureOf("changed"), + ), + new ProviderCleanupError( + "elf", + ["/tmp/runtime"], + { reason: "close failed" }, + { operation: "inspect_elf_notes" }, + ), + "inspect_elf_notes", + ); + const projected = projectAnalysisError(composed); + releaseOwnedCleanup(composed); + expect(projected).toMatchObject({ + code: "cleanup_incomplete", + retryable: false, + }); + expect(projected.retry_class).not.toBe("same_call"); + expect(projected).not.toHaveProperty("retry"); + }); + it("gives no two kinds with unrelated caller actions one code", () => { const actions = new Map>(); for (const kind of TARGET_FAILURE_KINDS) { diff --git a/src/domain/unknownRegistryError.ts b/src/domain/unknownRegistryError.ts index e5f7fa00ec8..382a26fac70 100644 --- a/src/domain/unknownRegistryError.ts +++ b/src/domain/unknownRegistryError.ts @@ -1,11 +1,20 @@ import type { ResidualUnknownGraphConstraint } from "./residualUnknownGraphError.js"; import { AnalysisError } from "./analysisErrorBase.js"; +/** Registry facts only the refusing ledger knows, for the caller's next step. */ +export interface UnknownRegistryFacts { + /** The stored head's revision, reported with a revision conflict. */ + readonly currentRevision?: number; + /** The stored unknown that a duplicate record would have created. */ + readonly existingUnknownId?: string; +} + /** Residual-unknown mutation failed a lifecycle, reference, or CAS invariant. */ export class UnknownRegistryError extends AnalysisError { readonly _tag = "UnknownRegistryError"; readonly constraint: ResidualUnknownGraphConstraint | undefined; + readonly facts: UnknownRegistryFacts; readonly reason: | "not-found" | "already-exists" @@ -24,7 +33,7 @@ export class UnknownRegistryError extends AnalysisError { | "integrity" | "limit" | ResidualUnknownGraphConstraint, - options?: ErrorOptions, + options?: ErrorOptions & UnknownRegistryFacts, ) { const reason = typeof failure === "string" @@ -35,5 +44,13 @@ export class UnknownRegistryError extends AnalysisError { super(`Residual unknown registry mutation failed: ${reason}`, options); this.reason = reason; this.constraint = typeof failure === "string" ? undefined : failure; + this.facts = { + ...(options?.currentRevision === undefined + ? {} + : { currentRevision: options.currentRevision }), + ...(options?.existingUnknownId === undefined + ? {} + : { existingUnknownId: options.existingUnknownId }), + }; } } diff --git a/src/gdb/GdbSessionManager.ts b/src/gdb/GdbSessionManager.ts index 09b740c6df6..c741a9b35eb 100644 --- a/src/gdb/GdbSessionManager.ts +++ b/src/gdb/GdbSessionManager.ts @@ -1356,7 +1356,8 @@ export class GdbSessionManager { ? "Multiple live GDB inferiors require an explicit disposition because automatic detach supports only one inferior." : "Live GDB inferiors require an explicit disposition because no durable inferior TTY is verified.", { - retryable: true, + // The caller must detach or kill the inferiors first. + retry: "change_first", // Why automatic detach is refused, as the cleanup code a // forced stop would report, and how many inferiors remain. diagnostics: { diff --git a/src/ghidra/GhidraProvider.behavior.test.ts b/src/ghidra/GhidraProvider.behavior.test.ts index e0ff0878002..75ed086131c 100644 --- a/src/ghidra/GhidraProvider.behavior.test.ts +++ b/src/ghidra/GhidraProvider.behavior.test.ts @@ -2393,12 +2393,35 @@ describe("Ghidra file-offset outcome projection", () => { }); describe("Ghidra ordinary input refusals", () => { + it("names the open program, not the schema, for a document the bridge does not hold", async () => { + const message = + "Unknown Ghidra Program identity: other; active program: fixture"; + const client = await createElfClient(remoteFailure("not_found", message)); + onTestFinished(async () => { + await client.close(); + }); + const result = await client.execute("procedure_pseudo_code", { + procedure: "main", + }); + if (result.ok) throw new Error("Expected an input refusal"); + const projected = projectAnalysisError(result.error); + expect(projected).toMatchObject({ + code: "invalid_request", + message, + remediation: { + action: + "Call list_documents for the open program's name, or omit document to use the current program, then retry.", + }, + details: { diagnostics: { remote_code: "not_found" } }, + }); + expect(projected).not.toHaveProperty("recovery"); + }); + it.each([ ["address_to_file_offset", { address: "0x403010" }, "invalid_request"], - ["procedure_pseudo_code", { procedure: "missing" }, "not_found"], ["search_bytes", { pattern: "00" }, "invalid_request"], ] as const)( - "keeps schema recovery for an ordinary %s refusal", + "keeps schema recovery for a request the bridge rejected as malformed (%s)", async (operation, parameters, remoteCode) => { const message = "Fixture bridge rejected the request"; const client = await createElfClient(remoteFailure(remoteCode, message)); diff --git a/src/ghidra/GhidraSessionErrorProjection.ts b/src/ghidra/GhidraSessionErrorProjection.ts index 15702de4615..0e0b4e327dd 100644 --- a/src/ghidra/GhidraSessionErrorProjection.ts +++ b/src/ghidra/GhidraSessionErrorProjection.ts @@ -154,7 +154,7 @@ const projectPrimarySessionError = ( failure.cause.message, { ...context, - retryable: true, + retry: "same_call", userMessage: `${failure.cause.message}. Sessions share a checkpointed target; one at a time saves it.`, remediationAction: ghidraCheckpointSaveWaitRecovery( failure.cause.wait, @@ -171,7 +171,7 @@ const projectPrimarySessionError = ( failure.cause.message, { ...context, - retryable: false, + retry: "change_first", userMessage: `${failure.cause.message}.`, remediationAction: "Reopen the target: call open_binary again for this path, or rerun the CLI command. The current checkpoint is intact and REA_GHIDRA_CHECKPOINT_DIR needs no change.", @@ -306,16 +306,15 @@ const projectPrimarySessionError = ( if (typeEdit !== undefined) return new AnalysisInputError( operation, - { - ...context, - ...(typeEdit.recovery === undefined - ? {} - : { - remediationAction: typeEdit.recovery.action, - conformsToInputContract: true, - related: { operations: typeEdit.recovery.operations }, - }), - }, + typeEdit.recovery === undefined + ? context + : { + ...context, + userMessage: failure.message, + remediationAction: typeEdit.recovery.action, + conformsToInputContract: true, + related: { operations: typeEdit.recovery.operations }, + }, [ { path: [typeEdit.field], @@ -498,6 +497,50 @@ const projectPrimarySessionError = ( ...context, userMessage: failure.message, }); + // The bridge reports not_found only for a `document` that is not the + // open program; the caller selects the current one. + if (failure.kind === "remote" && failure.remoteCode === "not_found") + return new AnalysisInputError( + operation, + { + ...context, + userMessage: failure.message, + remediationAction: + "Call list_documents for the open program's name, or omit document to use the current program, then retry.", + conformsToInputContract: true, + related: { operations: ["list_documents"] }, + }, + [ + { + path: ["document"], + reason: "invalid_value", + message: failure.message, + }, + ], + ); + // A lookup the bridge could not resolve is a valid request about the + // current inventory; only a request the bridge rejected as malformed is + // left to the input schema. + if (failure.kind === "remote" && failure.remoteCode === "ambiguous") + return new AnalysisInputError( + operation, + { + ...context, + userMessage: failure.message, + remediationAction: + "Select an item the current Ghidra inventory reports (list_procedures, search_procedures, list_names or list_strings), then retry. A miss leaves its presence in the artifact unknown.", + conformsToInputContract: true, + related: { + operations: [ + "list_procedures", + "search_procedures", + "list_names", + "list_strings", + ], + }, + }, + [{ path: [], reason: "invalid_value", message: failure.message }], + ); if (failure.kind === "remote" && isGhidraInputFailureCode(failure.remoteCode)) return new AnalysisInputError(operation, context, [ { path: [], reason: "invalid_value", message: failure.message }, diff --git a/src/gpu/GpuCodeObjectsProvider.ts b/src/gpu/GpuCodeObjectsProvider.ts index d658d3a9e62..1d64ca10699 100644 --- a/src/gpu/GpuCodeObjectsProvider.ts +++ b/src/gpu/GpuCodeObjectsProvider.ts @@ -68,6 +68,7 @@ import { sameRegularFileState, } from "../filesystem/RegularFile.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { hostDescriptorPressure } from "../process/hostDescriptorPressure.js"; const OPERATION = "inspect_gpu_code_objects"; @@ -259,15 +260,18 @@ export class GpuCodeObjectsProvider implements GpuCodeObjectsPort { }, ); } - // Other coded I/O failures remain host failures (for example, EMFILE). + // Other coded I/O failures remain host failures; descriptor pressure + // is occupied host capacity. else - error = new ProviderAdapterError(this.identity.id, OPERATION, { - cause, - diagnostics: { - path: input.path, - reason: errorMessage(primary), - }, - }); + error = + hostDescriptorPressure(OPERATION, primary, { path: input.path }) ?? + new ProviderAdapterError(this.identity.id, OPERATION, { + cause, + diagnostics: { + path: input.path, + reason: errorMessage(primary), + }, + }); if ( cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined diff --git a/src/hopper/HopperErrorProjection.test.ts b/src/hopper/HopperErrorProjection.test.ts index 36d45b4f26d..ad4165207ef 100644 --- a/src/hopper/HopperErrorProjection.test.ts +++ b/src/hopper/HopperErrorProjection.test.ts @@ -282,6 +282,59 @@ describe("analysis error projection: retry guidance", () => { ); }); +describe("Hopper retry and guidance by provider state", () => { + it("lets the unchanged call relaunch a released startup attempt, but not a dead bridge", () => { + const released = projectAnalysisError( + new HopperProcessError(9, { providerState: "exited", stage: "launch" }), + ); + expect(released).toMatchObject({ + retryable: true, + retry_class: "same_call", + details: { retry_action: "retry" }, + }); + // An exited launch has no continuing caller to steer. + expect(released.message).toBe( + analysisErrorUserMessage( + new HopperProcessError(9, { providerState: "exited", stage: "launch" }), + "invocation", + ), + ); + // A reported setup failure needs the setup changed first. + expect(projectAnalysisError(new HopperProcessError(82))).toMatchObject({ + retryable: false, + retry_class: "change_first", + }); + const dead = projectAnalysisError( + new HopperProcessError(9, { + operation: "search_strings", + providerState: "exited", + }), + ); + expect(dead).toMatchObject({ + retryable: false, + retry_class: "change_first", + details: { retry_action: "restart_provider" }, + }); + }); + + it("reports an authorization refusal as unavailable", () => { + expect( + projectAnalysisError( + new HopperRemoteError(1, "denied", { diagnosticType: "authorization" }), + ), + ).toMatchObject({ category: "unavailable", retryable: false }); + }); + + it("leaves another session's ownership of the target to the caller", () => { + expect( + projectAnalysisError(new HopperStartError({ ownerRunId: "run-1" })), + ).toMatchObject({ + retryable: false, + details: { retry_action: "unknown" }, + }); + }); +}); + describe("analysis error projection: operational diagnostics", () => { it("distinguishes an observed Hopper exit from an undetermined provider failure", () => { const exitedError = new HopperProcessError(7, { @@ -289,9 +342,11 @@ describe("analysis error projection: operational diagnostics", () => { requestId: 4, }); const exited = projectAnalysisError(exitedError); + // The same call does not relaunch the exited bridge; the caller restarts + // the owned provider first. expect(exited).toMatchObject({ code: "provider_unavailable", - retryable: true, + retryable: false, details: { stage: "analysis", provider_state: "exited", @@ -530,9 +585,49 @@ describe("analysis error projection: Hopper caller lifetime", () => { }); describe("Hopper error catalogue", () => { + it("lets an unsent cancellation repeat, but not one Hopper may still apply", () => { + expect(projectAnalysisError(new HopperCancelledError())).toMatchObject({ + retryable: true, + retry_class: "same_call", + }); + expect( + projectAnalysisError( + new HopperCancelledError(undefined, { requestSent: true }), + ), + ).toMatchObject({ retryable: false, retry_class: "unknown_outcome" }); + }); + + it("asks for changed launch arguments before retrying an unencodable launch", () => { + const projected = projectAnalysisError( + new HopperStartError({ + launchRejection: { + boundary: "argument_encoding", + reason: "applescript_literal", + source: "argument", + argument_index: 2, + }, + }), + ); + expect(projected).toMatchObject({ + code: "provider_unavailable", + retryable: false, + retry_class: "change_first", + details: { retry_action: "unknown" }, + }); + // A launch that failed for no declared reason may still succeed unchanged. + expect(projectAnalysisError(new HopperStartError())).toMatchObject({ + retryable: true, + retry_class: "same_call", + }); + }); + it.each([ ["", new HopperTimeoutError(30_000, "search_strings", 1, "busy")], ["", new HopperCancelledError()], + [ + "request sent to Hopper", + new HopperCancelledError(undefined, { requestSent: true }), + ], ["", new HopperProtocolError("bad reply")], ...( [ @@ -553,11 +648,21 @@ describe("Hopper error catalogue", () => { ["", new HopperProcessError(7, { operation: "search_strings" })], ["", new HopperStartError()], [ - "Apple Events authorization denied", + "Apple Events authorization denied, launch arguments not encodable, or another REA session owns the target", new HopperStartError({ launchRejection: hopperAppleEventsAuthorizationRejection, }), ], + [ + "Apple Events authorization denied, launch arguments not encodable, or another REA session owns the target", + new HopperStartError({ + launchRejection: { + boundary: "argument_encoding", + reason: "applescript_literal", + source: "launcher_path", + }, + }), + ], ] as const)( "lists the projected code, category and retryability (%s)", (discriminant, error) => { @@ -571,6 +676,7 @@ describe("Hopper error catalogue", () => { discriminant, code: projected.code, category: projected.category, + retry: projected.retry_class, retryableByDefault: projected.retryable, }); }, diff --git a/src/hopper/HopperErrors.ts b/src/hopper/HopperErrors.ts index dcc7b2c2612..393eb268b22 100644 --- a/src/hopper/HopperErrors.ts +++ b/src/hopper/HopperErrors.ts @@ -27,10 +27,22 @@ import { /** Hopper's caller-facing code and category; presentations and the catalogue read it. */ const HOPPER_CLASSIFICATIONS = { - timeout: { code: "provider_timeout", category: "timeout" }, - cancelled: { code: "cancelled", category: "cancelled" }, - protocol: { code: "unreadable_output", category: "execution_failure" }, - unavailable: { code: "provider_unavailable", category: "unavailable" }, + timeout: { + code: "provider_timeout", + category: "timeout", + retry: "same_call", + }, + cancelled: { code: "cancelled", category: "cancelled", retry: "same_call" }, + protocol: { + code: "unreadable_output", + category: "execution_failure", + retry: "never", + }, + unavailable: { + code: "provider_unavailable", + category: "unavailable", + retry: "same_call", + }, } as const satisfies Record; /** A remote error's classification follows the bridge's diagnostic type. */ @@ -39,13 +51,18 @@ const hopperRemoteClassification = ( ): AnalysisErrorClassification => diagnosticType === "invalid_request" || diagnosticType === "selector_not_found" - ? { code: "invalid_request", category: "invalid_input" } + ? { + code: "invalid_request", + category: "invalid_input", + retry: "change_first", + } : { code: "execution_failure", category: diagnosticType === "authorization" ? "unavailable" : "execution_failure", + retry: diagnosticType === "authorization" ? "change_first" : "never", }; /** Base class for failures produced specifically by the Hopper provider. */ @@ -238,6 +255,8 @@ export class HopperCancelledError extends HopperError { }; return { ...HOPPER_CLASSIFICATIONS.cancelled, + // Hopper may still apply it: read the state before any repeat. + retry: "unknown_outcome", message: "The operation was cancelled after Hopper received it. Hopper may still apply it.", remediation: @@ -493,8 +512,23 @@ export class HopperProcessError extends HopperError { override ownPresentation(): AnalysisErrorOwnPresentation { const continuing = this.#continuing(); + const retryAction = providerRetryAction( + this.providerState, + this.failureCode !== undefined || this.stage === "launch", + ); return { ...HOPPER_CLASSIFICATIONS.unavailable, + // A startup attempt whose process exited without a setup failure code + // was released, so the next unchanged call launches again. A reported + // setup failure needs the setup changed first, and an exited or + // unreachable bridge after readiness is not relaunched by the same + // call: the caller restarts the owned provider (close_binary, then + // reopen) or reads its health first. Incomplete cleanup still blocks a + // same-call retry in the projection. + retry: + retryAction === "retry" && this.failureCode === undefined + ? "same_call" + : "change_first", message: this.#message(), ...(continuing === undefined ? {} : { continuing }), remediation: @@ -507,10 +541,7 @@ export class HopperProcessError extends HopperError { exit_code: this.exitCode, stage: this.stage, provider_state: this.providerState, - retry_action: providerRetryAction( - this.providerState, - this.failureCode !== undefined || this.stage === "launch", - ), + retry_action: retryAction, ...(this.failureCode === undefined ? {} : { failure_code: this.failureCode }), @@ -673,6 +704,8 @@ export class HopperStartError extends HopperError { override ownPresentation(): AnalysisErrorOwnPresentation { const denied = hopperAppleEventsAuthorizationDenied(this.launchRejection); + // The same launcher path or argument meets the same pre-launch guard. + const unencodable = this.launchRejection?.boundary === "argument_encoding"; return { ...HOPPER_CLASSIFICATIONS.unavailable, message: denied @@ -684,7 +717,11 @@ export class HopperStartError extends HopperError { : this.ownerRunId === undefined ? "Check the Hopper launcher and target details, then retry opening the target." : `Use the active REA session ${this.ownerRunId} or close it before opening this target again.`, - ...(denied ? { retryable: false as const } : {}), + // Authorization, another REA session or the launch arguments must + // change before a retry. + ...(denied || unencodable || this.ownerRunId !== undefined + ? { retry: "change_first" as const } + : {}), details: { stage: "launch", provider_state: "unknown", @@ -692,7 +729,9 @@ export class HopperStartError extends HopperError { ? {} : { launch_rejection: { ...this.launchRejection } }), retry_action: - this.ownerRunId === undefined && !denied ? "retry" : "unknown", + this.ownerRunId === undefined && !denied && !unencodable + ? "retry" + : "unknown", ...(this.ownerRunId === undefined ? {} : { owner_run_id: this.ownerRunId }), @@ -717,6 +756,11 @@ export const hopperErrorCatalogue = "", HOPPER_CLASSIFICATIONS.cancelled, ), + catalogueRow( + providerErrorTag("HopperCancelledError"), + "request sent to Hopper", + { ...HOPPER_CLASSIFICATIONS.cancelled, retry: "unknown_outcome" }, + ), catalogueRow( providerErrorTag("HopperProtocolError"), "", @@ -729,11 +773,10 @@ export const hopperErrorCatalogue = hopperRemoteClassification(diagnosticType), ), ), - catalogueRow( - providerErrorTag("HopperProcessError"), - "", - HOPPER_CLASSIFICATIONS.unavailable, - ), + catalogueRow(providerErrorTag("HopperProcessError"), "", { + ...HOPPER_CLASSIFICATIONS.unavailable, + retry: "change_first", + }), catalogueRow( providerErrorTag("HopperStartError"), "", @@ -741,8 +784,7 @@ export const hopperErrorCatalogue = ), catalogueRow( providerErrorTag("HopperStartError"), - "Apple Events authorization denied", - HOPPER_CLASSIFICATIONS.unavailable, - false, + "Apple Events authorization denied, launch arguments not encodable, or another REA session owns the target", + { ...HOPPER_CLASSIFICATIONS.unavailable, retry: "change_first" }, ), ]; diff --git a/src/ida/IdaSessionClient.ts b/src/ida/IdaSessionClient.ts index a675a5f6d2a..95e024bf20b 100644 --- a/src/ida/IdaSessionClient.ts +++ b/src/ida/IdaSessionClient.ts @@ -20,7 +20,10 @@ import { isAborted, } from "../domain/analysisErrorCore.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; -import { withDelegatedCleanupOwner } from "../domain/analysisErrorCleanup.js"; +import { + withDelegatedCleanupOwner, + analysisErrorWithCleanupDependencies, +} from "../domain/analysisErrorCleanup.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js"; @@ -83,7 +86,6 @@ import { } from "../resources/index.js"; import { classifyProviderFailure } from "../providers/classifyProviderFailure.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; -import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { analysisClientFailureContext, analysisClientFailureForOperation, @@ -1026,7 +1028,12 @@ export class IdaSessionClient implements AnalysisClient { ? "IDA auto-analysis is incomplete." : "IDA auto-analysis readiness is unknown.", { - retryable: metadata.auto_analysis_ready === false, + // Incomplete analysis finishes by itself; unknown readiness + // needs the worker inspected first. + retry: + metadata.auto_analysis_ready === false + ? "same_call" + : "change_first", remediationAction: metadata.auto_analysis_ready === false ? "Wait for IDA auto-analysis to complete, then retry the request." diff --git a/src/model/ModelArtifactProvider.ts b/src/model/ModelArtifactProvider.ts index e43d3f2e546..27c28264380 100644 --- a/src/model/ModelArtifactProvider.ts +++ b/src/model/ModelArtifactProvider.ts @@ -50,6 +50,7 @@ import { sameRegularFileState, } from "../filesystem/RegularFile.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { hostDescriptorPressure } from "../process/hostDescriptorPressure.js"; const OPERATION = "inspect_model_artifact"; /** One admitted descriptor and bounded report at a time; retained cleanup blocks new work. */ @@ -155,14 +156,17 @@ export class ModelArtifactProvider implements ModelArtifactPort { ); else if (isSelectedRegularFileError(primary)) error = selectedFileTargetError(input.path, primary, cause); + // Descriptor pressure is occupied host capacity, not a provider fault. else - error = new ProviderAdapterError(this.identity.id, OPERATION, { - cause, - diagnostics: { - path: input.path, - reason: errorMessage(primary), - }, - }); + error = + hostDescriptorPressure(OPERATION, primary, { path: input.path }) ?? + new ProviderAdapterError(this.identity.id, OPERATION, { + cause, + diagnostics: { + path: input.path, + reason: errorMessage(primary), + }, + }); if ( cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined diff --git a/src/nuget/NugetNupkgParser.ts b/src/nuget/NugetNupkgParser.ts index 41b1e7610de..a4609720fc6 100644 --- a/src/nuget/NugetNupkgParser.ts +++ b/src/nuget/NugetNupkgParser.ts @@ -1,5 +1,9 @@ import { accountZipMemberRegion } from "../domain/zip/zipMemberRegion.js"; -import { decodeLimit, malformedInput } from "../domain/parseFailure.js"; +import { + decodeLimit, + malformedInput, + unrecognizedInput, +} from "../domain/parseFailure.js"; import { Reader, ZipReader, type Entry, type FileEntry } from "@zip.js/zip.js"; import type { Element, Node } from "@xmldom/xmldom"; @@ -471,8 +475,9 @@ export const parseNugetNupkg = async ( NUGET_NUPKG_FORMAT, "Selected artifact length disagrees with the retained bytes.", ); + // Bytes without a ZIP signature are another format, not a damaged package. if (!hasZipSignature(source.prefix)) - throw malformedInput( + throw unrecognizedInput( NUGET_NUPKG_FORMAT, "Selected file is not a ZIP archive (NuGet .nupkg).", ); diff --git a/src/process/capture/ProcessCaptureError.test.ts b/src/process/capture/ProcessCaptureError.test.ts index 3a0d77bd4bb..d09aa31ffc1 100644 --- a/src/process/capture/ProcessCaptureError.test.ts +++ b/src/process/capture/ProcessCaptureError.test.ts @@ -2,6 +2,7 @@ import { expect, it } from "vitest"; import { AnalysisCleanupLease } from "../../resources/AnalysisCleanupLease.js"; import { ProcessCaptureReadFailure } from "./ProcessCaptureRead.js"; import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; +import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; import { projectAnalysisError } from "../../domain/analysisErrorProjection.js"; import { DarwinProcessOwnershipInspectionError } from "../DarwinProcessRunTokenReader.js"; import { @@ -101,7 +102,24 @@ it("marks a timed-out Darwin compiler inspection as retryable", () => { }); if (!(normalized instanceof ProcessCaptureError)) throw new Error("Expected normalized capture failure"); - expect(projectAnalysisError(normalized)).toMatchObject({ retryable: true }); + expect(projectAnalysisError(normalized)).toMatchObject({ + retryable: true, + retry_class: "same_call", + }); +}); + +it("keeps a retryable capture's choice while its cleanup is pending", () => { + const error = new ProcessCaptureError("compiler timed out", { + reason: "cleanup_incomplete", + retryable: true, + }); + expect(error.retryable).toBe(true); + // Settle cleanup, then retry: not the same call now, and not never. + expect(projectAnalysisError(error)).toMatchObject({ + code: "cleanup_incomplete", + retryable: false, + retry_class: "change_first", + }); }); it("retains compiler facts and cleanup dependency through capture finalization", () => { @@ -270,3 +288,25 @@ it("inherits primary diagnostics without duplicating finalization history", asyn }); expect(projected.details).not.toHaveProperty("cleanup_history"); }); + +it("keeps the primary's own execution failure when cleanup stays incomplete", () => { + const composed = analysisErrorWithCleanupFailure( + new ProcessCaptureError("read failed", { + executionFailure: "metadata read failed", + }), + new ProviderCleanupError( + "process", + ["/tmp/capture-root"], + { reason: "remove failed" }, + { operation: "capture_process" }, + ), + "capture_process", + ); + const projected = projectAnalysisError(composed); + expect(projected.code).toBe("cleanup_incomplete"); + expect(projected.details).toMatchObject({ + cleanup: "incomplete", + execution_failure: "metadata read failed", + }); + releaseOwnedCleanup(composed); +}); diff --git a/src/process/capture/ProcessCaptureError.ts b/src/process/capture/ProcessCaptureError.ts index 224ee67cdbc..048539df2cd 100644 --- a/src/process/capture/ProcessCaptureError.ts +++ b/src/process/capture/ProcessCaptureError.ts @@ -54,11 +54,11 @@ export class ProcessCaptureError extends AnalysisError { | PartialProcessCaptureObservation | undefined; override readonly cleanupReport: ProcessCaptureCleanupReport | undefined; - readonly #retryable: boolean; - - get retryable(): boolean { - return this.#retryable && !this.cleanupIncomplete; - } + /** + * The producer's retry choice. Pending cleanup does not change it: the + * projection applies the cleanup rule once (`analysisErrorRetry`). + */ + readonly retryable: boolean; constructor(message: string, options?: ProcessCaptureErrorOptions) { super(message, options); @@ -71,7 +71,7 @@ export class ProcessCaptureError extends AnalysisError { this.executionFailure = options?.executionFailure ?? message; this.partialObservation = options?.partialObservation; this.cleanupReport = options?.cleanupReport; - this.#retryable = options?.retryable === true; + this.retryable = options?.retryable === true; } /** Add final capture observations while preserving primary facts and cleanup ownership. */ @@ -113,7 +113,7 @@ export class ProcessCaptureError extends AnalysisError { ...(executionFailure === undefined ? {} : { executionFailure }), ...(partialObservation === undefined ? {} : { partialObservation }), ...(cleanupReport === undefined ? {} : { cleanupReport }), - ...(this.#retryable ? { retryable: true } : {}), + ...(this.retryable ? { retryable: true } : {}), }).bindCleanupDependencies([ this, ...(secondary === undefined ? [] : [secondary]), diff --git a/src/process/hostDescriptorPressure.ts b/src/process/hostDescriptorPressure.ts new file mode 100644 index 00000000000..be872ebf377 --- /dev/null +++ b/src/process/hostDescriptorPressure.ts @@ -0,0 +1,39 @@ +import { + occupiedHostCapacityConstraint, + type AnalysisResourceConstraintError, +} from "../domain/analysisErrorCore.js"; +import type { JsonValue } from "../domain/jsonValue.js"; +import { errorMessage } from "../kernel/errorMessage.js"; +import { systemCodeFromError } from "../kernel/reportedSystemCode.js"; + +/** Process or host descriptor exhaustion; the selected input is not at fault. */ +const DESCRIPTOR_EXHAUSTION_CODES: ReadonlySet = new Set([ + "EMFILE", + "ENFILE", +]); + +/** Recovery for descriptor pressure; the unchanged request may then succeed. */ +export const DESCRIPTOR_PRESSURE_REMEDIATION = + "Close unused files or raise the open-file limit of the REA process, then retry; the request does not need to change."; + +/** + * Project a file operation refused for descriptor exhaustion as occupied host + * capacity. Like a launch refused with the same errno, it clears when other + * work releases descriptors, so the unchanged request is retryable. Undefined + * for any other failure. + */ +export const hostDescriptorPressure = ( + operation: string, + cause: unknown, + facts: Readonly> = {}, +): AnalysisResourceConstraintError | undefined => { + const code = systemCodeFromError(cause); + if (code === undefined || !DESCRIPTOR_EXHAUSTION_CODES.has(code)) + return undefined; + return occupiedHostCapacityConstraint( + operation, + `The host ran out of file descriptors (${code}): ${errorMessage(cause)}`, + { ...facts, system_code: code }, + { cause, remediationAction: DESCRIPTOR_PRESSURE_REMEDIATION }, + ); +}; diff --git a/src/process/privateWorkspaceFailure.ts b/src/process/privateWorkspaceFailure.ts index 7c8703b0d29..4c5c7999c93 100644 --- a/src/process/privateWorkspaceFailure.ts +++ b/src/process/privateWorkspaceFailure.ts @@ -3,6 +3,7 @@ import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { hostDescriptorPressure } from "./hostDescriptorPressure.js"; /** Host storage exhaustion; only these errors establish a storage constraint. */ const STORAGE_EXHAUSTION_CODES: ReadonlySet = new Set([ @@ -10,12 +11,6 @@ const STORAGE_EXHAUSTION_CODES: ReadonlySet = new Set([ "EDQUOT", ]); -/** Host or process descriptor exhaustion; the workspace location is usable. */ -const DESCRIPTOR_EXHAUSTION_CODES: ReadonlySet = new Set([ - "EMFILE", - "ENFILE", -]); - const systemPath = (cause: unknown): string | null => cause instanceof Error && "path" in cause && typeof cause.path === "string" ? cause.path @@ -38,6 +33,12 @@ export const privateWorkspaceFailure = ( ): AnalysisError => { const code = systemCodeFromError(cause) ?? null; const path = systemPath(cause) ?? workspacePath; + // Descriptor exhaustion leaves the workspace location usable. + const pressure = hostDescriptorPressure(operation, cause, { + workspace_path: workspacePath, + path, + }); + if (pressure !== undefined) return pressure; const reason = errorMessage(cause); if (code !== null && (STORAGE_EXHAUSTION_CODES.has(code) || code === "EFBIG")) return new AnalysisResourceConstraintError( @@ -60,9 +61,7 @@ export const privateWorkspaceFailure = ( cause, userMessage: `Cannot prepare the private analysis workspace${code === null ? "" : ` (${code})`}: ${reason}`, remediationAction: - code !== null && DESCRIPTOR_EXHAUSTION_CODES.has(code) - ? "Close unused files or raise the open-file limit of the REA process, then retry." - : "Review details.diagnostics.system_code and details.diagnostics.path. Make the host temporary directory (TMPDIR) an existing directory this user can create files in on a writable filesystem, then retry.", + "Review details.diagnostics.system_code and details.diagnostics.path. Make the host temporary directory (TMPDIR) an existing directory this user can create files in on a writable filesystem, then retry.", diagnostics: { stage: "workspace", workspace_path: workspacePath, diff --git a/src/providers/AnalysisClientFailure.test.ts b/src/providers/AnalysisClientFailure.test.ts index 5fa036149c2..1aac379869c 100644 --- a/src/providers/AnalysisClientFailure.test.ts +++ b/src/providers/AnalysisClientFailure.test.ts @@ -124,7 +124,7 @@ it("preserves sibling operations, sibling reasons, and remediation action when r siblingReasons: { analyze_function: "analyze_function export failed", }, - retryable: true, + retry: "same_call", }, ); const attributed = analysisClientFailureForOperation( @@ -243,7 +243,11 @@ it("reattributes a provider-owned failure through the request facts it reports", super(`Example ${operation} failed`, options); } override ownPresentation(): AnalysisErrorOwnPresentation { - return { code: "execution_failure", category: "execution_failure" }; + return { + code: "execution_failure", + category: "execution_failure", + retry: "never", + }; } override providerRequest(): ProviderRequestFailure { return { diff --git a/src/providers/AnalysisClientFailure.ts b/src/providers/AnalysisClientFailure.ts index b74cf8246d7..8e508fa9946 100644 --- a/src/providers/AnalysisClientFailure.ts +++ b/src/providers/AnalysisClientFailure.ts @@ -192,7 +192,7 @@ export const analysisClientFailureForOperation = ( ...(cause.siblingReasons === undefined ? {} : { siblingReasons: cause.siblingReasons }), - retryable: cause.retryable, + retry: cause.retry, }, ); else if (cause instanceof AnalysisAccessDeniedError) diff --git a/src/providers/artifactResourceFailure.ts b/src/providers/artifactResourceFailure.ts index 00bda8c4b3c..d6b86efa2ba 100644 --- a/src/providers/artifactResourceFailure.ts +++ b/src/providers/artifactResourceFailure.ts @@ -1,7 +1,7 @@ import { ArtifactReaderFailure, type readStableArtifact, - stableArtifactInputRecovery, + stableArtifactInputOptions, } from "../resources/index.js"; import { AnalysisInputError } from "../domain/analysisErrorCore.js"; import type { JsonValue } from "../domain/jsonValue.js"; @@ -59,13 +59,7 @@ export const artifactResourceDialect = ( unclassified: (cause, details) => new AnalysisInputError( operation, - { - ...details, - cause, - ...(cause instanceof ArtifactReaderFailure - ? stableArtifactInputRecovery(cause) - : {}), - }, + stableArtifactInputOptions(cause, details), [ { path: ["path"], diff --git a/src/resources/ArtifactOperationFailure.test.ts b/src/resources/ArtifactOperationFailure.test.ts index 56d34ae71b0..448d775396f 100644 --- a/src/resources/ArtifactOperationFailure.test.ts +++ b/src/resources/ArtifactOperationFailure.test.ts @@ -273,9 +273,10 @@ it("preserves adjustable reader admission facts and gives cleanup priority", () const adjustable = projectAnalysisError( translateArtifactFailure("inspect_artifact", "/selected/artifact", failure), ); + // The same arguments hit the same limit: the caller raises it first. expect(adjustable).toMatchObject({ code: "partial", - retryable: true, + retryable: false, details: { reader_limit: { parameter: "artifact_limits.node_sea.argument_count", diff --git a/src/resources/StableArtifactFailure.ts b/src/resources/StableArtifactFailure.ts index 571a1d39975..87f6d27cd74 100644 --- a/src/resources/StableArtifactFailure.ts +++ b/src/resources/StableArtifactFailure.ts @@ -23,6 +23,7 @@ import { AnalysisAccessDeniedError, AnalysisArtifactChangedError, AnalysisInputError, + type AnalysisInputErrorOptions, AnalysisTargetFailureError, cancelledBy, carriedReason, @@ -149,14 +150,27 @@ export const projectSelectedArtifactFileFailure = ( ...options, cause, }); - if (isSelectedRegularFileError(cause)) - return new AnalysisInputError(operation, { ...options, cause }, [ + if (isSelectedRegularFileError(cause)) { + // The path is well formed; the host refused it as a regular file. + const message = `Selected ${description} could not be read (${String(cause.code)}): ${path}.`; + return new AnalysisInputError( + operation, { - path: requestFieldPath(field), - reason: "invalid_value", - message: `Selected ${description} could not be read (${String(cause.code)}): ${path}.`, + ...options, + cause, + userMessage: message, + remediationAction: `Select an existing, readable regular file as ${requestFieldPath(field).join(".")}, then retry.`, + conformsToInputContract: true, }, - ]); + [ + { + path: requestFieldPath(field), + reason: "invalid_value", + message, + }, + ], + ); + } return undefined; }; @@ -173,14 +187,26 @@ export const imageFileSizeRemediation = ( export const regularFileSymlinkRecovery = (resolvedPath: string): string => `Retry with the resolved regular file path ${resolvedPath}. The selected symlink is not admitted; the retry will validate the target again.`; -/** Offer the verified regular-file target after a selected symlink is rejected. */ -export const stableArtifactInputRecovery = (cause: ArtifactReaderFailure) => - cause.reason === "path" && cause.resolvedPath !== undefined +/** + * Input-refusal options for a rejected artifact path. A selected symlink whose + * regular-file target was verified conforms to the input contract, so the + * refusal names that target; any other rejected path is left to the schema. + */ +export const stableArtifactInputOptions = ( + cause: unknown, + options: AnalysisErrorOptions = {}, +): AnalysisInputErrorOptions => + cause instanceof ArtifactReaderFailure && + cause.reason === "path" && + cause.resolvedPath !== undefined ? { - remediationAction: regularFileSymlinkRecovery(cause.resolvedPath), + ...options, + cause, conformsToInputContract: true, + userMessage: cause.message, + remediationAction: regularFileSymlinkRecovery(cause.resolvedPath), } - : {}; + : { ...options, cause }; /** Report a rejected artifact path with its source-provided recovery. */ export const stableArtifactInputFailure = ( @@ -191,7 +217,7 @@ export const stableArtifactInputFailure = ( ): AnalysisInputError => new AnalysisInputError( operation, - { ...options, cause, ...stableArtifactInputRecovery(cause) }, + stableArtifactInputOptions(cause, options), [ { path: requestFieldPath(field), diff --git a/src/resources/index.ts b/src/resources/index.ts index c71be544cf2..c470996f380 100644 --- a/src/resources/index.ts +++ b/src/resources/index.ts @@ -110,7 +110,7 @@ export { projectStableArtifactFailure, readerIntegrityFailure, stableArtifactInputFailure, - stableArtifactInputRecovery, + stableArtifactInputOptions, } from "./StableArtifactFailure.js"; export type { RequestField } from "./StableArtifactFailure.js"; export { selectedFileTargetError } from "./RegularFileErrorProjection.js"; diff --git a/src/signals/SigrokHostAdmission.ts b/src/signals/SigrokHostAdmission.ts index 15d1fc8925c..f8b23c916a7 100644 --- a/src/signals/SigrokHostAdmission.ts +++ b/src/signals/SigrokHostAdmission.ts @@ -26,6 +26,5 @@ export const sigrokUnsupportedHostError = ( { userMessage: SIGROK_UNSUPPORTED_HOST_REASON, remediationAction: SIGROK_HOST_REMEDIATION, - retryable: false, }, ); diff --git a/src/sqlite/SqliteDatabaseFailures.ts b/src/sqlite/SqliteDatabaseFailures.ts index cd23d2b9597..be2b316bf2f 100644 --- a/src/sqlite/SqliteDatabaseFailures.ts +++ b/src/sqlite/SqliteDatabaseFailures.ts @@ -137,7 +137,8 @@ export const sqliteDatabaseDialect = ( `Selected database file set is in use by another process (EBUSY): ${busyMember(cause, path)}`, { cause, - retryable: true, + // Like occupied capacity, the holder may release the file by itself. + retry: "same_call", userMessage: "The selected SQLite database is held open by another process without read sharing. Close that application or inspect a copy, then retry.", }, diff --git a/src/vsix/VsixPackageParser.test.ts b/src/vsix/VsixPackageParser.test.ts index b2514d626a5..27748e3ce95 100644 --- a/src/vsix/VsixPackageParser.test.ts +++ b/src/vsix/VsixPackageParser.test.ts @@ -654,14 +654,15 @@ it("refuses a non-ZIP file without claiming a package inventory", async () => { const bytes = Buffer.from("not a zip"); const parsed = parseVsixPackage(bytes, artifactOf(bytes), defaults); await expect(parsed).rejects.toBeInstanceOf(ParseFailureError); - // The refusal carries only the malformed-format fact, no partial inventory. + // Bytes without a ZIP signature are another format: the refusal carries + // only the unrecognized-format fact, no partial inventory. await expect(parsed).rejects.toSatisfy( (error: ParseFailureError) => Object.keys(error).sort().join(",") === "_tag,failure,name", ); await expect(parsed).rejects.toMatchObject({ failure: { - kind: "malformed", + kind: "unrecognized", format: "vsix-package", detail: "Selected file is not a ZIP archive (VS Code .vsix).", }, diff --git a/src/vsix/VsixPackageParser.ts b/src/vsix/VsixPackageParser.ts index ea0dd02a524..2c8f3cddeba 100644 --- a/src/vsix/VsixPackageParser.ts +++ b/src/vsix/VsixPackageParser.ts @@ -3,6 +3,7 @@ import { accountZipMemberRegion } from "../domain/zip/zipMemberRegion.js"; import { decodeLimit, malformedInput, + unrecognizedInput, ParseFailureError, } from "../domain/parseFailure.js"; import { @@ -822,8 +823,9 @@ export const parseVsixPackage = async ( VSIX_PACKAGE_FORMAT, "Selected artifact length disagrees with the retained bytes.", ); + // Bytes without a ZIP signature are another format, not a damaged package. if (!hasZipSignature(bytes)) - throw malformedInput( + throw unrecognizedInput( VSIX_PACKAGE_FORMAT, "Selected file is not a ZIP archive (VS Code .vsix).", ); diff --git a/src/yara/YaraMatchesProvider.ts b/src/yara/YaraMatchesProvider.ts index 8d373711574..128d8828f1e 100644 --- a/src/yara/YaraMatchesProvider.ts +++ b/src/yara/YaraMatchesProvider.ts @@ -279,6 +279,8 @@ const pathInputRefusal = ( OPERATION, { conformsToInputContract: true, + userMessage: + "yara cannot be given these paths: its output is line-oriented, and a Windows path must not depend on the working drive.", remediationAction: `${remediation} Then retry.`, }, issues, diff --git a/tests/acceptance/androidSparseImageCli.test.ts b/tests/acceptance/androidSparseImageCli.test.ts index efd0f64baef..7324bc4cdbe 100644 --- a/tests/acceptance/androidSparseImageCli.test.ts +++ b/tests/acceptance/androidSparseImageCli.test.ts @@ -124,7 +124,7 @@ cliTest( expect(refused.exitCode).toBe(1); expect(refused.json).toMatchObject({ code: "partial", - retryable: true, + retryable: false, details: { reader_limit: { parameter: "artifact_limits.android_sparse_image.chunk_count", diff --git a/tests/acceptance/androidSuperImageCli.test.ts b/tests/acceptance/androidSuperImageCli.test.ts index 56b09c7c069..448c0e39f2f 100644 --- a/tests/acceptance/androidSuperImageCli.test.ts +++ b/tests/acceptance/androidSuperImageCli.test.ts @@ -87,7 +87,7 @@ cliTest( expect(inspected.exitCode, inspected.stdout + inspected.stderr).toBe(1); expect(inspected.json).toMatchObject({ code: "partial", - retryable: true, + retryable: false, details: { reader_limit: { effective_value: 11, required_value: 12 }, }, diff --git a/tests/acceptance/apkSignatureLimitsCliMcp.test.ts b/tests/acceptance/apkSignatureLimitsCliMcp.test.ts index 983162731e2..b82ffabe5f9 100644 --- a/tests/acceptance/apkSignatureLimitsCliMcp.test.ts +++ b/tests/acceptance/apkSignatureLimitsCliMcp.test.ts @@ -91,16 +91,12 @@ cliTest( const error = analysisErrorProjectionSchema.parse(reply.json); expect(error).toMatchObject(expected); expect(error.remediation.action).toContain("4096"); + // A damaged signing block is the target's bytes, not the request. const malformedExpected = { - code: "invalid_request", + code: "unsupported_target", details: { - issues: [ - { - path: ["path"], - reason: "invalid_value", - message: expect.stringContaining("pair length out of range"), - }, - ], + failure_kind: "malformed", + reason: expect.stringContaining("pair length out of range"), }, }; const malformedReply = await cli.run({ diff --git a/tests/acceptance/apkSignatureV1Cli.test.ts b/tests/acceptance/apkSignatureV1Cli.test.ts index 895ff43f445..927acf321ce 100644 --- a/tests/acceptance/apkSignatureV1Cli.test.ts +++ b/tests/acceptance/apkSignatureV1Cli.test.ts @@ -730,17 +730,12 @@ cliTest( "malformed", malformed, { - code: "invalid_request", + code: "unsupported_target", details: { - issues: [ - { - path: ["path"], - reason: "invalid_value", - message: expect.stringContaining( - "central-directory file name runs past the directory", - ), - }, - ], + failure_kind: "malformed", + reason: expect.stringContaining( + "central-directory file name runs past the directory", + ), }, }, ], diff --git a/tests/acceptance/apkZip64FramingCli.test.ts b/tests/acceptance/apkZip64FramingCli.test.ts index b90eba76d14..61b79ddcf54 100644 --- a/tests/acceptance/apkZip64FramingCli.test.ts +++ b/tests/acceptance/apkZip64FramingCli.test.ts @@ -82,7 +82,7 @@ const expectRefusal = async ( }; cliTest( - "classifies damaged Zip64 framing as input errors through CLI and stdio MCP", + "classifies damaged Zip64 framing as a malformed target through CLI and stdio MCP", async ({ cli }) => { const root = await createTestTempDirectory("rea-apk-zip64-framing-"); const path = join(root, "selected.apk"); @@ -142,22 +142,16 @@ cliTest( for (const scenario of cases) { const bytes = Uint8Array.from(fixture.bytes); new DataView(bytes.buffer).setUint32(scenario.at, scenario.value, true); + // Damaged framing is the selected target's bytes, not the request. await expectRefusal(cli, path, bytes, { - code: "invalid_request", - category: "invalid_input", + code: "unsupported_target", + category: "unsupported_target", retryable: false, - recovery: { - kind: "inspect_input_contract", - operation: "inspect_apk_signature", - }, details: { - issues: [ - { - path: ["path"], - reason: "invalid_value", - message: `Damaged ZIP/APK at byte ${String(scenario.diagnosticOffset)}: ${scenario.detail}.`, - }, - ], + path, + failure_kind: "malformed", + offset: scenario.diagnosticOffset, + reason: `Damaged ZIP/APK at byte ${String(scenario.diagnosticOffset)}: ${scenario.detail}.`, }, }); } @@ -195,16 +189,11 @@ cliTest( const bytes = Uint8Array.from(original); new DataView(bytes.buffer).setUint16(eocd + 8, entriesOnDisk, true); await expectRefusal(cli, path, bytes, { - code: "invalid_request", - category: "invalid_input", + code: "unsupported_target", + category: "unsupported_target", details: { - issues: [ - { - path: ["path"], - reason: "invalid_value", - message: expect.stringContaining(`byte ${String(eocd + 8)}`), - }, - ], + failure_kind: "malformed", + reason: expect.stringContaining(`byte ${String(eocd + 8)}`), }, }); } diff --git a/tests/acceptance/applications/bundleResourceRootCliMcp.test.ts b/tests/acceptance/applications/bundleResourceRootCliMcp.test.ts index d4dcc1d1cdf..ae1ab8a7867 100644 --- a/tests/acceptance/applications/bundleResourceRootCliMcp.test.ts +++ b/tests/acceptance/applications/bundleResourceRootCliMcp.test.ts @@ -7,9 +7,7 @@ import { expect } from "vitest"; import { sqliteDatabaseCapability } from "../../../src/application/sqlite/SqliteDatabaseCapability.js"; import { toolContract } from "../../../src/contracts/toolContracts.js"; -import { analysisErrorRemediationAction } from "../../../src/domain/analysisErrorPresentation.js"; import { parseEvidence } from "../../../src/domain/evidence.js"; -import { ResourceSnapshotMismatchError } from "../../../src/domain/evidenceErrors.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; import { cliTest } from "../../support/cli/cliFixture.js"; @@ -200,13 +198,12 @@ cliTest.skipIf(process.platform !== "darwin")( expect(refusedSnapshot.isError).toBe(true); expect(errorBody(refusedSnapshot)).toMatchObject({ error: { - code: "evidence_integrity_mismatch", - category: "integrity_mismatch", + code: "invalid_request", + category: "invalid_input", retryable: false, remediation: { - action: analysisErrorRemediationAction( - new ResourceSnapshotMismatchError("export"), - ), + action: + "Call close_binary without snapshot_path to close this resource-only session.", }, }, }); diff --git a/tests/acceptance/applications/javascriptFailureEvidenceOutput.test.ts b/tests/acceptance/applications/javascriptFailureEvidenceOutput.test.ts index 183496d25ad..236e27d6646 100644 --- a/tests/acceptance/applications/javascriptFailureEvidenceOutput.test.ts +++ b/tests/acceptance/applications/javascriptFailureEvidenceOutput.test.ts @@ -285,6 +285,8 @@ cliTest( .extend({ code: z.literal("cleanup_incomplete"), retryable: z.literal(false), + // Never same_call while the publication cleanup is unreleased. + retry_class: z.enum(["change_first", "never"]), }) .parse(reply.json); expect(failure.remediation.action).toContain("cleanup"); @@ -423,6 +425,8 @@ cliTest( .extend({ code: z.literal("cleanup_incomplete"), retryable: z.literal(false), + // Never same_call while the publication cleanup is unreleased. + retry_class: z.enum(["change_first", "never"]), }) .parse(reply.json); const receipt = z @@ -534,6 +538,8 @@ cliTest( .extend({ code: z.literal("cleanup_incomplete"), retryable: z.literal(false), + // Never same_call while the publication cleanup is unreleased. + retry_class: z.enum(["change_first", "never"]), }) .parse(reply.json); expect(failure.details).toMatchObject({ diff --git a/tests/acceptance/artifactReaderLimitsCli.test.ts b/tests/acceptance/artifactReaderLimitsCli.test.ts index adfe7558bbd..e04d1061e9c 100644 --- a/tests/acceptance/artifactReaderLimitsCli.test.ts +++ b/tests/acceptance/artifactReaderLimitsCli.test.ts @@ -247,7 +247,7 @@ for (const reader of readers) expect(refused.exitCode).toBe(1); expect(refused.json).toMatchObject({ code: "partial", - retryable: true, + retryable: false, details: { reader_limit: { parameter: reader.parameter, @@ -332,7 +332,7 @@ test("admits the same vbmeta image above the default 4096-descriptor admission", expect(refused.exitCode).toBe(1); expect(refused.json).toMatchObject({ code: "partial", - retryable: true, + retryable: false, details: { reader_limit: { parameter: "artifact_limits.android_vbmeta.descriptor_count", diff --git a/tests/acceptance/bunPathBudgetCli.test.ts b/tests/acceptance/bunPathBudgetCli.test.ts index a1818837783..c43b7c2f08a 100644 --- a/tests/acceptance/bunPathBudgetCli.test.ts +++ b/tests/acceptance/bunPathBudgetCli.test.ts @@ -32,7 +32,7 @@ for (const shared of [false, true]) expect(result.exitCode).toBe(1); expect(result.json).toMatchObject({ code: "partial", - retryable: true, + retryable: false, details: { reason: "limit", boundary: "capacity", diff --git a/tests/acceptance/bunStandaloneCli.test.ts b/tests/acceptance/bunStandaloneCli.test.ts index f7807791f90..421fdd63adf 100644 --- a/tests/acceptance/bunStandaloneCli.test.ts +++ b/tests/acceptance/bunStandaloneCli.test.ts @@ -48,7 +48,7 @@ cliTest( expect(result.exitCode).toBe(1); expect(result.json).toMatchObject({ code: moduleCount < 13 ? "partial" : "artifact_operation_failed", - retryable: moduleCount < 13, + retryable: false, details: moduleCount < 13 ? { @@ -90,7 +90,7 @@ cliTest( return result.json; }; expect(await inspect()).toMatchObject({ - retryable: true, + retryable: false, details: { reason: "limit", reader_limit: { diff --git a/tests/acceptance/dotnetBundleJourney.test.ts b/tests/acceptance/dotnetBundleJourney.test.ts index 3b5f064b5ae..f252f961228 100644 --- a/tests/acceptance/dotnetBundleJourney.test.ts +++ b/tests/acceptance/dotnetBundleJourney.test.ts @@ -248,7 +248,7 @@ test("reports excessive bundle path depth as a public CLI limit", async ({ expect(result.json).toMatchObject({ code: "partial", category: "partial", - retryable: true, + retryable: false, details: { reason: "limit", truncated: true, diff --git a/tests/acceptance/godotPck.test.ts b/tests/acceptance/godotPck.test.ts index aed01677957..610221268ea 100644 --- a/tests/acceptance/godotPck.test.ts +++ b/tests/acceptance/godotPck.test.ts @@ -454,7 +454,7 @@ cliTest( expect(reply.exitCode, reply.stdout + reply.stderr).toBe(1); expect(reply.json).toMatchObject({ code: "partial", - retryable: true, + retryable: false, details: { reason: "limit", truncated: true, diff --git a/tests/acceptance/nodeSeaCli.test.ts b/tests/acceptance/nodeSeaCli.test.ts index c4d1661b775..21f9e8d1e82 100644 --- a/tests/acceptance/nodeSeaCli.test.ts +++ b/tests/acceptance/nodeSeaCli.test.ts @@ -345,7 +345,7 @@ cliTest( expect(result.exitCode).not.toBe(0); expect(result.json).toMatchObject({ code: "partial", - retryable: true, + retryable: false, details: { reason: "limit", boundary: "capacity", diff --git a/tests/acceptance/nugetNupkgCli.test.ts b/tests/acceptance/nugetNupkgCli.test.ts index 0e8cd2e2078..f888b3a6bf0 100644 --- a/tests/acceptance/nugetNupkgCli.test.ts +++ b/tests/acceptance/nugetNupkgCli.test.ts @@ -266,7 +266,8 @@ cliTest("refuses a non-ZIP file through the public CLI", async ({ cli }) => { category: "unsupported_target", details: { operation: "inspect_nuget_nupkg", - failure_kind: "malformed", + // Bytes of another format are unrecognized, not a damaged package. + failure_kind: "unrecognized", reason: expect.stringContaining("not a ZIP"), }, }); diff --git a/tests/acceptance/vsixPackageCli.test.ts b/tests/acceptance/vsixPackageCli.test.ts index 14e8120f335..edd48ce9541 100644 --- a/tests/acceptance/vsixPackageCli.test.ts +++ b/tests/acceptance/vsixPackageCli.test.ts @@ -147,11 +147,18 @@ cliTest( ); cliTest.for([ - { kind: "non-ZIP", bytes: Buffer.from("not a zip"), reason: "not a ZIP" }, + // Bytes of another format are unrecognized; a damaged ZIP is malformed. + { + kind: "non-ZIP", + bytes: Buffer.from("not a zip"), + reason: "not a ZIP", + failureKind: "unrecognized", + }, { kind: "ZIP with no central directory", bytes: Buffer.from([0x50, 0x4b, 0x03, 0x04]), reason: "ZIP archive is malformed", + failureKind: "malformed", }, ])("refuses a $kind file through the public CLI", async (input, { cli }) => { const root = await createTestTempDirectory("rea-vsix-cli-invalid-"); @@ -166,7 +173,7 @@ cliTest.for([ category: "unsupported_target", details: { operation: "inspect_vsix_package", - failure_kind: "malformed", + failure_kind: input.failureKind, reason: expect.stringContaining(input.reason), }, }); diff --git a/tests/boundary/application/evtxArchiveService.test.ts b/tests/boundary/application/evtxArchiveService.test.ts index 55a57966643..3eca5710a2b 100644 --- a/tests/boundary/application/evtxArchiveService.test.ts +++ b/tests/boundary/application/evtxArchiveService.test.ts @@ -28,9 +28,17 @@ it("reports the selected path and cause when it cannot resolve the event log", a expect(result.ok).toBe(false); if (result.ok || !(result.error instanceof AnalysisInputError)) throw new Error("Expected input refusal"); - // A resolved-but-unreadable path does not conform to the input contract, so - // the projection asks the caller to inspect the schema and names the path. - expect(result.error.conformsToInputContract).toBe(false); + // The path is well formed; the host refused it as a regular file, so the + // refusal names its own next step instead of the input schema. + expect(result.error.conformsToInputContract).toBe(true); + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "invalid_request", + remediation: { + action: + "Select an existing, readable regular file as path, then retry.", + }, + }); + expect(projectAnalysisError(result.error)).not.toHaveProperty("recovery"); expect(result.error.issues).toEqual([ { path: ["path"], diff --git a/tests/boundary/mcp/addressContextInputErrors.test.ts b/tests/boundary/mcp/addressContextInputErrors.test.ts index c682f82d5b5..33d845e4776 100644 --- a/tests/boundary/mcp/addressContextInputErrors.test.ts +++ b/tests/boundary/mcp/addressContextInputErrors.test.ts @@ -56,7 +56,7 @@ const createContextRecoverySession = () => { operation, "temporarily unavailable", { - retryable: true, + retry: "same_call", remediationAction: "Wait for the fixture to become ready.", }, ), @@ -253,11 +253,17 @@ it.each([ await writeFile(target, Buffer.from([0xb8, 0x00, 0x4c, 0xcd, 0x21])); const inputFailure = new AnalysisInputError( rejectedOperation, - { - userMessage: "Controlled facet refusal", - conformsToInputContract: conforms, - diagnostics: { producer_fact: "retained" }, - }, + conforms + ? { + userMessage: "Controlled facet refusal", + remediationAction: "Select a controlled value.", + conformsToInputContract: true, + diagnostics: { producer_fact: "retained" }, + } + : { + userMessage: "Controlled facet refusal", + diagnostics: { producer_fact: "retained" }, + }, [ { path: [rejectedOperation === "comment" ? "address" : "document"], diff --git a/tests/boundary/mcp/androidSparseImageMcp.test.ts b/tests/boundary/mcp/androidSparseImageMcp.test.ts index 038929b5a8b..688d334d8f4 100644 --- a/tests/boundary/mcp/androidSparseImageMcp.test.ts +++ b/tests/boundary/mcp/androidSparseImageMcp.test.ts @@ -92,7 +92,7 @@ it("refuses a chunk table above the selected budget and admits it on retry throu }); expect(parseMcpToolError(refused).error).toMatchObject({ code: "partial", - retryable: true, + retryable: false, details: { reader_limit: { parameter: "artifact_limits.android_sparse_image.chunk_count", diff --git a/tests/boundary/mcp/androidSuperImageMcp.test.ts b/tests/boundary/mcp/androidSuperImageMcp.test.ts index 3c3418acf3f..b0d7a424e2b 100644 --- a/tests/boundary/mcp/androidSuperImageMcp.test.ts +++ b/tests/boundary/mcp/androidSuperImageMcp.test.ts @@ -49,7 +49,7 @@ it("keeps the Android super record-limit error inline when the verified slot exc const error = parseMcpToolError(limited).error; expect(error).toMatchObject({ code: "partial", - retryable: true, + retryable: false, details: { reader_limit: { parameter: "artifact_limits.android_super_image.record_count", @@ -113,7 +113,7 @@ it("keeps the Android super record-limit error inline when the verified slot exc }); expect(parseMcpToolError(explicit).error).toMatchObject({ code: "partial", - retryable: true, + retryable: false, details: { partial_observation: { kind: "retained-evidence", evidence_id }, }, @@ -149,7 +149,7 @@ it("opens backup geometry, then retains Android super partition provenance throu const error = parseMcpToolError(limited).error; expect(error).toMatchObject({ code: "partial", - retryable: true, + retryable: false, details: { reader_limit: { parameter: "artifact_limits.android_super_image.record_count", diff --git a/tests/boundary/mcp/androidVbmetaMcp.test.ts b/tests/boundary/mcp/androidVbmetaMcp.test.ts index 964e608056c..010cf6b969b 100644 --- a/tests/boundary/mcp/androidVbmetaMcp.test.ts +++ b/tests/boundary/mcp/androidVbmetaMcp.test.ts @@ -167,7 +167,7 @@ it("refuses descriptors past the default count and admits them on retry through const { error } = parseMcpToolError(await call("inspect_artifact", {})); expect(error).toMatchObject({ code: "partial", - retryable: true, + retryable: false, details: { reason: "limit", reader_limit: { diff --git a/tests/boundary/mcp/artifactMcp.test.ts b/tests/boundary/mcp/artifactMcp.test.ts index 2ab458fabbd..655306eecd8 100644 --- a/tests/boundary/mcp/artifactMcp.test.ts +++ b/tests/boundary/mcp/artifactMcp.test.ts @@ -188,6 +188,7 @@ it.for([ related_parameters: ["integrity_policy"], }, retryable: false, + retry_class: "never", remediation: { action: projected.error.message }, }, }); diff --git a/tests/boundary/mcp/batchSourcePublicationCleanup.test.ts b/tests/boundary/mcp/batchSourcePublicationCleanup.test.ts index 6a6e3916c30..9d598a7903c 100644 --- a/tests/boundary/mcp/batchSourcePublicationCleanup.test.ts +++ b/tests/boundary/mcp/batchSourcePublicationCleanup.test.ts @@ -34,6 +34,7 @@ const expectRecoveredBatch = (response: CallToolResult, owned: string) => { category: "resource_constraint", message: expect.any(String), retryable: true, + retry_class: "same_call", remediation: expect.any(Object), details: expect.objectContaining({ operation: "record_evidence" }), }, diff --git a/tests/boundary/mcp/buildComputerMcp.test.ts b/tests/boundary/mcp/buildComputerMcp.test.ts index 0b51d0ffecf..dd4d3f4f886 100644 --- a/tests/boundary/mcp/buildComputerMcp.test.ts +++ b/tests/boundary/mcp/buildComputerMcp.test.ts @@ -135,9 +135,12 @@ it("keeps a computer up, forwards actions with their images and tears it down on }); expect(await runner.notes("teardowns.jsonl")).toHaveLength(1); const after = await act("screenshot"); - expect(parseMcpToolError(after).error.message).toContain( - "start_build_computer", - ); + // A closed computer's id names nothing; the refusal names the next step. + expect(parseMcpToolError(after).error).toMatchObject({ + code: "invalid_request", + message: "No build computer has this id in this REA server.", + remediation: { action: "Start one with start_build_computer." }, + }); }); it("renders a build bundle from a request with REA's payload and starts it", async () => { @@ -766,6 +769,10 @@ it("cancels a computer's call in progress on close and refuses the calls waiting expect(await runner.notes("teardowns.jsonl")).toHaveLength(1); expect( parseMcpToolError(await call("act_on_build_computer", { action: "wait" })) - .error.message, - ).toContain("start_build_computer"); + .error, + ).toMatchObject({ + code: "invalid_request", + message: "No build computer has this id in this REA server.", + remediation: { action: "Start one with start_build_computer." }, + }); }); diff --git a/tests/boundary/mcp/bunStandaloneMcp.test.ts b/tests/boundary/mcp/bunStandaloneMcp.test.ts index 3f032f43d78..6e37c3ff175 100644 --- a/tests/boundary/mcp/bunStandaloneMcp.test.ts +++ b/tests/boundary/mcp/bunStandaloneMcp.test.ts @@ -92,7 +92,9 @@ it("keeps a budget-limited Bun layout unresolved through MCP", async () => { expect(reply.isError).toBe(true); expect(parseMcpToolError(reply).error).toMatchObject({ code: moduleCount < 13 ? "partial" : "artifact_operation_failed", - retryable: moduleCount < 13, + // The caller must change the selected budget before a retry can differ. + retryable: false, + retry_class: "change_first", details: moduleCount < 13 ? { diff --git a/tests/boundary/mcp/enhancedTools.03-returns-typed-graph-failures-and.test.ts b/tests/boundary/mcp/enhancedTools.03-returns-typed-graph-failures-and.test.ts index 13dee71f3eb..d3991edb994 100644 --- a/tests/boundary/mcp/enhancedTools.03-returns-typed-graph-failures-and.test.ts +++ b/tests/boundary/mcp/enhancedTools.03-returns-typed-graph-failures-and.test.ts @@ -32,7 +32,12 @@ describe("enhanced MCP tools", () => { : err( new AnalysisInputError( operation, - { conformsToInputContract: true }, + { + conformsToInputContract: true, + userMessage: "No procedure matches the selector.", + remediationAction: + "Select an observed procedure name or address.", + }, [{ path: ["procedure"], reason: "invalid_value" }], ), ), diff --git a/tests/boundary/mcp/enhancedTools.callPathsAndBatches.test.ts b/tests/boundary/mcp/enhancedTools.callPathsAndBatches.test.ts index dfd53b7ffb6..6bec5b1bed3 100644 --- a/tests/boundary/mcp/enhancedTools.callPathsAndBatches.test.ts +++ b/tests/boundary/mcp/enhancedTools.callPathsAndBatches.test.ts @@ -632,6 +632,7 @@ describe("enhanced MCP batches", () => { /result REA could not read.*repeating the unchanged request.*not expected to succeed/i, ), retryable: false, + retry_class: "never", remediation: { action: expect.stringMatching( /result REA could not read.*repeating the unchanged request.*not expected to succeed/i, diff --git a/tests/boundary/mcp/gdbCloseDisposition.test.ts b/tests/boundary/mcp/gdbCloseDisposition.test.ts index 2cd4da7e7fd..61cbdb1b1a2 100644 --- a/tests/boundary/mcp/gdbCloseDisposition.test.ts +++ b/tests/boundary/mcp/gdbCloseDisposition.test.ts @@ -89,7 +89,9 @@ createInterface({ input: process.stdin }).on('line', line => { error: { code: "capability_unavailable", category: "unavailable", - retryable: true, + // The identical replay below fails the same way until the caller + // disposes the inferior, so the refusal is not retryable unchanged. + retryable: false, remediation: { action: expect.stringContaining("gdb_console") }, details: { provider_id: "gnu.gdb", diff --git a/tests/boundary/mcp/nativeSymbolSelection.test.ts b/tests/boundary/mcp/nativeSymbolSelection.test.ts index e20366df550..cd202d05ac3 100644 --- a/tests/boundary/mcp/nativeSymbolSelection.test.ts +++ b/tests/boundary/mcp/nativeSymbolSelection.test.ts @@ -118,13 +118,21 @@ const procedureMiss = ( procedure: string, ): Result => err( - new AnalysisInputError(operation, { conformsToInputContract: true }, [ + new AnalysisInputError( + operation, { - path: ["procedure"], - reason: "invalid_value", - message: `Unknown Ghidra procedure name or address: ${procedure}`, + conformsToInputContract: true, + userMessage: "No procedure matches the selector.", + remediationAction: "Select an observed procedure name or address.", }, - ]), + [ + { + path: ["procedure"], + reason: "invalid_value", + message: `Unknown Ghidra procedure name or address: ${procedure}`, + }, + ], + ), ); const containment = (address: string) => diff --git a/tests/boundary/mcp/navigationAlternativesMcp.test.ts b/tests/boundary/mcp/navigationAlternativesMcp.test.ts index 8d21ffb5d1f..f085d7d3d03 100644 --- a/tests/boundary/mcp/navigationAlternativesMcp.test.ts +++ b/tests/boundary/mcp/navigationAlternativesMcp.test.ts @@ -84,6 +84,7 @@ describe("address navigation refusals", () => { category: "unsupported_provider", message: `The selected provider does not declare ${name}.`, retryable: false, + retry_class: "never", remediation: { action: remediationFor(name, GHIDRA_ALTERNATIVES), }, @@ -226,6 +227,7 @@ describe("address navigation refusal alternatives", () => { category: "unsupported_provider", message: `The selected provider does not declare ${name}.`, retryable: false, + retry_class: "never", remediation: { action: expect.stringContaining("binary_session") }, details: { provider_id: "fixture", diff --git a/tests/boundary/mcp/nodeSeaMcp.test.ts b/tests/boundary/mcp/nodeSeaMcp.test.ts index 4024282a813..93a27d7a641 100644 --- a/tests/boundary/mcp/nodeSeaMcp.test.ts +++ b/tests/boundary/mcp/nodeSeaMcp.test.ts @@ -72,7 +72,7 @@ it.each(["compact"] as const)( }); expect(parseMcpToolError(assetRefusal).error).toMatchObject({ code: "partial", - retryable: true, + retryable: false, details: { operation: "inspect_artifact", reason: "limit", diff --git a/tests/boundary/mcp/partialObservationBudgetMcp.test.ts b/tests/boundary/mcp/partialObservationBudgetMcp.test.ts index 099b040301f..4d81b35680c 100644 --- a/tests/boundary/mcp/partialObservationBudgetMcp.test.ts +++ b/tests/boundary/mcp/partialObservationBudgetMcp.test.ts @@ -198,6 +198,8 @@ it("delivers an over-budget partial observation as its summary with a cursor on category: "resource_constraint", message: "The fixture stopped after completing its observation.", retryable: true, + // Occupied capacity admits the same request later. + retry_class: "same_call", // Guidance is delivered as its owning projection words it. remediation: projectAnalysisError( stoppedWith(undefined, "inspect_binary_layout"), diff --git a/tests/boundary/mcp/pcapWorkspaceAllocation.test.ts b/tests/boundary/mcp/pcapWorkspaceAllocation.test.ts index 98277c4cc6a..1cb9c2ec0c6 100644 --- a/tests/boundary/mcp/pcapWorkspaceAllocation.test.ts +++ b/tests/boundary/mcp/pcapWorkspaceAllocation.test.ts @@ -154,8 +154,8 @@ it("reaches input admission when the workspace parent is usable", async () => { it.each([ ["ENOSPC", "resource_constraint", "Free disk space or quota"], ["EDQUOT", "resource_constraint", "Free disk space or quota"], - ["EMFILE", "execution_failure", "open-file limit"], - ["ENFILE", "execution_failure", "open-file limit"], + ["EMFILE", "resource_constraint", "open-file limit"], + ["ENFILE", "resource_constraint", "open-file limit"], ["EROFS", "execution_failure", "TMPDIR"], ])( "classifies simulated %s allocation by its storage or descriptor cause", @@ -168,9 +168,20 @@ it.each([ ); expect(error).toMatchObject({ code: expected, + // Descriptor pressure clears once other work releases descriptors. + retryable: code === "EMFILE" || code === "ENFILE", remediation: { action: expect.stringContaining(recovery) as unknown }, }); - if (expected === "resource_constraint") + if (code === "EMFILE" || code === "ENFILE") + expect(error.details).toMatchObject({ + resource: "capacity", + reported_limits: { + workspace_path: null, + path: template, + system_code: code, + }, + }); + else if (expected === "resource_constraint") expect(error.details).toMatchObject({ resource: "file-size", reported_limits: { diff --git a/tests/boundary/mcp/retryableReplayContract.test.ts b/tests/boundary/mcp/retryableReplayContract.test.ts new file mode 100644 index 00000000000..23d253b252e --- /dev/null +++ b/tests/boundary/mcp/retryableReplayContract.test.ts @@ -0,0 +1,134 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import type { CallToolResult } from "@modelcontextprotocol/server"; +import { afterEach, expect, it } from "vitest"; + +import { androidVbmetaDescriptorCountOverflow } from "../../../src/domain/firmware/androidVbmeta.fixture.js"; +import type { AnalysisProvider } from "../../../src/ports/AnalysisProvider.js"; +import { createServer } from "../../../src/server/createServer.js"; +import { createTestBinarySession } from "../../fixtures/binarySession.js"; +import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { connectFixtureClient } from "../../support/mcp/mcpFixture.js"; +import { structured } from "../../support/mcp/toolResult.js"; + +/** + * `retryable: true` promises that the unchanged request may succeed. Each + * refusal here is deterministic, so replaying it unchanged shows whether that + * promise holds: a retryable refusal must not fail the same way again. + */ +const expectReplayContract = async ( + call: () => Promise, +): Promise["error"]> => { + const first = parseMcpToolError(await call()).error; + expect(first.retry_class).toBeDefined(); + expect(first.retryable).toBe(first.retry_class === "same_call"); + const replay = await call(); + if (first.retryable && replay.isError === true) + expect(parseMcpToolError(replay).error.code).not.toBe(first.code); + if (!first.retryable) { + expect(replay.isError).toBe(true); + expect(parseMcpToolError(replay).error).toMatchObject({ + code: first.code, + retryable: false, + }); + } + return first; +}; + +const resources: Array<{ close(): Promise }> = []; + +afterEach(async () => { + await Promise.all( + resources.splice(0).map(async (resource) => resource.close()), + ); +}); + +const noProvider: AnalysisProvider = { + identity: () => ({ id: "fixture", name: "Fixture", version: "1" }), + capabilities: () => [], + createClient: () => { + throw new Error("No client is needed for residual unknowns."); + }, +}; + +it("does not mark a stale unknown revision or a duplicate record retryable", async () => { + const client = await connectFixtureClient( + createServer({ + kind: "session", + session: createTestBinarySession(noProvider), + }), + { name: "retryable-replay", version: "1" }, + resources, + ); + const call = (name: string, args: Record) => () => + client.callTool({ name, arguments: args }); + const fields = { + question: "Does the replayed refusal stay refused?", + severity: "medium", + domain: "replay", + required_authority: "controlled-replay", + required_confidence: "observed", + required_environment: null, + recommended_probes: [], + relationships: [], + supporting_evidence_ids: [], + contradicting_evidence_ids: [], + }; + const { question: _question, domain: _domain, ...updateFields } = fields; + const recorded = await client.callTool({ + name: "record_unknown", + arguments: fields, + }); + expect(recorded.isError, JSON.stringify(recorded)).not.toBe(true); + const head = structured(recorded).result as { + unknown_id: string; + revision: number; + }; + + const duplicate = await expectReplayContract( + call("record_unknown", { ...fields, severity: "high" }), + ); + expect(duplicate).toMatchObject({ + retryable: false, + details: { reason: "already-exists", existing_unknown_id: head.unknown_id }, + }); + + const stale = await expectReplayContract( + call("update_unknown", { + ...updateFields, + unknown_id: head.unknown_id, + expected_revision: head.revision + 1, + status: "open", + resolution: null, + }), + ); + expect(stale).toMatchObject({ + code: "revision_conflict", + retryable: false, + details: { current_revision: head.revision }, + }); +}); + +it("does not mark a per-call reader limit retryable", async () => { + const root = await createTestTempDirectory("rea-retryable-replay-"); + const path = join(root, "vbmeta.img"); + await writeFile(path, androidVbmetaDescriptorCountOverflow()); + const { call } = await connectLocalToolsMcp({ + REA_MCP_INPUT_SCHEMA_PROFILE: "compact", + }); + try { + expect((await call("open_binary", { path })).isError).not.toBe(true); + const limited = await expectReplayContract(() => + call("inspect_artifact", {}), + ); + expect(limited).toMatchObject({ + retryable: false, + details: { reason: "limit", reader_limit: { can_increase: true } }, + }); + } finally { + await call("close_binary", {}); + } +}); diff --git a/tests/boundary/mcp/serverUnknownsMcp.test.ts b/tests/boundary/mcp/serverUnknownsMcp.test.ts index aae84f25384..d8a8ee66371 100644 --- a/tests/boundary/mcp/serverUnknownsMcp.test.ts +++ b/tests/boundary/mcp/serverUnknownsMcp.test.ts @@ -824,9 +824,13 @@ it("preserves graph constraint facts and rejects atomically until input is corre const conflict = parseMcpToolError( await client.callTool({ name: "update_unknown", arguments: update }), ).error; + // The stale revision cannot succeed unchanged; the conflict names the + // stored revision to retry with. expect(conflict).toMatchObject({ code: "revision_conflict", - retryable: true, + retryable: false, + details: { reason: "revision-conflict", current_revision: 2 }, + remediation: { action: expect.stringContaining("expected_revision 2") }, }); }); diff --git a/tests/boundary/mcp/sourceToBundleViewsMcp.test.ts b/tests/boundary/mcp/sourceToBundleViewsMcp.test.ts index e9026b1409a..30771493278 100644 --- a/tests/boundary/mcp/sourceToBundleViewsMcp.test.ts +++ b/tests/boundary/mcp/sourceToBundleViewsMcp.test.ts @@ -390,14 +390,15 @@ const expectReferenceRefusals = async ({ reference: { kind: "file", path }, }), ).toMatchObject({ - code: "invalid_request", + // A well-formed graph whose entries disagree with its root commitment is + // an integrity failure of the selected file, not a request error. + code: "evidence_integrity_mismatch", + category: "integrity_mismatch", + retry_class: "never", + message: + "The selected historical source graph's entries do not match its root_sha256 commitment.", details: { - issues: [ - { - path: ["reference", "root_sha256"], - reason: "invalid_value", - }, - ], + reason: `Historical source graph ${path} does not match its root_sha256 commitment.`, }, }); expect( diff --git a/tests/boundary/mcp/wxapkgMcp.test.ts b/tests/boundary/mcp/wxapkgMcp.test.ts index f78cca00a5a..e7ccdbe2e89 100644 --- a/tests/boundary/mcp/wxapkgMcp.test.ts +++ b/tests/boundary/mcp/wxapkgMcp.test.ts @@ -101,7 +101,7 @@ it("refuses a wxapkg member table above artifact_limits.wxapkg.table_bytes and a expect(reply.isError, JSON.stringify(reply)).toBe(true); const { error } = parseMcpToolError(reply); expect(error).toMatchObject({ - retryable: true, + retryable: false, details: { reader_limit: { parameter: "artifact_limits.wxapkg.table_bytes", diff --git a/tests/boundary/process/gpuDescriptorPressure.test.ts b/tests/boundary/process/gpuDescriptorPressure.test.ts index f6c352a3604..2486525d2ca 100644 --- a/tests/boundary/process/gpuDescriptorPressure.test.ts +++ b/tests/boundary/process/gpuDescriptorPressure.test.ts @@ -40,8 +40,9 @@ it.skipIf(process.platform === "win32")( name, system_code: "EMFILE", projection: expect.objectContaining({ - code: "execution_failure", - category: "execution_failure", + code: "resource_constraint", + category: "resource_constraint", + retryable: true, }), }), ), diff --git a/tests/boundary/providers/GdbSessionManagerCoverage.test.ts b/tests/boundary/providers/GdbSessionManagerCoverage.test.ts index 269a07b320c..540ce6d9585 100644 --- a/tests/boundary/providers/GdbSessionManagerCoverage.test.ts +++ b/tests/boundary/providers/GdbSessionManagerCoverage.test.ts @@ -850,7 +850,8 @@ it.each([ ok: false, error: { _tag: "AnalysisCapabilityUnavailableError", - retryable: true, + retry: "change_first", + retryable: false, diagnostics: { inferior_disposition_required: reason, live_inferiors: inferiorCount, diff --git a/tests/boundary/providers/apktoolRuntimeExhaustion.test.ts b/tests/boundary/providers/apktoolRuntimeExhaustion.test.ts index 0577a865f34..162e029fdc2 100644 --- a/tests/boundary/providers/apktoolRuntimeExhaustion.test.ts +++ b/tests/boundary/providers/apktoolRuntimeExhaustion.test.ts @@ -53,18 +53,19 @@ it("reports the decoder JVM's heap exhaustion as memory, not a target refusal", }); it.each([ - ["Metaspace", "metaspace", "memory"], - ["Requested array size exceeds VM limit", "array-size", "memory"], - ["unable to create native thread", "native-thread", "capacity"], -])( + ["Metaspace", "metaspace", "memory", false], + ["Requested array size exceeds VM limit", "array-size", "memory", false], + // Native threads free as other host work ends, so the same call may succeed. + ["unable to create native thread", "native-thread", "capacity", true], +] as const)( "names the memory area a %s report exhausted", - async (detail, area, resource) => { + async (detail, area, resource, retryable) => { const projected = await failingDecode( `printf 'Exception in thread "main" java.lang.OutOfMemoryError: ${detail}\\n' >&2`, ); expect(projected).toMatchObject({ code: "resource_constraint", - retryable: false, + retryable, details: { resource, diagnostics: { diff --git a/tests/boundary/providers/hopper/hopperClient.protocol.test.ts b/tests/boundary/providers/hopper/hopperClient.protocol.test.ts index 75d25c3df0f..47135dc5ab6 100644 --- a/tests/boundary/providers/hopper/hopperClient.protocol.test.ts +++ b/tests/boundary/providers/hopper/hopperClient.protocol.test.ts @@ -528,7 +528,8 @@ describe("HopperClient operational diagnostics", () => { const projected = projectAnalysisError(result.error); expect(projected).toMatchObject({ code: "provider_unavailable", - retryable: true, + // The same call does not relaunch the bridge; restart it first. + retryable: false, details: { stage: "analysis", provider_state: result.error.providerState, diff --git a/tests/composition/directAnalysisCleanup.test.ts b/tests/composition/directAnalysisCleanup.test.ts index 439803b529e..6e45c403ad1 100644 --- a/tests/composition/directAnalysisCleanup.test.ts +++ b/tests/composition/directAnalysisCleanup.test.ts @@ -432,6 +432,10 @@ describe("one-shot finalization cancellation", () => { ).then(projectCliAnalysisResult); expect(result).toMatchObject({ code: closeFails ? "cleanup_incomplete" : "provider_timeout", + // A timeout may repeat unchanged; one whose close also failed may + // repeat only after cleanup settles. + retryable: !closeFails, + retry_class: closeFails ? "change_first" : "same_call", message: projectAnalysisError(failure).message, details: { captured_output: failure.capturedOutput, @@ -461,6 +465,8 @@ describe("one-shot finalization cancellation", () => { expect(result).toMatchObject({ code: "cleanup_incomplete", category: "cancelled", + retryable: false, + retry_class: "change_first", details: { execution_failure: "cancelled", resources: ["fixture-provider-process"], diff --git a/tests/composition/directAnalysisXrefs.test.ts b/tests/composition/directAnalysisXrefs.test.ts index 7f8da68732e..dbc996ab353 100644 --- a/tests/composition/directAnalysisXrefs.test.ts +++ b/tests/composition/directAnalysisXrefs.test.ts @@ -73,7 +73,12 @@ const fixture = ( : err( new AnalysisInputError( "procedure_address", - { conformsToInputContract: true }, + { + conformsToInputContract: true, + userMessage: "No procedure matches the selector.", + remediationAction: + "Select an observed procedure name or address.", + }, [{ path: ["procedure"], reason: "invalid_value" }], ), ), diff --git a/tests/fixtures/cli-parity/error-jsonl-not-collection.txt b/tests/fixtures/cli-parity/error-jsonl-not-collection.txt index 581e012651c..d2fe682c62f 100644 --- a/tests/fixtures/cli-parity/error-jsonl-not-collection.txt +++ b/tests/fixtures/cli-parity/error-jsonl-not-collection.txt @@ -1,7 +1,7 @@ $ rea inspect-byte-entropy /sample.bin --filter-output normalized_result.blocks --format jsonl exit: 1 --- stdout -{"$rea":"jsonl/v1","type":"error","ok":false,"result":{"code":"invalid_request","category":"invalid_input","message":"The --filter-output selection normalized_result.blocks is not a JSON Lines record collection: normalized_result.blocks is an array. JSON Lines needs a top-level array, or exactly one rows, items, records, or occurrences array directly in the result, under page, or under normalized_result.","retryable":false,"remediation":{"action":"Use --format json for the complete document, or select one record collection with --filter-output."},"recovery":{"kind":"inspect_input_contract","operation":"inspect-byte-entropy"},"details":{"operation":"inspect-byte-entropy","issues":[{"path":["filter-output"],"reason":"invalid_value","message":"The --filter-output selection normalized_result.blocks is not a JSON Lines record collection: normalized_result.blocks is an array.","observed":[{"path":["normalized_result","blocks"],"shape":"array"}]}]}}} +{"$rea":"jsonl/v1","type":"error","ok":false,"result":{"code":"invalid_request","category":"invalid_input","message":"The --filter-output selection normalized_result.blocks is not a JSON Lines record collection: normalized_result.blocks is an array. JSON Lines needs a top-level array, or exactly one rows, items, records, or occurrences array directly in the result, under page, or under normalized_result.","retryable":false,"retry_class":"change_first","remediation":{"action":"Use --format json for the complete document, or select one record collection with --filter-output."},"recovery":{"kind":"inspect_input_contract","operation":"inspect-byte-entropy"},"details":{"operation":"inspect-byte-entropy","issues":[{"path":["filter-output"],"reason":"invalid_value","message":"The --filter-output selection normalized_result.blocks is not a JSON Lines record collection: normalized_result.blocks is an array.","observed":[{"path":["normalized_result","blocks"],"shape":"array"}]}]}}} --- stderr diff --git a/tests/process-global/javascriptFilesystemErrors.test.ts b/tests/process-global/javascriptFilesystemErrors.test.ts index 9b41239159a..6eabfdcaa55 100644 --- a/tests/process-global/javascriptFilesystemErrors.test.ts +++ b/tests/process-global/javascriptFilesystemErrors.test.ts @@ -1,4 +1,5 @@ import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; +import { realpath } from "node:fs/promises"; import { expect, it, vi } from "vitest"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; @@ -29,6 +30,10 @@ vi.mock("node:fs/promises", async (importOriginal) => { inject("access", args[0]); return native.access(...args); }, + opendir: (...args: Parameters) => { + inject("opendir", args[0]); + return native.opendir(...args); + }, }; }); import { createServer } from "../../src/server/createServer.js"; @@ -39,6 +44,8 @@ it.each([ { method: "lstat", code: "EACCES" }, { method: "realpath", code: "EIO" }, { method: "access", code: "EMFILE" }, + // The directory reader wraps this as its own I/O failure. + { method: "opendir", code: "EMFILE" }, ])( "retains selected input and host facts through MCP after $method/$code refusal and accepts a readable retry", async ({ method, code }) => { @@ -59,7 +66,8 @@ it.each([ await server.connect(serverTransport); await client.connect(clientTransport); fault.method = method; - fault.path = root; + // The reader opens the directory at its canonical path. + fault.path = method === "opendir" ? await realpath(root) : root; fault.calls = 0; fault.error = Object.assign( new Error(`${code}: selected ${method} failed at ${root}`), @@ -85,6 +93,25 @@ it.each([ boundary: "filesystem-read", }, }); + // Descriptor pressure is occupied host capacity; the readable control + // below shows the unchanged call succeeds once it clears. + else if (code === "EMFILE") + expect(result.error).toMatchObject({ + code: "resource_constraint", + retryable: true, + details: { + resource: "capacity", + reported_limits: + method === "opendir" + ? { input_path: root, system_code: code } + : { + input_path: root, + path: root, + system_code: code, + syscall: method, + }, + }, + }); else expect(result.error).toMatchObject({ code: "artifact_operation_failed", diff --git a/tests/process-global/modelHostReadFailure.test.ts b/tests/process-global/modelHostReadFailure.test.ts index c9a78614ade..65784260811 100644 --- a/tests/process-global/modelHostReadFailure.test.ts +++ b/tests/process-global/modelHostReadFailure.test.ts @@ -87,18 +87,31 @@ mcpTest.for(["gguf", "safetensors"] as const)( { code }, ); const { error } = parseMcpToolError(await call()); - expect(error).toMatchObject({ - code: "execution_failure", - category: "execution_failure", - retryable: false, - details: { - provider_id: "model-artifact", - diagnostics: { - path, - reason: `controlled ${stage} failure (${code})`, - }, - }, - }); + // Descriptor pressure is occupied host capacity: the unchanged call + // succeeds once it clears, as the accepted retry below shows. + expect(error).toMatchObject( + code === "EMFILE" + ? { + code: "resource_constraint", + retryable: true, + details: { + resource: "capacity", + reported_limits: { path, system_code: code }, + }, + } + : { + code: "execution_failure", + category: "execution_failure", + retryable: false, + details: { + provider_id: "model-artifact", + diagnostics: { + path, + reason: `controlled ${stage} failure (${code})`, + }, + }, + }, + ); expect(error.message).not.toContain("Check that the path exists"); if (stage === "read") expect(fault.handles.length).toBeGreaterThan(0); expect(fault.handles.every((handle) => handle.fd === -1)).toBe(true); diff --git a/tests/process-global/sourceToBundleReferenceGuards.test.ts b/tests/process-global/sourceToBundleReferenceGuards.test.ts index ad19f998919..cbefd183aae 100644 --- a/tests/process-global/sourceToBundleReferenceGuards.test.ts +++ b/tests/process-global/sourceToBundleReferenceGuards.test.ts @@ -8,10 +8,11 @@ import { afterEach, expect, it, onTestFinished, vi } from "vitest"; import { resolveSourceToBundleReference } from "../../src/application/javascript/SourceToBundleReference.js"; import { requireAuthenticationHeadroom } from "../../src/application/JsonAuthenticationHeadroom.js"; import * as workflow from "../../src/application/javascript/JavaScriptApplicationWorkflowService.js"; -import { historicalSourceGraphSchema } from "../../src/domain/referenceSourceGraph.js"; +import { historicalSourceGraphStructureSchema } from "../../src/domain/referenceSourceGraph.js"; import { ArtifactResourceScope } from "../../src/resources/ArtifactResourceScope.js"; import { SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE } from "../../src/contracts/javascript/javascriptApplicationWorkflowExamples.js"; import { createServer } from "../../src/server/createServer.js"; +import { projectAnalysisError } from "../../src/domain/analysisErrorProjection.js"; import { ToolResultDelivery } from "../../src/server/ToolResultDelivery.js"; import { createTestBinarySession } from "../fixtures/binarySession.js"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; @@ -79,6 +80,38 @@ it("reports graph headroom before invalid reference data", async () => { expect(resources.hasPending).toBe(false); }); +it("reports a graph file whose entries contradict its root commitment as an integrity failure", async () => { + const root = await createTestTempDirectory("rea-source-tampered-"); + const path = join(root, "graph.json"); + await writeFile( + path, + JSON.stringify({ + ...SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference, + root_sha256: "0".repeat(64), + }), + ); + const resources = new ArtifactResourceScope(); + try { + const resolved = await resolveSourceToBundleReference( + { kind: "file", path }, + undefined, + resources, + ); + if (resolved.ok) throw new Error("Expected a commitment refusal"); + // The entries disagree with their commitment; the request is not at fault, + // so no input-contract recovery applies. + const projected = projectAnalysisError(resolved.error); + expect(projected).toMatchObject({ + code: "evidence_integrity_mismatch", + category: "integrity_mismatch", + retryable: false, + }); + expect(projected).not.toHaveProperty("recovery"); + } finally { + await resources.close(); + } +}); + it("attributes file-I/O cancellation to the comparison and preserves its exact cause", async () => { const root = await createTestTempDirectory("rea-reference-io-cancel-"); const path = join(root, "graph.json"); @@ -123,16 +156,17 @@ it.each(["validation", "comparison"] as const)( const controller = new AbortController(); const before = session.exportEvidenceBundle(); if (stage === "validation") { - const parse = historicalSourceGraphSchema.safeParse; - vi.spyOn(historicalSourceGraphSchema, "safeParse").mockImplementationOnce( - (value) => { - const parsed = parse(value); - setImmediate(() => - controller.abort(new Error("cancel during graph validation")), - ); - return parsed; - }, - ); + const parse = historicalSourceGraphStructureSchema.safeParse; + vi.spyOn( + historicalSourceGraphStructureSchema, + "safeParse", + ).mockImplementationOnce((value) => { + const parsed = parse(value); + setImmediate(() => + controller.abort(new Error("cancel during graph validation")), + ); + return parsed; + }); } else { const actual = await vi.importActual( "../../src/application/javascript/JavaScriptApplicationWorkflowService.js",