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.
This commit is contained in:
morluto
2026-10-12 08:59:14 +08:00
parent f889a69fb9
commit aada0ca812
11 changed files with 955 additions and 411 deletions
@@ -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<ReconstructionObligation["diagnostics"]>,
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 = <Value extends string, Item>(
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,
}));
@@ -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<ReconstructionObligationLedger, "closure_digest"> = {
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,
@@ -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 = <Value>(
actual: readonly Value[],
expected: readonly Value[],
): boolean => {
if (actual.length !== expected.length) return false;
const counts = new Map<string, number>();
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 = <Schema extends z.ZodType>(
}),
);
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,
+115 -6
View File
@@ -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);