mirror of
https://github.com/morluto/rea.git
synced 2026-11-16 19:53:50 +00:00
* fix(native): report a target-selected plist against the target, not the unsent path input inspect_plist resolved a plist that the open target itself selects with the same origin as a caller's path input, so an unreadable target plist was reported as an input issue on path even when the caller never sent path. The selection now records a target origin, and unreadablePlist reports it as a BinaryTargetError for the target. The inspect-plist CLI command is projected from its contract, so its --relative-path issues are named by the CLI key. * refactor(cli)!: route analyze to the contract its target selects (#10808) * refactor(cli): route analyze to the contract its target selects analyze hand-declared both lanes: native open options for binary_overview and the JavaScript integrity policy and source selection for analyze_javascript_application, with its own routing and refusals. registerTargetRoutedCommand now projects each route from its contract, takes the union of their options, runs the first route that owns every given option and takes the target, and refuses options the chosen route does not own by their CLI key. Omitted union fields, including a root discriminator, no longer need an argv projection. * fix(cli): give a routed command's chosen route its CLI-only option defaults Routing strips option defaults so an omitted option routes no target. Contract fields regain theirs on admission, but CLI-only options have no later parse, so a defaulted one reached the handler as undefined. The chosen route's omitted CLI-only options now receive their defaults before the handler runs. * refactor(cli): deliver decompile and inspect-macho Evidence by the contract's detail (#10813) * refactor(cli): deliver decompile and inspect-macho Evidence by the contract's detail decompile and inspect-macho omitted the contract's detail field and always printed complete Evidence. Both now declare evidenceDelivery, adding --detail and --evidence_output from the contract. Publishing a result never used the provider id it required, so publication takes no provider and runOnSessionTarget no longer needs one to deliver. * refactor(cli): project managed artifact and native-boundary inspectors from their contracts (#10816) inspect-managed-artifact and inspect-managed-native-boundaries re-declared the managed budget fields by hand. Both now register from their contracts on a session target, and inspect-managed-artifact gains --detail and --evidence_output from its detail field. * fix(cli): name every contract command's input issues by their CLI key Commands applied their CLI field binding only where a session-target or direct handler returned an undelivered result. With evidenceDelivery, decompile publishes through the shared delivery, which returned a provider failure unprojected, so an issue about the procedure would be reported at ["procedure"] instead of the advertised positional "address". Handlers that run a service or publish themselves never applied it: inspect-il2cpp-metadata reported ["generic_instances"], inspect-go-binary ["max_string_literals"] and inspect-apple-ips ["join_path"] rather than the CLI keys other commands report. The contract command now projects whatever its handler returns through the binding it owns, for plain and target-routed commands alike, and the handler context no longer carries the binding. * fix(analysis-view): summarize pseudocode that selected an independent fresh decompile The pseudocode view parsed its parent's parameters with a selection schema that admitted only procedure and document. A procedure_pseudo_code observation made with analysis independent_fresh records that field, so its summary view refused the parent. Through the CLI's new summary delivery, `decompile --analysis independent_fresh --detail summary --evidence_output <file>` would fail after a successful decompile and never save the bundle; an inline inspect_analysis_view of such Evidence failed the same way. The selection schema now admits the analysis the contract offers, and the contract reads that enum from the same owner. * test(cli): restore the worker's exit status after synthetic contract command runs logCliCommand sets process.exitCode on a refused or failed command. The synthetic routed and input-field harnesses ran in the cli-boundary project's shared workers (isolate: false) and left that status for later tests. Each invocation now restores the previous status. * refactor(cli)!: deliver inspect-managed-members Evidence through the shared --evidence_output (#10845) inspect-managed-members was the last command with its own Evidence delivery: a hand-written registration passed --detail and --evidence-bundle to runProviderAnalysis, whose members-only delivery variant re-checked heap headroom and published through deliverAnalysisEvidence. Every other producer writes its bundle with --evidence_output through publishCliAnalysisEvidence, and elsewhere on the CLI --evidence-bundle names an input bundle to read. The command now registers from the inspect_managed_members contract on a session target with evidenceDelivery, like inspect-managed-artifact; --type is the contract's type_names. runProviderAnalysis loses its delivery parameter and its two refusals, and deliverAnalysisEvidence, now unused, is deleted. Its lifecycle tests drive publishEvidenceDelivery directly or the CLI delivery; the managed-only headroom pre-check tests are removed, since the shared delivery deliberately does not re-authenticate immutable Evidence and keeps the writer's check for mutable sources. BREAKING CHANGE: `rea inspect-managed-members --evidence-bundle <path>` is now `--evidence_output <path>`; the old flag is refused as an unknown flag. With `--detail summary`, stdout is now `{"summary": <summary Evidence>, "evidence_bundle": {"path", "bytes"}}` instead of the summary Evidence alone, and a publication failure is the shared delivery's error projection without the `error` label or `input_path`. A summary without a destination names `evidence_output` in its issue path. Migrate by renaming the flag and reading `.summary`. Compatibility is not kept: one spelling cannot mean "read this bundle" on view and workflow commands and "write this bundle" on one producer. * refactor(cli): project analyze-javascript-application and analyze's JavaScript route from one contract projection analyze-javascript-application declared its options by hand, mapped about twelve option names to contract fields itself, parsed its delivery separately and resolved its own caller path. analyze's JavaScript route, projected from the same contract, omitted every field but the path, source selection and integrity policy, so the two commands for one contract offered different options. Both now use javaScriptApplicationCliProjection and runJavaScriptApplicationCommand: the path positional, --artifact-format, --source-path, and the two options that accept a JSON file (--source-paths-json, --semantic-precision), with contract delivery. analyze therefore takes the JavaScript budgets, --artifact-format, --semantic-precision and --detail/--evidence_output/--view for JavaScript targets, and refuses them by CLI key for native targets. javascriptApplicationOptions is deleted. The command's missing-target refusal now names its CLI key, "path", as every contract command does. * refactor(cli): project the apktool commands from their contracts (#10878) * refactor(cli): project the apktool commands from their contracts * refactor(cli): project the Flutter commands from their contracts (#10882) * refactor(cli): project the Flutter commands from their contracts * refactor(cli): project the JEB commands from their contracts (#10888) * refactor(cli): project the JEB commands from their contracts * refactor(cli): project the Android package, class, method and reference commands from their contracts (#10893) * refactor(cli): compose compare-managed-members from its contract over two inspected targets (#10914) * refactor(cli): compose compare-managed-members from its contract over two inspected targets The contract command builder takes Evidence targets: required contract fields that each take the Evidence a source contract produces for one positional target, with the source's options admitted for every target. compare-managed-members now inspects each path through the typed managed runner, as inspect-managed-members does, and compares the records as MCP compare_managed_members does. A failing candidate names its argument and retains the baseline's Evidence; a cancellation as the comparison settles retains the comparison. The path-only comparison service is removed. * fix(cli): drain queued interrupts before a composed command settles Select snapshot faults by file identity, guard real permission denial to hosts that enforce it, and release retained owners when a test fails. * refactor(cli): project the ADB commands from their contracts (#10934) Each ADB command is registered from its ADB_TOOL_CONTRACTS entry through registerContractCommand, keeping its positionals, flags and kebab-case path keys. start-adb-activity keeps its repeatable --extra type:key:value option, which supplies the contract's extras. * refactor(cli): project Frida discovery from its contracts and share Frida request mapping with MCP (#10951) list-frida-devices and list-frida-processes are registered from their contracts, with each remote member as its own option, and admit the request MCP would send. instrument-with-frida keeps its argv but builds and admits the instrument_with_frida contract input. One application owner maps Frida contract inputs to service requests for both adapters. * refactor(cli): finalize the Evidence-target composition through runOwned runOnEvidenceTargets turned a completed comparison into a cancellation by reading the abort signal by hand, which main's architecture guard now refuses outside runOwned. The composition now finalizes through runOwned: its close drains queued interrupts (it owns no resource), and a cancellation observed as it settles keeps the completed Evidence as the partial observation, as before. * fix(errors)!: keep every completed argument's observation beside a composite failure's own partial (#10961) * fix(errors): keep every completed argument's observation beside a composite failure's own partial * test(errors): cover argument observations through cleanup composition and the partial-free fallback * test(errors): settle the cleanup through its owner's release in the argument-observation case * refactor(cli): project instrument-with-frida through the contract builder (#10962) * refactor(cli): project instrument-with-frida through the contract builder with CLI-only positionals and handler-filled fields * fix(cli): keep omitted flattened members omitted so partial capture limits keep their Evidence * refactor(cli): project the CDP page-target browser commands from their contracts (#10976) * refactor(cli): project the CDP page-target browser commands from their contracts * refactor(cli): project inspect-web-page from its contract with a branch-selecting flag * test(cli): enroll the browser commands in the parity registration check and refuse unenrolled argv fixtures * refactor(cli): project the V8 Inspector and Electron commands from their contracts (#10977) * refactor(cli): project the V8 Inspector runtime commands from their contracts * test(cli): enroll the V8 Inspector runtime commands in the parity registration check * refactor(cli): project the Electron page observation commands from their contracts (#10987) * refactor(cli): project the Electron page observation commands from their contracts * test(cli): enroll the Electron page observation commands in the parity registration check * refactor(cli): project inspect-electron-fuses from its contract with the shared caller-path rule The command now registers through registerContractCommand with `path` as a caller path, so the builder's absoluteCallerPath owns relative-path anchoring and the command's own absoluteElectronFusePath copy is removed. inspectWithService records the caller's spelling as caller_input_path. The named file is unchanged: every `..` is kept for the filesystem, and Win32 resolves as before. The recorded selected_path drops `.` segments and repeated separators (`App.app/./` -> `App.app/`), and an empty path is now refused at argv parsing (VALIDATION_ERROR) like every other caller-path command. * test(cli): derive contract-built commands from the builder registries instead of a hand list Every command named after a public tool contract must register through a contract builder unless it is in a shrinking list of hand registrations, and the renamed contract commands are listed exactly, so an earlier migration that reverts fails instead of dropping out of the parity cases. The JSON-document command hand list is covered by the same check and removed. * test(cli): drop the empty inspect-electron-fuses path mismatch the CLI now refuses * refactor(cli): project compare-web-screenshots and analyze-web-bundle from their contracts with builder JSON inputs (#11012) * refactor(cli): project compare-web-screenshots from its contract with builder JSON inputs read from inline text or a file The contract command builder gains jsonInputs: structured fields taken as inline JSON or a JSON file path (- reads stdin), read when the command runs and admitted with the contract input before any target is opened. Inline text that is not JSON is refused under its CLI key; a file that cannot be read keeps its own failure. compare-web-screenshots takes both artifacts this way, replacing its hand-written JSON argument parsing. * refactor(cli): project analyze-web-bundle from its contract analyze-web-bundle now registers through registerContractCommand with Evidence and view delivery, semantic_precision as a builder JSON input, and source_map_limits flattened onto the existing --source-map-* flags. Page-inspection extras stay omitted, and script sources stay on as the contract default. The superseded javascriptRouteDelivery options, passive browser scope options, observation duration helper and fetched source-map option set are removed. * refactor(cli): take semantic_precision of JavaScript application analysis as a builder JSON input analyze-javascript-application and the analyze route read --semantic-precision through the contract builder's jsonInputs instead of a CLI-only option decoded in the handler, so the decoded budgets are admitted with the contract input before analysis. * refactor(cli): route compare-web-captures to the contract input shape its documents select (#11027) * refactor(cli): route compare-web-captures to the contract input shape its documents select * fix(cli): keep routed defaults advertised and reuse the admitted capture parse * fix(cli): keep explicit routed options distinct from advertised defaults * refactor(cli): project inspect-ntfs-journal from its contract (#11043) * refactor(cli): project inspect-ntfs-journal from its contract * refactor(cli): project the pcap commands from their contracts (#11045) * refactor(cli): project the pcap commands from their contracts * refactor(cli): project inspect-playwright-trace, the Cutter commands and execute-rizin-command from their contracts (#11046) * refactor(cli): project inspect-playwright-trace from its contract * refactor(cli): project the Cutter commands from their contracts (#11047) * refactor(cli): project the Cutter commands from their contracts * refactor(cli): project execute-rizin-command from its contract (#11048) * fix(cli): refuse a selected page without summary delivery before opening the target * refactor(cli): project export-web-scripts and trace-web-module-imports from their contracts (#11053) * refactor(cli): project export-web-scripts and trace-web-module-imports from their contracts * fix(cli): describe export-web-scripts paths as resolved against the working directory * refactor(cli): project the web runtime and JavaScript recovery commands from their contracts (#11084) * refactor(cli): project the web runtime commands from their contracts * refactor(cli): project recover-javascript-sources from its contract * refactor(cli): select a contract input branch by its literal field and project guided-workflows (#11085) * refactor(cli): select a contract input branch by its literal field and project guided-workflows * fix(cli): refuse delivery options before reading JSON inputs * fix(cli): keep branch-only defaults to their branch and name admission issues by CLI key A branch-only field no longer carries its default into the shared options, so another branch never receives it; the selected branch applies the default on parse. Contract admission failures are projected to CLI keys like handler failures. CLI defaults are typed only on top-level fields, the one place that applies them. * refactor(cli): project compare-process-captures from its contract, checking each capture before reading the next (#11114) * refactor(cli): project compare-process-captures from its contract, checking each capture before reading the next The contract builder gains jsonInputChecks: each check runs on a decoded JSON input as soon as it is read, in argv order, so a refused input stops the command before the next is read; the handler receives what each check admitted. compare-process-captures authenticates the left capture before reading the right and the right before the trace specification, then compares the authenticated facts. It now also takes inline JSON, stdin and --max-capture-age-ms like MCP. Empty JSON input text is refused at argv. A JSON input whose final file close fails is reported as cleanup_incomplete naming the file instead of an unclassified failure. compareProcessEvidenceFiles and its trace-spec parser are removed. * fix(cli): retry a refused JSON input close and keep the read's refusal beside incomplete cleanup parseCliJsonInput gives the file's owner a resource scope, so a transient close refusal is retried before the command fails. A close that still fails reports cleanup_incomplete composed with the read's own refusal. Routed commands refuse routes that check a shared JSON input differently, since it is checked before the route is chosen. * refactor(cli): project inspect-web-network-capture from its contract with nested protobuf options The contract builder flattens a nested optional object member in turn (protobuf.schema), resolves a flattened caller-path member and reports it as spelled under its dotted path in callerInputs, keeps a flattened member's contract default out of argv so an omitted member stays omitted, and takes an array of numbers as repeated decimal tokens within its bounds. inspect-web-network-capture registers from its contract with the same option names; Evidence keeps the capture and descriptor paths as the caller spelled them. CLI input issues name the capturePath argument. * fix(cli): name a selector field by its own option in admission issues A selector parameter's positional may share another key (decompile's procedure positional is address), so mapping the field to its positional key renamed selection issues that already name the option, such as a missing or conflicting --procedure. Map a selector field to its option. * fix(cli): retain a JSON input file whose close fails and keep why its read stopped parseCliJsonInput dropped its per-read scope after the owner's close retry failed, so the handle lost its owner, and a read or cancellation failure recorded before the close was replaced by the cleanup failure. The read's scope now stays with the CLI process until final CLI cleanup retries it, and the recorded outcome is translated once into the primary failure with the cleanup attached. The module moves into src/cli so it can register with the CLI process owner without a layer cycle. * refactor(cli): project inspect-with-objdump and inspect-api-contract from their contracts (#11142) * refactor(cli): project inspect-with-objdump, list-objdump-architectures and inspect-api-contract from their contracts The contract builder selects input branches by a field that is a literal in one branch and an enum in another, takes the default of the one branch that admits omission, and lets a command take a subset of a union's branches by their discriminating values, fixing the field when one value is selected. * refactor(cli): project trace-web-source-location from its contract with flattened positional objects (#11167) * refactor(cli): project trace-web-source-location from its contract with flattened positional objects The contract builder flattens required objects as well as optional ones; a flattened field listed in positionals takes its members as positionals in member order. The hand-written source-map limit options and the separate CLI delivery schema are removed. * fix(cli): refuse to flatten a required object without a required member * fix(cli): refuse a malformed Evidence-input document before reading the selected bundle runEvidenceInputCommand admits the document with its transport frame before it reads --evidence-bundle, so every Evidence-input command refuses a malformed document first, as compare-static-and-observed-endpoints already did by hand. * test(cli): expect a selector field to be named by its option in input issues * fix(cli): report a refused view before the delivery rule it would trip Refusing delivery options before JSON inputs are read checked --evidence_output before the view's own schema, so a summary view naming an unknown field reported only the missing bundle. Admit the view with the contract's view field first, as full admission does. * refactor(cli): project inspect-android-jni-bindings from its contract with a grouped --query option (#11196) * refactor(cli): project inspect-android-jni-bindings from its contract with a grouped --query option A projection's fieldGroups take several optional top-level contract fields as the members of one JSON object option. The text is decoded when the command runs, refused with the group's message when it is not a JSON object, a member that is not one of the group's fields is refused by its path, and the contract admits each member as its field. inspect-android-jni-bindings keeps its --query selection through a group and now registers through the contract builder, so the hand-registered contract command list is empty; the superseded parseCliAnalysisEvidenceDelivery and androidJniDeliverySchema are removed. * fix(cli): refuse an object rule that names a grouped field A grouped field is a JSON member, not an option, so a contract rule such as dependentRequired naming it would be advertised over an option that does not exist. Registration now refuses that combination. * fix(cli): describe the --view and --maxCaptureAgeMs options of projected commands A projected view field kept no help because the contract's own description was skipped and none replaced it, and compare-process-captures exposed max_capture_age_ms without help. The canonical CLI catalog test refused both. The view option now takes the same help in both builders. * refactor(cli): derive the CLI command inventory from the contract registry (#11248) A contract now declares `cli: true` when the CLI exposes it as the command named by its kebab-case name. The primary CLI inventory (CLI_COMMAND_NAMES, now owned by catalogIdentity.ts) is derived from those declarations plus the commands no contract names, and a contract projection omits `command`: the builder names the command from the contract and refuses a contract that does not declare one. CLI_COMMANDS keeps only the 32 commands no contract names; the 164 contract-named entries and the copied MCP-only list in cliToolCoverage.test.ts are removed. * fix(managed): keep decoded members when only their loaded literals exceed capacity A capacity failure while decoding #US literals discarded the member facts already decoded, because the shared representation budget threw through the whole inspection. Literals carry their own coverage, so the inspection is retried without them and reports user_strings as partial with the capacity issue. compare-managed-members, which now runs full inspections, keeps comparing members it used to read with literals disabled. * test(cli): expect builder-admitted issues by CLI key and option help with its default Builder admission of compare-web-captures, compare-web-screenshots and analyze-web-bundle names input issues by the CLI key (beforeJson, afterJson, normalizationJson, endpoint), and --integrity-policy help states its default. Four test files still expected the contract field names and the old help, so they failed on the stack. * test(cli): read each refused browser input's CLI path directly now that every case names one Every invalid browser input now carries its CLI key, so the fallback branch narrowed to never and failed the TypeScript compiler's typecheck. * chore(verify): carry the moved cliJsonInput baseline entry into its per-guard file Rebased on main after #11316 split the guard baselines and #11181 threaded the launch environment into the web bundle command; the contract-built analyze-web-bundle command now passes that environment to the browser provider. * refactor(cli): hand whole-input contract handlers the admitted parse instead of parsing again (#11301) * refactor(cli): hand whole-input contract handlers the admitted parse instead of parsing again * refactor(cli): parse an argv whole input only when the handler reads it Admission parsed every argv whole-input command eagerly, so handlers that hand the raw input to a service (inspectWithService) parsed it twice. parseWholeInput now parses on the first admittedContractInput call and reuses the result; run-time JSON and view delivery still parse at admission. The test counts whole-schema evaluations. * refactor(cli): hand JSON-document handlers the admitted parse of their document (#11332) observe-native-calls, capture-electron-scenario and match-native-functions parsed their resolved document against the contract schema in the handler. registerContractDocumentCommand now gives each document handler parseWholeInput, a memoized parse of the resolved document as the whole contract input whose refusal names the caller's spelling, so admittedContractInput serves argv and document commands alike. A handler whose document is not the whole input never calls it, so it adds no parse. * fix(cli): admit checked JSON inputs through their checks only compare-process-captures walked and copied both capture records again in the whole-input parse after their checks had admitted them. Admission now parses the remaining fields with the contract and hands the handler the checked documents uncopied. The managed summary example names --evidence_output.
1199 lines
40 KiB
TypeScript
1199 lines
40 KiB
TypeScript
import { projectArtifactIntegrityDetails } from "./artifactIntegrity.js";
|
|
import {
|
|
cleanupRetryRecovery,
|
|
cleanupRetryRemediation,
|
|
type AnalysisErrorRecovery,
|
|
} from "./analysisErrorRecovery.js";
|
|
import { jsonValueSchema, type JsonValue } from "./jsonValue.js";
|
|
import { isImmutableJsonSnapshot } from "./immutableJson.js";
|
|
|
|
import {
|
|
analysisErrorCategory,
|
|
UNRETAINED_EVIDENCE_EXPORT_GUIDANCE,
|
|
analysisErrorRemediationAction,
|
|
analysisErrorUserMessage,
|
|
assertKnownAnalysisErrorTag,
|
|
hasAnalysisContinuingCallerGuidance,
|
|
} from "./analysisErrorPresentation.js";
|
|
import {
|
|
AnalysisAccessDeniedError,
|
|
AnalysisArtifactChangedError,
|
|
AnalysisCancelledError,
|
|
AnalysisCapabilityUnavailableError,
|
|
AnalysisUnsupportedTargetError,
|
|
AnalysisInputError,
|
|
AnalysisOutputError,
|
|
AnalysisTimeoutError,
|
|
AnalysisResourceConstraintError,
|
|
} from "./analysisErrorCore.js";
|
|
import { ArtifactOperationError } from "./artifactOperationError.js";
|
|
import {
|
|
BinaryTargetError,
|
|
ConfigurationError,
|
|
} from "./configurationErrors.js";
|
|
import { BrowserObservationError } from "./browserObservationError.js";
|
|
import {
|
|
AnalysisSnapshotMismatchError,
|
|
EvidenceFileError,
|
|
EvidenceIntegrityError,
|
|
EvidenceReferenceError,
|
|
} from "./evidenceErrors.js";
|
|
import {
|
|
HopperCancelledError,
|
|
HopperProcessError,
|
|
HopperRemoteError,
|
|
HopperStartError,
|
|
HopperTimeoutError,
|
|
hopperAppleEventsAuthorizationDenied,
|
|
} from "./hopperErrors.js";
|
|
import { ProviderAdapterError } from "./providerAdapterError.js";
|
|
import { ProviderSelectionError } from "./providerSelectionError.js";
|
|
import { UnknownRegistryError } from "./unknownRegistryError.js";
|
|
import { providerRetryAction } from "./providerOperationHealth.js";
|
|
import {
|
|
primaryAnalysisError,
|
|
resolvedAnalysisError,
|
|
sourcePublicationRecoveryOf,
|
|
type AnalysisCallerLifetime,
|
|
type AnalysisError,
|
|
type AnalysisErrorOptions,
|
|
type AnalysisErrorTag,
|
|
} from "./analysisErrorBase.js";
|
|
import { invocationLimit } from "./analysisSettingDefinitions.js";
|
|
import { analysisErrorRefusal } from "./analysisErrorRefusal.js";
|
|
import { analysisRefusalDetails } from "./analysisRefusal.js";
|
|
|
|
/**
|
|
* Project expected failures into exhaustive, secret-safe caller fields. The
|
|
* default describes a continuing caller, such as an MCP connection, and is
|
|
* also the adapter-independent form retained inside Evidence. An adapter that
|
|
* releases its provider session and runtime after this request, such as a
|
|
* one-shot CLI command, passes `"invocation"`.
|
|
*/
|
|
export const projectAnalysisError = (
|
|
error: AnalysisError,
|
|
callerLifetime: AnalysisCallerLifetime = "continuing",
|
|
): AnalysisErrorProjection =>
|
|
projectError(
|
|
error,
|
|
{
|
|
capturedOutput: true,
|
|
partialObservation: true,
|
|
secondary: true,
|
|
},
|
|
callerLifetime,
|
|
);
|
|
|
|
/** Cleanup history references output retained by its enclosing error owner. */
|
|
export const projectAnalysisErrorWithoutCapturedOutput = (
|
|
error: AnalysisError,
|
|
callerLifetime: AnalysisCallerLifetime = "continuing",
|
|
): AnalysisErrorProjection =>
|
|
projectError(
|
|
error,
|
|
{
|
|
capturedOutput: false,
|
|
partialObservation: true,
|
|
secondary: true,
|
|
},
|
|
callerLifetime,
|
|
);
|
|
|
|
/** Bounded fallback when the completed observation itself cannot be delivered. */
|
|
export const projectAnalysisErrorWithoutPartialObservation = (
|
|
error: AnalysisError,
|
|
callerLifetime: AnalysisCallerLifetime = "continuing",
|
|
): AnalysisErrorProjection =>
|
|
projectError(
|
|
error,
|
|
{
|
|
capturedOutput: true,
|
|
partialObservation: false,
|
|
secondary: true,
|
|
},
|
|
callerLifetime,
|
|
);
|
|
|
|
export interface UnretainedEvidenceCandidate {
|
|
readonly field: "partial_observation" | "completed_observation";
|
|
readonly secondaryPath: readonly number[];
|
|
readonly value: JsonValue;
|
|
}
|
|
|
|
/** Enumerate recoveries owned by this projection, including secondary failures. */
|
|
export function* unretainedEvidenceCandidates(
|
|
projected: AnalysisErrorProjection,
|
|
secondaryPath: readonly number[] = [],
|
|
): Generator<UnretainedEvidenceCandidate> {
|
|
for (const field of [
|
|
"partial_observation",
|
|
"completed_observation",
|
|
] as const) {
|
|
const value = projected.details?.[field];
|
|
if (
|
|
typeof value === "object" &&
|
|
value !== null &&
|
|
!Array.isArray(value) &&
|
|
(value.kind === "unretained-evidence" ||
|
|
value.kind === "unretained-observation" ||
|
|
value.kind === "inline-evidence")
|
|
)
|
|
yield { field, secondaryPath, value };
|
|
}
|
|
const secondary = projected.details?.secondary_failures;
|
|
if (!Array.isArray(secondary)) return;
|
|
for (const [index, failure] of secondary.entries()) {
|
|
if (
|
|
typeof failure !== "object" ||
|
|
failure === null ||
|
|
Array.isArray(failure)
|
|
)
|
|
continue;
|
|
const remediation = failure.remediation;
|
|
if (
|
|
typeof remediation !== "object" ||
|
|
remediation === null ||
|
|
Array.isArray(remediation) ||
|
|
typeof remediation.action !== "string"
|
|
)
|
|
continue;
|
|
yield* unretainedEvidenceCandidates(
|
|
failure as unknown as AnalysisErrorProjection,
|
|
[...secondaryPath, index],
|
|
);
|
|
}
|
|
}
|
|
|
|
/** Omit one explicitly unretained recovery when a complete reply cannot fit. */
|
|
export const omitUnretainedEvidenceFromError = (
|
|
projected: AnalysisErrorProjection,
|
|
limit: {
|
|
readonly constraint: "receive-buffer" | "string-length";
|
|
readonly bytesAtLeast: number;
|
|
},
|
|
candidate: UnretainedEvidenceCandidate,
|
|
): AnalysisErrorProjection | undefined => {
|
|
const { field, secondaryPath } = candidate;
|
|
if (secondaryPath.length > 0) {
|
|
const [index, ...rest] = secondaryPath;
|
|
const secondary = projected.details?.secondary_failures;
|
|
if (!Array.isArray(secondary) || index === undefined) return undefined;
|
|
const failure = secondary[index];
|
|
if (
|
|
typeof failure !== "object" ||
|
|
failure === null ||
|
|
Array.isArray(failure)
|
|
)
|
|
return undefined;
|
|
const omitted = omitUnretainedEvidenceFromError(
|
|
failure as unknown as AnalysisErrorProjection,
|
|
limit,
|
|
{ ...candidate, secondaryPath: rest },
|
|
);
|
|
if (omitted === undefined) return undefined;
|
|
return {
|
|
...projected,
|
|
details: {
|
|
...projected.details,
|
|
secondary_failures: secondary.map((item, i) =>
|
|
i === index ? omitted : item,
|
|
),
|
|
},
|
|
};
|
|
}
|
|
const partial = projected.details?.[field];
|
|
if (
|
|
typeof partial !== "object" ||
|
|
partial === null ||
|
|
Array.isArray(partial) ||
|
|
(partial.kind !== "unretained-evidence" &&
|
|
partial.kind !== "unretained-observation" &&
|
|
partial.kind !== "inline-evidence")
|
|
) {
|
|
return undefined;
|
|
}
|
|
const { [field]: _partial, ...details } = projected.details!;
|
|
const evidence = partial.evidence;
|
|
const evidenceId =
|
|
typeof evidence === "object" &&
|
|
evidence !== null &&
|
|
!Array.isArray(evidence)
|
|
? evidence.evidence_id
|
|
: undefined;
|
|
const retention =
|
|
partial.kind === "inline-evidence"
|
|
? typeof partial.retention === "string"
|
|
? partial.retention
|
|
: "unknown"
|
|
: "unretained";
|
|
return {
|
|
...projected,
|
|
remediation: {
|
|
action: `${projected.remediation.action} ${recoveryOmissionRemediation(retention)}`,
|
|
},
|
|
details: {
|
|
...details,
|
|
[`${field}_omitted`]: {
|
|
reason: "mcp-response-limit",
|
|
retention,
|
|
constraint: limit.constraint,
|
|
original_response_bytes_at_least: limit.bytesAtLeast,
|
|
...(typeof evidenceId === "string" ? { evidence_id: evidenceId } : {}),
|
|
...(field === "completed_observation"
|
|
? { source_closure: "not-established" }
|
|
: {}),
|
|
},
|
|
},
|
|
};
|
|
};
|
|
|
|
/** Explain the delivered omission without inferring ledger membership. */
|
|
export const recoveryOmissionRemediation = (retention: string): string =>
|
|
retention === "unretained"
|
|
? "The omitted observation was not retained and could not fit within MCP delivery limits."
|
|
: retention === "unknown"
|
|
? "The omitted observation's retention is unknown, and it could not fit within MCP delivery limits."
|
|
: "The observation could not fit within MCP delivery limits.";
|
|
|
|
/** A child failure embedded in a composed error's diagnostics. */
|
|
export interface AnalysisChildFailure {
|
|
readonly error: AnalysisError;
|
|
/** Omit output that the composing error already retains. */
|
|
readonly capturedOutput?: "omit";
|
|
/** Omit recovery facts retained by the composing error. */
|
|
readonly omitRecovery?: boolean;
|
|
}
|
|
|
|
/**
|
|
* Record child failures as composition-time snapshots, so cleanup history
|
|
* keeps the state it had. The invocation form is recorded only when a child's
|
|
* projection depends on the caller lifetime; the final projection selects it.
|
|
*/
|
|
export const childFailureDiagnostics = (
|
|
children: Readonly<Record<string, AnalysisChildFailure>>,
|
|
diagnostics: Readonly<Record<string, JsonValue>> = {},
|
|
): Pick<AnalysisErrorOptions, "diagnostics" | "invocationDiagnostics"> => {
|
|
const entries = Object.entries(children);
|
|
const project = (
|
|
{ error, capturedOutput, omitRecovery }: AnalysisChildFailure,
|
|
callerLifetime: AnalysisCallerLifetime,
|
|
) =>
|
|
projectError(
|
|
error,
|
|
{
|
|
capturedOutput: capturedOutput !== "omit",
|
|
partialObservation: omitRecovery !== true,
|
|
secondary: omitRecovery !== true,
|
|
},
|
|
callerLifetime,
|
|
);
|
|
const continuing = {
|
|
...diagnostics,
|
|
...Object.fromEntries(
|
|
entries.map(([key, child]) => [key, project(child, "continuing")]),
|
|
),
|
|
};
|
|
const varying = entries.filter(([, { error, omitRecovery }]) =>
|
|
projectionDependsOnCallerLifetime(error, omitRecovery !== true),
|
|
);
|
|
return varying.length === 0
|
|
? { diagnostics: continuing }
|
|
: {
|
|
diagnostics: continuing,
|
|
invocationDiagnostics: {
|
|
...continuing,
|
|
...Object.fromEntries(
|
|
varying.map(([key, child]) => [key, project(child, "invocation")]),
|
|
),
|
|
},
|
|
};
|
|
};
|
|
|
|
/** Check the primary chain and the secondary failures included in its projection. */
|
|
const projectionDependsOnCallerLifetime = (
|
|
error: AnalysisError,
|
|
includeSecondary: boolean,
|
|
): boolean => {
|
|
const chainDepends = (first: AnalysisError): boolean => {
|
|
for (
|
|
let node: AnalysisError | undefined = first;
|
|
node !== undefined;
|
|
node = node.cleanupPrimary
|
|
)
|
|
if (
|
|
node.limit !== undefined ||
|
|
hasAnalysisContinuingCallerGuidance(node) ||
|
|
node.invocationDiagnostics !== undefined ||
|
|
node.workflowUnknownPublication !== undefined
|
|
)
|
|
return true;
|
|
return false;
|
|
};
|
|
if (chainDepends(error)) return true;
|
|
if (!includeSecondary) return false;
|
|
for (
|
|
let node: AnalysisError | undefined = error;
|
|
node !== undefined;
|
|
node = node.cleanupPrimary
|
|
)
|
|
if (node.secondaryFailures.some(chainDepends)) return true;
|
|
return false;
|
|
};
|
|
|
|
const projectError = (
|
|
error: AnalysisError,
|
|
options: {
|
|
readonly capturedOutput: boolean;
|
|
readonly partialObservation: boolean;
|
|
readonly secondary: boolean;
|
|
},
|
|
callerLifetime: AnalysisCallerLifetime,
|
|
): AnalysisErrorProjection => {
|
|
const composed = error;
|
|
error = resolvedAnalysisError(error);
|
|
let diagnosticSource = error;
|
|
while (
|
|
diagnosticSource.diagnostics === undefined &&
|
|
diagnosticSource.cleanupPrimary !== undefined
|
|
)
|
|
diagnosticSource = diagnosticSource.cleanupPrimary;
|
|
const diagnostics = diagnosticSource.diagnosticsFor(callerLifetime);
|
|
const cleanupHistory =
|
|
composed === error ? undefined : composed.diagnosticsFor(callerLifetime);
|
|
const capturedOutput = composed.capturedOutput ?? error.capturedOutput;
|
|
const publication = sourcePublicationRecoveryOf(composed);
|
|
const secondary = new Set<AnalysisError>();
|
|
for (
|
|
let owner: AnalysisError | undefined = composed;
|
|
owner !== undefined;
|
|
owner = owner.cleanupPrimary
|
|
) {
|
|
for (const failure of owner.secondaryFailures) secondary.add(failure);
|
|
}
|
|
let partialObservation =
|
|
composed.partialObservation ??
|
|
error.partialObservation ??
|
|
publication?.source;
|
|
for (
|
|
let owner = composed.cleanupPrimary;
|
|
partialObservation === undefined && owner !== undefined;
|
|
owner = owner.cleanupPrimary
|
|
)
|
|
partialObservation = owner.partialObservation;
|
|
let argumentObservations =
|
|
composed.argumentObservations.length > 0
|
|
? composed.argumentObservations
|
|
: error.argumentObservations;
|
|
for (
|
|
let owner = composed.cleanupPrimary;
|
|
argumentObservations.length === 0 && owner !== undefined;
|
|
owner = owner.cleanupPrimary
|
|
)
|
|
argumentObservations = owner.argumentObservations;
|
|
const completedSourceObservation =
|
|
publication?.completed.kind === "omitted"
|
|
? undefined
|
|
: publication?.completed;
|
|
const completedSourceOmission =
|
|
publication?.completed.kind === "omitted"
|
|
? {
|
|
reason: publication.completed.reason,
|
|
source_closure: publication.completed.source_closure,
|
|
}
|
|
: undefined;
|
|
// A finalizer can add a report above the semantic primary, including while
|
|
// its cleanup is pending or beneath another cleanup composition.
|
|
let cleanupReport = composed.cleanupReport;
|
|
for (
|
|
let owner = composed.cleanupPrimary;
|
|
cleanupReport === undefined && owner !== undefined;
|
|
owner = owner.cleanupPrimary
|
|
)
|
|
cleanupReport = owner.cleanupReport;
|
|
assertKnownAnalysisErrorTag(error._tag);
|
|
const primary = primaryAnalysisError(error);
|
|
assertKnownAnalysisErrorTag(primary._tag);
|
|
const underlyingCode = underlyingErrorCode(primary);
|
|
const code = error.cleanupIncomplete ? "cleanup_incomplete" : underlyingCode;
|
|
const primaryDetails = errorDetails(primary);
|
|
const refusal = analysisErrorRefusal(primary);
|
|
const unknownPublication =
|
|
composed.workflowUnknownPublication ?? primary.workflowUnknownPublication;
|
|
const details = {
|
|
...primaryDetails,
|
|
...(unknownPublication === undefined
|
|
? {}
|
|
: {
|
|
workflow_unknown_publication: {
|
|
...unknownPublication,
|
|
evidence_retention:
|
|
callerLifetime === "invocation" &&
|
|
unknownPublication.evidence_retention === "retained"
|
|
? "invocation-only"
|
|
: unknownPublication.evidence_retention,
|
|
},
|
|
}),
|
|
...(primary.limit === undefined
|
|
? {}
|
|
: {
|
|
limit:
|
|
callerLifetime === "invocation"
|
|
? { ...invocationLimit(primary.limit) }
|
|
: { ...primary.limit },
|
|
}),
|
|
...(refusal === undefined
|
|
? {}
|
|
: { refusal: analysisRefusalDetails(refusal) }),
|
|
...(!options.secondary || secondary.size === 0
|
|
? {}
|
|
: {
|
|
secondary_failures: [...secondary].map((failure) =>
|
|
projectError(
|
|
failure,
|
|
{ ...options, secondary: false },
|
|
callerLifetime,
|
|
),
|
|
),
|
|
}),
|
|
...(cleanupReport === undefined
|
|
? {}
|
|
: { cleanup_report: jsonValueSchema.parse(cleanupReport) }),
|
|
...(diagnostics === undefined
|
|
? {}
|
|
: {
|
|
diagnostics,
|
|
...(primaryDetails?.diagnostics === undefined
|
|
? {}
|
|
: { provider_diagnostics: primaryDetails.diagnostics }),
|
|
}),
|
|
...(cleanupHistory === undefined
|
|
? {}
|
|
: { cleanup_history: cleanupHistory }),
|
|
...(error.cleanupIncomplete
|
|
? {
|
|
cleanup: "incomplete",
|
|
resources: [...error.cleanupResources],
|
|
...(error.cleanup === undefined
|
|
? {}
|
|
: { cleanup_reason: error.cleanup.reason }),
|
|
execution_failure:
|
|
primaryDetails?.execution_failure ?? underlyingCode,
|
|
}
|
|
: {}),
|
|
...(!options.capturedOutput || capturedOutput === undefined
|
|
? {}
|
|
: {
|
|
captured_output: {
|
|
...capturedOutput,
|
|
},
|
|
}),
|
|
...(!options.partialObservation || partialObservation === undefined
|
|
? {}
|
|
: {
|
|
partial_observation: isImmutableJsonSnapshot(partialObservation)
|
|
? partialObservation
|
|
: jsonValueSchema.parse(partialObservation),
|
|
}),
|
|
...(!options.partialObservation || argumentObservations.length === 0
|
|
? {}
|
|
: {
|
|
argument_observations: argumentObservations.map(
|
|
({ argument, observation }) => ({
|
|
argument,
|
|
observation: isImmutableJsonSnapshot(observation)
|
|
? observation
|
|
: jsonValueSchema.parse(observation),
|
|
}),
|
|
),
|
|
}),
|
|
...(!options.partialObservation || completedSourceObservation === undefined
|
|
? {}
|
|
: {
|
|
completed_observation: isImmutableJsonSnapshot(
|
|
completedSourceObservation,
|
|
)
|
|
? completedSourceObservation
|
|
: jsonValueSchema.parse(completedSourceObservation),
|
|
}),
|
|
...(!options.partialObservation || completedSourceOmission === undefined
|
|
? {}
|
|
: { completed_observation_omitted: completedSourceOmission }),
|
|
};
|
|
// The retained cleanup owner's retry precedes the failed operation's hint.
|
|
const cleanupRetry = error.cleanupRetry;
|
|
const recovery =
|
|
cleanupRetry === undefined
|
|
? errorRecovery(error)
|
|
: cleanupRetryRecovery(cleanupRetry);
|
|
const remediation = analysisErrorRemediationAction(error, callerLifetime);
|
|
const includesUnretainedEvidence =
|
|
options.partialObservation &&
|
|
[partialObservation, completedSourceObservation].some(
|
|
(observation) =>
|
|
typeof observation === "object" &&
|
|
observation !== null &&
|
|
"kind" in observation &&
|
|
observation.kind === "unretained-evidence",
|
|
);
|
|
const retentionGuidance =
|
|
error instanceof AnalysisResourceConstraintError &&
|
|
error.resource === "capacity" &&
|
|
includesUnretainedEvidence
|
|
? ` ${UNRETAINED_EVIDENCE_EXPORT_GUIDANCE}`
|
|
: "";
|
|
const publicationRemediation =
|
|
callerLifetime === "continuing" &&
|
|
unknownPublication?.evidence_retention === "retained"
|
|
? " Use get_evidence_bundle with the Evidence ID in details.workflow_unknown_publication to retrieve the completed result; use list_unknowns to inspect recorded questions. Publication stopped at the reported index; later questions were not checked in this attempt."
|
|
: "";
|
|
return {
|
|
code,
|
|
category: analysisErrorCategory(error),
|
|
message: analysisErrorUserMessage(error, callerLifetime),
|
|
retryable:
|
|
(RETRYABLE_CODES.has(code) &&
|
|
!(
|
|
error instanceof HopperStartError &&
|
|
hopperAppleEventsAuthorizationDenied(error.launchRejection)
|
|
)) ||
|
|
(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")),
|
|
remediation: {
|
|
action:
|
|
cleanupRetry === undefined
|
|
? `${remediation}${retentionGuidance}${publicationRemediation}`
|
|
: `${remediation}${retentionGuidance} ${cleanupRetryRemediation(cleanupRetry)}${publicationRemediation}`,
|
|
},
|
|
...(recovery === undefined ? {} : { recovery }),
|
|
...(Object.keys(details).length === 0 ? {} : { details }),
|
|
};
|
|
};
|
|
|
|
const errorRecovery = (
|
|
error: AnalysisError,
|
|
): AnalysisErrorRecovery | undefined => {
|
|
if (error instanceof AnalysisInputError)
|
|
return error.conformsToInputContract
|
|
? undefined
|
|
: { kind: "inspect_input_contract", operation: error.operation };
|
|
if (error instanceof AnalysisTimeoutError)
|
|
return {
|
|
kind: "inspect_timeout_state",
|
|
operation: error.operation,
|
|
timeout_ms: error.timeoutMs,
|
|
};
|
|
return undefined;
|
|
};
|
|
|
|
const underlyingErrorCode = (
|
|
error: AnalysisError,
|
|
): AnalysisErrorProjection["code"] => {
|
|
if (
|
|
error instanceof HopperRemoteError &&
|
|
error.diagnosticType === "invalid_request"
|
|
)
|
|
return "invalid_request";
|
|
if (error instanceof ProviderSelectionError)
|
|
return error.reason === "provider_unavailable"
|
|
? "provider_unavailable"
|
|
: "capability_unavailable";
|
|
if (error instanceof BrowserObservationError)
|
|
return error.userCategory === "cancelled"
|
|
? "cancelled"
|
|
: BROWSER_ERROR_CODES[error.reason];
|
|
if (error instanceof ArtifactOperationError)
|
|
return artifactOperationCode(error);
|
|
if (error instanceof BinaryTargetError)
|
|
return error.constraint === "load_selection_rejected"
|
|
? "invalid_request"
|
|
: error.systemCode === undefined
|
|
? "target_unavailable"
|
|
: "access_denied";
|
|
if (error instanceof EvidenceFileError) return evidenceFileCode(error.reason);
|
|
if (error instanceof UnknownRegistryError)
|
|
return unknownRegistryCode(error.reason);
|
|
if (error._tag === "ProcessCaptureError") return processCaptureCode(error);
|
|
return staticErrorCode(error._tag);
|
|
};
|
|
|
|
const BROWSER_ERROR_CODES: Readonly<
|
|
Record<BrowserObservationError["reason"], AnalysisErrorProjection["code"]>
|
|
> = {
|
|
endpoint_unreachable: "provider_unavailable",
|
|
invalid_endpoint_response: "unreadable_output",
|
|
target_not_found: "target_unavailable",
|
|
target_not_allowed: "target_unavailable",
|
|
service_worker_blocked: "target_unavailable",
|
|
target_changed: "target_unavailable",
|
|
target_session_detached: "target_unavailable",
|
|
protocol_error: "unreadable_output",
|
|
disconnected: "provider_unavailable",
|
|
payload_limit: "truncated",
|
|
window_not_found: "unreadable_output",
|
|
window_metadata_missing: "unreadable_output",
|
|
process_ownership_unavailable: "unreadable_output",
|
|
application_already_running: "target_unavailable",
|
|
cleanup_failed: "execution_failure",
|
|
cancelled: "cancelled",
|
|
timeout: "provider_timeout",
|
|
};
|
|
|
|
const artifactOperationCode = (
|
|
error: ArtifactOperationError,
|
|
): AnalysisErrorProjection["code"] => {
|
|
if (error.reason === "integrity" && error.artifactDetails !== undefined)
|
|
return "artifact_integrity_mismatch";
|
|
if (error.reason === "limit") return "truncated";
|
|
if (error.reason === "cancelled") return "cancelled";
|
|
return "artifact_operation_failed";
|
|
};
|
|
|
|
const evidenceFileCode = (
|
|
reason: EvidenceFileError["reason"],
|
|
): AnalysisErrorProjection["code"] => {
|
|
if (reason === "invalid-json") return "evidence_integrity_mismatch";
|
|
if (reason === "path-limit" || reason === "storage-limit")
|
|
return "resource_constraint";
|
|
// A missing, non-file or already-existing path is the caller's selection.
|
|
if (reason === "io") return "execution_failure";
|
|
return "invalid_request";
|
|
};
|
|
|
|
const unknownRegistryCode = (
|
|
reason: UnknownRegistryError["reason"],
|
|
): AnalysisErrorProjection["code"] => {
|
|
if (reason === "revision-conflict") return "revision_conflict";
|
|
if (reason === "already-exists" || reason === "constraint")
|
|
return "invalid_request";
|
|
if (reason === "limit") return "truncated";
|
|
if (reason === "integrity") return "evidence_integrity_mismatch";
|
|
return "execution_failure";
|
|
};
|
|
|
|
const processCaptureCode = (
|
|
error: AnalysisError,
|
|
): AnalysisErrorProjection["code"] => {
|
|
if (error.cleanupIncomplete) return "cleanup_incomplete";
|
|
if (error.userCategory === "cancelled") return "cancelled";
|
|
return "process_capture_failed";
|
|
};
|
|
|
|
type SpecializedErrorTag =
|
|
| "ArtifactOperationError"
|
|
| "BinaryTargetError"
|
|
| "BrowserObservationError"
|
|
| "EvidenceFileError"
|
|
| "ProcessCaptureError"
|
|
| "ProviderSelectionError"
|
|
| "UnknownRegistryError";
|
|
|
|
const STATIC_ERROR_CODES = {
|
|
AnalysisProtocolError: "unreadable_output",
|
|
AnalysisOutputError: "unreadable_output",
|
|
HopperProtocolError: "unreadable_output",
|
|
AnalysisInputError: "invalid_request",
|
|
AnalysisAccessDeniedError: "access_denied",
|
|
AnalysisArtifactChangedError: "artifact_changed",
|
|
AnalysisCapabilityUnavailableError: "capability_unavailable",
|
|
AnalysisUnsupportedTargetError: "unsupported_target",
|
|
AnalysisCancelledError: "cancelled",
|
|
HopperCancelledError: "cancelled",
|
|
AnalysisTimeoutError: "provider_timeout",
|
|
AnalysisResourceConstraintError: "resource_constraint",
|
|
HopperTimeoutError: "provider_timeout",
|
|
HopperProcessError: "provider_unavailable",
|
|
HopperStartError: "provider_unavailable",
|
|
ConfigurationError: "configuration_invalid",
|
|
NoBinaryOpenError: "target_unavailable",
|
|
EvidenceIntegrityError: "evidence_integrity_mismatch",
|
|
ProviderAdapterError: "execution_failure",
|
|
HopperRemoteError: "execution_failure",
|
|
} as const satisfies Readonly<
|
|
Record<
|
|
Exclude<AnalysisErrorTag, SpecializedErrorTag>,
|
|
AnalysisErrorProjection["code"]
|
|
>
|
|
>;
|
|
|
|
const staticErrorCode = (
|
|
tag: AnalysisErrorTag,
|
|
): AnalysisErrorProjection["code"] => {
|
|
switch (tag) {
|
|
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_CODES[tag];
|
|
}
|
|
};
|
|
|
|
const errorDetails = (
|
|
error: AnalysisError,
|
|
): Readonly<Record<string, JsonValue>> | undefined =>
|
|
requestErrorDetails(error) ??
|
|
artifactStateErrorDetails(error) ??
|
|
providerErrorDetails(error) ??
|
|
lifecycleErrorDetails(error);
|
|
|
|
const requestErrorDetails = (
|
|
error: AnalysisError,
|
|
): Readonly<Record<string, JsonValue>> | undefined => {
|
|
if (error instanceof AnalysisUnsupportedTargetError)
|
|
return {
|
|
operation: error.operation,
|
|
path: error.path,
|
|
reason: error.reason,
|
|
};
|
|
if (error instanceof AnalysisResourceConstraintError)
|
|
return {
|
|
operation: error.operation,
|
|
resource: error.resource,
|
|
reason: error.reason,
|
|
reported_limits: error.reportedLimits,
|
|
...(error.requestSent === undefined
|
|
? {}
|
|
: { request_sent: error.requestSent }),
|
|
};
|
|
if (error instanceof AnalysisArtifactChangedError)
|
|
return {
|
|
operation: error.operation,
|
|
path: error.path,
|
|
reason: error.reason,
|
|
boundary: "stable-artifact-read",
|
|
...(error.integrityCheck === undefined
|
|
? {}
|
|
: { integrity_check: error.integrityCheck }),
|
|
};
|
|
if (error instanceof AnalysisAccessDeniedError)
|
|
return {
|
|
operation: error.operation,
|
|
path: error.path,
|
|
system_code: error.systemCode,
|
|
boundary: "filesystem-read",
|
|
};
|
|
if (error instanceof AnalysisOutputError)
|
|
return {
|
|
operation: error.operation,
|
|
reason: error.reason,
|
|
...(error.diagnostics === undefined
|
|
? {}
|
|
: { diagnostics: error.diagnostics }),
|
|
};
|
|
if (error instanceof AnalysisInputError && error.issues.length > 0)
|
|
return {
|
|
operation: error.operation,
|
|
issues: error.issues.map((issue) => ({
|
|
path: [...issue.path],
|
|
reason: issue.reason,
|
|
...(issue.message === undefined ? {} : { message: issue.message }),
|
|
...(issue.expected === undefined ? {} : { expected: issue.expected }),
|
|
...(issue.observed === undefined ? {} : { observed: issue.observed }),
|
|
...(issue.minimum === undefined ? {} : { minimum: issue.minimum }),
|
|
...(issue.maximum === undefined ? {} : { maximum: issue.maximum }),
|
|
})),
|
|
};
|
|
if (error instanceof EvidenceReferenceError)
|
|
return {
|
|
evidence_id: error.evidenceId,
|
|
reason: error.reason,
|
|
...(typeof error.diagnostics?.operation === "string"
|
|
? { operation: error.diagnostics.operation }
|
|
: {}),
|
|
...(error.referenceScope === undefined
|
|
? {}
|
|
: { reference_scope: error.referenceScope }),
|
|
expected: error.expected,
|
|
actual: error.actual,
|
|
};
|
|
if (error instanceof AnalysisSnapshotMismatchError)
|
|
return {
|
|
reason: error.message,
|
|
...(error.bindingMismatch === undefined
|
|
? {}
|
|
: { binding_mismatch: jsonValueSchema.parse(error.bindingMismatch) }),
|
|
};
|
|
if (error instanceof EvidenceIntegrityError)
|
|
return {
|
|
reason: error.message,
|
|
...(error.side === undefined ? {} : { side: error.side }),
|
|
...(error.issuePath === undefined
|
|
? {}
|
|
: { issue_path: [...error.issuePath] }),
|
|
...(error.constraint === undefined
|
|
? {}
|
|
: { constraint: error.constraint }),
|
|
...(error.remainingIssueCount === undefined
|
|
? {}
|
|
: { remaining_issue_count: error.remainingIssueCount }),
|
|
};
|
|
return undefined;
|
|
};
|
|
|
|
const artifactStateErrorDetails = (
|
|
error: AnalysisError,
|
|
): Readonly<Record<string, JsonValue>> | undefined => {
|
|
if (error instanceof ArtifactOperationError && error.artifactDetails)
|
|
return {
|
|
...projectArtifactIntegrityDetails(error.artifactDetails),
|
|
...(error.integrityCheck === undefined
|
|
? {}
|
|
: { integrity_check: error.integrityCheck }),
|
|
};
|
|
if (error instanceof ArtifactOperationError)
|
|
return {
|
|
operation: error.operation,
|
|
reason: error.reason,
|
|
...(error.reason === "limit" ? { truncated: true } : {}),
|
|
...(error.detail === undefined ? {} : { detail: error.detail }),
|
|
...(error.boundary === undefined ? {} : { boundary: error.boundary }),
|
|
...(error.integrityCheck === undefined
|
|
? {}
|
|
: { integrity_check: error.integrityCheck }),
|
|
...(error.readerLimit === undefined
|
|
? {}
|
|
: { reader_limit: { ...error.readerLimit } }),
|
|
...(error.admission === undefined
|
|
? {}
|
|
: {
|
|
admission: error.admission.kind,
|
|
...(error.admission.kind === "asar-header"
|
|
? {
|
|
maximum_header_bytes: error.admission.maximumBytes,
|
|
maximum_header_bytes_source: error.admission.source,
|
|
setting: "REA_ASAR_MAX_HEADER_BYTES",
|
|
}
|
|
: {
|
|
maximum_listing_bytes: error.admission.maximumBytes,
|
|
maximum_listing_bytes_source: error.admission.source,
|
|
setting: "REA_ASAR_MAX_LISTING_BYTES",
|
|
}),
|
|
}),
|
|
};
|
|
if (error instanceof UnknownRegistryError)
|
|
return {
|
|
reason: error.reason,
|
|
...(error.constraint === undefined
|
|
? {}
|
|
: { constraint: error.constraint }),
|
|
};
|
|
if (error instanceof EvidenceFileError)
|
|
return {
|
|
operation: error.operation,
|
|
reason: error.reason,
|
|
...(error.reason === "path-limit" ? { boundary: "filesystem-path" } : {}),
|
|
...(error.detectedKind === undefined
|
|
? {}
|
|
: { detected_kind: error.detectedKind }),
|
|
...(error.systemCode === undefined
|
|
? {}
|
|
: { system_code: error.systemCode }),
|
|
...(error.path === undefined ? {} : { path: error.path }),
|
|
...(error.contentIssues === undefined
|
|
? {}
|
|
: {
|
|
content_issues: error.contentIssues.map((issue) => ({
|
|
...issue,
|
|
path: [...issue.path],
|
|
})),
|
|
}),
|
|
...(error.published === undefined
|
|
? {}
|
|
: {
|
|
published: true,
|
|
bytes: error.published.bytes,
|
|
...(error.published.path === undefined
|
|
? {}
|
|
: { published_path: error.published.path }),
|
|
}),
|
|
};
|
|
return undefined;
|
|
};
|
|
|
|
const providerErrorDetails = (
|
|
error: AnalysisError,
|
|
): Readonly<Record<string, JsonValue>> | undefined => {
|
|
if (error instanceof AnalysisCapabilityUnavailableError)
|
|
return {
|
|
provider_id: error.providerId,
|
|
operation: error.operation,
|
|
reason: error.reason,
|
|
...(error.alternatives.length === 0
|
|
? {}
|
|
: { alternatives: [...error.alternatives] }),
|
|
};
|
|
if (error instanceof ProviderSelectionError)
|
|
return {
|
|
operation: error.operation,
|
|
selection_reason: error.reason,
|
|
requested_provider_id: error.requestedProviderId,
|
|
candidate_ids: [...error.candidateIds],
|
|
rejections: error.rejections.map((rejection) => ({
|
|
provider_id: rejection.providerId,
|
|
origin: rejection.origin,
|
|
code: rejection.code,
|
|
reason: rejection.reason,
|
|
...(rejection.remediation === undefined
|
|
? {}
|
|
: { remediation: rejection.remediation }),
|
|
diagnostics: rejection.diagnostics,
|
|
})),
|
|
};
|
|
if (error instanceof ProviderAdapterError)
|
|
return {
|
|
provider_id: error.providerId,
|
|
operation: error.operation,
|
|
...(error.cleanupIncomplete
|
|
? {
|
|
cleanup: "incomplete",
|
|
resources: [...error.cleanupResources],
|
|
}
|
|
: {}),
|
|
};
|
|
if (error instanceof BrowserObservationError) {
|
|
const primaryReason = primaryBrowserFailureReason(error);
|
|
return {
|
|
operation: error.operation,
|
|
reason: error.reason,
|
|
...(error.cleanupIncomplete
|
|
? {
|
|
cleanup: "incomplete",
|
|
resources: [...error.cleanupResources],
|
|
...(primaryReason === undefined
|
|
? {}
|
|
: { primary_reason: primaryReason }),
|
|
}
|
|
: {}),
|
|
};
|
|
}
|
|
if (error instanceof HopperRemoteError)
|
|
return {
|
|
stage: "analysis",
|
|
provider_code: error.code,
|
|
diagnostic_type: error.diagnosticType,
|
|
...(error.operation === undefined ? {} : { operation: error.operation }),
|
|
...(error.requestId === undefined ? {} : { request_id: error.requestId }),
|
|
};
|
|
if (error instanceof HopperProcessError) {
|
|
const stage = error.stage;
|
|
return {
|
|
exit_code: error.exitCode,
|
|
stage,
|
|
provider_state: error.providerState,
|
|
retry_action: providerRetryAction(
|
|
error.providerState,
|
|
error.failureCode !== undefined || error.stage === "launch",
|
|
),
|
|
...(error.failureCode === undefined
|
|
? {}
|
|
: { failure_code: error.failureCode }),
|
|
...(error.operation === undefined ? {} : { operation: error.operation }),
|
|
...(error.requestId === undefined ? {} : { request_id: error.requestId }),
|
|
...(error.diagnostic === undefined
|
|
? {}
|
|
: { diagnostics: { ...error.diagnostic } }),
|
|
...(error.launcherFailure === undefined
|
|
? {}
|
|
: { launcher: error.launcherFailure }),
|
|
};
|
|
}
|
|
if (error instanceof HopperStartError)
|
|
return {
|
|
stage: "launch",
|
|
provider_state: "unknown",
|
|
...(error.launchRejection === undefined
|
|
? {}
|
|
: { launch_rejection: { ...error.launchRejection } }),
|
|
retry_action:
|
|
error.ownerRunId === undefined &&
|
|
!hopperAppleEventsAuthorizationDenied(error.launchRejection)
|
|
? "retry"
|
|
: "unknown",
|
|
...(error.ownerRunId === undefined
|
|
? {}
|
|
: { owner_run_id: error.ownerRunId }),
|
|
...(error.launcherFailure === undefined
|
|
? {}
|
|
: { launcher: error.launcherFailure }),
|
|
};
|
|
return undefined;
|
|
};
|
|
|
|
const primaryBrowserFailureReason = (
|
|
error: BrowserObservationError,
|
|
): string | undefined => {
|
|
const aggregate = error.cause instanceof AggregateError;
|
|
const primary =
|
|
error.cause instanceof AggregateError ? error.cause.errors[0] : error.cause;
|
|
if (primary instanceof BrowserObservationError) return primary.reason;
|
|
if (primary instanceof AnalysisCancelledError) return "cancelled";
|
|
if (primary instanceof AnalysisTimeoutError) return "timeout";
|
|
if (typeof primary === "object" && primary !== null && "_tag" in primary)
|
|
return typeof primary._tag === "string"
|
|
? primary._tag
|
|
: "execution_failure";
|
|
return aggregate ? "execution_failure" : undefined;
|
|
};
|
|
|
|
const lifecycleErrorDetails = (
|
|
error: AnalysisError,
|
|
): Readonly<Record<string, JsonValue>> | undefined => {
|
|
if (error instanceof AnalysisCancelledError)
|
|
return {
|
|
operation: error.operation,
|
|
cleanup: error.cleanupIncomplete ? "incomplete" : "complete",
|
|
...(error.cleanup === undefined || !error.cleanupIncomplete
|
|
? {}
|
|
: {
|
|
cleanup_reason: error.cleanup.reason,
|
|
resources: [...error.cleanup.resources],
|
|
execution_failure: "cancelled",
|
|
}),
|
|
};
|
|
if (error instanceof HopperCancelledError)
|
|
return { operation: "hopper", cleanup: "complete" };
|
|
if (error instanceof AnalysisTimeoutError)
|
|
return {
|
|
operation: error.operation,
|
|
timeout_ms: error.timeoutMs,
|
|
...(error.cleanup === undefined || !error.cleanupIncomplete
|
|
? {}
|
|
: {
|
|
cleanup: "incomplete",
|
|
cleanup_reason: error.cleanup.reason,
|
|
resources: [...error.cleanup.resources],
|
|
}),
|
|
};
|
|
if (error instanceof HopperTimeoutError)
|
|
return {
|
|
stage: error.operation === undefined ? "startup" : error.stage,
|
|
timeout_ms: error.timeoutMs,
|
|
...(error.launcherOutcome === undefined
|
|
? {}
|
|
: { launcher: error.launcherOutcome }),
|
|
provider_state: error.providerState,
|
|
retry_action: error.providerState === "busy" ? "wait" : "retry",
|
|
...(error.operation === undefined ? {} : { operation: error.operation }),
|
|
...(error.requestId === undefined ? {} : { request_id: error.requestId }),
|
|
};
|
|
if (error._tag === "ProcessCaptureError" && error.cleanupIncomplete)
|
|
return {
|
|
cleanup: "incomplete",
|
|
resources: [...error.cleanupResources],
|
|
...(error.cleanupReport === undefined
|
|
? {}
|
|
: { cleanup_report: jsonValueSchema.parse(error.cleanupReport) }),
|
|
...(error.executionFailure === undefined
|
|
? {}
|
|
: { execution_failure: error.executionFailure }),
|
|
};
|
|
if (error._tag === "ProcessCaptureError") {
|
|
const details = {
|
|
...(error.userCategory === "cancelled"
|
|
? { operation: "process_capture", cleanup: "complete" }
|
|
: {}),
|
|
...(error.cleanupReport === undefined
|
|
? {}
|
|
: { cleanup_report: jsonValueSchema.parse(error.cleanupReport) }),
|
|
...(error.executionFailure === undefined
|
|
? {}
|
|
: { execution_failure: error.executionFailure }),
|
|
};
|
|
return Object.keys(details).length === 0 ? undefined : details;
|
|
}
|
|
if (error instanceof ConfigurationError && error.settings.length > 0)
|
|
return {
|
|
settings: error.settings.map((issue) => ({
|
|
setting: issue.setting,
|
|
constraint: issue.constraint,
|
|
...(issue.update_mode === undefined
|
|
? {}
|
|
: { update_mode: issue.update_mode }),
|
|
...(issue.pending_restart === undefined
|
|
? {}
|
|
: { pending_restart: issue.pending_restart }),
|
|
})),
|
|
};
|
|
if (error instanceof BinaryTargetError)
|
|
return {
|
|
path: error.path,
|
|
reason: error.reason,
|
|
...(error.constraint === undefined
|
|
? {}
|
|
: { constraint: error.constraint }),
|
|
...(error.infoPlist === undefined ? {} : { info_plist: error.infoPlist }),
|
|
...(error.probedPaths === undefined
|
|
? {}
|
|
: { probed_paths: [...error.probedPaths] }),
|
|
...(error.systemCode === undefined
|
|
? {}
|
|
: { system_code: error.systemCode, boundary: "filesystem-read" }),
|
|
};
|
|
return undefined;
|
|
};
|
|
|
|
const RETRYABLE_CODES: ReadonlySet<AnalysisErrorProjection["code"]> = new Set([
|
|
"artifact_changed",
|
|
"provider_timeout",
|
|
"cancelled",
|
|
"revision_conflict",
|
|
"provider_unavailable",
|
|
]);
|
|
|
|
export interface AnalysisErrorProjection extends Readonly<
|
|
Record<string, JsonValue>
|
|
> {
|
|
readonly code:
|
|
| "invalid_request"
|
|
| "access_denied"
|
|
| "artifact_changed"
|
|
| "unreadable_output"
|
|
| "capability_unavailable"
|
|
| "unsupported_target"
|
|
| "provider_unavailable"
|
|
| "provider_timeout"
|
|
| "resource_constraint"
|
|
| "cancelled"
|
|
| "artifact_integrity_mismatch"
|
|
| "artifact_operation_failed"
|
|
| "evidence_integrity_mismatch"
|
|
| "truncated"
|
|
| "process_capture_failed"
|
|
| "cleanup_incomplete"
|
|
| "revision_conflict"
|
|
| "configuration_invalid"
|
|
| "target_unavailable"
|
|
| "execution_failure";
|
|
readonly category:
|
|
| "invalid_input"
|
|
| "unsupported_provider"
|
|
| "unsupported_target"
|
|
| "integrity_mismatch"
|
|
| "truncated"
|
|
| "cancelled"
|
|
| "timeout"
|
|
| "resource_constraint"
|
|
| "unavailable"
|
|
| "execution_failure";
|
|
readonly message: string;
|
|
readonly retryable: boolean;
|
|
readonly remediation: Readonly<{
|
|
action: string;
|
|
}>;
|
|
readonly recovery?: AnalysisErrorRecovery;
|
|
readonly details?: Readonly<Record<string, JsonValue>>;
|
|
}
|