diff --git a/docs/development/tool-design.md b/docs/development/tool-design.md index 24844c40e89..88c75154d52 100644 --- a/docs/development/tool-design.md +++ b/docs/development/tool-design.md @@ -351,7 +351,9 @@ incompatible workflow roles are explicit failures; do not infer a substitute from ledger order, display names or the active target. A summary or inspection page has its own identity: consumers needing complete source facts use its `normalized_result.parent_evidence_id`, unless their contract explicitly accepts -that view. +that view. Name those producers in `resolveEvidenceRequest`'s +`completeProducers`; the shared resolver then replaces a selected summary with +its retained parent before format admission. New provider-owned source observations require a retention owner. Existing caller-owned inputs can also compose on a fixed port without a recorder; diff --git a/docs/guides/web/website-script-export.md b/docs/guides/web/website-script-export.md index c12cae17bcc..98b576a9869 100644 --- a/docs/guides/web/website-script-export.md +++ b/docs/guides/web/website-script-export.md @@ -9,8 +9,14 @@ verified manifest into one caller-selected, absent directory. For passive inspection, select `include_script_sources: true` (CLI: `--include-script-sources`). For scenarios, select -`capture.network.response_body: true`. Save either the complete Evidence record -or its normalized result as UTF-8 JSON. MCP `structuredContent` contains the complete Evidence record. +`capture.network.response_body: true`. + +In MCP, pass the capture as `capture`: the complete Evidence record, or a +`{"kind": "retained-evidence", "evidence_id": ...}` reference. A reference to +the capture's `inspect_analysis_view` summary reads the retained complete +capture it names, so a large capture returned as a summary needs no second +request. The CLI reads `capture_path`, a saved complete Evidence record or +normalized result as UTF-8 JSON. The capture must be a regular file. A symlink to a regular file is accepted; directories, named pipes and device files are rejected before reading capture @@ -21,8 +27,8 @@ rea export-web-scripts /analysis/capture.json /analysis/exported-scripts --json rea analyze-javascript-application /analysis/exported-scripts/files --json ``` -MCP uses `export_web_scripts` with `capture_path` and `output_directory` absolute -filesystem paths. Its inline result includes `analysis_input`, which can be +MCP uses `export_web_scripts` with `capture` or an absolute `capture_path`, and +an absolute `output_directory`; supply exactly one capture selector. Its inline result includes `analysis_input`, which can be passed directly to `analyze_javascript_application`. When no script bytes are exportable, `analysis_input` is null and the manifest retains the unavailable sources and their reasons. Capture again with the corresponding content option. @@ -37,8 +43,10 @@ A failed rollback reports residual paths. Every source is returned inline with its URL and its script/frame identity or request transaction and event sequence references. The result also contains -the input capture's byte digest, original coverage, source Evidence link when -provided, and the persisted manifest's digest and byte count. A saved Evidence +the input capture file's byte digest, original coverage, source Evidence link when +provided, and the persisted manifest's digest and byte count. A capture supplied +as Evidence has a null `capture_path` and `capture_sha256`; `source_evidence_id` +names the complete record that was read. A saved Evidence envelope must have a valid semantic identifier and matching operation. Exported `relative_path` values are relative to `analysis_input.input_path`. diff --git a/scripts/verify/advertised-schemas/tools/export_web_scripts.json b/scripts/verify/advertised-schemas/tools/export_web_scripts.json index 215a598d2ec..5d6f2496829 100644 --- a/scripts/verify/advertised-schemas/tools/export_web_scripts.json +++ b/scripts/verify/advertised-schemas/tools/export_web_scripts.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "b18c35aaccafe15a", + "input compact": "8ca0e91e236b0d2d", "output compact": "fc6c5d5a78a47254" }, "patterns": { diff --git a/src/application/EvidenceInputResolver.ts b/src/application/EvidenceInputResolver.ts index 9443fba1ba3..d3322851222 100644 --- a/src/application/EvidenceInputResolver.ts +++ b/src/application/EvidenceInputResolver.ts @@ -15,6 +15,7 @@ import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { cancelledBy } from "../domain/analysisErrorCore.js"; import { EvidenceReferenceError } from "../domain/evidenceErrors.js"; import { err, ok, type Result } from "../domain/result.js"; +import { isRecord } from "../kernel/isRecord.js"; import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; import { parseAnalysisInput } from "./AnalysisInput.js"; import { @@ -28,6 +29,12 @@ export type EvidenceLookup = (evidenceId: string) => Evidence | undefined; export interface EvidenceRequestResolutionOptions { readonly signal?: AbortSignal; readonly referenceScope?: "retained-closure"; + /** + * Producers whose complete records this consumer reads. A selected + * inspect_analysis_view summary of one of them stands for its retained + * parent, which replaces it before admission. + */ + readonly completeProducers?: readonly string[]; /** Optional format-owner admission, after lookup and before source use. */ readonly readEvidence?: ( input: unknown, @@ -129,6 +136,19 @@ export function resolveEvidenceRequest( ); selected = found.value; } + if (options.completeProducers !== undefined) { + const parent = summaryParent( + selected, + options.completeProducers, + read, + options.referenceScope, + ); + if (!parent.ok) { + parent.error.retainDiagnostics({ input_path: [...path] }); + return parent; + } + selected = parent.value; + } if (options.readEvidence !== undefined) { const admitted = options.readEvidence(selected, path); if (!admitted.ok) { @@ -153,6 +173,48 @@ export function resolveEvidenceRequest( : result; } +/** + * The retained parent a summary of one of `producers` names, or `selected` + * itself. Only the parent's identity is read from the summary; the parent + * comes from the ledger and is admitted by its format owner like any record. + */ +const summaryParent = ( + selected: unknown, + producers: readonly string[], + lookup: EvidenceLookup, + referenceScope: EvidenceReferenceError["referenceScope"], +): Result => { + if (!isRecord(selected) || selected.operation !== "inspect_analysis_view") + return ok(selected); + const summary = selected.normalized_result; + if ( + !isRecord(summary) || + summary.kind !== "summary" || + typeof summary.parent_operation !== "string" || + !producers.includes(summary.parent_operation) || + typeof summary.parent_evidence_id !== "string" + ) + return ok(selected); + const parent = resolveEvidenceInput( + { kind: "retained-evidence", evidence_id: summary.parent_evidence_id }, + lookup, + referenceScope, + ); + if (!parent.ok) return parent; + return parent.value.operation === summary.parent_operation + ? parent + : err( + new EvidenceReferenceError( + summary.parent_evidence_id, + "wrong_operation", + { + expected: summary.parent_operation, + actual: parent.value.operation, + }, + ), + ); +}; + /** Normalize each selected record using its file context and the current ledger. */ export interface EvidenceSourceResolutionOptions extends EvidenceFileReadOptions { readonly operation: string; diff --git a/src/application/PublishWebScripts.ts b/src/application/PublishWebScripts.ts index b170e55d86f..ce0bda1bbbb 100644 --- a/src/application/PublishWebScripts.ts +++ b/src/application/PublishWebScripts.ts @@ -52,7 +52,7 @@ interface PublishWebScriptsOptions { export const publishWebScripts = async ( input: ExportWebScriptsInput, capture: SelectedScriptCapture & { readonly sourceEvidenceId: string | null }, - captureSha256: string, + captureSha256: string | null, options: PublishWebScriptsOptions, ): Promise => options.resources.run(async () => { @@ -89,7 +89,7 @@ export const publishWebScripts = async ( ); } const manifest = webScriptExportManifestSchema.parse({ - capture_path: input.capture_path, + capture_path: input.capture_path ?? null, capture_sha256: captureSha256, capture_kind: capture.kind, source_evidence_id: capture.sourceEvidenceId, diff --git a/src/application/WebScriptExportService.ts b/src/application/WebScriptExportService.ts index a6713f021a8..3ec85aec75f 100644 --- a/src/application/WebScriptExportService.ts +++ b/src/application/WebScriptExportService.ts @@ -12,7 +12,21 @@ import { artifactReaderTargetFailure, } from "../resources/index.js"; import { publishWebScripts } from "./PublishWebScripts.js"; -import { selectScriptCapture } from "../domain/webScriptCaptureAdapters.js"; +import { + selectEvidenceScriptCapture, + selectScriptCapture, + UNSUPPORTED_SCRIPT_CAPTURE_MESSAGE, +} from "../domain/webScriptCaptureAdapters.js"; +import { readEvidence } from "../domain/evidenceValidation.js"; +import { invariantViolation } from "../domain/internalInvariant.js"; +import { unknownTarget } from "../domain/targetIdentity.js"; +import type { EvidenceInputPath } from "../domain/evidenceInputContract.js"; +import { + resolveEvidenceRequest, + type EvidenceLookup, +} from "./EvidenceInputResolver.js"; +import { recordEvidenceSources } from "./investigation/recordEvidenceSources.js"; +import type { EvidenceWriter } from "./investigation/InvestigationRecordPort.js"; import { AnalysisAccessDeniedError, AnalysisInputError, @@ -26,13 +40,13 @@ import { WindowsChangeTimeConfigurationError } from "../config/windowsChangeTime import { ConfigurationError } from "../domain/configurationErrors.js"; import { createEvidence, type Evidence } from "../domain/evidence.js"; import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; -import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { err, ok, type Result } from "../domain/result.js"; import { safeParseJson } from "../domain/safeJson.js"; import { exportWebScriptsInputSchema, + WEB_SCRIPT_CAPTURE_PRODUCERS, type ExportWebScriptsInput, } from "../domain/webScriptExport.js"; import { WebScriptExportError } from "../domain/webScriptExportError.js"; @@ -68,43 +82,67 @@ interface CaptureRead { } interface PreparedCapture { - readonly bytes: Buffer; + /** The selected file's bytes; undefined for a capture supplied as Evidence. */ + readonly bytes: Buffer | undefined; readonly loaded: ReturnType; } -/** Export one local capture through the shared CLI/MCP application workflow. */ +/** + * Export one capture through the shared CLI/MCP application workflow. A + * capture supplied as Evidence resolves through the shared Evidence input + * owner: a retained reference, or a summary that names its retained parent. + * The session retains that capture before anything is written, so a full + * retention allowance refuses the export instead of hiding a completed one, + * and a later failure never leaves the export without its source. + */ export const exportWebScripts = async ( rawInput: unknown, resources: ArtifactResourceScope, options: ExecutionOptions = {}, + evidence: { + readonly lookup?: EvidenceLookup | undefined; + readonly recordEvidence?: EvidenceWriter["recordEvidence"] | undefined; + } = {}, ): Promise> => { - const input = exportWebScriptsInputSchema.safeParse(rawInput); - return input.success - ? exportWebScriptsValidated(input.data, resources, options) - : err( - analysisInputErrorFromIssues(OPERATION, input.error.issues, rawInput), - ); -}; - -/** Publish input already parsed by a named adapter contract. */ -export const exportWebScriptsValidated = async ( - input: ExportWebScriptsInput, - resources: ArtifactResourceScope, - options: ExecutionOptions = {}, -): Promise> => { + const resolved = resolveEvidenceRequest( + OPERATION, + rawInput, + exportWebScriptsInputSchema, + evidence.lookup, + { + ...(options.signal === undefined ? {} : { signal: options.signal }), + completeProducers: WEB_SCRIPT_CAPTURE_PRODUCERS, + readEvidence: admitCapture, + }, + ); + if (!resolved.ok) return resolved; + const { capture, ...selection } = resolved.value.input; + const input: ExportWebScriptsInput = selection; + if (capture !== undefined) { + const retained = recordEvidenceSources(evidence.recordEvidence, [capture]); + if (!retained.ok) return retained; + } try { if (options.signal?.aborted) return err(cancelledBy(OPERATION, options.signal)); - const prepared = await prepareCapture( - input.capture_path, - resources, - options.signal, - ); + const prepared = + capture !== undefined + ? evidenceCapture(capture) + : input.capture_path !== undefined + ? await prepareCapture(input.capture_path, resources, options.signal) + : undefined; + if (prepared === undefined) + throw invariantViolation( + "The export_web_scripts input admits exactly one capture selector", + ); if (!prepared.ok) return prepared; - const { bytes, loaded } = prepared.value; + const { loaded } = prepared.value; if (options.signal?.aborted) return err(cancelledBy(OPERATION, options.signal)); - const sha256 = sha256Hex(bytes); + const sha256 = + prepared.value.bytes === undefined + ? null + : sha256Hex(prepared.value.bytes); const result = await publishWebScripts(input, loaded, sha256, { resources, ...(options.signal === undefined ? {} : { signal: options.signal }), @@ -117,13 +155,25 @@ export const exportWebScriptsValidated = async ( ); return ok( createEvidence( - { path: input.capture_path, sha256, format: "file" }, + input.capture_path === undefined || sha256 === null + ? unknownTarget("derived-from-linked-evidence") + : { path: input.capture_path, sha256, format: "file" }, PROVIDER, { predicateType: "rea.web-script-export", operation: OPERATION, parameters: { - capture_path: input.capture_path, + ...(input.capture_path === undefined + ? {} + : { capture_path: input.capture_path }), + ...(capture === undefined + ? {} + : { + capture: { + kind: "retained-evidence", + evidence_id: capture.evidence_id, + }, + }), output_directory: input.output_directory, }, result, @@ -142,6 +192,49 @@ export const exportWebScriptsValidated = async ( } }; +/** Authenticate a capture record and require one of its producers. */ +const admitCapture = ( + input: unknown, + path: EvidenceInputPath, +): Result => { + const record = readEvidence(input); + if ( + !record.ok || + (WEB_SCRIPT_CAPTURE_PRODUCERS as readonly string[]).includes( + record.value.operation, + ) + ) + return record; + const message = `Expected inspect_web_page or capture_browser_scenario Evidence, received ${record.value.operation}`; + return err( + new AnalysisInputError(OPERATION, { userMessage: message }, [ + { path: [...path], reason: "invalid_value", message }, + ]), + ); +}; + +/** The capture an admitted record retains; it has no file bytes of its own. */ +const evidenceCapture = ( + evidence: Evidence, +): Result => { + const loaded = selectEvidenceScriptCapture(evidence); + return loaded === undefined + ? err( + new AnalysisInputError( + OPERATION, + { userMessage: UNSUPPORTED_SCRIPT_CAPTURE_MESSAGE }, + [ + { + path: ["capture"], + reason: "invalid_format", + message: UNSUPPORTED_SCRIPT_CAPTURE_MESSAGE, + }, + ], + ), + ) + : ok({ bytes: undefined, loaded }); +}; + const prepareCapture = async ( path: string, resources: ArtifactResourceScope, @@ -189,7 +282,11 @@ const mapExportFailure = ( ? cancelledBy(OPERATION, carriedReason(cause.cancellation.reason), { partialObservation: cause.partialObservation, }) - : (artifactReaderTargetFailure(OPERATION, input.capture_path, cause) ?? + : (artifactReaderTargetFailure( + OPERATION, + input.capture_path ?? input.output_directory, + cause, + ) ?? new WebScriptExportError( artifactOperationReason(cause), input.output_directory, @@ -207,14 +304,14 @@ const mapExportFailure = ( ) return new WebScriptExportError( "io", - `${input.capture_path} → ${input.output_directory}`, + `${input.capture_path ?? "capture Evidence"} → ${input.output_directory}`, cause.message, { cause }, ); return new ProviderAdapterError(PROVIDER.id, OPERATION, { cause, diagnostics: { - capture_path: input.capture_path, + capture_path: input.capture_path ?? null, output_directory: input.output_directory, error_name: cause instanceof Error ? cause.name : "UnknownError", error_message: diff --git a/src/application/wasm/WasmInterfaceComparisonService.test.ts b/src/application/wasm/WasmInterfaceComparisonService.test.ts index 5072b760780..040e001d169 100644 --- a/src/application/wasm/WasmInterfaceComparisonService.test.ts +++ b/src/application/wasm/WasmInterfaceComparisonService.test.ts @@ -145,22 +145,140 @@ it("withholds absence claims for historical or partial inventories and unsupport it("authenticates semantic Evidence and rejects altered artifact digests", async () => { const left = JSON.parse(JSON.stringify(evidence(facts("f")))); left.normalized_result.interface.entries[0].name = "tampered"; - expect( - await compareWasmInterfaces({ - left, - right: evidence(facts("f")), - scope: "both", - }), - ).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } }); const rebound = JSON.parse(JSON.stringify(evidence(facts("f")))); rebound.subject.identity.sha256 = "b".repeat(64); + for (const rejected of [left, rebound]) + expect( + await compareWasmInterfaces({ + left: rejected, + right: evidence(facts("f")), + scope: "both", + }), + ).toMatchObject({ + ok: false, + error: { + _tag: "EvidenceIntegrityError", + side: "left", + diagnostics: { input_path: ["left"] }, + }, + }); +}); + +it("refuses a non-Evidence side with the shared bounded integrity failure", async () => { + const result = await compareWasmInterfaces({ + left: {}, + right: evidence(facts("f")), + scope: "both", + }); + if (result.ok) throw new Error("an empty object was admitted as Evidence"); + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "evidence_integrity_mismatch", + }); + // The schema failure is summarized, not embedded as raw issue JSON. + expect(result.error.message.length).toBeLessThan(600); +}); + +it("refuses another producer's Evidence by its operation", async () => { + const other = createEvidence( + { path: "/artifacts/app.wasm", sha256: "a".repeat(64), format: "file" }, + { id: "fixture", name: "typed fixture", version: "1" }, + { operation: "inspect_binary", parameters: {}, result: {} }, + ); expect( await compareWasmInterfaces({ - left: rebound, - right: evidence(facts("f")), + left: evidence(facts("f")), + right: other, scope: "both", }), - ).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } }); + ).toMatchObject({ + ok: false, + error: { + _tag: "AnalysisInputError", + issues: [ + { + path: ["right"], + reason: "invalid_value", + message: + "Expected inspect_wasm_artifact Evidence, received inspect_binary", + }, + ], + }, + }); +}); + +it("resolves the right side through the shared resolver once the left is admitted", async () => { + const left = evidence(facts("f")); + const missingId = `ev_${"e".repeat(64)}`; + expect( + await compareWasmInterfaces( + { + left, + right: { kind: "retained-evidence", evidence_id: missingId }, + scope: "both", + }, + {}, + () => undefined, + ), + ).toMatchObject({ + ok: false, + error: { + evidenceId: missingId, + reason: "missing", + diagnostics: { input_path: ["right"] }, + }, + }); +}); + +it("reads the retained parent of a supplied inspection summary", async () => { + const left = evidence(facts("f")); + const right = evidence(facts("f", "i64")); + const summary = createEvidence( + { kind: "unknown", reason: "derived-from-linked-evidence" }, + { id: "fixture", name: "typed fixture", version: "1" }, + { + operation: "inspect_analysis_view", + parameters: {}, + result: { + kind: "summary", + parent_operation: "inspect_wasm_artifact", + parent_evidence_id: right.evidence_id, + }, + }, + ); + const lookup = (id: string) => + id === left.evidence_id + ? left + : id === right.evidence_id + ? right + : undefined; + const result = await compareWasmInterfaces( + { + left: { kind: "retained-evidence", evidence_id: left.evidence_id }, + right: summary, + scope: "both", + }, + {}, + lookup, + ); + if (!result.ok) throw result.error; + expect(result.value.sources.map(({ evidence_id }) => evidence_id)).toEqual([ + left.evidence_id, + right.evidence_id, + ]); + expect( + await compareWasmInterfaces( + { left: summary, right: summary, scope: "both" }, + {}, + () => undefined, + ), + ).toMatchObject({ + ok: false, + error: { + evidenceId: right.evidence_id, + reason: "missing", + diagnostics: { input_path: ["left"] }, + }, + }); }); it("requires the producer's file subject format even for authentic Evidence", async () => { @@ -172,7 +290,10 @@ it("requires the producer's file subject format even for authentic Evidence", as right: evidence(facts("f")), scope: "both", }), - ).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } }); + ).toMatchObject({ + ok: false, + error: { _tag: "EvidenceIntegrityError", side: "left" }, + }); }); it.each(["left", "right"] as const)( @@ -204,7 +325,7 @@ it.each(["left", "right"] as const)( }), ).toMatchObject({ ok: false, - error: { issues: [{ path: [side], reason: "invalid_value" }] }, + error: { _tag: "EvidenceIntegrityError", side }, }); }, ); diff --git a/src/application/wasm/WasmInterfaceComparisonService.ts b/src/application/wasm/WasmInterfaceComparisonService.ts index dbe07bc507f..c4039ed1c69 100644 --- a/src/application/wasm/WasmInterfaceComparisonService.ts +++ b/src/application/wasm/WasmInterfaceComparisonService.ts @@ -37,7 +37,12 @@ import { } from "../EvidenceInputResolver.js"; import type { ExecutionOptions } from "../../ports/AnalysisProvider.js"; import type { z } from "zod"; -import { safeParseEvidence } from "../../domain/evidenceValidation.js"; +import { + readEvidence, + readEvidencePayload, +} from "../../domain/evidenceValidation.js"; +import { EvidenceIntegrityError } from "../../domain/evidenceErrors.js"; +import type { EvidenceInputPath } from "../../domain/evidenceInputContract.js"; import { completeProviderEvidence } from "../ProviderOperationExecution.js"; import type { EvidenceWorkflowExecution } from "../investigation/EvidenceWorkflowExecution.js"; import { @@ -46,48 +51,49 @@ import { } from "../investigation/recordEvidenceSources.js"; const OPERATION = "compare_wasm_interfaces"; -const parseInspection = ( - raw: unknown, - side: "left" | "right", -): Result<{ evidence: Evidence; result: WasmArtifact }, AnalysisInputError> => { - const authenticated = safeParseEvidence(raw); - if (!authenticated.ok) - return inspectionInputFailure(authenticated.error, side); - const evidence = authenticated.value; - if (evidence.operation !== "inspect_wasm_artifact") - return inspectionInputFailure( - new TypeError("Expected complete inspect_wasm_artifact Evidence"), - side, - ); - const parsed = wasmArtifactSchema.safeParse(evidence.normalized_result); - if (!parsed.success) return inspectionInputFailure(parsed.error, side); - const result = parsed.data; - if ( - !wasmArtifactMatchesSubject( - result.artifact, - evidenceFileTarget(evidence), - ) || - evidence.parameters.path !== result.artifact.path - ) - return inspectionInputFailure( - new TypeError( - "WASM Evidence subject/selection does not match normalized artifact identity", - ), - side, - ); - return ok({ evidence, result }); -}; +const PRODUCER = "inspect_wasm_artifact"; -/** Attribute a rejected side to the input argument that supplied it. */ -const inspectionInputFailure = ( - cause: Error, - side: "left" | "right", -): Result => - err( - new AnalysisInputError(OPERATION, { cause }, [ - { path: [side], reason: "invalid_value", message: cause.message }, +/** Authenticate one side and require the inspection producer's record. */ +const admitInspection = ( + input: unknown, + path: EvidenceInputPath, +): Result => { + const side = path[0] === "right" ? "right" : "left"; + const record = readEvidence(input, { side }); + if (!record.ok || record.value.operation === PRODUCER) return record; + const message = `Expected ${PRODUCER} Evidence, received ${record.value.operation}`; + return err( + new AnalysisInputError(OPERATION, { userMessage: message }, [ + { path: [...path], reason: "invalid_value", message }, ]), ); +}; + +/** Read the inspection payload and bind it to the record's own subject. */ +const readInspection = ( + evidence: Evidence, + side: "left" | "right", +): Result< + { evidence: Evidence; result: WasmArtifact }, + EvidenceIntegrityError +> => { + const parsed = readEvidencePayload( + wasmArtifactSchema, + evidence.normalized_result, + { side, within: ["normalized_result"] }, + ); + if (!parsed.ok) return parsed; + const result = parsed.value; + if ( + wasmArtifactMatchesSubject(result.artifact, evidenceFileTarget(evidence)) && + evidence.parameters.path === result.artifact.path + ) + return ok({ evidence, result }); + const message = `WASM Evidence ${evidence.evidence_id} subject or selected path does not match its normalized artifact identity`; + return err( + new EvidenceIntegrityError(message, { userMessage: message, side }), + ); +}; /** Compare only producer-owned typed facts; no raw WAT or original file is reread. */ export const compareWasmInterfaces = async ( @@ -102,7 +108,11 @@ export const compareWasmInterfaces = async ( rawInput, compareWasmInterfacesInputSchema, lookup, - options, + { + ...(options?.signal === undefined ? {} : { signal: options.signal }), + completeProducers: [PRODUCER], + readEvidence: admitInspection, + }, ); if (!resolved.ok) return resolved; const assertActive = () => { @@ -111,9 +121,9 @@ export const compareWasmInterfaces = async ( try { await setImmediate(); assertActive(); - const parsedLeft = parseInspection(resolved.value.input.left, "left"); + const parsedLeft = readInspection(resolved.value.input.left, "left"); if (!parsedLeft.ok) return parsedLeft; - const parsedRight = parseInspection(resolved.value.input.right, "right"); + const parsedRight = readInspection(resolved.value.input.right, "right"); if (!parsedRight.ok) return parsedRight; const left = parsedLeft.value; const right = parsedRight.value; diff --git a/src/cli/webScriptCommands.ts b/src/cli/webScriptCommands.ts index 91b28b42892..d90c96f4d92 100644 --- a/src/cli/webScriptCommands.ts +++ b/src/cli/webScriptCommands.ts @@ -23,6 +23,10 @@ export const registerWebScriptCommands = ( "Export retained website scripts into an absent directory for static JavaScript analysis", positionals: ["capture_path", "output_directory"], callerPaths: ["capture_path", "output_directory"], + omit: { + capture: + "The CLI reads the capture from capture_path, which also accepts a complete Evidence file", + }, fields: { capture_path: { description: diff --git a/src/contracts/webScriptToolContracts.ts b/src/contracts/webScriptToolContracts.ts index 3eed82c5a05..7dbd83a24f0 100644 --- a/src/contracts/webScriptToolContracts.ts +++ b/src/contracts/webScriptToolContracts.ts @@ -119,7 +119,7 @@ export const WEB_SCRIPT_TOOL_CONTRACTS = [ }), ), description: - "Export JavaScript bytes already retained in one local inspect_web_page or capture_browser_scenario JSON capture (normalized result or complete Evidence). Writes scripts and a digest-verified manifest into an absent absolute output_directory. Returns all source URLs, script or transaction/event references, unavailable states, and an analysis_input for analyze_javascript_application when any bytes were exported. Include script sources in inspect_web_page or select capture.network.response_body in scenarios. No refetch or execution. Safe unambiguous URL layouts preserve relative module paths; versions, query variants, inline scripts, and path collisions are isolated with explicit resolution limitations.", + "Export JavaScript bytes already retained in one inspect_web_page or capture_browser_scenario capture: a local JSON file at capture_path (normalized result or complete Evidence), or capture Evidence (inline, retained reference, or its retained summary). Writes scripts and a digest-verified manifest into an absent absolute output_directory. Returns all source URLs, script or transaction/event references, unavailable states, and an analysis_input for analyze_javascript_application when any bytes were exported. Include script sources in inspect_web_page or select capture.network.response_body in scenarios. No refetch or execution. Safe unambiguous URL layouts preserve relative module paths; versions, query variants, inline scripts, and path collisions are isolated with explicit resolution limitations.", kind: "application", inputSchema: exportWebScriptsInputSchema, outputSchema: evidenceResultOf(webScriptExportResultSchema), diff --git a/src/domain/webScriptCaptureAdapters.ts b/src/domain/webScriptCaptureAdapters.ts index cc555adfa9b..df02678af2a 100644 --- a/src/domain/webScriptCaptureAdapters.ts +++ b/src/domain/webScriptCaptureAdapters.ts @@ -1,6 +1,6 @@ import { webPageInspectionSchema } from "./browserObservationSchemas.js"; import { retainedBrowserScenarioCaptureSchema } from "./browserScenarioCapture.js"; -import { parseEvidence } from "./evidence.js"; +import { parseEvidence, type Evidence } from "./evidence.js"; import type { CapturedWebScript, WebScriptExportResult, @@ -54,6 +54,25 @@ export const SCRIPT_CAPTURE_ADAPTERS: readonly ScriptCaptureAdapter[] = [ }, ]; +/** The capture an authenticated producer record retains, if it has script sources. */ +export const selectEvidenceScriptCapture = ( + evidence: Evidence, + adapters: readonly ScriptCaptureAdapter[] = SCRIPT_CAPTURE_ADAPTERS, +): + | (SelectedScriptCapture & { readonly sourceEvidenceId: string }) + | undefined => { + const selected = adapters + .find(({ operation }) => operation === evidence.operation) + ?.parse(evidence.normalized_result); + return selected === undefined + ? undefined + : { ...selected, sourceEvidenceId: evidence.evidence_id }; +}; + +/** The refusal for a record or file without exportable script sources. */ +export const UNSUPPORTED_SCRIPT_CAPTURE_MESSAGE = + "Expected a valid inspect_web_page or capture_browser_scenario capture, with retained script sources or response bytes. Evidence envelopes must have a matching operation and semantic identifier."; + /** Reject unsupported/malformed captures and tampered Evidence before writing. */ export const selectScriptCapture = ( raw: unknown, @@ -64,12 +83,8 @@ export const selectScriptCapture = ( raw !== null && ("normalized_result" in raw || "evidence_id" in raw) ) { - const evidence = parseEvidence(raw); - const selected = adapters - .find(({ operation }) => operation === evidence.operation) - ?.parse(evidence.normalized_result); - if (selected !== undefined) - return { ...selected, sourceEvidenceId: evidence.evidence_id }; + const selected = selectEvidenceScriptCapture(parseEvidence(raw), adapters); + if (selected !== undefined) return selected; } else { for (const adapter of adapters) { const selected = adapter.parse(raw); @@ -77,7 +92,5 @@ export const selectScriptCapture = ( return { ...selected, sourceEvidenceId: null }; } } - throw new TypeError( - "Expected a valid inspect_web_page or capture_browser_scenario capture, with retained script sources or response bytes. Evidence envelopes must have a matching operation and semantic identifier.", - ); + throw new TypeError(UNSUPPORTED_SCRIPT_CAPTURE_MESSAGE); }; diff --git a/src/domain/webScriptExport.ts b/src/domain/webScriptExport.ts index 331c06c7ace..7a706916dfb 100644 --- a/src/domain/webScriptExport.ts +++ b/src/domain/webScriptExport.ts @@ -4,16 +4,39 @@ import { browserCompletenessSchema } from "./browserCompleteness.js"; import { browserScenarioCompletenessSchema } from "./browserScenarioCaptureValues.js"; import { digestSchema, prefixedDigestSchema } from "./digests.js"; import { absoluteLocalPathStringSchema } from "./localPath.js"; +import { evidenceInputSchema } from "./evidenceReference.js"; + +/** Producers whose captures retain exportable script bytes. */ +export const WEB_SCRIPT_CAPTURE_PRODUCERS = [ + "inspect_web_page", + "capture_browser_scenario", +] as const; /** Export already captured scripts into one absent, caller-selected directory. */ -export const exportWebScriptsInputSchema = z.strictObject({ - capture_path: absoluteLocalPathStringSchema.describe( - "Absolute filesystem path to saved inspect_web_page or capture_browser_scenario JSON, normalized result or complete Evidence", - ), - output_directory: absoluteLocalPathStringSchema.describe( - "Absolute absent filesystem directory for verified scripts and manifest; parent directory must exist", - ), -}); +export const exportWebScriptsInputSchema = z + .strictObject({ + capture_path: absoluteLocalPathStringSchema + .describe( + "Absolute filesystem path to saved inspect_web_page or capture_browser_scenario JSON, normalized result or complete Evidence. Supply this or capture.", + ) + .optional(), + capture: evidenceInputSchema + .describe( + "Complete inspect_web_page or capture_browser_scenario Evidence, or a retained-evidence reference to it or to its inspect_analysis_view summary. Supply this or capture_path.", + ) + .optional(), + output_directory: absoluteLocalPathStringSchema.describe( + "Absolute absent filesystem directory for verified scripts and manifest; parent directory must exist", + ), + }) + .refine( + (input) => + (input.capture_path === undefined) !== (input.capture === undefined), + { + message: "Supply exactly one of capture_path or capture", + path: ["capture"], + }, + ); export type ExportWebScriptsInput = z.output< typeof exportWebScriptsInputSchema >; @@ -69,8 +92,10 @@ export type ExportedWebScript = z.output; /** Persisted manifest, also returned inline without duplicating script bytes. */ export const webScriptExportManifestSchema = z.strictObject({ - capture_path: z.string().min(1), - capture_sha256: digestSchema, + /** The selected capture file; null when the capture was Evidence input. */ + capture_path: z.string().min(1).nullable(), + /** That file's digest; source_evidence_id identifies Evidence input. */ + capture_sha256: digestSchema.nullable(), capture_kind: z.enum(["page-inspection", "browser-scenario"]), source_evidence_id: prefixedDigestSchema("ev").nullable(), capture_completeness: z.union([ diff --git a/src/server/serviceToolBindings.ts b/src/server/serviceToolBindings.ts index bd64e23c28f..47df19823a5 100644 --- a/src/server/serviceToolBindings.ts +++ b/src/server/serviceToolBindings.ts @@ -95,7 +95,7 @@ import { matchNativeFunctions } from "../application/native/NativeFunctionMatchi import type { NativeMatchingAllowance } from "../config/nativeMatchingAllowance.js"; import type { ConfigurationError } from "../domain/configurationErrors.js"; import type { WebRuntimeService } from "../application/WebRuntimeService.js"; -import { exportWebScriptsValidated } from "../application/WebScriptExportService.js"; +import { exportWebScripts } from "../application/WebScriptExportService.js"; import type { ArtifactResourceScope } from "../resources/index.js"; import { DetailedFailure, ReducibleValue } from "./contractToolHandler.js"; import type { DesktopBuildToolComputers } from "./desktopBuildDelivery.js"; @@ -449,11 +449,14 @@ const SERVICE_TOOL_BINDINGS = { run: (input, options) => service.inspect(input, options), }, })) satisfies Bind, - webScripts: ((resources) => ({ + webScripts: ((resources, retention) => ({ export_web_scripts: { admission: "sdk", - run: (input, options) => - exportWebScriptsValidated(input, resources, options), + run: (rawInput, options) => + exportWebScripts(rawInput, resources, options, { + lookup: retention.evidenceById, + recordEvidence: retention.recordEvidence, + }), }, })) satisfies Bind, javascriptRecovery: ((service) => ({ diff --git a/tests/boundary/filesystem/webScriptExport.test.ts b/tests/boundary/filesystem/webScriptExport.test.ts index 61ba3aa17e3..d8b5dd0e355 100644 --- a/tests/boundary/filesystem/webScriptExport.test.ts +++ b/tests/boundary/filesystem/webScriptExport.test.ts @@ -26,7 +26,10 @@ import { import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js"; import { exportWebScripts } from "../../../src/application/WebScriptExportService.js"; -import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js"; +import { + AnalysisCancelledError, + AnalysisCapabilityUnavailableError, +} from "../../../src/domain/analysisErrorCore.js"; import { ArtifactResourceScope } from "../../../src/resources/ArtifactResourceScope.js"; import { publishWebScripts } from "../../../src/application/PublishWebScripts.js"; import { DestinationCaseCollisionFailure } from "../../../src/resources/ArtifactPaths.js"; @@ -1502,3 +1505,45 @@ it.each(["basename", "directory"])( ).toEqual(result.scripts); }, ); + +describe("captured script source retention", () => { + it("retains an inline capture before writing, and refuses without output when retention rejects it", async () => { + const root = await createTestTempDirectory("rea-script-source-retention-"); + const capture = scriptCaptureEvidenceFixture(); + const recorded: string[] = []; + const acceptedScope = new ArtifactResourceScope(); + onTestFinished(() => acceptedScope.close()); + const accepted = await exportWebScripts( + { capture, output_directory: join(root, "accepted") }, + acceptedScope, + {}, + { + recordEvidence: (evidence) => { + recorded.push(evidence.evidence_id); + return { ok: true, value: "added" }; + }, + }, + ); + expect(accepted.ok, JSON.stringify(accepted)).toBe(true); + expect(recorded).toEqual([capture.evidence_id]); + + const full = new AnalysisCapabilityUnavailableError( + "rea", + "export_web_scripts", + "The session's Evidence retention allowance is full.", + ); + const output = join(root, "refused"); + const refusedScope = new ArtifactResourceScope(); + onTestFinished(() => refusedScope.close()); + const refused = await exportWebScripts( + { capture, output_directory: output }, + refusedScope, + {}, + { recordEvidence: () => ({ ok: false, error: full }) }, + ); + expect(refused.ok).toBe(false); + if (refused.ok) return; + expect(refused.error).toBe(full); + await expect(access(output)).rejects.toMatchObject({ code: "ENOENT" }); + }); +}); diff --git a/tests/boundary/mcp/evidenceInputResolutionCatalog.test.ts b/tests/boundary/mcp/evidenceInputResolutionCatalog.test.ts new file mode 100644 index 00000000000..fbd2f355074 --- /dev/null +++ b/tests/boundary/mcp/evidenceInputResolutionCatalog.test.ts @@ -0,0 +1,96 @@ +import { expect, it } from "vitest"; + +import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js"; +import { getEvidenceInputContract } from "../../../src/domain/evidenceInputContract.js"; +import { ok } from "../../../src/domain/result.js"; +import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; + +/** A distinct absent identity, so sources that must differ still do. */ +const missingId = (index: number): string => + `ev_${index.toString(16).padStart(64, "f")}`; +const missing = (index: number) => ({ + kind: "retained-evidence", + evidence_id: missingId(index), +}); + +/** Inputs for contracts whose advertised examples select no Evidence source. */ +const SOURCE_INPUTS: Readonly> = { + compare_wasm_interfaces: { + left: missing(0), + right: missing(1), + scope: "both", + }, + export_web_scripts: { + capture: missing(0), + output_directory: "/rea-evidence-catalog/never-created", + }, +}; + +/** Every declared Evidence position in `input`, each replaced by an absent reference. */ +const withMissingSources = ( + contract: (typeof TOOL_CONTRACTS)[number], + input: unknown, +): { + readonly input: unknown; + readonly sources: ReadonlySet; + readonly first: string | undefined; +} => { + const evidence = getEvidenceInputContract(contract.inputSchema); + const framed = evidence.frameSchema.safeParse(input); + const sources = new Set(); + if (!framed.success) return { input, sources, first: undefined }; + const replaced = evidence.resolve(framed.data, () => { + const reference = missing(sources.size); + sources.add(reference.evidence_id); + return ok(reference); + }); + return { + input: replaced.ok ? replaced.value : input, + sources, + first: [...sources][0], + }; +}; + +it("resolves every declared Evidence input through the shared resolver", async () => { + const { client } = await createApplicationMcpHarness(); + const contracts = TOOL_CONTRACTS.filter( + ({ inputSchema }) => getEvidenceInputContract(inputSchema).hasEvidence, + ); + expect(contracts.map(({ name }) => name)).toEqual( + expect.arrayContaining(Object.keys(SOURCE_INPUTS)), + ); + const failures: string[] = []; + for (const contract of contracts) { + const candidates = [ + ...(SOURCE_INPUTS[contract.name] === undefined + ? [] + : [SOURCE_INPUTS[contract.name]]), + ...contract.examples.map(({ input }) => input), + ]; + const selected = candidates + .map((input) => withMissingSources(contract, input)) + .find(({ sources }) => sources.size > 0); + if (selected === undefined) { + failures.push(`${contract.name}: no input selects an Evidence source`); + continue; + } + const response = await client.callTool({ + name: contract.name, + arguments: selected.input as Record, + }); + if (response.isError !== true) { + failures.push(`${contract.name}: admitted a missing reference`); + continue; + } + const { error } = parseMcpToolError(response); + const details: Readonly> = error.details ?? {}; + // The shared resolver stops at the first declared position and names its + // exact missing reference; an adapter that parses Evidence itself reports + // a schema or kind failure instead. Later positions need a valid + // producer-specific source first, so each owner's tests cover them. + if (details.evidence_id !== selected.first || details.reason !== "missing") + failures.push(`${contract.name}: ${error.code} ${error.message}`); + } + expect(failures).toEqual([]); +}); diff --git a/tests/boundary/mcp/webScriptSelectionMcp.test.ts b/tests/boundary/mcp/webScriptSelectionMcp.test.ts index 6eed48800df..b4d7a2baa9d 100644 --- a/tests/boundary/mcp/webScriptSelectionMcp.test.ts +++ b/tests/boundary/mcp/webScriptSelectionMcp.test.ts @@ -14,7 +14,10 @@ import { createToolResultDelivery } from "../../../src/server/toolResult.js"; import { readWithoutFifoWriter } from "../../fixtures/fifoInput.js"; import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; -import { scriptScenarioFixture } from "../../fixtures/webScriptCapture.js"; +import { + scriptCaptureEvidenceFixture, + scriptScenarioFixture, +} from "../../fixtures/webScriptCapture.js"; import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js"; import { createTestBinarySession } from "../../fixtures/binarySession.js"; import { createTestMcp } from "../../support/mcp/mcpFixture.js"; @@ -200,3 +203,94 @@ it("publishes script bytes and retains the returned Evidence without starting an scripts: exported.scripts, }); }); + +it("exports a capture selected by retained reference or by its retained summary", async () => { + const root = await createTestTempDirectory("rea-script-export-reference-"); + const session = createTestBinarySession(() => { + throw new Error("local script export must not start an analysis provider"); + }); + const { client } = await createApplicationMcpHarness({ + session, + clientIdentity: { name: "script-export-reference", version: "1" }, + }); + const capture = scriptCaptureEvidenceFixture(); + expect(session.recordEvidence(capture).ok).toBe(true); + const summaryResponse = await client.callTool({ + name: "inspect_analysis_view", + arguments: { + source: { kind: "retained-evidence", evidence_id: capture.evidence_id }, + view: { kind: "summary" }, + }, + }); + expect(summaryResponse.isError).not.toBe(true); + const summary = parseEvidence(summaryResponse.structuredContent); + expect(summary.operation).toBe("inspect_analysis_view"); + for (const [name, evidenceId] of [ + ["reference", capture.evidence_id], + ["summary", summary.evidence_id], + ] as const) { + const outputDirectory = join(root, name); + const response = await client.callTool({ + name: "export_web_scripts", + arguments: { + capture: { kind: "retained-evidence", evidence_id: evidenceId }, + output_directory: outputDirectory, + }, + }); + expect(response.isError, JSON.stringify(response)).not.toBe(true); + const evidence = parseEvidence(response.structuredContent); + // The export reads the complete capture, never the summary page. + expect(evidence.evidence_links).toEqual([capture.evidence_id]); + expect(evidence.parameters).toEqual({ + capture: { kind: "retained-evidence", evidence_id: capture.evidence_id }, + output_directory: outputDirectory, + }); + const exported = webScriptExportResultSchema.parse( + evidence.normalized_result, + ); + expect(exported).toMatchObject({ + capture_path: null, + capture_sha256: null, + capture_kind: "browser-scenario", + source_evidence_id: capture.evidence_id, + output_directory: outputDirectory, + }); + expect(exported.scripts.map(({ content }) => content.state)).toEqual([ + "exported", + ]); + } + const missingId = `ev_${"0".repeat(64)}`; + const missing = await client.callTool({ + name: "export_web_scripts", + arguments: { + capture: { kind: "retained-evidence", evidence_id: missingId }, + output_directory: join(root, "missing"), + }, + }); + expect(parseMcpToolError(missing).error).toMatchObject({ + details: { evidence_id: missingId, reason: "missing" }, + }); + const ambiguous = await client.callTool({ + name: "export_web_scripts", + arguments: { + capture_path: join(root, "capture.json"), + capture: { kind: "retained-evidence", evidence_id: capture.evidence_id }, + output_directory: join(root, "ambiguous"), + }, + }); + expect(parseMcpToolError(ambiguous).error).toMatchObject({ + code: "invalid_request", + details: { + issues: [ + expect.objectContaining({ + path: ["capture"], + message: "Supply exactly one of capture_path or capture", + }), + ], + }, + }); + for (const directory of ["missing", "ambiguous"]) + await expect(access(join(root, directory))).rejects.toMatchObject({ + code: "ENOENT", + }); +});