From aada0ca8126bf14c60750a4ccd4a79667770a1e4 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Mon, 12 Oct 2026 08:54:08 +0800 Subject: [PATCH] fix(evidence): validate closure projections and browser body coverage Share ledger status, coverage, reports, graphs, Evidence links and closure commitments between the producer and readiness validation. Preserve limitation-driven unknown results and reject stale or inconsistent projections. Distinguish malformed CDP response envelopes from unavailable JSON payload shapes. Validate required encoding flags and preserve partial request facts. Validation: 116 focused tests, static and architecture checks, documentation checks. Browser regression coverage uses controlled CDP responses. --- ...nstructionObligationLedger.closure.test.ts | 117 ++++++--- ...constructionObligationLedgerDiagnostics.ts | 5 - ...econstructionObligationLedgerEvaluation.ts | 77 ++---- ...econstructionObligationLedgerProjection.ts | 142 +--------- src/browser/CdpCaptureEventBodyShapes.ts | 13 +- .../reconstructionReadinessExample.ts | 246 +++++++++--------- ...reconstructionObligationLedgerIntegrity.ts | 212 +++++++++++++++ ...onstructionObligationLedgerSchemas.test.ts | 22 +- .../reconstructionObligationLedgerSchemas.ts | 239 ++++++++++++++--- src/domain/reconstructionReadiness.test.ts | 121 ++++++++- .../cdpBrowserProvider.network.test.ts | 172 ++++++++++++ 11 files changed, 955 insertions(+), 411 deletions(-) create mode 100644 src/domain/reconstructionObligationLedgerIntegrity.ts diff --git a/src/application/ReconstructionObligationLedger.closure.test.ts b/src/application/ReconstructionObligationLedger.closure.test.ts index e11bffadd..86dc84474 100644 --- a/src/application/ReconstructionObligationLedger.closure.test.ts +++ b/src/application/ReconstructionObligationLedger.closure.test.ts @@ -9,6 +9,8 @@ import { request, reviewedObligation, } from "./ReconstructionObligationLedger.fixture.js"; +import { deriveReconstructionObligationCandidates } from "./ReconstructionObligationCandidates.js"; +import { evaluateReconstructionObligationLedger } from "./ReconstructionObligationLedgerEvaluation.js"; describe("reconstruction obligation ledger", () => { it("emits the complete deterministic ledger and closure identity", () => { @@ -86,6 +88,34 @@ describe("reconstruction obligation ledger", () => { }); }); +describe("reconstruction obligation ledger Evidence provenance", () => { + it("links observed-case Evidence separately from authority references", () => { + const capture = processEvidence(); + const caseEvidence = proofEvidence("distinct-original-case"); + const bundle = request([capture, caseEvidence]).evidence_bundle; + const generated = deriveReconstructionObligationCandidates(bundle, []); + const candidates = generated.candidates.map((candidate) => ({ + ...candidate, + observed_cases: candidate.observed_cases.map((observedCase) => ({ + ...observedCase, + evidence_id: caseEvidence.evidence_id, + })), + })); + + const result = evaluateReconstructionObligationLedger({ + candidates, + bundle, + manifest: { bindings: [], contradictions: [] }, + generationLimitations: [], + }); + + expect(result.obligations[0]?.authority_references[0]?.evidence_id).toBe( + capture.evidence_id, + ); + expect(result.evidence_links).toContain(caseEvidence.evidence_id); + }); +}); + describe("reconstruction obligation ledger case closure", () => { it("keeps unobserved original cases open", () => { const capture = processEvidence(); @@ -166,45 +196,44 @@ describe("reconstruction obligation ledger case closure", () => { verifier_ids: ["verifier.packaged"], claim_ids: ["claim.process"], }); - const result = build( - request([capture, proof], { - manifest: { - bindings: [ - { - obligation_id: obligation.obligation_id, - owner: { - module_path: "src/processOwner.ts", - symbol: "runProcess", - owner_sha256: "2".repeat(64), - }, - parser_type: null, - original_cases: originalCases(obligation, capture.evidence_id), - fixtures: obligation.required_case_kinds.map((caseKind) => ({ - fixture_id: `packaged.${caseKind}`, - case_kind: caseKind, - authority: "packaged-process", - evidence_ids: [proof.evidence_id], - })), - verifier: { - verifier_id: "verifier.packaged", - claim_id: "claim.process", - command: "npm run verify:package -- process", - authority: "packaged-process", - status: "pass", - result_evidence_id: proof.evidence_id, - enumerated_obligation_ids: [obligation.obligation_id], - nondeterminism: { - mode: "partial-order", - specification: - "Startup precedes teardown; worker completion is unordered.", - }, + const ledgerRequest = request([capture, proof], { + manifest: { + bindings: [ + { + obligation_id: obligation.obligation_id, + owner: { + module_path: "src/processOwner.ts", + symbol: "runProcess", + owner_sha256: "2".repeat(64), + }, + parser_type: null, + original_cases: originalCases(obligation, capture.evidence_id), + fixtures: obligation.required_case_kinds.map((caseKind) => ({ + fixture_id: `packaged.${caseKind}`, + case_kind: caseKind, + authority: "packaged-process", + evidence_ids: [proof.evidence_id], + })), + verifier: { + verifier_id: "verifier.packaged", + claim_id: "claim.process", + command: "npm run verify:package -- process", + authority: "packaged-process", + status: "pass", + result_evidence_id: proof.evidence_id, + enumerated_obligation_ids: [obligation.obligation_id], + nondeterminism: { + mode: "partial-order", + specification: + "Startup precedes teardown; worker completion is unordered.", }, }, - ], - contradictions: [], - }, - }), - ); + }, + ], + contradictions: [], + }, + }); + const result = build(ledgerRequest); expect(result.obligations[0]).toMatchObject({ status: "verified", @@ -212,5 +241,19 @@ describe("reconstruction obligation ledger case closure", () => { }); expect(result.status).toBe("ready"); expect(result.summary.required_open).toBe(0); + + const generated = deriveReconstructionObligationCandidates( + ledgerRequest.evidence_bundle, + ledgerRequest.reviewed_obligations, + ); + const limited = evaluateReconstructionObligationLedger({ + candidates: generated.candidates, + bundle: ledgerRequest.evidence_bundle, + manifest: ledgerRequest.manifest, + generationLimitations: ["A supplementary source was unavailable."], + }); + expect(limited.obligations[0]?.status).toBe("verified"); + expect(limited.status).toBe("unknown"); + expect(limited.coverage.status).toBe("partial"); }); }); diff --git a/src/application/ReconstructionObligationLedgerDiagnostics.ts b/src/application/ReconstructionObligationLedgerDiagnostics.ts index 7d6d84637..5d53d8f4a 100644 --- a/src/application/ReconstructionObligationLedgerDiagnostics.ts +++ b/src/application/ReconstructionObligationLedgerDiagnostics.ts @@ -57,11 +57,6 @@ export const uniqueObligationDiagnostics = ( ), ); -export const hasObligationDiagnostic = ( - diagnostics: readonly Diagnostic[], - code: Diagnostic["code"], -): boolean => diagnostics.some((diagnostic) => diagnostic.code === code); - export const contradictionDiagnostics = ( obligationId: string, contradictions: ReadonlyMap, diff --git a/src/application/ReconstructionObligationLedgerEvaluation.ts b/src/application/ReconstructionObligationLedgerEvaluation.ts index fe7626344..a9366c331 100644 --- a/src/application/ReconstructionObligationLedgerEvaluation.ts +++ b/src/application/ReconstructionObligationLedgerEvaluation.ts @@ -9,6 +9,17 @@ import { type ReconstructionObligationLedger, type ReconstructionObligationManifest, } from "../domain/reconstructionObligationLedgerSchemas.js"; +import { digestCanonicalValue } from "../domain/canonicalDigest.js"; +import { + reconstructionObligationCoverage, + reconstructionObligationDependencyGraph, + reconstructionObligationLedgerClosureDigest, + reconstructionObligationLedgerStatus, + hasReconstructionObligationDiagnostic as hasDiagnostic, + reconstructionObligationOwnershipGraph, + reconstructionObligationReports, + summarizeReconstructionObligations, +} from "../domain/reconstructionObligationLedgerIntegrity.js"; import type { ReconstructionObligationCandidate } from "./ReconstructionObligationCandidates.js"; import { evidenceAuthoritySupportsProof, @@ -20,22 +31,13 @@ import { contradictionDiagnostics, groupManifestBindings, groupManifestContradictions, - hasObligationDiagnostic as hasDiagnostic, uniqueObligationDiagnostics as uniqueDiagnostics, } from "./ReconstructionObligationLedgerDiagnostics.js"; import { originalCaseDiagnostics, originalCasesFor, } from "./ReconstructionObligationOriginalCases.js"; -import { - digestObligationLedgerValue, - obligationLedgerCoverage, - obligationEdgeOrder, - obligationLedgerEvidenceLinks, - obligationLedgerStatus, - obligationReports, - summarizeObligations, -} from "./ReconstructionObligationLedgerProjection.js"; +import { obligationLedgerEvidenceLinks } from "./ReconstructionObligationLedgerProjection.js"; import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js"; type Diagnostic = ReconstructionObligation["diagnostics"][number]; @@ -70,64 +72,41 @@ export const evaluateReconstructionObligationLedger = ({ candidates.map((candidate) => evaluateObligation(candidate, context)), context, ); - const ownershipGraph = obligations - .flatMap((obligation) => - obligation.binding === null - ? [] - : [ - { - obligation_id: obligation.obligation_id, - module_path: obligation.binding.owner.module_path, - symbol: obligation.binding.owner.symbol, - }, - ], - ) - .sort(obligationEdgeOrder); - const dependencyGraph = obligations - .flatMap((obligation) => - obligation.dependency_obligation_ids.map((dependencyId) => ({ - obligation_id: obligation.obligation_id, - depends_on_obligation_id: dependencyId, - })), - ) - .sort(obligationEdgeOrder); + const ownershipGraph = reconstructionObligationOwnershipGraph(obligations); + const dependencyGraph = reconstructionObligationDependencyGraph(obligations); const evidenceLinks = obligationLedgerEvidenceLinks(obligations, manifest); const limitations = ledgerLimitations( generationLimitations, allCandidates.length, orphanManifestIds, ); - const coverage = obligationLedgerCoverage(limitations.length > 0); + const coverage = reconstructionObligationCoverage(limitations); const semantic = { coverage, - summary: summarizeObligations(obligations), - reports: obligationReports(obligations), + summary: summarizeReconstructionObligations(obligations), + reports: reconstructionObligationReports(obligations), ownership_graph: ownershipGraph, dependency_graph: dependencyGraph, obligations, evidence_links: evidenceLinks, limitations, }; - const evaluatedStatus = obligationLedgerStatus(obligations); - const status = - evaluatedStatus === "failed" - ? evaluatedStatus - : limitations.length > 0 - ? "unknown" - : evaluatedStatus; - const closureDigest = digestObligationLedgerValue({ - schema: "ReconstructionObligationClosure", + const status = reconstructionObligationLedgerStatus(obligations, limitations); + const closureDigest = reconstructionObligationLedgerClosureDigest({ status, ...semantic, }); return reconstructionObligationLedgerSchema.parse({ schema: "ReconstructionObligationLedger", - ledger_id: `rol_${digestObligationLedgerValue({ - schema: "ReconstructionObligationLedger", - evidence_ids: bundle.records.map(({ evidence_id: id }) => id), - obligation_ids: obligations.map(({ obligation_id: id }) => id), - closure_digest: closureDigest, - })}`, + ledger_id: `rol_${digestCanonicalValue( + { + schema: "ReconstructionObligationLedger", + evidence_ids: bundle.records.map(({ evidence_id: id }) => id), + obligation_ids: obligations.map(({ obligation_id: id }) => id), + closure_digest: closureDigest, + }, + "Reconstruction obligation ledger", + )}`, closure_digest: closureDigest, status, ...semantic, diff --git a/src/application/ReconstructionObligationLedgerProjection.ts b/src/application/ReconstructionObligationLedgerProjection.ts index f77a6c9d1..4976465bf 100644 --- a/src/application/ReconstructionObligationLedgerProjection.ts +++ b/src/application/ReconstructionObligationLedgerProjection.ts @@ -1,83 +1,9 @@ -import { createHash } from "node:crypto"; - -import canonicalize from "canonicalize"; - -import { canonicalJson } from "../domain/comparisonSemantics.js"; -import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js"; - import type { ReconstructionObligation, - ReconstructionObligationLedger, ReconstructionObligationManifest, } from "../domain/reconstructionObligationLedgerSchemas.js"; - -type DiagnosticCode = ReconstructionObligation["diagnostics"][number]["code"]; - -export const obligationLedgerCoverage = ( - incomplete: boolean, -): ReconstructionObligationLedger["coverage"] => ({ - status: incomplete ? "partial" : "complete", -}); - -export const summarizeObligations = ( - obligations: readonly ReconstructionObligation[], -): ReconstructionObligationLedger["summary"] => ({ - total: obligations.length, - required: obligations.filter(({ required }) => required).length, - verified: obligations.filter(({ status }) => status === "verified").length, - required_open: obligations.filter( - ({ required, status }) => required && status !== "verified", - ).length, - by_status: countBy( - obligations, - [ - "unowned", - "characterized", - "implemented", - "verified", - "contradicted", - "blocked", - "out-of-scope", - "unknown", - ], - ({ status }) => status, - ), - by_application_layer: countBy( - obligations, - [ - "cli", - "protocol", - "electron", - "persistence", - "process", - "runtime", - "packaging", - "native-abi", - "application", - "other", - ], - ({ application_layer: layer }) => layer, - ), - by_evidence_authority: countBy( - obligations, - ["candidate", "observed", "reviewed", "unknown"], - ({ source_state: state }) => state, - ), -}); - -export const obligationReports = ( - obligations: readonly ReconstructionObligation[], -): ReconstructionObligationLedger["reports"] => ({ - missing_owner_obligation_ids: obligationIdsWith(obligations, "missing-owner"), - missing_verifier_obligation_ids: obligationIdsWith( - obligations, - "missing-verifier", - ), - contradicted_obligation_ids: obligationIdsWith(obligations, "contradiction"), - residual_unknown_ids: [ - ...new Set(obligations.flatMap(({ residual_unknown_ids: ids }) => ids)), - ].sort(), -}); +import { reconstructionObligationEvidenceIds } from "../domain/reconstructionObligationLedgerIntegrity.js"; +import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js"; export const obligationLedgerEvidenceLinks = ( obligations: readonly ReconstructionObligation[], @@ -85,9 +11,7 @@ export const obligationLedgerEvidenceLinks = ( ): string[] => [ ...new Set([ - ...obligations.flatMap(({ authority_references: references }) => - references.map(({ evidence_id: id }) => id), - ), + ...reconstructionObligationEvidenceIds(obligations), ...manifest.bindings.flatMap((binding) => [ ...binding.original_cases.map(({ evidence_id: id }) => id), ...binding.fixtures.flatMap(({ evidence_ids: ids }) => ids), @@ -97,62 +21,4 @@ export const obligationLedgerEvidenceLinks = ( ]), ...manifest.contradictions.flatMap(({ evidence_ids: ids }) => ids), ]), - ].sort(); - -export const obligationLedgerStatus = ( - obligations: readonly ReconstructionObligation[], -): ReconstructionObligationLedger["status"] => { - if (obligations.length === 0) return "unknown"; - const requiredOpen = obligations.filter( - ({ required, status }) => required && status !== "verified", - ); - if ( - requiredOpen.some( - ({ status, diagnostics }) => - status === "contradicted" || - hasDiagnostic(diagnostics, "verifier-failed"), - ) - ) - return "failed"; - if (requiredOpen.some(({ status }) => status === "unknown")) return "unknown"; - return requiredOpen.length === 0 ? "ready" : "open"; -}; - -export const obligationEdgeOrder = ( - left: { readonly obligation_id: string }, - right: { readonly obligation_id: string }, -): number => - compareUnicodeCodePoints(canonicalJson(left), canonicalJson(right)); - -export const digestObligationLedgerValue = (value: unknown): string => { - const encoded = canonicalize(value); - if (encoded === undefined) - throw new TypeError( - "Reconstruction obligation ledger is not canonical JSON", - ); - return createHash("sha256").update(encoded).digest("hex"); -}; - -const countBy = ( - items: readonly Item[], - values: readonly Value[], - valueFor: (item: Item) => Value, -): { key: Value; count: number }[] => - values.map((value) => ({ - key: value, - count: items.filter((item) => valueFor(item) === value).length, - })); - -const obligationIdsWith = ( - obligations: readonly ReconstructionObligation[], - code: DiagnosticCode, -): string[] => - obligations - .filter(({ diagnostics }) => hasDiagnostic(diagnostics, code)) - .map(({ obligation_id: id }) => id) - .sort(); - -const hasDiagnostic = ( - diagnostics: ReconstructionObligation["diagnostics"], - code: DiagnosticCode, -): boolean => diagnostics.some((diagnostic) => diagnostic.code === code); + ].sort(compareUnicodeCodePoints); diff --git a/src/browser/CdpCaptureEventBodyShapes.ts b/src/browser/CdpCaptureEventBodyShapes.ts index 53882a819..f3b22bfe7 100644 --- a/src/browser/CdpCaptureEventBodyShapes.ts +++ b/src/browser/CdpCaptureEventBodyShapes.ts @@ -15,19 +15,19 @@ export const ingestResponseBodyShape = ( ): void => { const result = recordValue(value); const body = cdpStringValue(result?.body); - if (body === undefined) { + const base64Encoded = result?.base64Encoded; + if (body === undefined || typeof base64Encoded !== "boolean") { invalidResponseBodyShape(state, requestId); return; } - const decoded = - result?.base64Encoded === true - ? decodeBase64(body)?.toString("utf8") - : body; + const decoded = base64Encoded ? decodeBase64(body)?.toString("utf8") : body; if (decoded === undefined) { invalidResponseBodyShape(state, requestId); return; } - updateResponseBodyShape(state, requestId, inferJsonShape(decoded)); + const shape = inferJsonShape(decoded); + if (shape === null) state.completeness.unavailable("json_body_shapes"); + updateResponseBodyShape(state, requestId, shape); }; export const requestBodyShape = ( @@ -40,6 +40,7 @@ export const requestBodyShape = ( if (!isJsonContentType(recordValue(request.headers)) || body === undefined) return { status: "unavailable", request: null, response: null }; const shape = inferJsonShape(body); + if (shape === null) state.completeness.unavailable("json_body_shapes"); return { status: shape === null ? "unavailable" : "included", request: shape, diff --git a/src/contracts/reconstructionReadinessExample.ts b/src/contracts/reconstructionReadinessExample.ts index 0b81cf60b..124ce2a05 100644 --- a/src/contracts/reconstructionReadinessExample.ts +++ b/src/contracts/reconstructionReadinessExample.ts @@ -4,6 +4,8 @@ import { READINESS_REQUIRED_CHECKS, READINESS_STAGE_IDS, } from "../domain/reconstructionReadinessJourneyFindings.js"; +import { reconstructionObligationLedgerClosureDigest } from "../domain/reconstructionObligationLedgerIntegrity.js"; +import type { ReconstructionObligationLedger } from "../domain/reconstructionObligationLedgerSchemas.js"; import type { ReconstructionReadinessInput } from "../domain/reconstructionReadinessSchemas.js"; const HASH = "a".repeat(64); @@ -69,6 +71,129 @@ const EVIDENCE_STATES = [ "reviewed", "unknown", ] as const; +const READINESS_OBLIGATION_LEDGER = (() => { + const ledger: Omit = { + schema: "ReconstructionObligationLedger", + ledger_id: `rol_${HASH}`, + status: "ready", + coverage: { + status: "complete", + }, + summary: { + total: 1, + required: 1, + verified: 1, + required_open: 0, + by_status: STATUSES.map((key) => ({ + key, + count: key === "verified" ? 1 : 0, + })), + by_application_layer: LAYERS.map((key) => ({ + key, + count: key === "process" ? 1 : 0, + })), + by_evidence_authority: EVIDENCE_STATES.map((key) => ({ + key, + count: key === "observed" ? 1 : 0, + })), + }, + reports: { + missing_owner_obligation_ids: [], + missing_verifier_obligation_ids: [], + contradicted_obligation_ids: [], + residual_unknown_ids: [], + }, + ownership_graph: [ + { + obligation_id: "obl.readiness", + module_path: "src/readiness.ts", + symbol: "runReadiness", + }, + ], + dependency_graph: [], + obligations: [ + { + obligation_id: "obl.readiness", + obligation_version: 1, + title: "Preserve the packaged readiness fixture lifecycle", + origin: "reviewed", + application_layer: "process", + family: "packaged-process-lifecycle", + target: { + artifact_sha256: HASH, + application_node_id: null, + semantic_node_id: null, + location: "/fixture", + }, + authority_references: [ + { + evidence_id: EVIDENCE_ID, + authority: "controlled-replay", + state: "observed", + location: "/fixture", + }, + ], + source_state: "observed", + observed_cases: CASES.map((kind) => ({ + kind, + evidence_id: EVIDENCE_ID, + location: `/original/${kind}`, + })), + required: true, + required_case_kinds: [...CASES], + required_original_authority: "process", + required_fixture_authority: "packaged-process", + required_verifier_authority: "packaged-process", + requires_parser_type: false, + dependency_obligation_ids: [], + residual_unknown_ids: [], + unavailable_authority: [], + required_next_evidence: [], + binding: { + obligation_id: "obl.readiness", + owner: { + module_path: "src/readiness.ts", + symbol: "runReadiness", + owner_sha256: HASH, + }, + parser_type: null, + original_cases: CASES.map((kind) => ({ + kind, + evidence_id: EVIDENCE_ID, + location: `/original/${kind}`, + })), + fixtures: CASES.map((kind) => ({ + fixture_id: `fixture.${kind}`, + case_kind: kind, + authority: "packaged-process", + evidence_ids: [EVIDENCE_ID], + })), + verifier: { + verifier_id: "verifier.readiness", + claim_id: "claim.readiness", + command: "npm run verify:readiness", + authority: "packaged-process", + status: "pass", + result_evidence_id: EVIDENCE_ID, + enumerated_obligation_ids: ["obl.readiness"], + nondeterminism: { + mode: "partial-order", + specification: "Startup precedes teardown.", + }, + }, + }, + status: "verified", + diagnostics: [], + }, + ], + evidence_links: [EVIDENCE_ID], + limitations: [], + }; + return { + ...ledger, + closure_digest: reconstructionObligationLedgerClosureDigest(ledger), + }; +})(); /** Complete synthetic input shared by docs, tests, CLI, MCP, and verifier. */ export const RECONSTRUCTION_READINESS_EXAMPLE: ReconstructionReadinessInput = { @@ -217,124 +342,7 @@ export const RECONSTRUCTION_READINESS_EXAMPLE: ReconstructionReadinessInput = { evidence_ids: [EVIDENCE_ID, CONTRADICTING_SOURCE.evidence_id], }, ], - obligation_ledger: { - schema: "ReconstructionObligationLedger", - ledger_id: `rol_${HASH}`, - closure_digest: HASH, - status: "ready", - coverage: { - status: "complete", - }, - summary: { - total: 1, - required: 1, - verified: 1, - required_open: 0, - by_status: STATUSES.map((key) => ({ - key, - count: key === "verified" ? 1 : 0, - })), - by_application_layer: LAYERS.map((key) => ({ - key, - count: key === "process" ? 1 : 0, - })), - by_evidence_authority: EVIDENCE_STATES.map((key) => ({ - key, - count: key === "observed" ? 1 : 0, - })), - }, - reports: { - missing_owner_obligation_ids: [], - missing_verifier_obligation_ids: [], - contradicted_obligation_ids: [], - residual_unknown_ids: [], - }, - ownership_graph: [ - { - obligation_id: "obl.readiness", - module_path: "src/readiness.ts", - symbol: "runReadiness", - }, - ], - dependency_graph: [], - obligations: [ - { - obligation_id: "obl.readiness", - obligation_version: 1, - title: "Preserve the packaged readiness fixture lifecycle", - origin: "reviewed", - application_layer: "process", - family: "packaged-process-lifecycle", - target: { - artifact_sha256: HASH, - application_node_id: null, - semantic_node_id: null, - location: "/fixture", - }, - authority_references: [ - { - evidence_id: EVIDENCE_ID, - authority: "controlled-replay", - state: "observed", - location: "/fixture", - }, - ], - source_state: "observed", - observed_cases: CASES.map((kind) => ({ - kind, - evidence_id: EVIDENCE_ID, - location: `/original/${kind}`, - })), - required: true, - required_case_kinds: [...CASES], - required_original_authority: "process", - required_fixture_authority: "packaged-process", - required_verifier_authority: "packaged-process", - requires_parser_type: false, - dependency_obligation_ids: [], - residual_unknown_ids: [], - unavailable_authority: [], - required_next_evidence: [], - binding: { - obligation_id: "obl.readiness", - owner: { - module_path: "src/readiness.ts", - symbol: "runReadiness", - owner_sha256: HASH, - }, - parser_type: null, - original_cases: CASES.map((kind) => ({ - kind, - evidence_id: EVIDENCE_ID, - location: `/original/${kind}`, - })), - fixtures: CASES.map((kind) => ({ - fixture_id: `fixture.${kind}`, - case_kind: kind, - authority: "packaged-process", - evidence_ids: [EVIDENCE_ID], - })), - verifier: { - verifier_id: "verifier.readiness", - claim_id: "claim.readiness", - command: "npm run verify:readiness", - authority: "packaged-process", - status: "pass", - result_evidence_id: EVIDENCE_ID, - enumerated_obligation_ids: ["obl.readiness"], - nondeterminism: { - mode: "partial-order", - specification: "Startup precedes teardown.", - }, - }, - }, - status: "verified", - diagnostics: [], - }, - ], - evidence_links: [EVIDENCE_ID], - limitations: [], - }, + obligation_ledger: READINESS_OBLIGATION_LEDGER, operation_outcomes: [ { sequence: 0, @@ -404,7 +412,7 @@ export const RECONSTRUCTION_READINESS_EXAMPLE: ReconstructionReadinessInput = { }, { sequence: 1, - ledger_digest: HASH, + ledger_digest: READINESS_OBLIGATION_LEDGER.closure_digest, status: "ready", required_open: 0, newly_verified_obligation_ids: ["obl.readiness"], diff --git a/src/domain/reconstructionObligationLedgerIntegrity.ts b/src/domain/reconstructionObligationLedgerIntegrity.ts new file mode 100644 index 000000000..c0f9dd099 --- /dev/null +++ b/src/domain/reconstructionObligationLedgerIntegrity.ts @@ -0,0 +1,212 @@ +import { digestCanonicalValue } from "./canonicalDigest.js"; +import { canonicalJson } from "./comparisonSemantics.js"; +import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; + +import type { + ReconstructionObligation, + ReconstructionObligationLedger, +} from "./reconstructionObligationLedgerSchemas.js"; + +/** Derive the ledger summary from the obligation facts. */ +export const summarizeReconstructionObligations = ( + obligations: readonly ReconstructionObligation[], +): ReconstructionObligationLedger["summary"] => ({ + total: obligations.length, + required: obligations.filter(({ required }) => required).length, + verified: obligations.filter(({ status }) => status === "verified").length, + required_open: obligations.filter( + ({ required, status }) => required && status !== "verified", + ).length, + by_status: countBy( + obligations, + [ + "unowned", + "characterized", + "implemented", + "verified", + "contradicted", + "blocked", + "out-of-scope", + "unknown", + ], + ({ status }) => status, + ), + by_application_layer: countBy( + obligations, + [ + "cli", + "protocol", + "electron", + "persistence", + "process", + "runtime", + "packaging", + "native-abi", + "application", + "other", + ], + ({ application_layer }) => application_layer, + ), + by_evidence_authority: countBy( + obligations, + ["candidate", "observed", "reviewed", "unknown"], + ({ source_state }) => source_state, + ), +}); + +/** Derive closure status from required obligations and their diagnostic facts. */ +export const reconstructionObligationLedgerStatus = ( + obligations: readonly ReconstructionObligation[], + limitations: readonly string[], +): ReconstructionObligationLedger["status"] => { + if (obligations.length === 0) return "unknown"; + const requiredOpen = obligations.filter( + ({ required, status }) => required && status !== "verified", + ); + if ( + requiredOpen.some( + ({ status, diagnostics }) => + status === "contradicted" || + hasReconstructionObligationDiagnostic(diagnostics, "verifier-failed"), + ) + ) + return "failed"; + if (limitations.length > 0) return "unknown"; + if (requiredOpen.some(({ status }) => status === "unknown")) return "unknown"; + return requiredOpen.length === 0 ? "ready" : "open"; +}; + +export const reconstructionObligationCoverage = ( + limitations: readonly string[], +): ReconstructionObligationLedger["coverage"] => ({ + status: limitations.length === 0 ? "complete" : "partial", +}); + +export const reconstructionObligationReports = ( + obligations: readonly ReconstructionObligation[], +): ReconstructionObligationLedger["reports"] => ({ + missing_owner_obligation_ids: obligationIdsWith(obligations, "missing-owner"), + missing_verifier_obligation_ids: obligationIdsWith( + obligations, + "missing-verifier", + ), + contradicted_obligation_ids: obligationIdsWith(obligations, "contradiction"), + residual_unknown_ids: [ + ...new Set(obligations.flatMap(({ residual_unknown_ids: ids }) => ids)), + ].sort(compareUnicodeCodePoints), +}); + +export const reconstructionObligationOwnershipGraph = ( + obligations: readonly ReconstructionObligation[], +): ReconstructionObligationLedger["ownership_graph"] => + obligations + .flatMap((obligation) => + obligation.binding === null + ? [] + : [ + { + obligation_id: obligation.obligation_id, + module_path: obligation.binding.owner.module_path, + symbol: obligation.binding.owner.symbol, + }, + ], + ) + .sort(obligationEdgeOrder); + +export const reconstructionObligationDependencyGraph = ( + obligations: readonly ReconstructionObligation[], +): ReconstructionObligationLedger["dependency_graph"] => + obligations + .flatMap((obligation) => + obligation.dependency_obligation_ids.map((dependencyId) => ({ + obligation_id: obligation.obligation_id, + depends_on_obligation_id: dependencyId, + })), + ) + .sort(obligationEdgeOrder); + +/** Evidence attached to facts serialized on an obligation. */ +export const reconstructionObligationEvidenceIds = ( + obligations: readonly ReconstructionObligation[], +): string[] => + [ + ...new Set( + obligations.flatMap((obligation) => [ + ...obligation.authority_references.map(({ evidence_id: id }) => id), + ...obligation.observed_cases.map(({ evidence_id: id }) => id), + ...(obligation.binding === null + ? [] + : [ + ...obligation.binding.original_cases.map( + ({ evidence_id: id }) => id, + ), + ...obligation.binding.fixtures.flatMap( + ({ evidence_ids: ids }) => ids, + ), + ...(obligation.binding.verifier === null + ? [] + : [obligation.binding.verifier.result_evidence_id]), + ]), + ]), + ), + ].sort(compareUnicodeCodePoints); + +const obligationEdgeOrder = ( + left: { readonly obligation_id: string }, + right: { readonly obligation_id: string }, +): number => + compareUnicodeCodePoints(canonicalJson(left), canonicalJson(right)); + +const obligationIdsWith = ( + obligations: readonly ReconstructionObligation[], + code: ReconstructionObligation["diagnostics"][number]["code"], +): string[] => + obligations + .filter(({ diagnostics }) => + hasReconstructionObligationDiagnostic(diagnostics, code), + ) + .map(({ obligation_id: id }) => id) + .sort(compareUnicodeCodePoints); + +export const hasReconstructionObligationDiagnostic = ( + diagnostics: Readonly, + code: ReconstructionObligation["diagnostics"][number]["code"], +): boolean => diagnostics.some((diagnostic) => diagnostic.code === code); + +/** Recompute the closure commitment from the fields carried by a ledger. */ +export const reconstructionObligationLedgerClosureDigest = (ledger: { + readonly status: ReconstructionObligationLedger["status"]; + readonly coverage: ReconstructionObligationLedger["coverage"]; + readonly summary: ReconstructionObligationLedger["summary"]; + readonly reports: ReconstructionObligationLedger["reports"]; + readonly ownership_graph: ReconstructionObligationLedger["ownership_graph"]; + readonly dependency_graph: ReconstructionObligationLedger["dependency_graph"]; + readonly obligations: ReconstructionObligationLedger["obligations"]; + readonly evidence_links: ReconstructionObligationLedger["evidence_links"]; + readonly limitations: ReconstructionObligationLedger["limitations"]; +}): string => + digestCanonicalValue( + { + schema: "ReconstructionObligationClosure", + status: ledger.status, + coverage: ledger.coverage, + summary: ledger.summary, + reports: ledger.reports, + ownership_graph: ledger.ownership_graph, + dependency_graph: ledger.dependency_graph, + obligations: ledger.obligations, + evidence_links: ledger.evidence_links, + limitations: ledger.limitations, + }, + "Reconstruction obligation ledger", + ); + +const countBy = ( + items: readonly Item[], + values: readonly Value[], + valueFor: (item: Item) => Value, +): { key: Value; count: number }[] => + values.map((value) => ({ + key: value, + count: items.filter((item) => valueFor(item) === value).length, + })); diff --git a/src/domain/reconstructionObligationLedgerSchemas.test.ts b/src/domain/reconstructionObligationLedgerSchemas.test.ts index c2aedd024..005758210 100644 --- a/src/domain/reconstructionObligationLedgerSchemas.test.ts +++ b/src/domain/reconstructionObligationLedgerSchemas.test.ts @@ -3,7 +3,12 @@ import { describe, expect, it } from "vitest"; import { reconstructionObligationLedgerSchema, reconstructionObligationManifestSchema, + type ReconstructionObligationLedger, } from "./reconstructionObligationLedgerSchemas.js"; +import { + reconstructionObligationLedgerClosureDigest, + summarizeReconstructionObligations, +} from "./reconstructionObligationLedgerIntegrity.js"; const digest = "a".repeat(64); @@ -32,20 +37,13 @@ describe("reconstruction obligation ledger schemas", () => { reconstructionObligationManifestSchema.parse(manifest).bindings, ).toHaveLength(10_001); - const ledger = { + const ledgerBase: Omit = { schema: "ReconstructionObligationLedger", ledger_id: `rol_${digest}`, - closure_digest: digest, - status: "ready", + status: "unknown", coverage: { status: "complete" }, summary: { - total: 0, - required: 0, - verified: 0, - required_open: 0, - by_status: [], - by_application_layer: [], - by_evidence_authority: [], + ...summarizeReconstructionObligations([]), }, reports: { missing_owner_obligation_ids: [], @@ -62,6 +60,10 @@ describe("reconstruction obligation ledger schemas", () => { ), limitations: [], }; + const ledger = { + ...ledgerBase, + closure_digest: reconstructionObligationLedgerClosureDigest(ledgerBase), + }; expect( reconstructionObligationLedgerSchema.parse(ledger).evidence_links, diff --git a/src/domain/reconstructionObligationLedgerSchemas.ts b/src/domain/reconstructionObligationLedgerSchemas.ts index bc61969a8..6d3403c8d 100644 --- a/src/domain/reconstructionObligationLedgerSchemas.ts +++ b/src/domain/reconstructionObligationLedgerSchemas.ts @@ -5,11 +5,42 @@ import { STABLE_IDENTIFIER_PATTERN } from "./stringPatterns.js"; import { evidenceBundleSchema } from "./evidenceBundle.js"; import { digestSchema } from "./../domain/digests.js"; import { prefixedDigestSchema } from "./../domain/digests.js"; +import { canonicalJson } from "./comparisonSemantics.js"; +import { + reconstructionObligationCoverage, + reconstructionObligationDependencyGraph, + reconstructionObligationLedgerClosureDigest, + reconstructionObligationLedgerStatus, + reconstructionObligationEvidenceIds, + reconstructionObligationOwnershipGraph, + reconstructionObligationReports, + summarizeReconstructionObligations, +} from "./reconstructionObligationLedgerIntegrity.js"; const evidenceIdSchema = prefixedDigestSchema("ev"); const stableIdSchema = z.string().regex(STABLE_IDENTIFIER_PATTERN); const textSchema = z.string().trim().min(1); +const sameProjection = ( + actual: readonly Value[], + expected: readonly Value[], +): boolean => { + if (actual.length !== expected.length) return false; + const counts = new Map(); + for (const value of actual) { + const key = canonicalJson(value, "Reconstruction obligation ledger"); + counts.set(key, (counts.get(key) ?? 0) + 1); + } + for (const value of expected) { + const key = canonicalJson(value, "Reconstruction obligation ledger"); + const count = counts.get(key); + if (count === undefined) return false; + if (count === 1) counts.delete(key); + else counts.set(key, count - 1); + } + return counts.size === 0; +}; + export const obligationStatusSchema = z.enum([ "unowned", "characterized", @@ -236,48 +267,174 @@ const countBySchema = ( }), ); -export const reconstructionObligationLedgerSchema = z.strictObject({ - schema: z.literal("ReconstructionObligationLedger"), - ledger_id: prefixedDigestSchema("rol"), - closure_digest: digestSchema, - status: z.enum(["ready", "open", "failed", "unknown"]), - coverage: z.strictObject({ - status: z.enum(["complete", "partial"]), - }), - summary: z.strictObject({ - total: z.number().int().min(0), - required: z.number().int().min(0), - verified: z.number().int().min(0), - required_open: z.number().int().min(0), - by_status: countBySchema(obligationStatusSchema), - by_application_layer: countBySchema(obligationLayerSchema), - by_evidence_authority: countBySchema( - z.enum(["candidate", "observed", "reviewed", "unknown"]), +const countEntriesMatch = ( + actual: readonly { readonly key: string; readonly count: number }[], + expected: readonly { readonly key: string; readonly count: number }[], +): boolean => { + const actualCounts = new Map(actual.map(({ key, count }) => [key, count])); + return ( + actualCounts.size === actual.length && + actual.length === expected.length && + expected.every(({ key, count }) => actualCounts.get(key) === count) + ); +}; + +const obligationSummariesMatch = ( + actual: ReconstructionObligationLedger["summary"], + expected: ReconstructionObligationLedger["summary"], +): boolean => + actual.total === expected.total && + actual.required === expected.required && + actual.verified === expected.verified && + actual.required_open === expected.required_open && + countEntriesMatch(actual.by_status, expected.by_status) && + countEntriesMatch( + actual.by_application_layer, + expected.by_application_layer, + ) && + countEntriesMatch( + actual.by_evidence_authority, + expected.by_evidence_authority, + ); + +export const reconstructionObligationLedgerSchema = z + .strictObject({ + schema: z.literal("ReconstructionObligationLedger"), + ledger_id: prefixedDigestSchema("rol"), + closure_digest: digestSchema, + status: z.enum(["ready", "open", "failed", "unknown"]), + coverage: z.strictObject({ + status: z.enum(["complete", "partial"]), + }), + summary: z.strictObject({ + total: z.number().int().min(0), + required: z.number().int().min(0), + verified: z.number().int().min(0), + required_open: z.number().int().min(0), + by_status: countBySchema(obligationStatusSchema), + by_application_layer: countBySchema(obligationLayerSchema), + by_evidence_authority: countBySchema( + z.enum(["candidate", "observed", "reviewed", "unknown"]), + ), + }), + reports: z.strictObject({ + missing_owner_obligation_ids: z.array(stableIdSchema), + missing_verifier_obligation_ids: z.array(stableIdSchema), + contradicted_obligation_ids: z.array(stableIdSchema), + residual_unknown_ids: z.array(stableIdSchema), + }), + ownership_graph: z.array( + z.strictObject({ + obligation_id: stableIdSchema, + module_path: textSchema, + symbol: textSchema, + }), ), - }), - reports: z.strictObject({ - missing_owner_obligation_ids: z.array(stableIdSchema), - missing_verifier_obligation_ids: z.array(stableIdSchema), - contradicted_obligation_ids: z.array(stableIdSchema), - residual_unknown_ids: z.array(stableIdSchema), - }), - ownership_graph: z.array( - z.strictObject({ - obligation_id: stableIdSchema, - module_path: textSchema, - symbol: textSchema, - }), - ), - dependency_graph: z.array( - z.strictObject({ - obligation_id: stableIdSchema, - depends_on_obligation_id: stableIdSchema, - }), - ), - obligations: z.array(reconstructionObligationSchema), - evidence_links: z.array(evidenceIdSchema), - limitations: z.array(textSchema), -}); + dependency_graph: z.array( + z.strictObject({ + obligation_id: stableIdSchema, + depends_on_obligation_id: stableIdSchema, + }), + ), + obligations: z.array(reconstructionObligationSchema), + evidence_links: z.array(evidenceIdSchema), + limitations: z.array(textSchema), + }) + .superRefine((ledger, context) => { + if ( + ledger.status !== + reconstructionObligationLedgerStatus( + ledger.obligations, + ledger.limitations, + ) + ) + context.addIssue({ + code: "custom", + path: ["status"], + message: "Ledger status does not match its obligations", + }); + if ( + !obligationSummariesMatch( + ledger.summary, + summarizeReconstructionObligations(ledger.obligations), + ) + ) + context.addIssue({ + code: "custom", + path: ["summary"], + message: "Ledger summary does not match its obligations", + }); + if ( + ledger.closure_digest !== + reconstructionObligationLedgerClosureDigest(ledger) + ) + context.addIssue({ + code: "custom", + path: ["closure_digest"], + message: "Ledger closure digest does not match its contents", + }); + if ( + ledger.coverage.status !== + reconstructionObligationCoverage(ledger.limitations).status + ) + context.addIssue({ + code: "custom", + path: ["coverage"], + message: "Ledger coverage does not match its limitations", + }); + const expectedReports = reconstructionObligationReports(ledger.obligations); + for (const key of [ + "missing_owner_obligation_ids", + "missing_verifier_obligation_ids", + "contradicted_obligation_ids", + "residual_unknown_ids", + ] as const) + if (!sameProjection(ledger.reports[key], expectedReports[key])) + context.addIssue({ + code: "custom", + path: ["reports", key], + message: "Ledger report does not match its obligations", + }); + if ( + !sameProjection( + ledger.ownership_graph, + reconstructionObligationOwnershipGraph(ledger.obligations), + ) + ) + context.addIssue({ + code: "custom", + path: ["ownership_graph"], + message: "Ownership graph does not match its obligations", + }); + if ( + !sameProjection( + ledger.dependency_graph, + reconstructionObligationDependencyGraph(ledger.obligations), + ) + ) + context.addIssue({ + code: "custom", + path: ["dependency_graph"], + message: "Dependency graph does not match its obligations", + }); + const ledgerEvidenceIds = new Set(ledger.evidence_links); + if (ledgerEvidenceIds.size !== ledger.evidence_links.length) + context.addIssue({ + code: "custom", + path: ["evidence_links"], + message: "Evidence links must be unique", + }); + if ( + reconstructionObligationEvidenceIds(ledger.obligations).some( + (evidenceId) => !ledgerEvidenceIds.has(evidenceId), + ) + ) + context.addIssue({ + code: "custom", + path: ["evidence_links"], + message: "Evidence links omit Evidence referenced by an obligation", + }); + }); export const reconstructionObligationLedgerInputSchema = z.strictObject({ evidence_bundle: evidenceBundleSchema, diff --git a/src/domain/reconstructionReadiness.test.ts b/src/domain/reconstructionReadiness.test.ts index df0d5e2a0..9418f0dd1 100644 --- a/src/domain/reconstructionReadiness.test.ts +++ b/src/domain/reconstructionReadiness.test.ts @@ -2,6 +2,12 @@ import { describe, expect, it } from "vitest"; import { RECONSTRUCTION_READINESS_EXAMPLE } from "../contracts/reconstructionReadinessExample.js"; import { createReconstructionReadinessReport } from "./reconstructionReadiness.js"; +import { + reconstructionObligationLedgerClosureDigest, + reconstructionObligationLedgerStatus, + summarizeReconstructionObligations, +} from "./reconstructionObligationLedgerIntegrity.js"; +import { reconstructionObligationLedgerSchema } from "./reconstructionObligationLedgerSchemas.js"; import { reconstructionReadinessInputSchema, type ReconstructionReadinessInput, @@ -86,7 +92,96 @@ describe("reconstruction readiness report", () => { nondeterministic_replay_count: 0, }); }); +}); +describe("readiness obligation ledger integrity", () => { + it("rejects a required obligation changed behind the old ledger commitment", () => { + const value = input(); + expect( + reconstructionObligationLedgerSchema.parse(value.obligation_ledger), + ).toEqual(value.obligation_ledger); + const obligation = value.obligation_ledger.obligations[0]; + if (obligation === undefined) + throw new TypeError("Missing reconstruction obligation"); + value.obligation_ledger.obligations[0] = { + ...obligation, + status: "blocked", + }; + + expect(() => createReconstructionReadinessReport(value)).toThrow( + /Ledger status does not match its obligations/u, + ); + }); + + it("rejects a recomputed commitment over a false obligation summary", () => { + const ledger = structuredClone(input().obligation_ledger); + ledger.summary.required_open = 1; + ledger.closure_digest = reconstructionObligationLedgerClosureDigest(ledger); + + expect(() => reconstructionObligationLedgerSchema.parse(ledger)).toThrow( + /Ledger summary does not match its obligations/u, + ); + }); + + it("accepts reordered summary count entries with the same keyed values", () => { + const ledger = structuredClone(input().obligation_ledger); + ledger.summary.by_status.reverse(); + ledger.closure_digest = reconstructionObligationLedgerClosureDigest(ledger); + + expect(reconstructionObligationLedgerSchema.parse(ledger)).toEqual(ledger); + }); + + it.each([ + [ + "reports", + (ledger: ReconstructionReadinessInput["obligation_ledger"]) => { + ledger.reports.missing_owner_obligation_ids.push("obl.extra"); + }, + /Ledger report does not match its obligations/u, + ], + [ + "ownership graph", + (ledger: ReconstructionReadinessInput["obligation_ledger"]) => { + const owner = ledger.ownership_graph[0]; + if (owner === undefined) + throw new TypeError("Missing owner graph edge"); + owner.symbol = "tamperedOwner"; + }, + /Ownership graph does not match its obligations/u, + ], + [ + "dependency graph", + (ledger: ReconstructionReadinessInput["obligation_ledger"]) => { + ledger.dependency_graph.push({ + obligation_id: "obl.readiness", + depends_on_obligation_id: "obl.extra", + }); + }, + /Dependency graph does not match its obligations/u, + ], + [ + "evidence links", + (ledger: ReconstructionReadinessInput["obligation_ledger"]) => { + ledger.evidence_links = []; + }, + /Evidence links omit Evidence referenced by an obligation/u, + ], + ] as const)( + "rejects recomputed commitments over tampered %s", + (_, mutate, expected) => { + const ledger = structuredClone(input().obligation_ledger); + mutate(ledger); + ledger.closure_digest = + reconstructionObligationLedgerClosureDigest(ledger); + + expect(() => reconstructionObligationLedgerSchema.parse(ledger)).toThrow( + expected, + ); + }, + ); +}); + +describe("readiness failure semantics", () => { it("rejects equivalence over truncated concurrent evidence", () => { const value = input(); const comparison = value.comparisons[0]; @@ -110,14 +205,28 @@ describe("reconstruction readiness report", () => { it("keeps green stages unknown while one reconstruction obligation is open", () => { const value = input(); - value.obligation_ledger = { + const obligation = value.obligation_ledger.obligations[0]; + if (obligation === undefined) + throw new TypeError("Missing reconstruction obligation"); + const obligations = [{ ...obligation, status: "blocked" as const }]; + const uncommitted = { ...value.obligation_ledger, + obligations, + status: reconstructionObligationLedgerStatus(obligations, []), + summary: summarizeReconstructionObligations(obligations), + }; + value.obligation_ledger = { + ...uncommitted, + closure_digest: reconstructionObligationLedgerClosureDigest(uncommitted), + }; + const latest = value.closure_history.at(-1); + if (latest === undefined) throw new TypeError("Missing closure history"); + value.closure_history[value.closure_history.length - 1] = { + ...latest, + ledger_digest: value.obligation_ledger.closure_digest, status: "open", - summary: { - ...value.obligation_ledger.summary, - verified: 0, - required_open: 1, - }, + required_open: 1, + newly_verified_obligation_ids: [], }; const report = createReconstructionReadinessReport(value); diff --git a/tests/boundary/browser/cdpBrowserProvider.network.test.ts b/tests/boundary/browser/cdpBrowserProvider.network.test.ts index a1e967122..65ed14180 100644 --- a/tests/boundary/browser/cdpBrowserProvider.network.test.ts +++ b/tests/boundary/browser/cdpBrowserProvider.network.test.ts @@ -131,6 +131,178 @@ it("preserves unavailable response observations and captures completed peers", a ).toEqual(["missing-body", "available"]); }); +it("marks malformed JSON body shapes unavailable while preserving partial request shapes", async () => { + const browser = await startFakeCdpBrowser({ + commandEvents(command, origin) { + if (command.method !== "Network.enable") return undefined; + const session = + command.sessionId === undefined ? {} : { sessionId: command.sessionId }; + return ["unavailable", "partial"].flatMap((requestId) => { + const url = `${origin}/${requestId}`; + return [ + { + ...session, + method: "Network.requestWillBeSent", + params: { + requestId, + request: { + url, + method: requestId === "partial" ? "POST" : "GET", + ...(requestId === "partial" + ? { + headers: { "Content-Type": "application/json" }, + postData: '{"request":true}', + } + : {}), + }, + initiator: { type: "other" }, + }, + }, + { + ...session, + method: "Network.responseReceived", + params: { + requestId, + response: { url, status: 200, mimeType: "application/json" }, + }, + }, + { + ...session, + method: "Network.loadingFinished", + params: { requestId, encodedDataLength: 0 }, + }, + ]; + }); + }, + commandResult(command) { + return command.method === "Network.getResponseBody" + ? { body: "{", base64Encoded: false } + : undefined; + }, + }); + trackBrowser(browser); + const result = await new CdpBrowserProvider().inspectPage( + inspectWebPageInputSchema.parse({ + cdp_endpoint: browser.endpoint, + allowed_origins: [browser.allowedOrigin], + target_id: "allowed-page", + observation_ms: 20, + include_json_body_shapes: true, + }), + ); + + if (!result.ok) throw result.error; + expect(result.value.network.requests).toEqual([ + expect.objectContaining({ + request_id: "unavailable", + body_shapes: { status: "unavailable", request: null, response: null }, + }), + expect.objectContaining({ + request_id: "partial", + body_shapes: { + status: "partial", + request: expect.any(Object), + response: null, + }, + }), + ]); + expect(result.value.completeness.unavailable_sections).toContain( + "json_body_shapes", + ); + expect(result.value.completeness.excluded).not.toContainEqual( + expect.objectContaining({ + section: "json_body_shapes", + reason: "invalid_protocol_value", + }), + ); +}); + +it("rejects malformed response-body envelopes and preserves request shapes", async () => { + const browser = await startFakeCdpBrowser({ + commandEvents(command, origin) { + if (command.method !== "Network.enable") return undefined; + const session = + command.sessionId === undefined ? {} : { sessionId: command.sessionId }; + return ["missing-encoding-flag", "invalid-encoding-flag"].flatMap( + (requestId) => { + const url = `${origin}/${requestId}`; + return [ + { + ...session, + method: "Network.requestWillBeSent", + params: { + requestId, + request: { + url, + method: + requestId === "invalid-encoding-flag" ? "POST" : "GET", + ...(requestId === "invalid-encoding-flag" + ? { + headers: { "Content-Type": "application/json" }, + postData: '{"request":true}', + } + : {}), + }, + initiator: { type: "other" }, + }, + }, + { + ...session, + method: "Network.responseReceived", + params: { + requestId, + response: { url, status: 200, mimeType: "application/json" }, + }, + }, + { + ...session, + method: "Network.loadingFinished", + params: { requestId, encodedDataLength: 0 }, + }, + ]; + }, + ); + }, + commandResult(command) { + if (command.method !== "Network.getResponseBody") return undefined; + return command.params.requestId === "missing-encoding-flag" + ? { body: '{"response":true}' } + : { body: '{"response":true}', base64Encoded: "false" }; + }, + }); + trackBrowser(browser); + const result = await new CdpBrowserProvider().inspectPage( + inspectWebPageInputSchema.parse({ + cdp_endpoint: browser.endpoint, + allowed_origins: [browser.allowedOrigin], + target_id: "allowed-page", + observation_ms: 20, + include_json_body_shapes: true, + }), + ); + + if (!result.ok) throw result.error; + expect(result.value.network.requests).toEqual([ + expect.objectContaining({ + request_id: "missing-encoding-flag", + body_shapes: { status: "unavailable", request: null, response: null }, + }), + expect.objectContaining({ + request_id: "invalid-encoding-flag", + body_shapes: { + status: "partial", + request: expect.any(Object), + response: null, + }, + }), + ]); + expect(result.value.completeness.excluded).toContainEqual({ + section: "json_body_shapes", + reason: "invalid_protocol_value", + count: 2, + }); +}); + it.each([ { options: {