import { AnalysisCapabilityUnavailableError, AnalysisResourceConstraintError, AnalysisTargetFailureError, } from "./analysisErrorCore.js"; import { TARGET_FAILURE_KINDS, TARGET_FAILURE_PROJECTIONS, targetFailureRetry, type TargetFailureKind, type TargetFailureRetry, } from "./targetFailure.js"; import { domainErrorTag, type AnalysisError, type AnalysisErrorTag, type ProviderErrorTag, } from "./analysisErrorBase.js"; import type { AnalysisErrorProjection } from "./analysisErrorProjection.js"; import { ArtifactOperationError, integrityCheckMeansChanged, } from "./artifactOperationError.js"; import { BrowserObservationError } from "./browserObservationError.js"; import type { BrowserObservationFailureReason } from "./browserObservationErrors.js"; import { BinaryTargetError, type BinaryTargetErrorOptions, } from "./configurationErrors.js"; import { EvidenceFileError, EvidenceReferenceError, ResourceSnapshotMismatchError, } from "./evidenceErrors.js"; import { ProviderSelectionError, type ProviderSelectionFailureReason, } from "./providerSelectionError.js"; import { UnknownRegistryError } from "./unknownRegistryError.js"; type ErrorCode = AnalysisErrorProjection["code"]; type ErrorCategory = AnalysisErrorProjection["category"]; /** * 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; } /** 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 = | "AnalysisTargetFailureError" | "ArtifactOperationError" | "BinaryTargetError" | "BrowserObservationError" | "EvidenceFileError" | "ProcessCaptureError" | "ProviderSelectionError" | "UnknownRegistryError"; const classified = ( code: ErrorCode, category: ErrorCategory, retry: AnalysisRetryClass, ): AnalysisErrorClassification => ({ code, category, retry }); const STATIC_ERROR_CLASSIFICATIONS = { 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", "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", ), EvidenceIntegrityError: classified( "evidence_integrity_mismatch", "integrity_mismatch", "never", ), ProviderAdapterError: classified( "execution_failure", "execution_failure", "never", ), } as const satisfies Readonly< Record< Exclude, AnalysisErrorClassification > >; /** * 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 classification the projection table gives one target failure kind. */ const kindClassification = ( kind: TargetFailureKind, ): AnalysisErrorClassification => { 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", "same_call"), // `limit` reports `partial`: the result was cut short. 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 >; /** An integrity failure that names the artifact's expected and observed identity. */ 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", "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", "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 = { // 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 >; const PROVIDER_SELECTION_CLASSIFICATIONS = { unknown_provider: classified( "capability_unavailable", "unsupported_provider", "change_first", ), provider_unavailable: classified( "provider_unavailable", "unavailable", "same_call", ), 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", ), } as const satisfies Readonly< Record >; type BinaryTargetConstraintKey = | NonNullable | "unconstrained"; const BINARY_TARGET_CLASSIFICATIONS = { 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", ), 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_current_version_missing: classified( "target_unavailable", "unavailable", "change_first", ), bundle_path_escapes: classified( "target_unavailable", "unavailable", "change_first", ), } as const satisfies Readonly< Record >; /** A target the host refused to read keeps its constraint's category. */ const binaryTargetClassification = ( constraint: BinaryTargetConstraintKey, readPermissionDenied: boolean, ): AnalysisErrorClassification => { const base = BINARY_TARGET_CLASSIFICATIONS[constraint]; return readPermissionDenied && constraint !== "load_selection_rejected" ? { ...base, code: "access_denied" } : base; }; const BROWSER_OBSERVATION_CLASSIFICATIONS = { 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", ), process_ownership_unavailable: classified( "unreadable_output", "execution_failure", "never", ), 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", "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. */ const staticClassification = ( error: AnalysisError, ): AnalysisErrorClassification => { const tag = domainErrorTag(error); if (tag === undefined) throw new TypeError(`Unpresented provider error: ${error._tag}`); switch (tag) { case "AnalysisTargetFailureError": case "ArtifactOperationError": case "BinaryTargetError": case "BrowserObservationError": case "EvidenceFileError": case "ProcessCaptureError": case "ProviderSelectionError": case "UnknownRegistryError": throw new TypeError(`Unhandled specialized analysis error: ${tag}`); default: return STATIC_ERROR_CLASSIFICATIONS[tag]; } }; /** * 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, retry: owned.retry }; if ( error instanceof AnalysisCapabilityUnavailableError && error.retry !== "never" ) return availableLaterCapability(error.retry); if (error instanceof AnalysisTargetFailureError) 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) return error.userCategory === "cancelled" ? 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") : ARTIFACT_OPERATION_CLASSIFICATIONS.integrity; } if (error instanceof BinaryTargetError) return binaryTargetClassification( error.constraint ?? "unconstrained", error.systemCode !== undefined, ); 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 : "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: 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; } /** * One catalogue row. A provider that presents its own errors lists them * through this, so its rows read like the domain's. */ export const catalogueRow = ( tag: AnalysisErrorTag | ProviderErrorTag, discriminant: string, classification: AnalysisErrorClassification, ): AnalysisErrorCatalogueEntry => ({ tag, discriminant, ...classification, retryableByDefault: classification.retry === "same_call", }); const reasonRows = ( tag: AnalysisErrorTag, table: Readonly>, ): AnalysisErrorCatalogueEntry[] => Object.entries(table).map(([reason, classification]) => catalogueRow(tag, `reason=${reason}`, classification), ); /** * Every domain error case and its caller-facing code and category. A * provider-owned error presents itself, and its provider lists its rows. * Cleanup that did not complete reports `cleanup_incomplete` above any row. */ export const analysisErrorCatalogue = (): readonly AnalysisErrorCatalogueEntry[] => [ ...Object.entries(STATIC_ERROR_CLASSIFICATIONS).map( ([tag, classification]) => catalogueRow(tag as AnalysisErrorTag, "", classification), ), catalogueRow( "AnalysisCapabilityUnavailableError", "retry=same_call", availableLaterCapability("same_call"), ), catalogueRow( "AnalysisCapabilityUnavailableError", "retry=change_first", availableLaterCapability("change_first"), ), ...TARGET_FAILURE_KINDS.map((kind) => catalogueRow( "AnalysisTargetFailureError", `kind=${kind}`, 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", kindClassification("changed"), ), ...Object.keys(BINARY_TARGET_CLASSIFICATIONS).flatMap((key) => { const constraint = key as BinaryTargetConstraintKey; const allowed = binaryTargetClassification(constraint, false); const denied = binaryTargetClassification(constraint, true); return [ catalogueRow("BinaryTargetError", `constraint=${constraint}`, allowed), ...(denied.code === allowed.code ? [] : [ catalogueRow( "BinaryTargetError", `constraint=${constraint}; read permission denied`, denied, ), ]), ]; }), ...reasonRows( "BrowserObservationError", BROWSER_OBSERVATION_CLASSIFICATIONS, ), catalogueRow( "BrowserObservationError", "caused by cancellation", 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), ...reasonRows("UnknownRegistryError", UNKNOWN_REGISTRY_CLASSIFICATIONS), ];