#!/usr/bin/env python3
"""Fail-closed organizational readiness gate (local reads only)."""
from __future__ import annotations

import base64
import binascii
import hashlib
import json
import os
import re
import stat
import subprocess
import sys
sys.dont_write_bytecode = True
from datetime import datetime, timedelta, timezone
from decimal import Decimal, ROUND_CEILING, localcontext
from pathlib import Path, PurePosixPath
from typing import Any

from strict_json_schema import StrictJSONError, json_equal, load_json, loads_json, validate

PACKAGE = Path(__file__).resolve().parents[1]
REPOSITORY = PACKAGE.parents[1]
DEFAULT_MANIFEST = PACKAGE / "manifests/organizational-readiness.template.json"
SCHEMA_PATH = PACKAGE / "schemas/organizational-readiness.schema.json"
TRUST_PATH = PACKAGE / "config/trusted-identities.json"
TRUST_SCHEMA_PATH = PACKAGE / "schemas/trusted-identities.schema.json"
EXPECTED_EXTERNAL_TRUST_POLICY = PACKAGE / "config/trust-root-policy.json"
TRUST_POLICY_SCHEMA_PATH = PACKAGE / "schemas/trust-root-policy.schema.json"
LEGAL_REGISTRY_TRUST_POLICY = PACKAGE / "config/legal-registry-trust-policy.json"
LEGAL_REGISTRY_TRUST_POLICY_SCHEMA = PACKAGE / "schemas/legal-registry-trust-policy.schema.json"
RANDOMNESS_BEACON_TRUST_POLICY = PACKAGE / "config/randomness-beacon-trust-policy.json"
RANDOMNESS_BEACON_TRUST_POLICY_SCHEMA = PACKAGE / "schemas/randomness-beacon-trust-policy.schema.json"
RANDOMNESS_AUTHORITY_ROOT_POLICY = PACKAGE / "config/randomness-authority-root-policy.json"
RANDOMNESS_AUTHORITY_ROOT_POLICY_SCHEMA = PACKAGE / "schemas/randomness-authority-root-policy.schema.json"
# No genuine independent authority is presently established. A later reviewed
# source change must pin the digest; input manifests and environment variables
# can never override this trust root.
PINNED_RANDOMNESS_AUTHORITY_ROOT_SHA256: str | None = None
PRIVACY_EXECUTION_TRUST_POLICY = PACKAGE / "config/privacy-execution-trust-policy.json"
PRIVACY_EXECUTION_TRUST_POLICY_SCHEMA = PACKAGE / "schemas/privacy-execution-trust-policy.schema.json"
PINNED_PRIVACY_EXECUTION_POLICY_SHA256 = "b3a4b647a8b2e0259373b4d59b4eb69f3e5ad6e8176efc52e401dcf00c40a348"
CANONICAL_PRIVACY_IMPLEMENTATION_PATH = "v3-src/privacy-portability/canonical_api.py"
CANONICAL_PRIVACY_INTERFACE_ID = "vaultfire.privacy-portability.cli-v1"
CANONICAL_PRIVACY_ORACLE_ID = "vaultfire.privacy-portability.oracle-v1"
SCOPE_REGISTRY_PATH = PACKAGE / "config/pilot-scope-registry.json"
SCOPE_REGISTRY_SCHEMA_PATH = PACKAGE / "schemas/pilot-scope-registry.schema.json"
ROLLOUT_PLAN_PATH = PACKAGE / "config/pilot-rollout-plan.json"
ROLLOUT_PLAN_SCHEMA_PATH = PACKAGE / "schemas/pilot-rollout-plan.schema.json"
EVIDENCE_SCHEMA_DIR = PACKAGE / "schemas/evidence"
EVIDENCE_ROOT = "pr10/partner-package/evidence/organizational/attestations"
ARTIFACT_MANIFEST_PATH = "pr10/partner-package/evidence/organizational/artifact-manifest.json"
POST_COMMIT_ENVELOPE_PATH = "pr10/partner-package/evidence/organizational/post-commit-attestation-envelope.json"
ROLE_IDS = {
    "authorized-signatory", "change-approver", "commercial-owner",
    "incident-commander", "independent-reviewer", "legal-reviewer",
    "privacy-reviewer", "release-manager", "security-contact", "support-owner",
}
ROLE_EVIDENCE = {
    "authorized-signatory": "AUTHORIZED-SIGNATORY",
    "change-approver": "CHANGE-RACI-ACCEPTANCE",
    "commercial-owner": "ROLE-ASSIGNMENTS",
    "incident-commander": "ROLE-ASSIGNMENTS",
    "independent-reviewer": "ROLE-ASSIGNMENTS",
    "legal-reviewer": "COUNSEL-SIGNOFF",
    "privacy-reviewer": "PRIVACY-SIGNOFF",
    "release-manager": "CANDIDATE-BINDING",
    "security-contact": "ACTUAL-CONTACTS",
    "support-owner": "SUPPORT-SLA-SELECTION",
}
COMMITMENTS = {
    "flourishingCannotSlashPrincipal": True,
    "flourishingCannotControlPrincipal": True,
    "flourishingCannotControlCollateral": True,
    "flourishingCannotControlAnyProtectedDecision": True,
    "rewardsCannotConsumeCollateral": True,
    "surveillanceNeverRequired": True,
    "surveillanceDataNeverPermittedForProtectedDecisions": True,
    "hashedDerivedAndTransitiveSurveillanceInputsProhibited": True,
    "explicitConsentRequired": True,
    "refundsAndTerminalExitsBoundedAndPauseSafe": True,
    "moduleByModuleGatedRollout": True,
    "liabilitiesStrictlyBounded": True,
    "pullPaymentsRequired": True,
    "failClosedApisRequired": True,
    "immutableEvidenceBindingRequired": True,
    "exactCommitTestsRequired": True,
    "privacyPreservingChainSpecificTrustPortabilityRequired": True,
    "crossChainValueFlowsExcludedFromPilot": True,
}
PROTECTED = ["access", "collateral", "custody", "disputes", "eligibility", "pricing", "principal", "routing", "settlement", "slashing"]
PROHIBITED = ["behavioral-routing", "belief", "biometric", "flourishing", "loyalty", "profiling", "quality", "reputation", "surveillance", "trust-score"]
ACTION_CLASSES = {"read-only-query"}
CANONICAL_PATHS = {
    "operationsStatus": "v3-operations/release-status.json",
    "policyCommitment": "v3-operations/policy-commitment.json",
    "readinessSupersession": "v3-operations/readiness-supersession.json",
    "openSpec": "v3-migration/completeness/supported-v3-modules.json",
    "canonicalLedger": "v3-migration/completeness/ledger.json",
    "partnerPackageSchema": "pr10/partner-package/schemas/organizational-readiness.schema.json",
    "trustedIdentities": "pr10/partner-package/config/trusted-identities.json",
    "scopeRegistry": "pr10/partner-package/config/pilot-scope-registry.json",
    "rolloutPlan": "pr10/partner-package/config/pilot-rollout-plan.json",
    "generatedRouteInventory": "pr7/generated/route-registry.json",
    "trustRootPolicy": "pr10/partner-package/config/trust-root-policy.json",
    "legalRegistryTrustPolicy": "pr10/partner-package/config/legal-registry-trust-policy.json",
    "randomnessAuthorityTrustPolicy": "pr10/partner-package/config/randomness-authority-root-policy.json",
}
DEPLOYMENT_PATH = "pr8/pilot/base_v3_deployment_manifest.json"
SHA256 = re.compile(r"^[0-9a-f]{64}$")
IDENTITY = re.compile(r"^identity:[0-9a-f]{64}$")
CHANNEL = re.compile(r"^channel:[0-9a-f]{64}$")
SYSTEM_REF = re.compile(r"^controlled-system:[0-9a-f]{64}$")
UTC = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$")


def spec(claim: str, roles: set[str], statement: str, prefixes: tuple[str, ...] = ()) -> dict[str, Any]:
    return {"claim": claim, "roles": roles, "statement": statement, "prefixes": prefixes}


EVIDENCE_SPECS = {
    "LEGAL-ENTITY": spec("legal-entity", {"legal-reviewer"}, "The contracting legal entity was verified in the controlled system."),
    "AUTHORIZED-SIGNATORY": spec("authorized-signatory", {"legal-reviewer"}, "The named signatory identity and authority basis were verified."),
    "ACTUAL-CONTACTS": spec("actual-contacts", {"release-manager"}, "Required security, privacy, incident, support, change, and commercial channels were control-tested."),
    "INSURANCE": spec("insurance", {"legal-reviewer"}, "The insurance decision and applicable evidence were reviewed; no coverage is inferred beyond the controlled record."),
    "COUNSEL-SIGNOFF": spec("counsel-signoff", {"legal-reviewer"}, "Qualified counsel approved the exact agreement and release candidate."),
    "PRIVACY-SIGNOFF": spec("privacy-signoff", {"privacy-reviewer"}, "The privacy reviewer approved the exact data map, consent, retention, and no-surveillance controls."),
    "PARTNER-ACCEPTANCE": spec("partner-acceptance", {"partner-authorized-signatory"}, "The partner explicitly accepted the exact agreement, scope, and release candidate."),
    "ROLE-ASSIGNMENTS": spec("role-assignments", {"authorized-signatory"}, "All mandatory roles, authority boundaries, separation rules, coverage, and channels were approved."),
    "COMMERCIAL-AGREEMENT": spec("commercial-agreement", {"authorized-signatory", "partner-authorized-signatory"}, "The commercial agreement for this exact candidate was executed by both authorized parties."),
    "SIGNATURES": spec("signatures", {"authorized-signatory", "partner-authorized-signatory"}, "Required detached signatures for the exact candidate-bound attestations were verified."),
    "SECURITY-POLICY-ACCEPTANCE": spec("security-policy-acceptance", {"security-contact"}, "The security and vulnerability-reporting policy and tested intake route were accepted.", ("pr10/partner-package/docs/SECURITY_AND_VULNERABILITY_REPORTING.md",)),
    "INCIDENT-PLAN-ACCEPTANCE": spec("incident-plan-acceptance", {"incident-commander"}, "The incident plan, escalation route, responder coverage, and exercise evidence were accepted.", ("pr10/partner-package/docs/INCIDENT_RESPONSE_AND_ESCALATION.md",)),
    "SUPPORT-SLA-SELECTION": spec("support-sla-selection", {"support-owner"}, "A staffed support tier, maintenance policy, and deprecation policy were selected.", ("pr10/partner-package/docs/SUPPORT_SLA_MAINTENANCE_DEPRECATION.md",)),
    "CHANGE-RACI-ACCEPTANCE": spec("change-raci-acceptance", {"change-approver"}, "The deployment and change-management RACI was accepted for this candidate.", ("pr10/partner-package/docs/DEPLOYMENT_CHANGE_MANAGEMENT_RACI.md",)),
    "CANDIDATE-BINDING": spec("candidate-binding", {"release-manager", "independent-reviewer"}, "The existing Git commit, tree, canonical files, package schema, trust registry, and candidate digest were independently reconciled."),
    "CANONICAL-OPERATIONS": spec("canonical-operations", {"release-manager", "independent-reviewer"}, "Canonical operations is complete, authorized, deployed, activated, blocker-free, fresh, and bound to this candidate.", ("v3-operations/release-status.json",)),
    "EXACT-COMMIT-TESTS": spec("exact-commit-tests", {"independent-reviewer"}, "All required tests passed against the exact existing clean Git commit and immutable tree."),
    "MODULE-ROLLOUT": spec("module-rollout", {"change-approver", "independent-reviewer"}, "Exactly one enumerated module, action class, and route are approved; every unrelated module is denied."),
    "BOUNDED-LIABILITIES": spec("bounded-liabilities", {"commercial-owner", "legal-reviewer"}, "Numeric caps, maximum loss, reserves, remedies, and residual liabilities are bounded and accepted.", ("pr10/partner-package/docs/CAP_MAXIMUM_LOSS_DECISION.md",)),
    "PULL-PAYMENTS": spec("pull-payments", {"independent-reviewer"}, "Released payment paths use recipient-initiated pull settlement and prohibit forced push payouts.", ("pr10/partner-package/docs/ACCOUNTABILITY_TYPED_ENFORCEMENT_V1.md",)),
    "FAIL-CLOSED-APIS": spec("fail-closed-apis", {"independent-reviewer"}, "Released APIs deny unknown, stale, malformed, unbound, or unauthorized inputs and routes."),
    "PRIVACY-CROSS-CHAIN": spec("privacy-cross-chain", {"privacy-reviewer", "independent-reviewer"}, "Chain-specific trust portability uses minimal commitments, explicit consent, unlinkability controls, and no cross-chain value flow.", ("pr10/partner-package/docs/PRIVACY_DATA_MINIMIZATION.md",)),
    "IMMUTABLE-EVIDENCE": spec("immutable-evidence", {"independent-reviewer"}, "Every evidence record has a unique canonical file and digest and is immutably bound to the exact candidate."),
    "PAUSE-SAFE-EXITS": spec("pause-safe-exits", {"independent-reviewer"}, "Refunds and terminal exits are bounded, available while paused, and preserve principal and withdrawal recovery.", ("pr10/partner-package/docs/ACCOUNTABILITY_TYPED_ENFORCEMENT_V1.md",)),
    "PROTECTED-DECISION-INPUTS": spec("protected-decision-inputs", {"privacy-reviewer", "independent-reviewer"}, "Surveillance, biometric, profiling, behavioral, reputation, belief, flourishing, quality, loyalty, hashed, derived, and transitive forms are prohibited for protected decisions.", ("v3-migration/completeness/supported-v3-modules.json",)),
}
for _evidence_id, _evidence_spec in EVIDENCE_SPECS.items():
    _objective = (
        f"pr10/partner-package/evidence/organizational/artifacts/"
        f"{_evidence_id.lower()}.json"
    )
    _evidence_spec["prefixes"] = (_objective,) + tuple(_evidence_spec["prefixes"])

ARTIFACT_FACT_KEYS = {
    "LEGAL-ENTITY": {"jurisdiction", "registrationReference", "entityVerified"},
    "AUTHORIZED-SIGNATORY": {"authorityBasis", "authorityScope", "authorityVerified"},
    "ACTUAL-CONTACTS": {"contactsArtifactSha256", "channelsControlTested", "requiredFunctionsCovered"},
    "INSURANCE": {"coverageDecision", "evidenceReviewed"},
    "COUNSEL-SIGNOFF": {"agreementSha256", "candidateApproved"},
    "PRIVACY-SIGNOFF": {"dataMapSha256", "noSurveillanceControlsApproved"},
    "PARTNER-ACCEPTANCE": {"agreementSha256", "scopeAccepted", "candidateAccepted"},
    "ROLE-ASSIGNMENTS": {"assignmentMatrixSha256", "separationVerified"},
    "COMMERCIAL-AGREEMENT": {"agreementSha256", "subjectExecuted", "partnerExecuted"},
    "SIGNATURES": {"signatureSetSha256", "subjectSignaturesVerified", "partnerSignaturesVerified"},
    "SECURITY-POLICY-ACCEPTANCE": {"policySha256", "intakeRouteControlTested"},
    "INCIDENT-PLAN-ACCEPTANCE": {"planSha256", "exerciseEvidenceSha256", "coverageVerified"},
    "SUPPORT-SLA-SELECTION": {"slaSha256", "tierSelected", "staffingVerified"},
    "CHANGE-RACI-ACCEPTANCE": {"raciSha256", "responsibilitiesAccepted"},
    "CANDIDATE-BINDING": {"sourceCommit", "gitTree"},
    "CANONICAL-OPERATIONS": {"operationsSha256", "candidateIdMatched", "allStagesComplete"},
    "EXACT-COMMIT-TESTS": {"testSourceCommit", "testGitTree", "testResultsSha256", "allPassed"},
    "MODULE-ROLLOUT": {"scopeRegistrySha256", "rolloutPlanSha256", "singleStageMatched"},
    "BOUNDED-LIABILITIES": {"capsArtifactSha256", "maximumLossBounded", "residualLiabilityAccepted"},
    "PULL-PAYMENTS": {"testResultsSha256", "forcedPushRejected", "pullSettlementVerified"},
    "FAIL-CLOSED-APIS": {"testResultsSha256", "unknownDenied", "staleDenied", "malformedDenied", "unauthorizedDenied"},
    "PRIVACY-CROSS-CHAIN": {"privacyArtifactSha256", "unlinkabilityTestResultsSha256", "unlinkabilityVerified", "crossChainValueFlowAbsent"},
    "IMMUTABLE-EVIDENCE": {"allEvidenceTracked", "ignoredEvidenceAbsent", "uniqueBlobs"},
    "PAUSE-SAFE-EXITS": {"testResultsSha256", "pausedRefundPassed", "terminalExitPassed", "principalPreserved"},
    "PROTECTED-DECISION-INPUTS": {"testResultsSha256", "closedInputEnumVerified", "forbiddenConceptMutationsRejected"},
}
for _artifact_keys in ARTIFACT_FACT_KEYS.values():
    _artifact_keys.add("sourceRecordSha256")
EXTERNAL_IDS = {
    "LEGAL-ENTITY", "AUTHORIZED-SIGNATORY", "ACTUAL-CONTACTS", "INSURANCE",
    "COUNSEL-SIGNOFF", "PRIVACY-SIGNOFF", "PARTNER-ACCEPTANCE",
    "ROLE-ASSIGNMENTS", "COMMERCIAL-AGREEMENT", "SIGNATURES",
    "SECURITY-POLICY-ACCEPTANCE", "INCIDENT-PLAN-ACCEPTANCE",
    "SUPPORT-SLA-SELECTION", "CHANGE-RACI-ACCEPTANCE",
}
MANDATORY_IDS = set(EVIDENCE_SPECS)
CONTACT_FUNCTION_ROLES = {
    "change": "change-approver",
    "commercial": "commercial-owner",
    "incident": "incident-commander",
    "privacy": "privacy-reviewer",
    "security": "security-contact",
    "support": "support-owner",
    "partner-escalation": "partner-authorized-signatory",
}
CONTACT_FUNCTION_CHANNEL_TYPES = {
    "change": {"ticket-queue", "secure-portal"},
    "commercial": {"email-alias", "secure-portal"},
    "incident": {"paging-route"},
    "partner-escalation": {"email-alias", "secure-portal"},
    "privacy": {"secure-portal"},
    "security": {"secure-portal"},
    "support": {"ticket-queue"},
}
OPERATIONAL_ACCEPTANCE_POLICIES = {
    "SECURITY-POLICY-ACCEPTANCE": {
        "schema": "security-policy-acceptance.schema.json",
        "recordType": "security-vulnerability-policy-acceptance",
        "role": "security-contact",
        "path": "pr10/partner-package/docs/SECURITY_AND_VULNERABILITY_REPORTING.md",
        "version": "1.0.0",
        "digestFact": "policySha256",
    },
    "INCIDENT-PLAN-ACCEPTANCE": {
        "schema": "incident-plan-acceptance.schema.json",
        "recordType": "incident-plan-acceptance",
        "role": "incident-commander",
        "path": "pr10/partner-package/docs/INCIDENT_RESPONSE_AND_ESCALATION.md",
        "version": "1.0.0",
        "digestFact": "planSha256",
    },
    "SUPPORT-SLA-SELECTION": {
        "schema": "support-sla-acceptance.schema.json",
        "recordType": "support-sla-selection",
        "role": "support-owner",
        "path": "pr10/partner-package/docs/SUPPORT_SLA_MAINTENANCE_DEPRECATION.md",
        "version": "1.0.0",
        "digestFact": "slaSha256",
    },
    "CHANGE-RACI-ACCEPTANCE": {
        "schema": "change-raci-acceptance.schema.json",
        "recordType": "change-raci-acceptance",
        "role": "change-approver",
        "path": "pr10/partner-package/docs/DEPLOYMENT_CHANGE_MANAGEMENT_RACI.md",
        "version": "1.0.0",
        "digestFact": "raciSha256",
    },
}


class Blocked(ValueError):
    pass


def require(condition: bool, message: str) -> None:
    if not condition:
        raise Blocked(message)


def canonical(value: object) -> bytes:
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


UNLINK_CONTENT_DOMAIN = b"vaultfire-unlinkability-content-v3\x00"
UNLINK_PAIR_DOMAIN = b"vaultfire-unlinkability-pair-v3\x00"
UNLINK_SELECTION_DOMAIN = b"vaultfire-unlinkability-selection-v1\x00"
UNLINK_OUTPUT_DOMAIN = b"vaultfire-unlinkability-output-v4\x00"
UNLINK_SAMPLES_PER_TEST = 400


def unlink_hash(domain: bytes, value: object) -> str:
    return hashlib.sha256(domain + canonical(value)).hexdigest()


def derive_unlink_side(side: object) -> dict:
    require(type(side) is dict and set(side) == {
        "contentId", "subjectCommitmentSha256", "partnerContextSha256",
        "chainId", "nonceSha256", "caseInputBase64", "caseInputSha256",
    }, "unlinkability challenge side fields must be exact")
    require(
        side["chainId"] in {"base", "ethereum", "solana"}
        and all(SHA256.fullmatch(side[key] or "") for key in (
            "subjectCommitmentSha256", "partnerContextSha256", "nonceSha256",
            "caseInputSha256",
        )),
        "unlinkability challenge side has malformed typed content",
    )
    try:
        case_input = base64.b64decode(side["caseInputBase64"], validate=True)
    except (ValueError, binascii.Error) as exc:
        raise Blocked("unlinkability case input encoding invalid") from exc
    require(
        case_input
        and hashlib.sha256(case_input).hexdigest() == side["caseInputSha256"],
        "unlinkability case input digest mismatch",
    )
    body = {key: side[key] for key in sorted(set(side) - {"contentId"})}
    require(
        side["contentId"] == "content:" + unlink_hash(UNLINK_CONTENT_DOMAIN, body),
        "unlinkability contentId is not deterministically content-derived",
    )
    return body


def derive_unlink_selection(rows: list[dict], seed: bytes) -> list[str]:
    groups = {test_id: {"linked": [], "unlinked": []} for test_id in (
        "privacy.commitment-reuse", "privacy.cross-partner-collusion",
        "privacy.metadata-timing-correlation",
    )}
    for row in rows:
        rank = hashlib.sha256(
            UNLINK_SELECTION_DOMAIN + seed + row["pairId"].encode()
        ).hexdigest()
        relationship = (
            "linked"
            if (
                row["left"]["subjectCommitmentSha256"],
                row["left"]["partnerContextSha256"],
                row["left"]["chainId"],
            )
            == (
                row["right"]["subjectCommitmentSha256"],
                row["right"]["partnerContextSha256"],
                row["right"]["chainId"],
            )
            else "unlinked"
        )
        groups[row["testId"]][relationship].append((rank, row["pairId"]))
    selected = []
    for test_id in sorted(groups):
        for relationship in ("linked", "unlinked"):
            require(
                len(groups[test_id][relationship]) >= UNLINK_SAMPLES_PER_TEST // 2,
                "unlinkability universe lacks mandatory per-test relationship coverage",
            )
            selected.extend(
                pair_id for _, pair_id
                in sorted(groups[test_id][relationship])[:UNLINK_SAMPLES_PER_TEST // 2]
            )
    return sorted(
        selected,
        key=lambda pair_id: hashlib.sha256(
            UNLINK_SELECTION_DOMAIN + seed + pair_id.encode()
        ).hexdigest(),
    )


def digest(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def parse_utc(value: object, label: str) -> datetime:
    require(isinstance(value, str) and UTC.fullmatch(value), f"{label} must be canonical RFC3339 UTC ending Z")
    try:
        parsed = datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
    except ValueError as exc:
        raise Blocked(f"{label} is not a real calendar timestamp") from exc
    return parsed


def unlinkability_upper_bound_bps(
    false_links: int, challenge_pairs: int, confidence_level_bps: int
) -> tuple[int, int]:
    require(
        type(false_links) is int and false_links >= 0
        and type(challenge_pairs) is int and challenge_pairs > 0
        and false_links <= challenge_pairs
        and type(confidence_level_bps) is int
        and 0 < confidence_level_bps < 10000,
        "unlinkability confidence inputs are invalid",
    )
    observed_bps = (false_links * 10000) // challenge_pairs
    # Do not round the empirical rate and margin separately.  A single,
    # high-precision ceiling over the complete bound is conservatively safe
    # at basis-point boundaries (for example 1/15000 at 95% is 101 bps).
    with localcontext() as context:
        context.prec = 80
        pairs = Decimal(challenge_pairs)
        alpha = Decimal(10000 - confidence_level_bps) / Decimal(10000)
        complete_bound = (
            Decimal(false_links) * Decimal(10000) / pairs
            + Decimal(10000)
            * ((Decimal(1) / alpha).ln() / (Decimal(2) * pairs)).sqrt()
        )
        upper_bps = int(
            complete_bound.to_integral_value(rounding=ROUND_CEILING)
        )
    return observed_bps, min(10000, upper_bps)


def safe_repo_file(path_text: object, label: str, root_prefix: str | None = None, suffix: str | None = None) -> Path:
    require(isinstance(path_text, str) and path_text, f"{label}: path required")
    pure = PurePosixPath(path_text)
    require(not pure.is_absolute() and "\\" not in path_text, f"{label}: path must be canonical POSIX repository-relative")
    require(all(part not in {"", ".", ".."} for part in pure.parts), f"{label}: path contains noncanonical traversal segments")
    require(pure.as_posix() == path_text, f"{label}: path is not normalized")
    if root_prefix is not None:
        require(path_text.startswith(root_prefix + "/"), f"{label}: path outside approved evidence root")
    if suffix is not None:
        require(pure.suffix == suffix, f"{label}: unapproved file type")
    path = REPOSITORY.joinpath(*pure.parts)
    require(path.is_file(), f"{label}: file does not exist")
    cursor = REPOSITORY
    for part in pure.parts:
        cursor = cursor / part
        require(not cursor.is_symlink(), f"{label}: symlinks are prohibited")
    require(path.resolve().is_relative_to(REPOSITORY.resolve()), f"{label}: path escapes repository")
    require(path.stat().st_nlink == 1, f"{label}: hardlinked evidence or implementation files are prohibited")
    return path


def require_finalized_generation_path(
    path: Path, label: str, *, directory: bool = False
) -> None:
    """Require the strongest enforceable local publication finalization.

    This checks owner, link count, object type, and absence of write bits.  It
    does not claim protection from the owning account or root; signed,
    candidate-bound content digests remain the authoritative mutation check.
    """
    metadata = path.lstat()
    required_type = stat.S_ISDIR if directory else stat.S_ISREG
    require(required_type(metadata.st_mode), f"{label}: wrong finalized object type")
    require(
        metadata.st_uid == os.geteuid(),
        f"{label}: finalized object ownership is not the checker account",
    )
    require(
        stat.S_IMODE(metadata.st_mode) & 0o222 == 0,
        f"{label}: finalized generation remains writable",
    )
    require(
        metadata.st_nlink == (2 if directory else 1),
        f"{label}: finalized object link count is unsafe",
    )


def expected_candidate_id(manifest: dict) -> str:
    release = manifest["releaseCandidate"]
    source_bindings = {
        key: value for key, value in release["canonicalBindings"].items()
        if key != "trustedIdentities"
    }
    payload = {
        "domain": "vaultfire-partner-candidate-freeze-v1",
        "canonicalArtifactDigests": source_bindings,
        "deploymentManifest": release["deploymentManifest"],
        "packageVersion": release["packageVersion"],
        "partnerOrganizationId": manifest["partnerOrganizationId"],
        "scope": manifest["scope"],
        "subjectOrganizationId": manifest["subjectOrganizationId"],
    }
    return "sha256:" + hashlib.sha256(canonical(payload)).hexdigest()


def expected_envelope_id(manifest: dict) -> str:
    release = manifest["releaseCandidate"]
    payload = {
        "domain": "vaultfire-partner-candidate-envelope-v1",
        "candidateId": release["candidateId"],
        "sourceCommit": release["sourceCommit"],
        "gitTree": release["gitTree"],
        "selectionCommit": release["selectionCommit"],
        "selectionTree": release["selectionTree"],
        "evidenceCommit": release["evidenceCommit"],
        "evidenceTree": release["evidenceTree"],
        "artifactManifest": release.get("artifactManifest"),
    }
    return "sha256:" + hashlib.sha256(canonical(payload)).hexdigest()


def git(*args: str) -> str:
    result = subprocess.run(["git", "-C", str(REPOSITORY), *args], text=True, capture_output=True, check=False)
    require(result.returncode == 0, f"Git verification failed: {' '.join(args)}")
    return result.stdout.strip()


def git_commit_exists(commit: str) -> bool:
    result = subprocess.run(
        ["git", "-C", str(REPOSITORY), "cat-file", "-e", f"{commit}^{{commit}}"],
        text=True,
        capture_output=True,
        check=False,
    )
    return result.returncode == 0


def git_bytes(commit: str, path_text: str) -> bytes:
    result = subprocess.run(
        ["git", "-C", str(REPOSITORY), "show", f"{commit}:{path_text}"],
        capture_output=True,
        check=False,
    )
    require(result.returncode == 0, f"{path_text}: not a tracked blob at candidate commit {commit}")
    return result.stdout


def git_blob_id(commit: str, path_text: str) -> str:
    result = subprocess.run(
        ["git", "-C", str(REPOSITORY), "rev-parse", f"{commit}:{path_text}"],
        text=True,
        capture_output=True,
        check=False,
    )
    value = result.stdout.strip()
    require(
        result.returncode == 0 and re.fullmatch(r"[0-9a-f]{40}", value or ""),
        f"{path_text}: tracked Git blob identity unavailable at {commit}",
    )
    return value


def require_tracked_exact(path_text: str, path: Path, commit: str, label: str) -> None:
    tracked = git_bytes(commit, path_text)
    require(tracked == path.read_bytes(), f"{label}: worktree bytes differ from tracked candidate blob")
    ignored = subprocess.run(
        ["git", "-C", str(REPOSITORY), "check-ignore", "-q", "--", path_text],
        check=False,
    )
    require(ignored.returncode != 0, f"{label}: ignored files are prohibited")


# Pure-Python Ed25519 verification (RFC 8032) to avoid optional dependencies.
_Q = 2**255 - 19
_L = 2**252 + 27742317777372353535851937790883648493
_D = (-121665 * pow(121666, _Q - 2, _Q)) % _Q
_I = pow(2, (_Q - 1) // 4, _Q)


def _xrecover(y: int) -> int:
    x = pow((y * y - 1) * pow(_D * y * y + 1, _Q - 2, _Q) % _Q, (_Q + 3) // 8, _Q)
    if (x * x - (y * y - 1) * pow(_D * y * y + 1, _Q - 2, _Q)) % _Q:
        x = x * _I % _Q
    return x


def _decode_point(data: bytes) -> tuple[int, int]:
    require(len(data) == 32, "Ed25519 point must be 32 bytes")
    y = int.from_bytes(data, "little") & ((1 << 255) - 1)
    require(y < _Q, "noncanonical Ed25519 point")
    x = _xrecover(y)
    require(not (x == 0 and (data[31] >> 7) == 1), "noncanonical Ed25519 x sign")
    if (x & 1) != (data[31] >> 7):
        x = _Q - x
    require((-x*x + y*y - 1 - _D*x*x*y*y) % _Q == 0, "invalid Ed25519 point")
    return x, y


def _add(p: tuple[int, int], q: tuple[int, int]) -> tuple[int, int]:
    x1, y1 = p; x2, y2 = q
    den = _D*x1*x2*y1*y2
    return ((x1*y2 + x2*y1) * pow(1 + den, _Q - 2, _Q) % _Q,
            (y1*y2 + x1*x2) * pow(1 - den, _Q - 2, _Q) % _Q)


def _mul(p: tuple[int, int], n: int) -> tuple[int, int]:
    out = (0, 1)
    while n:
        if n & 1:
            out = _add(out, p)
        p = _add(p, p); n >>= 1
    return out


_BY = 4 * pow(5, _Q - 2, _Q) % _Q
_BX = _xrecover(_BY)
if _BX & 1:
    _BX = _Q - _BX
_B = (_BX, _BY)


def verify_ed25519(public: bytes, signature: bytes, message: bytes) -> bool:
    try:
        if len(public) != 32 or len(signature) != 64:
            return False
        r_enc, s_enc = signature[:32], signature[32:]
        s = int.from_bytes(s_enc, "little")
        if s >= _L:
            return False
        a, r = _decode_point(public), _decode_point(r_enc)
        identity = (0, 1)
        if a == identity or r == identity:
            return False
        if _mul(a, _L) != identity or _mul(r, _L) != identity:
            return False
        h = int.from_bytes(hashlib.sha512(r_enc + public + message).digest(), "little") % _L
        return _mul(_B, s) == _add(r, _mul(a, h))
    except Blocked:
        return False


def validate_shape(manifest: dict) -> None:
    schema = load_json(SCHEMA_PATH)
    validate(manifest, schema)
    require(manifest["schemaVersion"] == "5.0.0", "organizational schema version drift")
    require(json_equal(manifest["commitments"], COMMITMENTS), "requirement #9/latest-principle commitments drift")
    require(json_equal(manifest["bondPurpose"], {
        "productClass": "flourishing-bonds",
        "bondTypes": ["AccountabilityBond", "PartnershipBond"],
        "supports": ["accountable-growth", "cooperation", "freedom"],
        "flourishingIsNeverAScoreEntitlementOrControlInput": True,
    }), "flourishing-bond purpose drift")
    policy = manifest["decisionInputPolicy"]
    require(json_equal(policy, {
        "protectedDecisions": PROTECTED,
        "prohibitedClasses": PROHIBITED,
        "hashedDerivedAndTransitiveFormsProhibited": True,
        "unknownOrOpaqueInputsProhibited": True,
        "observedInputClasses": policy["observedInputClasses"],
    }), "protected-decision input policy drift")
    allowed_inputs = {
        "allowed:bounded-time",
        "allowed:contract-state",
        "allowed:cryptographic-authorization",
        "allowed:explicit-participant-instruction",
        "allowed:objective-onchain-fact",
    }
    for item in policy["observedInputClasses"]:
        require(type(item) is str and item in allowed_inputs, "unknown, encoded, opaque, hashed, derived, or transitive decision input class")
    roles = manifest["roles"]
    require(len(roles) == len(ROLE_IDS) and {r["roleId"] for r in roles} == ROLE_IDS, "role IDs missing or duplicated")
    require(all(r["evidenceId"] == ROLE_EVIDENCE[r["roleId"]] for r in roles), "role-to-evidence link drift")
    blockers = manifest["blockers"]
    require(len(blockers) == len(MANDATORY_IDS) and {b["id"] for b in blockers} == MANDATORY_IDS, "mandatory blockers missing, duplicated, or invented")
    require(all(b["externalHumanAction"] == (b["id"] in EXTERNAL_IDS) for b in blockers), "external-human blocker classification drift")


def validate_blocked(manifest: dict) -> None:
    require(manifest["status"] == "blocked" and manifest["partnerReady"] is False, "blocked template state drift")
    release = manifest["releaseCandidate"]
    require(all(value is None for value in release.values()), "blocked template cannot invent a release candidate")
    require(manifest["subjectOrganizationId"] is None and manifest["partnerOrganizationId"] is None, "blocked template cannot invent organizations")
    require(manifest["scope"]["selectedModule"] is None and manifest["scope"]["selectedActionClass"] is None and manifest["scope"]["selectedRouteId"] is None and manifest["scope"]["deniedModules"] == [], "blocked template cannot select activation scope")
    require(manifest["evidence"] == [], "blocked template cannot contain unreviewed evidence")
    require(all(row["status"] == "open" for row in manifest["blockers"]), "blocked template must leave every blocker open")
    require(all(row["identityId"] is None and row["contactChannelId"] is None for row in manifest["roles"]), "blocked template cannot invent people or contacts")
    blocked_attestation = manifest["attestation"]
    require(
        all(
            value is None
            for key, value in blocked_attestation.items()
            if key != "postCommitSignatures"
        )
        and blocked_attestation["postCommitSignatures"] == [],
        "blocked template cannot invent approvals or signatures",
    )


def git_parents(commit: str) -> list[str]:
    parts = git("rev-list", "--parents", "-n", "1", commit).split()
    require(parts and parts[0] == commit, "Git parent lookup mismatch")
    return parts[1:]


def validate_staged_git_flow(
    repository: Path,
    source_commit: str,
    selection_commit: str,
    evidence_commit: str,
    envelope_path: Path,
) -> tuple[str, str, str, str]:
    def run_git(*args: str, binary: bool = False):
        result = subprocess.run(
            ["git", "-C", str(repository), *args],
            capture_output=True, text=not binary, check=False,
        )
        require(result.returncode == 0, f"staged Git verification failed: {' '.join(args)}")
        return result.stdout if binary else result.stdout.strip()

    source_parents = run_git("rev-list", "--parents", "-n", "1", source_commit).split()
    selection_parents = run_git("rev-list", "--parents", "-n", "1", selection_commit).split()
    evidence_parents = run_git("rev-list", "--parents", "-n", "1", evidence_commit).split()
    head = run_git("rev-parse", "HEAD")
    attestation_parents = run_git("rev-list", "--parents", "-n", "1", head).split()
    require(source_parents and source_parents[0] == source_commit, "source commit lookup mismatch")
    require(
        selection_parents == [selection_commit, source_commit],
        "selectionCommit must be the single direct child of sourceCommit",
    )
    require(
        evidence_parents == [evidence_commit, selection_commit],
        "execution evidenceCommit must be the single direct child of selectionCommit",
    )
    require(
        attestation_parents == [head, evidence_commit],
        "attestation HEAD must be the single direct child of evidenceCommit",
    )
    try:
        relative = envelope_path.resolve().relative_to(repository.resolve()).as_posix()
    except ValueError as exc:
        raise Blocked("post-commit envelope must be inside staged repository") from exc
    require(relative == POST_COMMIT_ENVELOPE_PATH, "post-commit envelope path mismatch")
    selection_changes = run_git("diff", "--name-only", source_commit, selection_commit).splitlines()
    require(
        selection_changes
        and all(
            path.startswith("pr10/partner-package/evidence/organizational/privacy-inputs/")
            for path in selection_changes
        )
        and POST_COMMIT_ENVELOPE_PATH not in selection_changes,
        "selection commit may contain only beacon, frozen universe, and deterministic selection inputs",
    )
    evidence_changes = run_git("diff", "--name-only", selection_commit, evidence_commit).splitlines()
    require(
        evidence_changes
        and all(
            path.startswith("pr10/partner-package/evidence/organizational/")
            or path == "pr10/partner-package/config/trusted-identities.json"
            for path in evidence_changes
        )
        and POST_COMMIT_ENVELOPE_PATH not in evidence_changes,
        "execution evidence commit may contain only evidence/trust blobs and never the post-commit envelope",
    )
    require(
        run_git("diff", "--name-only", evidence_commit, head).splitlines()
        == [POST_COMMIT_ENVELOPE_PATH],
        "phase-three commit may add only the post-commit envelope",
    )
    tracked = run_git("show", f"{head}:{relative}", binary=True)
    require(tracked == envelope_path.read_bytes(), "post-commit envelope differs from tracked HEAD blob")
    require(
        run_git("status", "--porcelain", "--untracked-files=all") == "",
        "staged repository worktree must be clean",
    )
    return (
        head,
        run_git("show", "-s", "--format=%T", selection_commit),
        run_git("show", "-s", "--format=%T", evidence_commit),
        run_git("show", "-s", "--format=%T", head),
    )


def validate_candidate(
    manifest: dict, scope_hash: str, as_of: datetime, manifest_path: Path
) -> tuple[str, str, dict, dict, dict]:
    release = manifest["releaseCandidate"]
    created = parse_utc(release["createdAtUtc"], "releaseCandidate.createdAtUtc")
    require(created <= as_of, "candidate creation must not follow readiness asOfUtc")
    require(as_of - created <= timedelta(days=30), "candidate is stale")
    commit = release["sourceCommit"]
    require(git_commit_exists(commit), "sourceCommit does not exist as a Git commit")
    require(release["gitTree"] == git("show", "-s", "--format=%T", commit), "gitTree does not match sourceCommit")
    evidence_commit = release["evidenceCommit"]
    selection_commit = release["selectionCommit"]
    require(git_commit_exists(selection_commit), "selectionCommit does not exist as a Git commit")
    require(release["selectionTree"] == git("show", "-s", "--format=%T", selection_commit), "selectionTree does not match selectionCommit")
    require(git_commit_exists(evidence_commit), "evidenceCommit does not exist as a Git commit")
    require(release["evidenceTree"] == git("show", "-s", "--format=%T", evidence_commit), "evidenceTree does not match evidenceCommit")
    validate_staged_git_flow(REPOSITORY, commit, selection_commit, evidence_commit, manifest_path)
    require(
        git_parents(selection_commit) == [commit],
        "selectionCommit must be the single direct child of sourceCommit",
    )
    require(
        git_parents(evidence_commit) == [selection_commit],
        "evidenceCommit must be the single direct child of selectionCommit",
    )
    attestation_commit = git("rev-parse", "HEAD")
    require(
        git_parents(attestation_commit) == [evidence_commit],
        "attestation HEAD must be the single direct child of evidenceCommit",
    )
    try:
        manifest_relative = manifest_path.resolve().relative_to(REPOSITORY.resolve()).as_posix()
    except ValueError as exc:
        raise Blocked("ready attestation envelope must be inside the repository") from exc
    require(
        manifest_relative == POST_COMMIT_ENVELOPE_PATH,
        "ready manifest must be the dedicated post-commit attestation envelope",
    )
    require_tracked_exact(
        manifest_relative, manifest_path, attestation_commit, "post-commit attestation envelope"
    )
    registry_source_commit = load_json(SCOPE_REGISTRY_PATH)["sourceCommit"]
    registry_ancestor = subprocess.run(
        ["git", "-C", str(REPOSITORY), "merge-base", "--is-ancestor", registry_source_commit, commit],
        check=False,
    )
    require(
        registry_ancestor.returncode == 0,
        "scope-registry upstream source commit must be an ancestor of candidate sourceCommit",
    )
    evidence_changes = git("diff", "--name-only", commit, evidence_commit).splitlines()
    require(
        all(
            path.startswith("pr10/partner-package/evidence/organizational/")
            or path == "pr10/partner-package/config/trusted-identities.json"
            for path in evidence_changes
        ),
        "evidenceCommit may change only organizational evidence and the externally attested identity registry",
    )
    require(
        git("diff", "--name-only", evidence_commit, attestation_commit).splitlines()
        == [POST_COMMIT_ENVELOPE_PATH],
        "attestation commit may add only the dedicated post-commit envelope",
    )
    require(git("status", "--porcelain", "--untracked-files=all") == "", "worktree is not clean/frozen for exact-commit readiness")

    artifact_binding = release["artifactManifest"]
    require(
        artifact_binding["path"] == ARTIFACT_MANIFEST_PATH,
        "artifact manifest path drift",
    )
    artifact_path = safe_repo_file(
        artifact_binding["path"], "artifact manifest", suffix=".json"
    )
    require_tracked_exact(
        artifact_binding["path"], artifact_path, evidence_commit, "artifact manifest"
    )
    require(
        artifact_binding["sha256"] == digest(artifact_path),
        "artifact manifest digest mismatch",
    )
    artifact_manifest = load_json(artifact_path)
    validate(
        artifact_manifest,
        load_json(EVIDENCE_SCHEMA_DIR / "artifact-manifest.schema.json"),
    )
    require(
        set(artifact_manifest)
        == {"schemaVersion", "candidateId", "sourceCommit", "gitTree", "entries"},
        "artifact manifest fields must be exact",
    )
    require(
        artifact_manifest["schemaVersion"] == "1.0.0"
        and artifact_manifest["candidateId"] == release["candidateId"]
        and artifact_manifest["sourceCommit"] == commit
        and artifact_manifest["gitTree"] == release["gitTree"],
        "artifact manifest candidate/source binding mismatch",
    )
    require(
        type(artifact_manifest["entries"]) is list
        and artifact_manifest["entries"],
        "artifact manifest requires nonempty typed entries",
    )
    for entry in artifact_manifest["entries"]:
        require(
            set(entry) == {"path", "sha256", "kind"}
            and entry["kind"]
            in {
                "evidence-claim", "objective-artifact", "supporting-artifact",
                "resolved-artifact", "trust-registry",
            }
            and SHA256.fullmatch(entry["sha256"] or ""),
            "artifact manifest entry fields/type invalid",
        )
        path = safe_repo_file(entry["path"], "artifact manifest entry")
        require_tracked_exact(
            entry["path"], path, evidence_commit, "artifact manifest entry"
        )
        require(digest(path) == entry["sha256"], "artifact manifest entry digest mismatch")
    require(
        len({entry["path"] for entry in artifact_manifest["entries"]})
        == len(artifact_manifest["entries"])
        and len({entry["sha256"] for entry in artifact_manifest["entries"]})
        == len(artifact_manifest["entries"]),
        "artifact manifest paths and digests must be unique",
    )

    dep = release["deploymentManifest"]
    require(dep["path"] == DEPLOYMENT_PATH, "deployment manifest path drift")
    dep_path = safe_repo_file(dep["path"], "deployment manifest", suffix=".json")
    require_tracked_exact(dep["path"], dep_path, commit, "deployment manifest")
    require(dep["sha256"] == digest(dep_path), "deployment manifest digest mismatch")
    deployment = load_json(dep_path)
    require(deployment.get("status") == "activated", "canonical deployment manifest is not activated")
    selected_module = manifest["scope"]["selectedModule"]
    require(selected_module in deployment.get("scope", {}).get("enabled", []), "deployment scope does not enable selected module")
    require(selected_module in {row.get("contract") for row in deployment.get("deployments", [])}, "deployment inventory lacks selected contract")

    bindings = release["canonicalBindings"]
    require(set(bindings) == set(CANONICAL_PATHS), "canonical binding set drift")
    for key, expected_path in CANONICAL_PATHS.items():
        binding = bindings[key]
        require(binding["path"] == expected_path, f"{key}: canonical path mismatch")
        path = safe_repo_file(binding["path"], key, suffix=".json")
        blob_commit = evidence_commit if key == "trustedIdentities" else commit
        require_tracked_exact(binding["path"], path, blob_commit, key)
        require(binding["sha256"] == digest(path), f"{key}: canonical hash mismatch")
    require(release["candidateId"] == expected_candidate_id(manifest), "release candidate digest mismatch")
    require(release["envelopeId"] == expected_envelope_id(manifest), "release candidate envelope digest mismatch")

    operations = load_json(REPOSITORY / CANONICAL_PATHS["operationsStatus"])
    require(operations.get("scopeSha256") == scope_hash, "canonical operations scope mismatch")
    require(operations.get("selectedModule") == manifest["scope"]["selectedModule"], "canonical operations module mismatch")
    require(operations.get("selectedRouteId") == manifest["scope"]["selectedRouteId"], "canonical operations route mismatch")
    require(operations.get("selectedActionClass") == manifest["scope"]["selectedActionClass"], "canonical operations action mismatch")
    require(all(operations.get(key) is True for key in ("sourceComplete", "evidenceComplete", "deploymentAuthorized", "deployed", "activated")), "canonical operations stages are incomplete")
    require(all(operations.get(key, {}).get("recorded") is True for key in ("humanAuthorization", "deploymentAuthorization", "activationAuthorization")), "canonical operations authorizations are not recorded")
    require(not any(x.get("status") == "open" for x in operations.get("blockers", []) + operations.get("externalBlockers", [])), "canonical operations has open blockers")
    op_time = parse_utc(operations.get("asOfUtc"), "canonical operations asOfUtc")
    require(created <= op_time <= as_of and as_of - op_time <= timedelta(hours=24), "canonical operations status is stale or causally invalid")

    ledger = load_json(REPOSITORY / CANONICAL_PATHS["canonicalLedger"])
    require(ledger.get("scopeSha256") == scope_hash, "canonical ledger scope mismatch")
    require(ledger.get("closureStatus") == "closed" and ledger.get("openItemCount") == 0, "canonical ledger is not closed for candidate scope")

    rollout = load_json(ROLLOUT_PLAN_PATH)
    validate(rollout, load_json(ROLLOUT_PLAN_SCHEMA_PATH))
    require(rollout["status"] == "candidate-bound-approved", "rollout plan is not candidate-bound-approved")
    require(rollout["scopeSha256"] == scope_hash, "rollout plan scope mismatch")
    require(rollout["scopeRegistrySha256"] == digest(SCOPE_REGISTRY_PATH), "rollout plan scope-registry mismatch")
    require(len(rollout["stages"]) == 1, "exactly one rollout stage required")
    stage = rollout["stages"][0]
    scope_registry = load_json(SCOPE_REGISTRY_PATH)
    route_row = next(
        row for row in scope_registry["routes"]
        if row["routeId"] == manifest["scope"]["selectedRouteId"]
    )
    require(
        stage["module"] == manifest["scope"]["selectedModule"]
        and stage["routeId"] == manifest["scope"]["selectedRouteId"]
        and stage["actionClass"] == manifest["scope"]["selectedActionClass"]
        and stage["stageId"] == route_row["rolloutStageId"]
        and stage["requiredDeploymentContract"] == route_row["requiredDeploymentContract"]
        and route_row["requiredDeploymentContract"] == manifest["scope"]["selectedModule"],
        "rollout stage does not exactly match selected scope",
    )
    return release["envelopeId"], release["candidateId"], deployment, operations, artifact_manifest


def load_trust(as_of: datetime | None = None) -> tuple[dict[str, dict], dict]:
    policy = load_json(EXPECTED_EXTERNAL_TRUST_POLICY)
    validate(policy, load_json(TRUST_POLICY_SCHEMA_PATH))
    require(
        policy["status"] == "pinned-external-authority",
        "positive readiness structurally disabled: no independently pinned external authority",
    )
    require(
        policy["expectedRootPath"] and policy["expectedRootId"]
        and policy["expectedRootSha256"]
        and policy["expectedAdministratorId"],
        "pinned external authority policy is incomplete",
    )
    trust = load_json(TRUST_PATH)
    validate(trust, load_json(TRUST_SCHEMA_PATH))
    require(trust["status"] == "external-human-attested", "trusted identity registry lacks external human attestation")
    require(trust["subjectOrganizationId"] != trust["partnerOrganizationId"], "subject and partner organizations must be distinct")
    root_text = os.environ.get("VAULTFIRE_EXTERNAL_TRUST_ROOT")
    require(root_text, "external trust root input location is required")
    root_path = Path(root_text).resolve()
    require(str(root_path) == policy["expectedRootPath"], "external trust root path differs from tracked pinned policy")
    require(root_path.is_file(), "external trust root file is absent")
    require(not root_path.is_relative_to(REPOSITORY.resolve()), "external trust root must be outside the candidate repository")
    require(digest(root_path) == policy["expectedRootSha256"], "external trust root digest does not match tracked pinned policy")
    root = load_json(root_path)
    require(set(root) == {"schemaVersion", "rootId", "keyType", "publicKeyBase64", "authorityClass", "administratorId"}, "external trust root fields must be exact")
    require(root["schemaVersion"] == "1.0.0" and root["keyType"] == "Ed25519" and root["authorityClass"] == "external-human-identity-authority", "external trust root policy mismatch")
    try:
        root_public = base64.b64decode(root["publicKeyBase64"], validate=True)
    except (ValueError, binascii.Error) as exc:
        raise Blocked("invalid external trust-root public key encoding") from exc
    require(len(root_public) == 32, "external trust-root key must be 32 bytes")
    require(root["rootId"] == "trust-root:" + hashlib.sha256(root_public).hexdigest(), "external trust-root ID mismatch")
    require(root["rootId"] == policy["expectedRootId"], "external trust-root ID differs from tracked pinned policy")
    require(trust["externalTrustRootId"] == root["rootId"], "registry is not bound to pinned external trust root")
    legal_policy = load_json(LEGAL_REGISTRY_TRUST_POLICY)
    validate(legal_policy, load_json(LEGAL_REGISTRY_TRUST_POLICY_SCHEMA))
    require(
        legal_policy["status"] == "pinned-external-authority",
        "positive readiness structurally disabled: no independently pinned legal-registry authority",
    )
    require(
        legal_policy["expectedRootPath"] and legal_policy["expectedRootId"]
        and legal_policy["expectedRootSha256"] and legal_policy["expectedIssuerId"]
        and legal_policy["expectedAdministratorId"],
        "pinned legal-registry authority policy is incomplete",
    )
    legal_root_text = os.environ.get("VAULTFIRE_LEGAL_REGISTRY_ROOT")
    require(legal_root_text, "external legal-registry root input location is required")
    legal_root_path = Path(legal_root_text).resolve()
    require(
        str(legal_root_path) == legal_policy["expectedRootPath"],
        "legal-registry root path differs from tracked pinned policy",
    )
    require(legal_root_path.is_file(), "external legal-registry root file is absent")
    require(
        not legal_root_path.is_relative_to(REPOSITORY.resolve()),
        "external legal-registry root must be outside the candidate repository",
    )
    require(
        digest(legal_root_path) == legal_policy["expectedRootSha256"],
        "external legal-registry root digest does not match tracked pinned policy",
    )
    legal_root = load_json(legal_root_path)
    require(
        set(legal_root) == {
            "schemaVersion", "rootId", "keyType", "publicKeyBase64",
            "authorityClass", "administratorId", "issuerId", "issuerName",
            "issuerClass",
        },
        "external legal-registry root fields must be exact",
    )
    require(
        legal_root["schemaVersion"] == "1.0.0"
        and legal_root["keyType"] == "Ed25519"
        and legal_root["authorityClass"] == "external-legal-entity-registry-authority"
        and legal_root["issuerClass"] in {
            "government-registry", "regulated-corporate-registry-provider",
        },
        "external legal-registry root policy mismatch",
    )
    require_meaningful(legal_root["issuerName"], "legal-registry root issuer")
    try:
        legal_root_public = base64.b64decode(legal_root["publicKeyBase64"], validate=True)
    except (ValueError, binascii.Error) as exc:
        raise Blocked("invalid legal-registry root public key encoding") from exc
    require(len(legal_root_public) == 32, "legal-registry root key must be 32 bytes")
    require(
        legal_root["rootId"]
        == "legal-registry-root:" + hashlib.sha256(legal_root_public).hexdigest(),
        "legal-registry root ID mismatch",
    )
    require(
        legal_root["rootId"] == legal_policy["expectedRootId"]
        and legal_root["issuerId"] == legal_policy["expectedIssuerId"]
        and legal_root["administratorId"]
        == legal_policy["expectedAdministratorId"],
        "legal-registry root or issuer differs from tracked pinned policy",
    )
    require(
        legal_root_path != root_path
        and legal_policy["expectedRootSha256"] != policy["expectedRootSha256"]
        and legal_root["rootId"] != root["rootId"]
        and legal_root["authorityClass"] != root["authorityClass"]
        and legal_root["administratorId"] != root["administratorId"]
        and root["administratorId"] == policy["expectedAdministratorId"]
        and legal_root_public != root_public,
        "human-identity and legal-registry trust domains require distinct "
        "paths, digests, authority IDs/classes/administrators, and Ed25519 public keys",
    )
    registry_attestation = trust["registryAttestation"]
    unsigned_registry = {key: value for key, value in trust.items() if key != "registryAttestation"}
    registry_payload = canonical(unsigned_registry)
    require(registry_attestation["registryPayloadSha256"] == hashlib.sha256(registry_payload).hexdigest(), "registry attestation payload mismatch")
    try:
        registry_signature = base64.b64decode(registry_attestation["signatureBase64"], validate=True)
    except (ValueError, binascii.Error) as exc:
        raise Blocked("invalid registry attestation signature encoding") from exc
    require(verify_ed25519(root_public, registry_signature, registry_payload), "external registry attestation signature invalid")
    issued = parse_utc(registry_attestation["issuedAtUtc"], "registryAttestation.issuedAtUtc")
    expires = parse_utc(registry_attestation["expiresAtUtc"], "registryAttestation.expiresAtUtc")
    if as_of is not None:
        require(issued <= as_of < expires and as_of - issued <= timedelta(days=30), "external registry attestation stale or not yet valid")
    identities = trust["identities"]
    legal_entities = trust["legalEntities"]
    require(
        len(legal_entities) == 2
        and {row["organizationId"] for row in legal_entities}
        == {trust["subjectOrganizationId"], trust["partnerOrganizationId"]},
        "trusted registry requires one independent legal-entity verification per contracting organization",
    )
    require(
        len({normalize_legal_name(row["legalName"]) for row in legal_entities}) == 2
        and len({(row["jurisdiction"].casefold(), row["registrationReference"].casefold()) for row in legal_entities}) == 2,
        "legal entities must have distinct normalized names and registration identities",
    )
    legal_response_paths: set[Path] = set()
    legal_response_digests: set[str] = set()
    raw_response_paths: set[Path] = set()
    raw_response_digests: set[str] = set()
    for entity in legal_entities:
        evidence_path = Path(entity["verificationEvidencePath"]).resolve()
        require(evidence_path.is_file(), "independent legal-entity verification evidence is absent")
        require(
            not evidence_path.is_relative_to(REPOSITORY.resolve()),
            "independent legal-entity verification must be outside the candidate repository",
        )
        require(
            digest(evidence_path) == entity["verificationEvidenceSha256"],
            "independent legal-entity verification digest mismatch",
        )
        verification = load_json(evidence_path)
        validate(
            verification,
            load_json(EVIDENCE_SCHEMA_DIR / "legal-entity-verification.schema.json"),
        )
        require(
            verification["authorityRootId"] == legal_root["rootId"]
            and verification["issuerId"] == legal_root["issuerId"]
            and verification["issuerClass"] == legal_root["issuerClass"]
            and verification["issuerName"] == legal_root["issuerName"]
            and verification["organizationId"] == entity["organizationId"]
            and normalize_legal_name(verification["legalName"]) == normalize_legal_name(entity["legalName"])
            and verification["jurisdiction"] == entity["jurisdiction"]
            and verification["registrationReference"] == entity["registrationReference"]
            and verification["entityStatus"] == "active",
            "independent legal-entity verification does not match trusted registry",
        )
        require_meaningful(verification["issuerName"], "legal-entity registry issuer")
        unsigned = {
            key: value for key, value in verification.items()
            if key not in {"signedPayloadSha256", "signatureBase64"}
        }
        payload = canonical({
            "domain": "vaultfire-independent-legal-entity-verification-v1",
            "record": unsigned,
        })
        require(
            verification["signedPayloadSha256"] == hashlib.sha256(payload).hexdigest(),
            "legal-entity verification signed payload mismatch",
        )
        try:
            signature = base64.b64decode(verification["signatureBase64"], validate=True)
        except (ValueError, binascii.Error) as exc:
            raise Blocked("invalid legal-entity verification signature encoding") from exc
        require(
            verify_ed25519(legal_root_public, signature, payload),
            "independent legal-entity verification signature invalid",
        )
        verified_at = parse_utc(verification["verifiedAtUtc"], "legalEntity.verifiedAtUtc")
        entity_expires = parse_utc(verification["expiresAtUtc"], "legalEntity.expiresAtUtc")
        if as_of is not None:
            require(
                verified_at <= as_of < entity_expires
                and as_of - verified_at <= timedelta(days=30),
                "independent legal-entity verification is stale or not yet valid",
            )
        response_path = Path(verification["registryResponsePath"]).resolve()
        require(response_path.is_file(), "legal-registry response evidence is absent")
        require(
            not response_path.is_relative_to(REPOSITORY.resolve())
            and response_path != evidence_path,
            "legal-registry response must be a distinct external artifact",
        )
        require(
            digest(response_path) == verification["registryResponseSha256"],
            "legal-registry response digest mismatch",
        )
        response = load_json(response_path)
        validate(
            response,
            load_json(EVIDENCE_SCHEMA_DIR / "legal-entity-registry-response.schema.json"),
        )
        require(
            response["authorityRootId"] == legal_root["rootId"]
            and response["issuerId"] == legal_root["issuerId"]
            and response["issuerClass"] == legal_root["issuerClass"]
            and response["issuerName"] == legal_root["issuerName"]
            and response["organizationId"] == entity["organizationId"]
            and normalize_legal_name(response["legalName"])
            == normalize_legal_name(entity["legalName"])
            and response["jurisdiction"] == entity["jurisdiction"]
            and response["registrationReference"] == entity["registrationReference"]
            and response["entityStatus"] == "active",
            "legal-registry response semantics do not match the exact contracting entity",
        )
        require_meaningful(response["queryReference"], "legal-registry query reference")
        raw_response_path = Path(response["rawResponsePath"]).resolve()
        require(
            raw_response_path.is_file()
            and not raw_response_path.is_relative_to(REPOSITORY.resolve())
            and raw_response_path not in {evidence_path, response_path},
            "raw legal-registry response must be a distinct external artifact",
        )
        require(
            digest(raw_response_path) == response["rawResponseSha256"]
            == response["responsePayloadSha256"],
            "raw legal-registry response digest mismatch",
        )
        raw_response = load_json(raw_response_path)
        validate(
            raw_response,
            load_json(
                EVIDENCE_SCHEMA_DIR
                / "legal-entity-raw-registry-response.schema.json"
            ),
        )
        require(
            raw_response["issuerId"] == response["issuerId"]
            and raw_response["issuerClass"] == response["issuerClass"]
            and raw_response["issuerName"] == response["issuerName"]
            and raw_response["queryReference"] == response["queryReference"]
            and raw_response["organizationId"] == response["organizationId"]
            and normalize_legal_name(raw_response["legalName"])
            == normalize_legal_name(response["legalName"])
            and raw_response["jurisdiction"] == response["jurisdiction"]
            and raw_response["registrationReference"]
            == response["registrationReference"]
            and raw_response["entityStatus"] == "active"
            and raw_response["issuedAtUtc"] == response["issuedAtUtc"],
            "raw legal-registry response does not match signed normalized response",
        )
        expected_response_id = "legal-registry-response:" + hashlib.sha256(
            canonical(
                {
                    "domain": "vaultfire-legal-registry-response-id-v1",
                    "issuerId": response["issuerId"],
                    "queryReference": response["queryReference"],
                    "rawResponseSha256": response["rawResponseSha256"],
                }
            )
        ).hexdigest()
        require(
            response["responseId"] == expected_response_id,
            "legal-registry response ID is not derived from issuer, query, and raw bytes",
        )
        require(
            response_path not in legal_response_paths
            and verification["registryResponseSha256"] not in legal_response_digests
            and raw_response_path not in raw_response_paths
            and response["rawResponseSha256"] not in raw_response_digests,
            "legal-registry normalized and raw response artifacts must be unique",
        )
        legal_response_paths.add(response_path)
        legal_response_digests.add(verification["registryResponseSha256"])
        raw_response_paths.add(raw_response_path)
        raw_response_digests.add(response["rawResponseSha256"])
        response_unsigned = {
            key: value for key, value in response.items()
            if key not in {"signedPayloadSha256", "signatureBase64"}
        }
        response_payload = canonical({
            "domain": "vaultfire-legal-entity-registry-response-v1",
            "record": response_unsigned,
        })
        require(
            response["signedPayloadSha256"]
            == hashlib.sha256(response_payload).hexdigest(),
            "legal-registry response signed payload mismatch",
        )
        try:
            response_signature = base64.b64decode(
                response["signatureBase64"], validate=True
            )
        except (ValueError, binascii.Error) as exc:
            raise Blocked("invalid legal-registry response signature encoding") from exc
        require(
            verify_ed25519(legal_root_public, response_signature, response_payload),
            "legal-registry response signature invalid",
        )
        response_issued = parse_utc(
            response["issuedAtUtc"], "legalRegistryResponse.issuedAtUtc"
        )
        response_observed = parse_utc(
            response["observedAtUtc"], "legalRegistryResponse.observedAtUtc"
        )
        response_expires = parse_utc(
            response["expiresAtUtc"], "legalRegistryResponse.expiresAtUtc"
        )
        require(
            response_issued <= response_observed <= verified_at < entity_expires
            and response_expires == entity_expires,
            "legal-registry response and verification timestamps are inconsistent",
        )
        if as_of is not None:
            require(
                response_observed <= as_of < response_expires
                and as_of - response_observed <= timedelta(days=30),
                "legal-registry response is stale or not yet valid",
            )
    require(len({x["identityId"] for x in identities}) == len(identities), "duplicate trusted identity")
    result = {}
    for item in identities:
        try:
            public = base64.b64decode(item["publicKeyBase64"], validate=True)
        except (ValueError, binascii.Error) as exc:
            raise Blocked("invalid trusted Ed25519 public key encoding") from exc
        require(len(public) == 32, "trusted Ed25519 key must be 32 bytes")
        require(item["identityId"] == "identity:" + hashlib.sha256(public).hexdigest(), "identityId does not match public key")
        ownership_unsigned = {
            key: value for key, value in item.items()
            if key not in {"keyOwnershipPayloadSha256", "keyOwnershipSignatureBase64"}
        }
        ownership_payload = canonical({
            "context": "vaultfire-partner-readiness-key-ownership-v1",
            "identity": ownership_unsigned,
        })
        require(
            item["keyOwnershipPayloadSha256"] == hashlib.sha256(ownership_payload).hexdigest(),
            "key-ownership payload digest mismatch",
        )
        try:
            ownership_signature = base64.b64decode(
                item["keyOwnershipSignatureBase64"], validate=True
            )
        except (ValueError, binascii.Error) as exc:
            raise Blocked("invalid key-ownership signature encoding") from exc
        require(
            verify_ed25519(public, ownership_signature, ownership_payload),
            "identity key-ownership proof invalid",
        )
        if item["identityClass"] == "partner-human":
            require(item["organizationId"] == trust["partnerOrganizationId"], "partner identity organization mismatch")
            require(item["allowedRoles"] == ["partner-authorized-signatory"], "partner identity may hold only partner-authorized-signatory")
            require(item["membershipEvidenceId"] == "PARTNER-ACCEPTANCE" and item["authorityEvidenceId"] == "PARTNER-ACCEPTANCE", "partner membership/authority evidence mismatch")
        else:
            require(item["organizationId"] == trust["subjectOrganizationId"], "internal identity organization mismatch")
            require("partner-authorized-signatory" not in item["allowedRoles"], "internal identity cannot hold a partner role")
            require(item["membershipEvidenceId"] == "ROLE-ASSIGNMENTS", "internal membership evidence mismatch")
            require(
                all(item["authorityEvidenceId"] == ROLE_EVIDENCE[role] for role in item["allowedRoles"]),
                "internal role authority evidence mismatch",
            )
        require(item["keyOwnershipEvidenceId"] == "SIGNATURES", "exact key-ownership evidence required")
        result[item["identityId"]] = {**item, "_public": public}
    return result, trust


def validate_scope(manifest: dict) -> str:
    scope = manifest["scope"]
    open_spec_path = REPOSITORY / CANONICAL_PATHS["openSpec"]
    route_inventory_path = REPOSITORY / CANONICAL_PATHS["generatedRouteInventory"]
    deployment_path = REPOSITORY / DEPLOYMENT_PATH
    spec_data = load_json(open_spec_path)
    route_inventory = load_json(route_inventory_path)
    deployment = load_json(deployment_path)
    modules_by_name = {x["module"]: x for x in spec_data["modules"]}
    modules = set(modules_by_name)
    registry = load_json(SCOPE_REGISTRY_PATH)
    validate(registry, load_json(SCOPE_REGISTRY_SCHEMA_PATH))
    require(registry["status"] == "candidate-bound-approved", "canonical pilot scope registry is not approved")
    require(registry["network"] == scope["network"] and registry["chainId"] == scope["chainId"], "scope registry chain mismatch")
    require(git_commit_exists(registry["sourceCommit"]), "scope registry upstream source commit does not exist")
    for path_text, path in (
        (CANONICAL_PATHS["openSpec"], open_spec_path),
        (CANONICAL_PATHS["generatedRouteInventory"], route_inventory_path),
        (DEPLOYMENT_PATH, deployment_path),
    ):
        require_tracked_exact(path_text, path, registry["sourceCommit"], "scope-registry upstream input")
    require(registry["openSpecSha256"] == digest(open_spec_path), "scope registry open-spec derivation mismatch")
    require(registry["generatedRouteInventorySha256"] == digest(route_inventory_path), "scope registry route-inventory derivation mismatch")
    require(registry["deploymentManifestSha256"] == digest(deployment_path), "scope registry deployment-manifest derivation mismatch")
    selected = scope["selectedModule"]
    require(selected in modules, "selected module is not in canonical open spec")
    require(scope["selectedActionClass"] in ACTION_CLASSES, "exact single action class required")
    route = scope["selectedRouteId"]
    matches = [
        row for row in registry["routes"]
        if row["routeId"] == route
        and row["module"] == selected
        and row["actionClass"] == scope["selectedActionClass"]
    ]
    require(len(matches) == 1, "selected module/route/action is not an exact canonical allowlisted combination")
    route_row = matches[0]
    module_row = modules_by_name[selected]
    inventory_matches = [
        row for row in route_inventory["routes"]
        if row["id"] == route_row["generatedRouteId"]
        and row["method"] == route_row["routeMethod"]
        and row["path"] == route_row["routePath"]
        and row.get("version") == "v3"
        and row.get("contractStatus") == "read-only"
    ]
    require(len(inventory_matches) == 1, "selected route is absent from canonical generated V3 read-only inventory")
    require(route == f"base.{route_row['generatedRouteId']}.read-only-query", "route ID is not deterministically derived from generated inventory")
    require(module_row["capabilityTags"] == ["objective-protocol"], "reputation, profiling, or other unsafe module capability prohibited")
    require(not set(module_row["capabilityTags"]) & set(spec_data["unsafeCapabilityClasses"]), "unsafe capability class prohibited")
    require(module_row["supportStatus"] == "supported-source" and module_row["deploymentStatus"] == "deployed-authorized", "selected module is not supported, deployed, and authorized")
    require(route_row["moduleSourcePath"] == module_row["path"], "scope registry module source mismatch")
    require(
        route_row["privacyPortabilityImplementationPath"]
        == CANONICAL_PRIVACY_IMPLEMENTATION_PATH
        and route_row["privacyPortabilityInterfaceId"]
        == CANONICAL_PRIVACY_INTERFACE_ID,
        "scope registry must bind the one canonical privacy-portability implementation/interface",
    )
    implementation_path = safe_repo_file(
        route_row["privacyPortabilityImplementationPath"],
        "scope canonical privacy-portability implementation",
        suffix=".py",
    )
    require_tracked_exact(
        route_row["privacyPortabilityImplementationPath"],
        implementation_path,
        registry["sourceCommit"],
        "scope canonical privacy-portability implementation",
    )
    require(
        digest(implementation_path)
        == route_row["privacyPortabilityImplementationSha256"]
        and git_blob_id(
            registry["sourceCommit"],
            route_row["privacyPortabilityImplementationPath"],
        )
        == route_row["privacyPortabilityImplementationGitBlob"],
        "scope privacy-portability implementation digest/blob mismatch",
    )
    require(route_row["protectedDecisionInfluence"] == module_row["allowedProtectedDecisions"], "scope registry protected-decision mapping mismatch")
    deployment_contracts = {row["contract"] for row in deployment.get("deployments", [])}
    require(route_row["requiredDeploymentContract"] == selected, "required deployment contract must exactly equal selected module")
    require(selected in deployment.get("scope", {}).get("enabled", []) and selected in deployment_contracts, "selected module is not in canonical deployment scope/contracts")
    rollout = load_json(ROLLOUT_PLAN_PATH)
    validate(rollout, load_json(ROLLOUT_PLAN_SCHEMA_PATH))
    rollout_matches = [
        stage for stage in rollout["stages"]
        if stage["stageId"] == route_row["rolloutStageId"]
        and stage["routeId"] == route
        and stage["module"] == selected
        and stage["actionClass"] == scope["selectedActionClass"]
        and stage["requiredDeploymentContract"] == route_row["requiredDeploymentContract"]
    ]
    require(len(rollout_matches) == 1, "scope route/deployment-contract/rollout-stage relationship mismatch")
    require(set(scope["deniedModules"]) == modules - {selected} and len(scope["deniedModules"]) == len(modules) - 1, "every unrelated module must be explicitly denied")
    return hashlib.sha256(canonical(scope)).hexdigest()


def validate_test_results(
    document: dict,
    expected_suite: str,
    manifest: dict,
    candidate_id: str,
    scope_hash: str,
    source_commit: str,
    git_tree: str,
) -> None:
    validate(document, load_json(EVIDENCE_SCHEMA_DIR / "test-results.schema.json"))
    require(
        set(document) == {
            "schemaVersion", "recordType", "suiteType", "candidateId",
            "sourceCommit", "gitTree", "scopeSha256", "allPassed", "summary",
            "tests",
        },
        "test-result document fields must be exact",
    )
    require(
        document["schemaVersion"] == "1.0.0"
        and document["recordType"] == "candidate-test-results"
        and document["suiteType"] == expected_suite
        and document["candidateId"] == candidate_id
        and document["sourceCommit"] == source_commit
        and document["gitTree"] == git_tree
        and document["scopeSha256"] == scope_hash
        and type(document["allPassed"]) is bool
        and document["allPassed"] is True,
        "test-result candidate/suite/source binding mismatch",
    )
    tests = document["tests"]
    require(type(tests) is list and tests, "test-result suite must be nonempty")
    ids: list[str] = []
    for test in tests:
        require(
            set(test) == {"testId", "passed", "assertionCount", "logSha256"}
            and type(test["testId"]) is str and re.fullmatch(r"[a-z0-9][a-z0-9._:-]{2,127}", test["testId"])
            and type(test["passed"]) is bool and test["passed"] is True
            and type(test["assertionCount"]) is int and not isinstance(test["assertionCount"], bool)
            and test["assertionCount"] > 0
            and SHA256.fullmatch(test["logSha256"] or ""),
            "test-result entry must be an exact passing object with assertions and log digest",
        )
        ids.append(test["testId"])
    require(len(set(ids)) == len(ids), "test-result IDs must be unique")
    summary = document["summary"]
    require(
        set(summary) == {"total", "passed", "failed", "combinedLogSha256"}
        and type(summary["total"]) is int and not isinstance(summary["total"], bool)
        and type(summary["passed"]) is int and not isinstance(summary["passed"], bool)
        and type(summary["failed"]) is int and not isinstance(summary["failed"], bool)
        and summary["total"] == summary["passed"] == len(tests)
        and summary["failed"] == 0
        and SHA256.fullmatch(summary["combinedLogSha256"] or ""),
        "test-result counts/log digest do not prove an all-passing suite",
    )


def signature_payload(candidate_id: str, subject: str, partner: str, roles: list[str]) -> bytes:
    return canonical({
        "domain": "vaultfire-partner-signature-set-v2",
        "candidateId": candidate_id,
        "organizationIds": sorted([subject, partner]),
        "requiredRoles": sorted(roles),
    })


def validate_signature_set(
    document: dict,
    manifest: dict,
    candidate_id: str,
    identities: dict[str, dict] | None,
    trust: dict | None,
) -> None:
    validate(document, load_json(EVIDENCE_SCHEMA_DIR / "signature-set.schema.json"))
    require(
        set(document) == {
            "schemaVersion", "recordType", "candidateId", "organizationIds",
            "threshold", "signers", "allVerified",
        },
        "signature-set fields must be exact",
    )
    assignments = {row["roleId"]: row["identityId"] for row in manifest["roles"]}
    partner_id = manifest["attestation"]["partnerAcceptedByIdentityId"]
    required = {
        "release-manager": assignments.get("release-manager"),
        "independent-reviewer": assignments.get("independent-reviewer"),
        "authorized-signatory": assignments.get("authorized-signatory"),
        "partner-authorized-signatory": partner_id,
    }
    require(all(required.values()), "signature-set requires all exact assigned identities")
    organizations = sorted([
        manifest["subjectOrganizationId"], manifest["partnerOrganizationId"]
    ])
    require(
        document["schemaVersion"] == "2.0.0"
        and document["recordType"] == "candidate-signature-set"
        and document["candidateId"] == candidate_id
        and document["organizationIds"] == organizations
        and document["threshold"] == {"required": 4, "total": 4}
        and type(document["allVerified"]) is bool and document["allVerified"] is True,
        "signature-set candidate/organization/threshold mismatch",
    )
    signers = document["signers"]
    require(type(signers) is list and len(signers) == 4, "signature-set requires exactly four signers")
    require(
        {row.get("roleId") for row in signers} == set(required)
        and {row.get("identityId") for row in signers} == set(required.values()),
        "signature-set signer identities/roles differ from exact authority chain",
    )
    require(identities is not None and trust is not None, "trusted signer registry required")
    payload = signature_payload(candidate_id, organizations[0], organizations[1], list(required))
    payload_sha = hashlib.sha256(payload).hexdigest()
    seen_signatures: set[str] = set()
    for signer in signers:
        require(
            set(signer) == {
                "identityId", "organizationId", "roleId", "keyType",
                "publicKeySha256", "authorityEvidenceId", "signedPayloadSha256",
                "signatureBase64", "verified",
            },
            "signature-set signer fields must be exact",
        )
        role = signer["roleId"]; identity_id = signer["identityId"]
        identity = identities.get(identity_id)
        expected_org = (
            manifest["partnerOrganizationId"]
            if role == "partner-authorized-signatory"
            else manifest["subjectOrganizationId"]
        )
        require(
            required[role] == identity_id
            and identity is not None
            and role in identity["allowedRoles"]
            and signer["organizationId"] == expected_org == identity["organizationId"]
            and signer["keyType"] == "Ed25519"
            and signer["publicKeySha256"] == hashlib.sha256(identity["_public"]).hexdigest()
            and signer["authorityEvidenceId"] == identity["authorityEvidenceId"]
            and signer["signedPayloadSha256"] == payload_sha
            and type(signer["verified"]) is bool and signer["verified"] is True,
            "signature-set signer key/organization/authority binding mismatch",
        )
        require(signer["signatureBase64"] not in seen_signatures, "signature-set signatures must be unique")
        seen_signatures.add(signer["signatureBase64"])
        try:
            detached = base64.b64decode(signer["signatureBase64"], validate=True)
        except (ValueError, binascii.Error) as exc:
            raise Blocked("signature-set signer encoding invalid") from exc
        require(
            verify_ed25519(identity["_public"], detached, payload),
            "signature-set detached signature invalid",
        )


def assigned_identity(manifest: dict, role: str) -> str | None:
    if role == "partner-authorized-signatory":
        return manifest["attestation"]["partnerAcceptedByIdentityId"]
    return next(
        (row["identityId"] for row in manifest["roles"] if row["roleId"] == role),
        None,
    )


def validate_bound_approvals(
    document: dict,
    field: str,
    required_roles: list[str],
    manifest: dict,
    identities: dict[str, dict] | None,
    domain: str,
) -> None:
    require(identities is not None, f"{domain}: externally attested identities required")
    approvals = document[field]
    required = {role: assigned_identity(manifest, role) for role in required_roles}
    require(all(required.values()), f"{domain}: exact assigned approver identities required")
    require(
        type(approvals) is list
        and len(approvals) == len(required)
        and {row["roleId"] for row in approvals} == set(required)
        and {row["identityId"] for row in approvals} == set(required.values()),
        f"{domain}: approver set differs from exact assigned roles",
    )
    signer_binding = sorted(
        [{"roleId": role, "identityId": identity_id} for role, identity_id in required.items()],
        key=lambda row: row["roleId"],
    )
    unsigned = {key: value for key, value in document.items() if key != field}
    payload = canonical({
        "domain": domain,
        "record": unsigned,
        "signers": signer_binding,
    })
    payload_sha256 = hashlib.sha256(payload).hexdigest()
    seen_signatures: set[str] = set()
    for row in approvals:
        expected_fields = {
            "identityId", "organizationId", "roleId", "keyType",
            "publicKeySha256", "authorityEvidenceId",
            "signedPayloadSha256", "signatureBase64",
        }
        if "externalAttestationId" in row:
            expected_fields.add("externalAttestationId")
        require(
            set(row) == expected_fields,
            f"{domain}: approval fields must be exact",
        )
        role = row["roleId"]; identity_id = row["identityId"]
        identity = identities.get(identity_id)
        require(identity is not None and identity_id == required[role], f"{domain}: substituted approver identity")
        expected_org = (
            manifest["partnerOrganizationId"]
            if role == "partner-authorized-signatory"
            else manifest["subjectOrganizationId"]
        )
        require(
            identity["organizationId"] == expected_org
            and row["organizationId"] == expected_org
            and role in identity["allowedRoles"]
            and row["keyType"] == "Ed25519"
            and row["publicKeySha256"] == hashlib.sha256(identity["_public"]).hexdigest()
            and row["authorityEvidenceId"] == identity["authorityEvidenceId"]
            and row["signedPayloadSha256"] == payload_sha256,
            f"{domain}: role/organization/key/authority/payload binding mismatch",
        )
        if "externalAttestationId" in row:
            require(
                row["externalAttestationId"] == identity["externalAttestationId"],
                f"{domain}: named-person external attestation mismatch",
            )
        require(row["signatureBase64"] not in seen_signatures, f"{domain}: signatures must be unique")
        seen_signatures.add(row["signatureBase64"])
        try:
            signature = base64.b64decode(row["signatureBase64"], validate=True)
        except (ValueError, binascii.Error) as exc:
            raise Blocked(f"{domain}: signature encoding invalid") from exc
        require(verify_ed25519(identity["_public"], signature, payload), f"{domain}: detached signature invalid")


def require_meaningful(value: str, label: str) -> None:
    require(type(value) is str and 3 <= len(value.strip()) <= 512, f"{label}: meaningful text required")
    normalized = re.sub(r"[^a-z0-9]+", "", value.lower())
    require(
        len(normalized) >= 3
        and len(set(normalized)) >= 3
        and not any(token in normalized for token in ("tbd", "placeholder", "unassigned", "unknown", "example", "notapplicable")),
        f"{label}: placeholders are prohibited",
    )


def normalize_legal_name(value: str) -> str:
    require_meaningful(value, "legal name")
    return re.sub(r"[^a-z0-9]+", "", value.casefold())


def resolve_candidate_json(
    path_text: str,
    expected_sha256: str,
    manifest: dict,
    label: str,
    commit_key: str = "evidenceCommit",
) -> tuple[dict, tuple[str, str]]:
    path = safe_repo_file(path_text, label, suffix=".json")
    require_tracked_exact(
        path_text, path, manifest["releaseCandidate"][commit_key], label
    )
    require(digest(path) == expected_sha256, f"{label}: digest mismatch")
    return load_json(path), (path_text, expected_sha256)


def scope_relationship(manifest: dict) -> dict:
    scope = manifest["scope"]
    registry = load_json(SCOPE_REGISTRY_PATH)
    matches = [
        row for row in registry["routes"]
        if row["module"] == scope["selectedModule"]
        and row["routeId"] == scope["selectedRouteId"]
        and row["actionClass"] == scope["selectedActionClass"]
    ]
    require(len(matches) == 1, "commercial scope is not one exact canonical registry relationship")
    return matches[0]


def validate_operational_acceptance(
    document: dict,
    evidence_id: str,
    manifest: dict,
    candidate_id: str,
    scope_hash: str,
    identities: dict[str, dict] | None,
    facts: dict,
    exercise_document: dict | None = None,
) -> list[tuple[str, str]]:
    additional_refs: list[tuple[str, str]] = []
    policy = OPERATIONAL_ACCEPTANCE_POLICIES[evidence_id]
    validate(document, load_json(EVIDENCE_SCHEMA_DIR / policy["schema"]))
    require(
        document["recordType"] == policy["recordType"]
        and document["candidateId"] == candidate_id
        and document["scopeSha256"] == scope_hash
        and document["subjectOrganizationId"] == manifest["subjectOrganizationId"]
        and document["partnerOrganizationId"] == manifest["partnerOrganizationId"],
        f"{evidence_id}: candidate/scope/organization mismatch",
    )
    canonical_policy = document["canonicalPolicy"]
    require(
        canonical_policy["path"] == policy["path"]
        and canonical_policy["version"] == policy["version"],
        f"{evidence_id}: canonical policy path/version mismatch",
    )
    policy_path = safe_repo_file(policy["path"], f"{evidence_id} canonical policy")
    require_tracked_exact(
        policy["path"], policy_path,
        manifest["releaseCandidate"]["evidenceCommit"],
        f"{evidence_id} canonical policy",
    )
    require(
        canonical_policy["sha256"] == digest(policy_path),
        f"{evidence_id}: canonical policy digest mismatch",
    )
    role_row = next(row for row in manifest["roles"] if row["roleId"] == policy["role"])
    channel_field = {
        "SECURITY-POLICY-ACCEPTANCE": "intakeChannelId",
        "INCIDENT-PLAN-ACCEPTANCE": "incidentChannelId",
        "SUPPORT-SLA-SELECTION": "supportChannelId",
        "CHANGE-RACI-ACCEPTANCE": "changeChannelId",
    }[evidence_id]
    require(
        document[channel_field] == role_row["contactChannelId"],
        f"{evidence_id}: operational channel differs from exact assigned role channel",
    )
    if evidence_id == "INCIDENT-PLAN-ACCEPTANCE":
        require(
            document["exerciseEvidenceSha256"] == facts["exerciseEvidenceSha256"],
            "incident plan exercise digest is not cross-bound",
        )
        require(exercise_document is not None, "incident exercise evidence must resolve to a typed artifact")
        validate(
            exercise_document,
            load_json(EVIDENCE_SCHEMA_DIR / "incident-exercise.schema.json"),
        )
        require(
            exercise_document["candidateId"] == candidate_id
            and exercise_document["sourceCommit"] == manifest["releaseCandidate"]["sourceCommit"]
            and exercise_document["gitTree"] == manifest["releaseCandidate"]["gitTree"]
            and exercise_document["scopeSha256"] == scope_hash,
            "incident exercise candidate/source/tree/scope binding mismatch",
        )
        started = parse_utc(exercise_document["startedAtUtc"], "incidentExercise.startedAtUtc")
        ended = parse_utc(exercise_document["endedAtUtc"], "incidentExercise.endedAtUtc")
        candidate_created = parse_utc(
            manifest["releaseCandidate"]["createdAtUtc"],
            "releaseCandidate.createdAtUtc",
        )
        as_of = parse_utc(manifest["asOfUtc"], "manifest.asOfUtc")
        require(
            candidate_created <= started < ended <= as_of
            and ended - started <= timedelta(hours=24)
            and as_of - ended <= timedelta(days=30),
            "incident exercise timing is stale, future, or outside the candidate interval",
        )
        require(identities is not None, "incident exercise requires trusted identities")
        required_participant_roles = {
            "incident-commander", "security-contact", "partner-authorized-signatory",
        }
        participants = exercise_document["participants"]
        require(
            {row["roleId"] for row in participants} == required_participant_roles,
            "incident exercise lacks exact mandatory separated participants",
        )
        participant_ids: set[str] = set()
        for participant in participants:
            role = participant["roleId"]
            identity_id = assigned_identity(manifest, role)
            expected_org = (
                manifest["partnerOrganizationId"]
                if role == "partner-authorized-signatory"
                else manifest["subjectOrganizationId"]
            )
            require(
                participant["identityId"] == identity_id
                and participant["organizationId"] == expected_org
                and identity_id in identities
                and identities[identity_id]["organizationId"] == expected_org
                and role in identities[identity_id]["allowedRoles"],
                "incident participant is not the exact assigned identity/role/organization",
            )
            participant_ids.add(identity_id)
        contact_control, _ = resolve_candidate_json(
            exercise_document["contactControlPath"],
            exercise_document["contactControlSha256"],
            manifest,
            "incident exercise contact-control matrix",
        )
        contacts_objective_path_text = (
            "pr10/partner-package/evidence/organizational/artifacts/"
            "actual-contacts.json"
        )
        contacts_objective_path = safe_repo_file(
            contacts_objective_path_text, "incident exact contacts objective"
        )
        require_tracked_exact(
            contacts_objective_path_text,
            contacts_objective_path,
            manifest["releaseCandidate"]["evidenceCommit"],
            "incident exact contacts objective",
        )
        contacts_objective = load_json(contacts_objective_path)
        require(
            contacts_objective.get("artifactId") == "ACTUAL-CONTACTS"
            and contacts_objective.get("candidateId") == candidate_id
            and contacts_objective.get("facts", {}).get("contactsArtifactSha256")
            == exercise_document["contactControlSha256"]
            and contacts_objective.get("blobRefs", {})
            .get("contactsArtifactSha256", {}).get("path")
            == exercise_document["contactControlPath"],
            "incident exercise is not cross-bound to the exact ACTUAL-CONTACTS artifact",
        )
        validate(
            contact_control,
            load_json(EVIDENCE_SCHEMA_DIR / "contact-control.schema.json"),
        )
        require(
            contact_control["candidateId"] == candidate_id
            and contact_control["subjectOrganizationId"]
            == manifest["subjectOrganizationId"]
            and contact_control["partnerOrganizationId"]
            == manifest["partnerOrganizationId"],
            "incident exercise contact-control candidate/organization mismatch",
        )
        contact_rows = {
            row["function"]: row for row in contact_control["channels"]
        }
        required_channel_functions = {"incident", "security", "partner-escalation"}
        exercise_channels = exercise_document["channelsExercised"]
        require(
            {row["function"] for row in exercise_channels}
            == required_channel_functions,
            "incident exercise lacks exact mandatory channel functions",
        )
        exercised_channel_ids: set[str] = set()
        for channel in exercise_channels:
            function = channel["function"]
            role = CONTACT_FUNCTION_ROLES[function]
            control = contact_rows.get(function)
            require(
                control is not None
                and channel == {
                    "function": function,
                    "roleId": role,
                    "identityId": control["identityId"],
                    "organizationId": control["organizationId"],
                    "channelId": control["channelId"],
                    "channelType": control["channelType"],
                },
                "incident exercise channel is not exact contact-control evidence",
            )
            exercised_channel_ids.add(channel["channelId"])
        objectives = exercise_document["objectives"]
        required_objectives = {
            "detect", "triage", "escalate", "contain", "notify-partner",
        }
        require(
            len({row["objectiveId"] for row in objectives}) == len(objectives)
            and {row["objectiveId"] for row in objectives}
            == required_objectives
            and all(row["passed"] is True and row["assertionCount"] > 0 for row in objectives)
            and exercise_document["failures"] == []
            and exercise_document["allPassed"] is True,
            "incident exercise does not prove required successful objectives",
        )
        require(
            len({row["evidenceLogPath"] for row in objectives}) == len(objectives)
            and len({row["evidenceLogSha256"] for row in objectives}) == len(objectives),
            "incident objective logs must be unique typed blobs",
        )
        objective_output_paths: set[str] = set()
        objective_output_digests: set[str] = set()
        assertion_paths: set[str] = set()
        assertion_digests: set[str] = set()
        source_record_paths: set[str] = set()
        source_record_digests: set[str] = set()
        incident_receipt_nonces: set[str] = set()
        evidence_type_by_objective = {
            "detect": "detection-event",
            "triage": "triage-record",
            "escalate": "escalation-receipt",
            "contain": "containment-record",
            "notify-partner": "partner-notification",
        }
        objective_bindings = {
            "detect": {
                "participantRoles": {"security-contact"},
                "channelFunction": "security",
                "controllerRole": "security-contact",
            },
            "triage": {
                "participantRoles": {"incident-commander"},
                "channelFunction": "incident",
                "controllerRole": "incident-commander",
            },
            "escalate": {
                "participantRoles": {
                    "incident-commander", "partner-authorized-signatory",
                },
                "channelFunction": "partner-escalation",
                "controllerRole": "partner-authorized-signatory",
            },
            "contain": {
                "participantRoles": {
                    "security-contact", "incident-commander",
                },
                "channelFunction": "incident",
                "controllerRole": "incident-commander",
            },
            "notify-partner": {
                "participantRoles": {
                    "incident-commander", "partner-authorized-signatory",
                },
                "channelFunction": "partner-escalation",
                "controllerRole": "partner-authorized-signatory",
            },
        }
        for objective in objectives:
            binding = objective_bindings[objective["objectiveId"]]
            expected_objective_participants = {
                assigned_identity(manifest, role)
                for role in binding["participantRoles"]
            }
            require(
                None not in expected_objective_participants,
                "incident objective has an unassigned mandatory role",
            )
            expected_objective_channel = contact_rows[
                binding["channelFunction"]
            ]["channelId"]
            objective_log, objective_ref = resolve_candidate_json(
                objective["evidenceLogPath"],
                objective["evidenceLogSha256"],
                manifest,
                f"incident objective log {objective['objectiveId']}",
            )
            validate(
                objective_log,
                load_json(EVIDENCE_SCHEMA_DIR / "incident-objective-log.schema.json"),
            )
            log_started = parse_utc(
                objective_log["startedAtUtc"],
                f"incidentObjective.{objective['objectiveId']}.startedAtUtc",
            )
            log_ended = parse_utc(
                objective_log["endedAtUtc"],
                f"incidentObjective.{objective['objectiveId']}.endedAtUtc",
            )
            require(
                objective_log["candidateId"] == candidate_id
                and objective_log["sourceCommit"]
                == manifest["releaseCandidate"]["sourceCommit"]
                and objective_log["gitTree"]
                == manifest["releaseCandidate"]["gitTree"]
                and objective_log["scopeSha256"] == scope_hash
                and objective_log["exerciseId"] == exercise_document["exerciseId"]
                and objective_log["objectiveId"] == objective["objectiveId"]
                and objective_log["assertionCount"] == objective["assertionCount"]
                and objective_log["passed"] is True
                and objective_log["failures"] == []
                and set(objective_log["participantIdentityIds"])
                == expected_objective_participants
                and objective_log["channelIds"]
                == [expected_objective_channel]
                and started <= log_started < log_ended <= ended,
                "incident objective log semantic, participant, channel, or timing mismatch",
            )
            require(
                objective_log["outputPath"] not in objective_output_paths
                and objective_log["outputSha256"] not in objective_output_digests,
                "incident objective outputs must be unique typed blobs",
            )
            objective_output, output_ref = resolve_candidate_json(
                objective_log["outputPath"],
                objective_log["outputSha256"],
                manifest,
                f"incident objective output {objective['objectiveId']}",
            )
            validate(
                objective_output,
                load_json(
                    EVIDENCE_SCHEMA_DIR / "incident-objective-output.schema.json"
                ),
            )
            output_started = parse_utc(
                objective_output["startedAtUtc"],
                f"incidentObjectiveOutput.{objective['objectiveId']}.startedAtUtc",
            )
            output_ended = parse_utc(
                objective_output["endedAtUtc"],
                f"incidentObjectiveOutput.{objective['objectiveId']}.endedAtUtc",
            )
            assertions = objective_output["assertions"]
            require(
                objective_output["candidateId"] == candidate_id
                and objective_output["sourceCommit"]
                == manifest["releaseCandidate"]["sourceCommit"]
                and objective_output["gitTree"]
                == manifest["releaseCandidate"]["gitTree"]
                and objective_output["scopeSha256"] == scope_hash
                and objective_output["exerciseId"] == exercise_document["exerciseId"]
                and objective_output["objectiveId"] == objective["objectiveId"]
                and set(objective_output["participantIdentityIds"])
                == expected_objective_participants
                and objective_output["channelIds"]
                == [expected_objective_channel]
                and len(assertions) == objective_log["assertionCount"]
                and len({row["assertionId"] for row in assertions}) == len(assertions)
                and len({row["evidencePath"] for row in assertions}) == len(assertions)
                and len({row["evidenceSha256"] for row in assertions}) == len(assertions)
                and objective_output["allPassed"] is True
                and log_started <= output_started < output_ended <= log_ended,
                "incident objective output is not exactly bound to its log/exercise",
            )
            for assertion in assertions:
                require(
                    assertion["evidencePath"] not in assertion_paths
                    and assertion["evidenceSha256"] not in assertion_digests,
                    "incident assertion evidence must be globally unique",
                )
                assertion_document, assertion_ref = resolve_candidate_json(
                    assertion["evidencePath"],
                    assertion["evidenceSha256"],
                    manifest,
                    f"incident assertion {assertion['assertionId']}",
                )
                validate(
                    assertion_document,
                    load_json(
                        EVIDENCE_SCHEMA_DIR
                        / "incident-assertion-evidence.schema.json"
                    ),
                )
                assertion_time = parse_utc(
                    assertion_document["observedAtUtc"],
                    f"incidentAssertion.{assertion['assertionId']}.observedAtUtc",
                )
                event = assertion_document["event"]
                event_bytes = canonical(event)
                event_digest = hashlib.sha256(event_bytes).hexdigest()
                receipt = assertion_document["controllerReceipt"]
                expected_event_type = evidence_type_by_objective[objective["objectiveId"]]
                require(
                    assertion_document["sourceRecordPath"]
                    not in source_record_paths
                    and assertion_document["sourceRecordSha256"]
                    not in source_record_digests,
                    "incident objective source records must be globally unique",
                )
                source_record, source_record_ref = resolve_candidate_json(
                    assertion_document["sourceRecordPath"],
                    assertion_document["sourceRecordSha256"],
                    manifest,
                    f"incident source record {assertion['assertionId']}",
                )
                validate(
                    source_record,
                    load_json(
                        EVIDENCE_SCHEMA_DIR
                        / "incident-objective-source-record.schema.json"
                    ),
                )
                expected_source_type = {
                    "detect": "detection-signal",
                    "triage": "triage-decision",
                    "escalate": "escalation-message",
                    "contain": "containment-verification",
                    "notify-partner": "partner-notice",
                }[objective["objectiveId"]]
                require(
                    source_record["candidateId"] == candidate_id
                    and source_record["sourceCommit"]
                    == manifest["releaseCandidate"]["sourceCommit"]
                    and source_record["gitTree"]
                    == manifest["releaseCandidate"]["gitTree"]
                    and source_record["scopeSha256"] == scope_hash
                    and source_record["exerciseId"]
                    == exercise_document["exerciseId"]
                    and source_record["objectiveId"]
                    == objective["objectiveId"]
                    and source_record["sourceType"] == expected_source_type
                    and source_record["content"]["sourceType"]
                    == expected_source_type
                    and parse_utc(
                        source_record["occurredAtUtc"],
                        f"incidentSource.{objective['objectiveId']}.occurredAtUtc",
                    ) == assertion_time
                    and set(source_record["actorIdentityIds"])
                    == expected_objective_participants
                    and source_record["organizationIds"]
                    == sorted({
                        identities[identity_id]["organizationId"]
                        for identity_id in expected_objective_participants
                    })
                    and source_record["channelIds"]
                    == [expected_objective_channel]
                    and output_started <= assertion_time <= output_ended,
                    "incident source record candidate/actor/org/channel binding mismatch",
                )
                require(
                    event["eventType"] == expected_event_type
                    and event_digest == assertion_document["eventSha256"]
                    and receipt["eventSha256"] == event_digest,
                    "incident assertion event is not the exact typed objective event",
                )
                # Objective-specific semantic bindings. Opaque bytes and a digest
                # label can never satisfy these closed records.
                if objective["objectiveId"] == "detect":
                    require(
                        event["detectorIdentityId"]
                        == assigned_identity(manifest, "security-contact")
                        and event["detectorId"]
                        == source_record["content"]["detectorId"]
                        and event["signalClass"]
                        == source_record["content"]["signalClass"]
                        and event["severity"]
                        == source_record["content"]["severity"]
                        and event["signalSha256"]
                        == assertion_document["sourceRecordSha256"]
                        and
                        parse_utc(event["detectedAtUtc"], "incident.detect.detectedAtUtc")
                        == assertion_time,
                        "detection event timestamp mismatch",
                    )
                elif objective["objectiveId"] == "triage":
                    require(
                        event["ownerIdentityId"]
                        == assigned_identity(manifest, "incident-commander")
                        and event["ticketId"]
                        == source_record["content"]["ticketId"]
                        and event["classification"]
                        == source_record["content"]["classification"]
                        and event["decisionSha256"]
                        == assertion_document["sourceRecordSha256"]
                        and parse_utc(event["openedAtUtc"], "incident.triage.openedAtUtc")
                        == assertion_time,
                        "triage event owner/timestamp mismatch",
                    )
                elif objective["objectiveId"] == "escalate":
                    sent = parse_utc(event["sentAtUtc"], "incident.escalate.sentAtUtc")
                    received = parse_utc(event["receivedAtUtc"], "incident.escalate.receivedAtUtc")
                    require(
                        event["fromIdentityId"]
                        == assigned_identity(manifest, "incident-commander")
                        and event["toIdentityId"]
                        == assigned_identity(
                            manifest, "partner-authorized-signatory"
                        )
                        and event["channelId"] == expected_objective_channel
                        and source_record["content"] == {
                            "sourceType": "escalation-message",
                            "fromIdentityId": event["fromIdentityId"],
                            "toIdentityId": event["toIdentityId"],
                            "channelId": event["channelId"],
                            "messageClass": "incident-escalation",
                            "deliveryConfirmed": True,
                        }
                        and event["messageSha256"]
                        == assertion_document["sourceRecordSha256"]
                        and output_started <= sent <= received == assertion_time
                        <= output_ended,
                        "escalation receipt identity/channel/timestamp mismatch",
                    )
                elif objective["objectiveId"] == "contain":
                    action_started = parse_utc(event["startedAtUtc"], "incident.contain.startedAtUtc")
                    action_completed = parse_utc(event["completedAtUtc"], "incident.contain.completedAtUtc")
                    require(
                        event["operatorIdentityId"]
                        == assigned_identity(manifest, "security-contact")
                        and event["controlId"]
                        == source_record["content"]["controlId"]
                        and event["actionClass"]
                        == source_record["content"]["actionClass"]
                        and source_record["content"]["operatorIdentityId"]
                        == event["operatorIdentityId"]
                        and event["verificationSha256"]
                        == assertion_document["sourceRecordSha256"]
                        and output_started <= action_started < action_completed
                        == assertion_time <= output_ended,
                        "containment operator/timestamp mismatch",
                    )
                else:
                    sent = parse_utc(event["sentAtUtc"], "incident.notify.sentAtUtc")
                    acknowledged = parse_utc(event["acknowledgedAtUtc"], "incident.notify.acknowledgedAtUtc")
                    require(
                        event["senderIdentityId"]
                        == assigned_identity(manifest, "incident-commander")
                        and event["recipientIdentityId"]
                        == assigned_identity(
                            manifest, "partner-authorized-signatory"
                        )
                        and event["channelId"] == expected_objective_channel
                        and source_record["content"] == {
                            "sourceType": "partner-notice",
                            "senderIdentityId": event["senderIdentityId"],
                            "recipientIdentityId": event["recipientIdentityId"],
                            "channelId": event["channelId"],
                            "noticeClass": "partner-incident-notification",
                            "acknowledged": True,
                        }
                        and event["noticeSha256"]
                        == assertion_document["sourceRecordSha256"]
                        and output_started <= sent <= acknowledged == assertion_time
                        <= output_ended,
                        "partner notification identity/channel/timestamp mismatch",
                    )
                controller_id = receipt["controllerIdentityId"]
                expected_controller_id = assigned_identity(
                    manifest, binding["controllerRole"]
                )
                receipt_signed_at = parse_utc(
                    receipt["signedAtUtc"],
                    f"incident.{objective['objectiveId']}.controllerReceipt.signedAtUtc",
                )
                require(
                    identities is not None
                    and controller_id == expected_controller_id
                    and controller_id in identities
                    and receipt["channelId"] == expected_objective_channel
                    and receipt["publicKeySha256"]
                    == identities[controller_id]["publicKeySha256"]
                    and receipt["nonceSha256"] not in incident_receipt_nonces
                    and assertion_time <= receipt_signed_at <= output_ended
                    and receipt_signed_at - assertion_time <= timedelta(minutes=5)
                    and candidate_created <= receipt_signed_at <= as_of,
                    "incident assertion controller is not an assigned exercise participant",
                )
                incident_receipt_nonces.add(receipt["nonceSha256"])
                signed_payload = canonical({
                    "domain": "vaultfire-incident-objective-event-v1",
                    "candidateId": candidate_id,
                    "exerciseId": exercise_document["exerciseId"],
                    "objectiveId": objective["objectiveId"],
                    "assertionId": assertion["assertionId"],
                    "eventSha256": event_digest,
                    "channelId": receipt["channelId"],
                    "nonceSha256": receipt["nonceSha256"],
                    "signedAtUtc": receipt["signedAtUtc"],
                })
                require(
                    hashlib.sha256(signed_payload).hexdigest()
                    == receipt["signedPayloadSha256"],
                    "incident assertion controller receipt payload digest mismatch",
                )
                try:
                    receipt_signature = base64.b64decode(
                        receipt["signatureBase64"], validate=True
                    )
                except (ValueError, binascii.Error) as exc:
                    raise Blocked("incident assertion controller signature is invalid base64") from exc
                require(
                    verify_ed25519(
                        identities[controller_id]["_public"],
                        receipt_signature,
                        signed_payload,
                    ),
                    "incident assertion controller signature is invalid",
                )
                expected_assertion_id = "assertion:" + hashlib.sha256(canonical({
                    "candidateId": candidate_id,
                    "exerciseId": exercise_document["exerciseId"],
                    "objectiveId": objective["objectiveId"],
                    "eventSha256": event_digest,
                    "controllerIdentityId": controller_id,
                    "nonceSha256": receipt["nonceSha256"],
                })).hexdigest()
                require(
                    assertion_document["assertionId"] == expected_assertion_id
                    and assertion_document["candidateId"] == candidate_id
                    and assertion_document["sourceCommit"]
                    == manifest["releaseCandidate"]["sourceCommit"]
                    and assertion_document["gitTree"]
                    == manifest["releaseCandidate"]["gitTree"]
                    and assertion_document["scopeSha256"] == scope_hash
                    and assertion_document["exerciseId"]
                    == exercise_document["exerciseId"]
                    and assertion_document["objectiveId"] == objective["objectiveId"]
                    and assertion_document["assertionId"] == assertion["assertionId"]
                    and assertion_document["evidenceType"]
                    == evidence_type_by_objective[objective["objectiveId"]]
                    and set(assertion_document["participantIdentityIds"])
                    == expected_objective_participants
                    and assertion_document["channelIds"]
                    == [expected_objective_channel]
                    and output_started <= assertion_time <= output_ended
                    and assertion_document["result"] == assertion["observedOutcome"]
                    == assertion["expectedOutcome"]
                    and assertion["passed"] is True,
                    "incident assertion content/type/candidate binding mismatch",
                )
                assertion_paths.add(assertion["evidencePath"])
                assertion_digests.add(assertion["evidenceSha256"])
                additional_refs.append(assertion_ref)
                source_record_paths.add(assertion_document["sourceRecordPath"])
                source_record_digests.add(
                    assertion_document["sourceRecordSha256"]
                )
                additional_refs.append(source_record_ref)
            objective_output_paths.add(objective_log["outputPath"])
            objective_output_digests.add(objective_log["outputSha256"])
            additional_refs.append(objective_ref)
            additional_refs.append(output_ref)
    validate_bound_approvals(
        document, "acceptedBy",
        [policy["role"], "partner-authorized-signatory"],
        manifest, identities,
        f"vaultfire-{policy['recordType']}-v1",
    )
    return additional_refs


def validate_unlinkability_results(
    document: dict,
    manifest: dict,
    candidate_id: str,
    scope_hash: str,
    identities: dict[str, dict] | None = None,
) -> list[tuple[str, str]]:
    additional_resolved_refs: list[tuple[str, str]] = []
    validate(document, load_json(EVIDENCE_SCHEMA_DIR / "unlinkability-test-results.schema.json"))
    require(
        document["candidateId"] == candidate_id
        and document["sourceCommit"] == manifest["releaseCandidate"]["sourceCommit"]
        and document["gitTree"] == manifest["releaseCandidate"]["gitTree"]
        and document["scopeSha256"] == scope_hash
        and document["chain"] == "base"
        and document["allPassed"] is True,
        "unlinkability tests are not bound to the exact Base candidate/scope",
    )
    require(
        document["threatModel"]["prohibitsCrossPartnerLinkage"] is True
        and document["threatModel"]["prohibitsCrossChainIdentityLinkage"] is True
        and document["methodology"]["usesRawPersonalData"] is False
        and document["methodology"]["usesSurveillanceInputs"] is False
        and document["privacyPredicates"] == {
            "explicitConsent": True,
            "dataMinimized": True,
            "chainSpecific": True,
            "nonLinkable": True,
            "crossChainValueFlowAbsent": True,
        },
        "unlinkability methodology/privacy predicates mismatch",
    )
    methodology = document["methodology"]
    require(
        methodology["sampleCount"] >= 1000
        and methodology["positivePairCount"] >= 100
        and methodology["negativePairCount"] >= 100
        and methodology["sampleCount"]
        == methodology["positivePairCount"] + methodology["negativePairCount"]
        and methodology["confidenceLevelBps"] >= 9500
        and methodology["confidenceMethod"] == "one-sided-hoeffding-v1",
        "unlinkability methodology lacks statistically meaningful coverage",
    )
    seed_commitment, seed_commitment_ref = resolve_candidate_json(
        methodology["seedCommitmentPath"],
        methodology["seedCommitmentSha256"],
        manifest,
        "unlinkability seed precommitment",
        commit_key="selectionCommit",
    )
    validate(
        seed_commitment,
        load_json(
            EVIDENCE_SCHEMA_DIR
            / "privacy-unlinkability-seed-commitment.schema.json"
        ),
    )
    seed_committed_at = parse_utc(
        seed_commitment["committedAtUtc"],
        "unlinkabilitySeedCommitment.committedAtUtc",
    )
    require(
        seed_commitment["candidateId"] == candidate_id
        and seed_commitment["sourceCommit"]
        == manifest["releaseCandidate"]["sourceCommit"]
        and seed_commitment["gitTree"] == manifest["releaseCandidate"]["gitTree"]
        and seed_commitment["scopeSha256"] == scope_hash
        and seed_commitment["chain"] == "base"
        and seed_commitment["methodologyId"] == methodology["methodologyId"],
        "unlinkability seed precommitment candidate/scope binding mismatch",
    )
    randomness_root = load_json(RANDOMNESS_AUTHORITY_ROOT_POLICY)
    validate(randomness_root, load_json(RANDOMNESS_AUTHORITY_ROOT_POLICY_SCHEMA))
    require(
        PINNED_RANDOMNESS_AUTHORITY_ROOT_SHA256 is not None
        and digest(RANDOMNESS_AUTHORITY_ROOT_POLICY)
        == PINNED_RANDOMNESS_AUTHORITY_ROOT_SHA256
        and randomness_root["status"] == "enabled-reviewed-pinned"
        and randomness_root["positiveReadinessAllowed"] is True
        and all(randomness_root[key] is not None for key in (
            "rootAuthorityId", "rootAdministratorIdentityId",
            "rootPublicKeyBase64", "rootPublicKeySha256", "rootPolicyCommit",
        )),
        "positive readiness is structurally impossible until a genuine "
        "independently governed randomness authority root is externally "
        "reviewed and pinned in package policy",
    )
    beacon_policy = load_json(RANDOMNESS_BEACON_TRUST_POLICY)
    validate(beacon_policy, load_json(RANDOMNESS_BEACON_TRUST_POLICY_SCHEMA))
    randomness_policy_relative = (
        "pr10/partner-package/config/randomness-beacon-trust-policy.json"
    )
    require_tracked_exact(
        randomness_policy_relative,
        RANDOMNESS_BEACON_TRUST_POLICY,
        manifest["releaseCandidate"]["sourceCommit"],
        "randomness beacon trust policy",
    )
    require(
        beacon_policy["status"] == "enabled-reviewed-pinned"
        and beacon_policy["positiveReadinessAllowed"] is True
        and beacon_policy["authorityId"] is not None
        and beacon_policy["publicKeyBase64"] is not None
        and beacon_policy["publicKeySha256"] is not None
        and beacon_policy["reviewedPolicyCommit"] is not None,
        "positive readiness is disabled until a genuine independent randomness "
        "beacon authority is reviewed and pinned",
    )
    require(
        beacon_policy["reviewedPolicyCommit"]
        == manifest["releaseCandidate"]["sourceCommit"],
        "randomness beacon trust policy is not reviewed at the exact source commit",
    )
    human_policy = load_json(EXPECTED_EXTERNAL_TRUST_POLICY)
    legal_policy = load_json(LEGAL_REGISTRY_TRUST_POLICY)
    require(
        beacon_policy["rootAuthorityId"] == randomness_root["rootAuthorityId"]
        and beacon_policy["authorityCredentialPath"] is not None
        and beacon_policy["authorityCredentialSha256"] is not None
        and beacon_policy["publicBeaconEndpoint"] is not None
        and randomness_root["rootAdministratorIdentityId"]
        not in {
            human_policy["expectedAdministratorId"],
            legal_policy["expectedAdministratorId"],
        },
        "randomness root/administrator must be pinned and separate from human "
        "identity and legal-registry authority chains",
    )
    credential, credential_ref = resolve_candidate_json(
        beacon_policy["authorityCredentialPath"],
        beacon_policy["authorityCredentialSha256"],
        manifest,
        "root-signed randomness beacon authority credential",
        commit_key="selectionCommit",
    )
    validate(
        credential,
        load_json(
            EVIDENCE_SCHEMA_DIR / "randomness-beacon-authority-credential.schema.json"
        ),
    )
    try:
        randomness_root_public = base64.b64decode(
            randomness_root["rootPublicKeyBase64"], validate=True
        )
        credential_signature = base64.b64decode(
            credential["rootSignatureBase64"], validate=True
        )
    except (ValueError, binascii.Error) as exc:
        raise Blocked("randomness authority-chain key/signature encoding invalid") from exc
    credential_payload = canonical({
        key: credential[key] for key in (
            "rootAuthorityId", "authorityId", "authorityClass",
            "publicKeySha256", "publicBeaconEndpoint", "validFromUtc",
            "validUntilUtc", "credentialNonceSha256",
        )
    })
    credential_valid_from = parse_utc(
        credential["validFromUtc"], "randomnessCredential.validFromUtc"
    )
    credential_valid_until = parse_utc(
        credential["validUntilUtc"], "randomnessCredential.validUntilUtc"
    )
    require(
        len(randomness_root_public) == 32
        and hashlib.sha256(randomness_root_public).hexdigest()
        == randomness_root["rootPublicKeySha256"]
        and credential["rootAuthorityId"] == randomness_root["rootAuthorityId"]
        and credential["authorityId"] == beacon_policy["authorityId"]
        and credential["publicKeySha256"] == beacon_policy["publicKeySha256"]
        and credential["publicBeaconEndpoint"]
        == beacon_policy["publicBeaconEndpoint"]
        and credential["signedPayloadSha256"]
        == hashlib.sha256(credential_payload).hexdigest()
        and verify_ed25519(
            randomness_root_public, credential_signature, credential_payload
        ),
        "randomness beacon authority credential is not signed by the pinned root",
    )
    beacon, beacon_ref = resolve_candidate_json(
        seed_commitment["beaconReceiptPath"],
        seed_commitment["beaconReceiptSha256"],
        manifest,
        "unlinkability independent randomness beacon receipt",
        commit_key="selectionCommit",
    )
    validate(
        beacon,
        load_json(
            EVIDENCE_SCHEMA_DIR / "privacy-randomness-beacon-receipt.schema.json"
        ),
    )
    beacon_issued_at = parse_utc(
        beacon["issuedAtUtc"], "unlinkabilityBeacon.issuedAtUtc"
    )
    require(
        credential_valid_from <= beacon_issued_at <= credential_valid_until,
        "randomness beacon receipt falls outside root-signed credential validity",
    )
    source_committed_at = datetime.fromtimestamp(
        int(git("show", "-s", "--format=%ct", manifest["releaseCandidate"]["sourceCommit"])),
        tz=timezone.utc,
    )
    selection_committed_at = datetime.fromtimestamp(
        int(git("show", "-s", "--format=%ct", manifest["releaseCandidate"]["selectionCommit"])),
        tz=timezone.utc,
    )
    try:
        beacon_public = base64.b64decode(
            beacon_policy["publicKeyBase64"], validate=True
        )
        beacon_signature = base64.b64decode(
            beacon["signatureBase64"], validate=True
        )
        raw_beacon_response = base64.b64decode(
            beacon["rawResponseBase64"], validate=True
        )
    except (ValueError, binascii.Error) as exc:
        raise Blocked("randomness beacon key/signature encoding invalid") from exc
    beacon_payload = canonical({
        key: beacon[key] for key in (
            "authorityId", "authorityClass", "round", "issuedAtUtc",
            "candidateId", "sourceCommit", "gitTree", "scopeSha256", "runnerSha256",
            "corpusCommitmentSha256", "evaluationContextSha256",
            "randomValueSha256",
        )
    })
    raw_beacon = loads_json(raw_beacon_response.decode("utf-8"))
    require(
        len(beacon_public) == 32
        and hashlib.sha256(beacon_public).hexdigest()
        == beacon_policy["publicKeySha256"]
        and beacon["authorityId"] == beacon_policy["authorityId"]
        and beacon["publicBeaconEndpoint"] == beacon_policy["publicBeaconEndpoint"]
        and hashlib.sha256(raw_beacon_response).hexdigest()
        == beacon["rawResponseSha256"]
        and json_equal(raw_beacon, {
            **{
                key: beacon[key] for key in (
                    "authorityId", "authorityClass", "round", "issuedAtUtc",
                    "candidateId", "sourceCommit", "gitTree", "scopeSha256",
                    "runnerSha256", "corpusCommitmentSha256",
                    "evaluationContextSha256", "randomValueSha256",
                )
            },
            "endpoint": beacon["publicBeaconEndpoint"],
            "signatureBase64": beacon["signatureBase64"],
        })
        and beacon["publicKeySha256"] == beacon_policy["publicKeySha256"]
        and beacon["signedPayloadSha256"]
        == hashlib.sha256(beacon_payload).hexdigest()
        and verify_ed25519(beacon_public, beacon_signature, beacon_payload)
        and beacon["candidateId"] == candidate_id
        and beacon["sourceCommit"] == manifest["releaseCandidate"]["sourceCommit"]
        and beacon["gitTree"] == manifest["releaseCandidate"]["gitTree"]
        and beacon["scopeSha256"] == scope_hash
        and beacon["authorityId"] == seed_commitment["beaconAuthorityId"]
        and beacon["round"] == seed_commitment["beaconRound"]
        and beacon["randomValueSha256"] == seed_commitment["beaconValueSha256"]
        and beacon["issuedAtUtc"] == seed_commitment["beaconIssuedAtUtc"]
        and beacon_issued_at == seed_committed_at
        and source_committed_at < beacon_issued_at <= selection_committed_at,
        "unlinkability seed does not resolve to the pinned, signed, exact-candidate "
        "independent randomness beacon",
    )
    additional_resolved_refs.append(seed_commitment_ref)
    additional_resolved_refs.append(credential_ref)
    additional_resolved_refs.append(beacon_ref)
    input_refs = methodology["inputs"]
    require(
        {row["inputType"] for row in input_refs}
        == {"random-seed-opening", "corpus-universe", "deterministic-selection", "test-command"}
        and len({row["path"] for row in input_refs}) == 4
        and len({row["sha256"] for row in input_refs}) == 4,
        "unlinkability methodology inputs must be exact unique typed blobs",
    )
    input_documents: dict[str, dict] = {}
    input_contents: dict[str, bytes] = {}
    input_created: dict[str, datetime] = {}
    corpus_rows: dict[str, dict] = {}
    command_record: dict | None = None
    selection_record: dict | None = None
    for input_ref in input_refs:
        input_document, resolved_ref = resolve_candidate_json(
            input_ref["path"], input_ref["sha256"], manifest,
            f"unlinkability methodology input {input_ref['inputType']}",
            commit_key="selectionCommit",
        )
        validate(
            input_document,
            load_json(
                EVIDENCE_SCHEMA_DIR
                / "privacy-unlinkability-methodology-input.schema.json"
            ),
        )
        try:
            input_content = base64.b64decode(
                input_document["inputContentBase64"], validate=True
            )
        except (ValueError, binascii.Error) as exc:
            raise Blocked("unlinkability methodology input content is not valid base64") from exc
        require(
            input_content
            and hashlib.sha256(input_content).hexdigest()
            == input_document["inputContentSha256"],
            "unlinkability methodology input content digest mismatch",
        )
        input_created_at = parse_utc(
            input_document["createdAtUtc"],
            f"unlinkabilityInput.{input_ref['inputType']}.createdAtUtc",
        )
        require(
            seed_committed_at <= input_created_at,
            "unlinkability input predates the seed precommitment",
        )
        if input_ref["inputType"] == "corpus-universe":
            try:
                corpus_lines = [
                    row for row in input_content.decode("utf-8").splitlines() if row
                ]
            except UnicodeDecodeError as exc:
                raise Blocked("unlinkability challenge corpus is not UTF-8") from exc
            require(
                len(corpus_lines) == input_document["itemCount"],
                "unlinkability challenge corpus count is not derived from content",
            )
            parsed_corpus: list[dict] = []
            unordered_pairs: set[frozenset[str]] = set()
            for line in corpus_lines:
                row = loads_json(line)
                require(
                    set(row) == {
                        "pairId", "testId", "left", "right",
                    }
                    and row["testId"] in {
                        "privacy.commitment-reuse",
                        "privacy.cross-partner-collusion",
                        "privacy.metadata-timing-correlation",
                    }
                    and re.fullmatch(r"pair:[0-9a-f]{64}", row["pairId"] or "")
                    and type(row["left"]) is dict
                    and type(row["right"]) is dict,
                    "unlinkability corpus row is not an exact structured challenge",
                )
                left = derive_unlink_side(row["left"])
                right = derive_unlink_side(row["right"])
                require(
                    row["left"]["contentId"] != row["right"]["contentId"],
                    "unlinkability corpus row is degenerate",
                )
                pair_identity = frozenset((
                    row["left"]["contentId"], row["right"]["contentId"],
                ))
                require(
                    pair_identity not in unordered_pairs,
                    "unlinkability corpus contains a repeated or reversed pair",
                )
                expected_pair_id = "pair:" + unlink_hash(UNLINK_PAIR_DOMAIN, {
                    "testId": row["testId"],
                    "contentIds": sorted(pair_identity),
                })
                require(
                    row["pairId"] == expected_pair_id,
                    "unlinkability pairId is not derived from canonical row content",
                )
                unordered_pairs.add(pair_identity)
                parsed_corpus.append(row)
            require(
                len({canonical(row) for row in parsed_corpus}) == len(parsed_corpus)
                and len({row["pairId"] for row in parsed_corpus}) == len(parsed_corpus)
                and len(unordered_pairs) == len(parsed_corpus),
                "unlinkability corpus contains repeated or degenerate challenges",
            )
            corpus_rows = {row["pairId"]: row for row in parsed_corpus}
        elif input_ref["inputType"] == "random-seed-opening":
            require(
                len(input_content) == 32
                and any(input_content)
                and len(set(input_content)) >= 24
                and input_content not in {
                    bytes(range(32)),
                    bytes(range(16)) * 2,
                    input_content[:1] * len(input_content),
                },
                "unlinkability seed opening is predictable, repeated, or weak",
            )
        elif input_ref["inputType"] == "deterministic-selection":
            selection_record = loads_json(input_content.decode("utf-8"))
            validate(
                selection_record,
                load_json(
                    EVIDENCE_SCHEMA_DIR / "privacy-unlinkability-selection.schema.json"
                ),
            )
        elif input_ref["inputType"] == "test-command":
            try:
                command_text = input_content.decode("utf-8")
            except UnicodeDecodeError as exc:
                raise Blocked("unlinkability test command is not UTF-8") from exc
            command_record = loads_json(command_text)
            require(
                set(command_record) == {
                    "protocolId", "executablePath", "executableSha256",
                    "candidateId", "sourceCommit", "gitTree", "scopeSha256",
                    "seedOpeningSha256", "seedCommitmentSha256",
                    "corpusUniverseSha256", "selectionManifestSha256",
                    "evaluationContextSha256", "runnerSha256", "argvTemplate",
                    "executionPolicySha256", "candidateImplementationPath",
                    "candidateImplementationSha256",
                    "candidateImplementationGitBlob", "candidateInterfaceId",
                    "candidateModuleId", "candidateRouteId",
                    "independentOracleId",
                }
                and command_record["protocolId"]
                == "vaultfire-unlinkability-execution-v4"
                and command_record["executablePath"]
                == "pr10/partner-package/scripts/run_unlinkability_protocol.py"
                and SHA256.fullmatch(command_record["executableSha256"] or "")
                and command_record["sourceCommit"]
                == manifest["releaseCandidate"]["sourceCommit"]
                and command_record["argvTemplate"] == [
                    "--execute-candidate-protocol",
                    "--context", "{contextPath}",
                    "--corpus-universe", "{corpusUniversePath}",
                    "--selection", "{selectionPath}",
                    "--selection-commit", "{selectionCommit}",
                    "--selection-tree", "{selectionTree}",
                    "--raw-events", "{rawEventsPath}",
                    "--execution-record", "{executionRecordPath}",
                    "--test-id", "{testId}",
                ]
                and command_record["candidateId"] == candidate_id
                and command_record["gitTree"] == manifest["releaseCandidate"]["gitTree"]
                and command_record["scopeSha256"] == scope_hash
                and command_record["executionPolicySha256"]
                == PINNED_PRIVACY_EXECUTION_POLICY_SHA256
                and command_record["candidateImplementationPath"]
                == CANONICAL_PRIVACY_IMPLEMENTATION_PATH
                and command_record["candidateInterfaceId"]
                == CANONICAL_PRIVACY_INTERFACE_ID
                and command_record["independentOracleId"]
                == CANONICAL_PRIVACY_ORACLE_ID
                and re.fullmatch(
                    r"[0-9a-f]{40}",
                    command_record["candidateImplementationGitBlob"] or "",
                )
                and all(SHA256.fullmatch(command_record[key] or "") for key in (
                    "seedOpeningSha256", "seedCommitmentSha256",
                    "corpusUniverseSha256", "selectionManifestSha256",
                    "evaluationContextSha256", "runnerSha256",
                    "executionPolicySha256",
                    "candidateImplementationSha256",
                )),
                "unlinkability command must identify the canonical nontrivial exact-commit runner",
            )
            executable_path = safe_repo_file(
                command_record["executablePath"],
                "unlinkability exact-commit executable",
                suffix=".py",
            )
            require_tracked_exact(
                command_record["executablePath"],
                executable_path,
                manifest["releaseCandidate"]["sourceCommit"],
                "unlinkability exact-commit executable",
            )
            executable_bytes = executable_path.read_bytes()
            require(
                digest(executable_path) == command_record["executableSha256"]
                and len(executable_bytes) >= 1000
                and b"execute_candidate_protocol" in executable_bytes
                and b"_run_isolated" in executable_bytes
                and b"_independent_oracle" in executable_bytes
                and b"runnerOutputSha256" in executable_bytes,
                "unlinkability runner is missing, trivial, or not exact-commit bound",
            )
            execution_policy_path = safe_repo_file(
                "pr10/partner-package/config/privacy-execution-trust-policy.json",
                "pinned privacy execution trust policy",
                suffix=".json",
            )
            require(
                digest(execution_policy_path)
                == PINNED_PRIVACY_EXECUTION_POLICY_SHA256,
                "privacy execution trust policy differs from the source-pinned digest",
            )
            execution_policy = load_json(execution_policy_path)
            validate(
                execution_policy,
                load_json(PRIVACY_EXECUTION_TRUST_POLICY_SCHEMA),
            )
            require(
                execution_policy["status"] == "reviewed-candidate-bound"
                and execution_policy["positiveReadinessAllowed"] is True,
                "privacy execution is structurally disabled until a genuine "
                "candidate/toolchain/execution authority is independently pinned",
            )
            relationship = scope_relationship(manifest)
            require(
                command_record["candidateModuleId"] == relationship["module"]
                and command_record["candidateRouteId"] == relationship["routeId"]
                and command_record["candidateImplementationPath"]
                == relationship["privacyPortabilityImplementationPath"]
                and command_record["candidateImplementationSha256"]
                == relationship["privacyPortabilityImplementationSha256"]
                and command_record["candidateImplementationGitBlob"]
                == relationship["privacyPortabilityImplementationGitBlob"]
                and command_record["candidateInterfaceId"]
                == relationship["privacyPortabilityInterfaceId"],
                "unlinkability implementation is not the exact implementation bound to "
                "the selected canonical module and route",
            )
            implementation_path = safe_repo_file(
                command_record["candidateImplementationPath"],
                "exact-candidate privacy-portability implementation",
                suffix=".py",
            )
            require_tracked_exact(
                command_record["candidateImplementationPath"],
                implementation_path,
                manifest["releaseCandidate"]["sourceCommit"],
                "exact-candidate privacy-portability implementation",
            )
            require(
                digest(implementation_path)
                == command_record["candidateImplementationSha256"]
                and git_blob_id(
                    manifest["releaseCandidate"]["sourceCommit"],
                    command_record["candidateImplementationPath"],
                )
                == command_record["candidateImplementationGitBlob"],
                "candidate implementation digest/blob identity is not exact",
            )
        require(
            input_document["candidateId"] == candidate_id
            and input_document["sourceCommit"]
            == manifest["releaseCandidate"]["sourceCommit"]
            and input_document["gitTree"] == manifest["releaseCandidate"]["gitTree"]
            and input_document["scopeSha256"] == scope_hash
            and input_document["chain"] == "base"
            and input_document["inputType"] == input_ref["inputType"]
            and input_document["methodologyId"] == methodology["methodologyId"]
            and input_document["containsRawPersonalData"] is False
            and input_document["containsSurveillanceInputs"] is False
            and (
                input_document["itemCount"] >= methodology["sampleCount"]
                if input_ref["inputType"] == "corpus-universe"
                else input_document["itemCount"] == 1
            ),
            "unlinkability methodology input semantic/candidate binding mismatch",
        )
        additional_resolved_refs.append(resolved_ref)
        input_documents[input_ref["inputType"]] = input_document
        input_contents[input_ref["inputType"]] = input_content
        input_created[input_ref["inputType"]] = input_created_at
    require(
        command_record is not None
        and selection_record is not None
        and len(corpus_rows) >= methodology["sampleCount"]
        and methodology["sampleCount"]
        == UNLINK_SAMPLES_PER_TEST * 3,
        "unlinkability command/corpus evidence incomplete",
    )
    seed_opening = input_contents["random-seed-opening"]
    corpus_bytes = input_contents["corpus-universe"]
    selection_bytes = input_contents["deterministic-selection"]
    selected_pair_ids = derive_unlink_selection(
        list(corpus_rows.values()), seed_opening
    )
    try:
        selection_seed = base64.b64decode(
            selection_record["seedOpeningBase64"], validate=True
        )
    except (ValueError, binascii.Error) as exc:
        raise Blocked("unlinkability selection seed encoding is invalid") from exc
    require(
        command_record["seedOpeningSha256"]
        == hashlib.sha256(seed_opening).hexdigest()
        == beacon["randomValueSha256"]
        and selection_seed == seed_opening
        and selection_record["seedOpeningSha256"]
        == hashlib.sha256(seed_opening).hexdigest()
        and selection_record["orderedPairIds"] == selected_pair_ids
        and selection_record["coverage"] == {
            test_id: UNLINK_SAMPLES_PER_TEST
            for test_id in sorted({
                "privacy.commitment-reuse",
                "privacy.cross-partner-collusion",
                "privacy.metadata-timing-correlation",
            })
        }
        and command_record["corpusUniverseSha256"]
        == hashlib.sha256(corpus_bytes).hexdigest()
        and command_record["selectionManifestSha256"]
        == hashlib.sha256(selection_bytes).hexdigest()
        and command_record["runnerSha256"]
        == command_record["executableSha256"],
        "unlinkability seed, unbiased selection, input, or runner binding mismatch",
    )
    evaluation_context = {
        "protocolId": command_record["protocolId"],
        "candidateId": candidate_id,
        "sourceCommit": manifest["releaseCandidate"]["sourceCommit"],
        "gitTree": manifest["releaseCandidate"]["gitTree"],
        "scopeSha256": scope_hash,
        "runnerSha256": command_record["runnerSha256"],
        "executionPolicySha256": command_record["executionPolicySha256"],
        "candidateImplementationPath": command_record["candidateImplementationPath"],
        "candidateImplementationSha256": command_record["candidateImplementationSha256"],
        "candidateImplementationGitBlob": command_record["candidateImplementationGitBlob"],
        "candidateInterfaceId": command_record["candidateInterfaceId"],
        "independentOracleId": command_record["independentOracleId"],
        "candidateModuleId": command_record["candidateModuleId"],
        "candidateRouteId": command_record["candidateRouteId"],
        "corpusUniverseSha256": command_record["corpusUniverseSha256"],
    }
    require(
        command_record["evaluationContextSha256"]
        == hashlib.sha256(canonical(evaluation_context)).hexdigest(),
        "unlinkability evaluation context is not exact-candidate derived",
    )
    seed_preimage = {
        "domain": "vaultfire-unlinkability-seed-v3",
        **evaluation_context,
        "seedOpeningSha256": command_record["seedOpeningSha256"],
        "beaconAuthorityId": seed_commitment["beaconAuthorityId"],
        "beaconRound": seed_commitment["beaconRound"],
        "beaconValueSha256": seed_commitment["beaconValueSha256"],
    }
    require(
        seed_commitment["commitmentDomain"] == "vaultfire-unlinkability-seed-v3"
        and seed_commitment["evaluationContextSha256"]
        == command_record["evaluationContextSha256"]
        and seed_commitment["runnerSha256"] == command_record["runnerSha256"]
        and seed_commitment["corpusCommitmentSha256"]
        == command_record["corpusUniverseSha256"]
        and seed_commitment["seedCommitmentSha256"]
        == hashlib.sha256(canonical(seed_preimage)).hexdigest()
        and command_record["seedCommitmentSha256"]
        == seed_commitment["seedCommitmentSha256"],
        "unlinkability seed is not domain-separated across exact candidate, "
        "source, selection stage, scope, runner, adapter, corpus, and context",
    )
    tests = document["tests"]
    require(type(tests) is list and tests, "unlinkability test suite must be nonempty")
    require(
        all(
            set(row) == {"testId", "methodId", "sampleCount", "expected", "observed", "passed", "logPath", "logSha256"}
            and row["passed"] is True
            and row["expected"] == "unlinkable"
            and row["observed"] == "unlinkable"
            and row["methodId"] == "statistical-linkage-challenge-v1"
            and row["sampleCount"] >= 100
            and SHA256.fullmatch(row["logSha256"] or "")
            for row in tests
        ),
        "unlinkability test entries must strictly prove non-linkability",
    )
    summary = document["summary"]
    require(
        summary["total"] == summary["passed"] == len(tests)
        and summary["failed"] == 0
        and summary["totalSamples"] == sum(row["sampleCount"] for row in tests)
        and methodology["sampleCount"] == summary["totalSamples"],
        "unlinkability test summary is inconsistent",
    )
    require(
        {row["testId"] for row in tests}
        == {
            "privacy.commitment-reuse",
            "privacy.cross-partner-collusion",
            "privacy.metadata-timing-correlation",
        },
        "unlinkability suite must contain each required adversarial test exactly once",
    )
    refs: list[tuple[str, str]] = []
    all_rows = [
        (row["logPath"], row["logSha256"], row["testId"], row["sampleCount"])
        for row in tests
    ] + [(
        summary["combinedLogPath"], summary["combinedLogSha256"],
        "privacy.combined", summary["totalSamples"],
    )]
    require(
        len({path for path, _, _, _ in all_rows}) == len(all_rows)
        and len({sha for _, sha, _, _ in all_rows}) == len(all_rows),
        "unlinkability logs must be unique tracked blobs",
    )
    resolved_logs: dict[str, dict] = {}
    resolved_transcripts: dict[str, dict] = {}
    transcript_refs: list[tuple[str, str]] = []
    execution_refs: list[tuple[str, str]] = []
    execution_paths: set[str] = set()
    execution_digests: set[str] = set()
    created_at = parse_utc(
        manifest["releaseCandidate"]["createdAtUtc"],
        "releaseCandidate.createdAtUtc",
    )
    as_of = parse_utc(manifest["asOfUtc"], "manifest.asOfUtc")
    for path_text, sha256, test_id, sample_count in all_rows:
        log, ref = resolve_candidate_json(
            path_text, sha256, manifest, f"unlinkability log {test_id}"
        )
        validate(log, load_json(EVIDENCE_SCHEMA_DIR / "privacy-unlinkability-log.schema.json"))
        require(
            log["candidateId"] == candidate_id
            and log["sourceCommit"] == manifest["releaseCandidate"]["sourceCommit"]
            and log["gitTree"] == manifest["releaseCandidate"]["gitTree"]
            and log["scopeSha256"] == scope_hash
            and log["chain"] == "base"
            and log["testId"] == test_id
            and log["methodId"] == "statistical-linkage-challenge-v1"
            and log["sampleCount"] == sample_count
            and log["challengePairs"] >= sample_count
            and log["falseLinkRateBps"]
            == (log["falseLinks"] * 10000) // log["challengePairs"]
            and log["passed"] is True,
            "unlinkability log semantic/candidate binding mismatch",
        )
        transcript, transcript_ref = resolve_candidate_json(
            log["transcriptPath"], log["transcriptSha256"], manifest,
            f"unlinkability transcript {test_id}",
        )
        validate(
            transcript,
            load_json(
                EVIDENCE_SCHEMA_DIR / "privacy-unlinkability-transcript.schema.json"
            ),
        )
        transcript_started = parse_utc(
            transcript["startedAtUtc"], f"unlinkabilityTranscript.{test_id}.startedAtUtc"
        )
        transcript_ended = parse_utc(
            transcript["endedAtUtc"], f"unlinkabilityTranscript.{test_id}.endedAtUtc"
        )
        transcript_events = transcript["events"]
        require(
            transcript["executionOutputPath"] not in execution_paths
            and transcript["executionOutputSha256"] not in execution_digests,
            "unlinkability execution outputs must be unique typed blobs",
        )
        execution, execution_ref = resolve_candidate_json(
            transcript["executionOutputPath"],
            transcript["executionOutputSha256"],
            manifest,
            f"unlinkability execution output {test_id}",
        )
        validate(
            execution,
            load_json(
                EVIDENCE_SCHEMA_DIR
                / "privacy-unlinkability-execution-output.schema.json"
            ),
        )
        generation_prefix = (
            "pr10/partner-package/evidence/organizational/privacy-outputs/"
            + execution["requestedRawEventsPath"].split("/")[-2]
            + "/generations/"
            + execution["generationId"]
            + "/"
        )
        require(
            execution["requestedRawEventsPath"].rsplit("/", 1)[0]
            == execution["requestedExecutionRecordPath"].rsplit("/", 1)[0]
            and execution["requestedRawEventsPath"].endswith("/raw-events.jsonl")
            and execution["requestedExecutionRecordPath"].endswith(
                "/execution-record.json"
            )
            and execution["rawEventsPath"]
            == generation_prefix + "raw-events.jsonl"
            and transcript["executionOutputPath"]
            == generation_prefix + "execution-record.json"
            and execution["generationPointerPath"]
            == execution["requestedRawEventsPath"].rsplit("/", 1)[0]
            + "/CURRENT.json",
            "unlinkability execution artifacts do not bind one atomic generation",
        )
        pointer_path = safe_repo_file(
            execution["generationPointerPath"],
            f"unlinkability generation pointer {test_id}",
            suffix=".json",
        )
        require_tracked_exact(
            execution["generationPointerPath"],
            pointer_path,
            manifest["releaseCandidate"]["evidenceCommit"],
            f"unlinkability generation pointer {test_id}",
        )
        generation_pointer = load_json(pointer_path)
        require_finalized_generation_path(
            pointer_path, f"unlinkability generation pointer {test_id}"
        )
        require(
            set(generation_pointer)
            == {
                "schemaVersion",
                "recordType",
                "generationId",
                "rawEventsPath",
                "rawEventsSha256",
                "executionRecordPath",
                "executionRecordSha256",
            }
            and generation_pointer["schemaVersion"] == "1.0.0"
            and generation_pointer["recordType"]
            == "privacy-execution-generation-pointer"
            and generation_pointer["generationId"] == execution["generationId"]
            and generation_pointer["rawEventsPath"] == execution["rawEventsPath"]
            and generation_pointer["rawEventsSha256"]
            == execution["rawEventsSha256"]
            and generation_pointer["executionRecordPath"]
            == transcript["executionOutputPath"]
            and generation_pointer["executionRecordSha256"]
            == transcript["executionOutputSha256"],
            "unlinkability generation pointer does not bind one complete generation",
        )
        raw_events_path = safe_repo_file(
            execution["rawEventsPath"],
            f"unlinkability raw execution output {test_id}",
            suffix=".jsonl",
        )
        generation_directory = REPOSITORY.joinpath(
            *PurePosixPath(generation_prefix.rstrip("/")).parts
        )
        require_finalized_generation_path(
            generation_directory,
            f"unlinkability generation directory {test_id}",
            directory=True,
        )
        require_finalized_generation_path(
            raw_events_path, f"unlinkability raw execution output {test_id}"
        )
        execution_output_path = safe_repo_file(
            transcript["executionOutputPath"],
            f"unlinkability execution output {test_id}",
            suffix=".json",
        )
        require_finalized_generation_path(
            execution_output_path, f"unlinkability execution output {test_id}"
        )
        require_tracked_exact(
            execution["rawEventsPath"],
            raw_events_path,
            manifest["releaseCandidate"]["evidenceCommit"],
            f"unlinkability raw execution output {test_id}",
        )
        try:
            raw_events = base64.b64decode(
                execution["rawEventsBase64"], validate=True
            )
            raw_lines = [
                line for line in raw_events.decode("utf-8").splitlines() if line
            ]
        except (ValueError, binascii.Error, UnicodeDecodeError) as exc:
            raise Blocked("unlinkability runner output encoding is invalid") from exc
        require(
            raw_events
            and raw_events_path.read_bytes() == raw_events
            and hashlib.sha256(raw_events).hexdigest()
            == execution["rawEventsSha256"],
            "unlinkability raw runner output digest mismatch",
        )
        derived_events: list[dict] = []
        for line in raw_lines:
            raw_row = loads_json(line)
            require(
                set(raw_row) == {
                    "pairId", "expectedRelationship", "observedRelationship",
                    "leftInputSha256", "rightInputSha256",
                    "leftCandidateOutputBase64", "rightCandidateOutputBase64",
                    "leftCandidateOutputSha256", "rightCandidateOutputSha256",
                    "oracleId", "candidateDeclaredPredicates",
                    "runnerOutputSha256",
                }
                and raw_row["expectedRelationship"] in {"linked", "unlinked"}
                and raw_row["observedRelationship"] in {"linked", "unlinked"}
                and re.fullmatch(r"pair:[0-9a-f]{64}", raw_row["pairId"] or "")
                and all(SHA256.fullmatch(raw_row[key] or "") for key in (
                    "leftInputSha256", "rightInputSha256",
                    "leftCandidateOutputSha256", "rightCandidateOutputSha256",
                    "runnerOutputSha256",
                )),
                "unlinkability runner output row shape invalid",
            )
            try:
                left_output_bytes = base64.b64decode(
                    raw_row["leftCandidateOutputBase64"], validate=True
                )
                right_output_bytes = base64.b64decode(
                    raw_row["rightCandidateOutputBase64"], validate=True
                )
            except (ValueError, binascii.Error) as exc:
                raise Blocked(
                    "unlinkability candidate output encoding is invalid"
                ) from exc
            require(
                left_output_bytes
                and right_output_bytes
                and hashlib.sha256(left_output_bytes).hexdigest()
                == raw_row["leftCandidateOutputSha256"]
                and hashlib.sha256(right_output_bytes).hexdigest()
                == raw_row["rightCandidateOutputSha256"]
                and raw_row["oracleId"] == CANONICAL_PRIVACY_ORACLE_ID
                and raw_row["candidateDeclaredPredicates"] is False,
                "candidate output bytes/digests or independent-oracle identity are invalid",
            )
            corpus_row = corpus_rows.get(raw_row["pairId"])
            require(
                corpus_row is not None
                and (
                    test_id == "privacy.combined"
                    or corpus_row["testId"] == test_id
                ),
                "unlinkability runner output does not resolve to exact corpus pair",
            )
            left = derive_unlink_side(corpus_row["left"])
            right = derive_unlink_side(corpus_row["right"])
            recomputed = {
                "pairId": corpus_row["pairId"],
                "expectedRelationship": (
                    "linked"
                    if (
                        left["subjectCommitmentSha256"],
                        left["partnerContextSha256"],
                        left["chainId"],
                    ) == (
                        right["subjectCommitmentSha256"],
                        right["partnerContextSha256"],
                        right["chainId"],
                    )
                    else "unlinked"
                ),
                "observedRelationship": (
                    "linked"
                    if raw_row["leftCandidateOutputSha256"]
                    == raw_row["rightCandidateOutputSha256"]
                    else "unlinked"
                ),
                "leftInputSha256": corpus_row["left"]["caseInputSha256"],
                "rightInputSha256": corpus_row["right"]["caseInputSha256"],
                "leftCandidateOutputSha256":
                    raw_row["leftCandidateOutputSha256"],
                "rightCandidateOutputSha256":
                    raw_row["rightCandidateOutputSha256"],
            }
            runner_event = {
                key: value for key, value in raw_row.items()
                if key != "runnerOutputSha256"
            }
            recomputed["runnerOutputSha256"] = unlink_hash(
                UNLINK_OUTPUT_DOMAIN,
                {
                    "context": command_record,
                    "executionTestId": test_id,
                    "event": runner_event,
                },
            )
            require(
                raw_row["expectedRelationship"]
                == recomputed["expectedRelationship"]
                and raw_row["observedRelationship"]
                == recomputed["observedRelationship"]
                and raw_row["leftInputSha256"]
                == recomputed["leftInputSha256"]
                and raw_row["rightInputSha256"]
                == recomputed["rightInputSha256"]
                and raw_row["runnerOutputSha256"]
                == recomputed["runnerOutputSha256"],
                "unlinkability runner row is not independently recomputed from "
                "exact-candidate behavior and corpus inputs",
            )
            derived_events.append(recomputed)
        execution_started = parse_utc(
            execution["startedAtUtc"],
            f"unlinkabilityExecution.{test_id}.startedAtUtc",
        )
        execution_ended = parse_utc(
            execution["endedAtUtc"],
            f"unlinkabilityExecution.{test_id}.endedAtUtc",
        )
        input_path_by_type = {
            row["inputType"]: row["path"] for row in input_refs
        }
        input_sha_by_type = {
            row["inputType"]: row["sha256"] for row in input_refs
        }
        expected_argv = [
            "--execute-candidate-protocol",
            "--context", input_path_by_type["test-command"],
            "--corpus-universe", input_path_by_type["corpus-universe"],
            "--selection", input_path_by_type["deterministic-selection"],
            "--selection-commit", manifest["releaseCandidate"]["selectionCommit"],
            "--selection-tree", manifest["releaseCandidate"]["selectionTree"],
            "--raw-events", execution["requestedRawEventsPath"],
            "--execution-record", execution["requestedExecutionRecordPath"],
            "--test-id", test_id,
        ]
        try:
            response_bytes = base64.b64decode(
                execution["responseBase64"], validate=True
            )
            receipt_nonce = base64.b64decode(
                execution["nonceBase64"], validate=True
            )
        except (ValueError, binascii.Error) as exc:
            raise Blocked("unlinkability execution response/nonce encoding is invalid") from exc
        require(
            response_bytes
            and hashlib.sha256(response_bytes).hexdigest()
            == execution["responseSha256"]
            and len(receipt_nonce) == 32,
            "unlinkability execution response/nonce digest is invalid",
        )
        selected_for_test = [
            corpus_rows[pair_id]
            for pair_id in selected_pair_ids
            if test_id == "privacy.combined"
            or corpus_rows[pair_id]["testId"] == test_id
        ]
        expected_requests: dict[str, dict] = {}
        for corpus_row in selected_for_test:
            for side_name in ("left", "right"):
                side = corpus_row[side_name]
                expected_requests[side["contentId"]] = {
                    "requestId": side["contentId"],
                    "candidateId": candidate_id,
                    "moduleId": command_record["candidateModuleId"],
                    "routeId": command_record["candidateRouteId"],
                    "scopeSha256": scope_hash,
                    "caseInputBase64": side["caseInputBase64"],
                    "caseInputSha256": side["caseInputSha256"],
                }
        expected_request_bytes = b"".join(
            canonical(expected_requests[request_id]) + b"\n"
            for request_id in sorted(expected_requests)
        )
        require(
            hashlib.sha256(expected_request_bytes).hexdigest()
            == execution["requestSha256"],
            "unlinkability execution request digest is not independently derived",
        )
        response_map: dict[str, str] = {}
        try:
            for line in response_bytes.decode("utf-8").splitlines():
                response_row = loads_json(line)
                require(
                    set(response_row) == {
                        "requestId", "portabilityOutputBase64"
                    }
                    and response_row["requestId"] in expected_requests
                    and response_row["requestId"] not in response_map,
                    "candidate response has undeclared fields or unexpected identity",
                )
                decoded_response = base64.b64decode(
                    response_row["portabilityOutputBase64"], validate=True
                )
                require(decoded_response, "candidate response is empty")
                response_map[response_row["requestId"]] = response_row[
                    "portabilityOutputBase64"
                ]
        except (UnicodeDecodeError, ValueError, binascii.Error) as exc:
            raise Blocked("candidate response bytes are not closed canonical JSONL") from exc
        require(
            set(response_map) == set(expected_requests),
            "candidate response does not exactly cover blinded request identities",
        )
        for raw_line in raw_lines:
            raw_row = loads_json(raw_line)
            corpus_row = corpus_rows[raw_row["pairId"]]
            require(
                response_map[corpus_row["left"]["contentId"]]
                == raw_row["leftCandidateOutputBase64"]
                and response_map[corpus_row["right"]["contentId"]]
                == raw_row["rightCandidateOutputBase64"],
                "independent oracle event does not match raw candidate response",
            )
        receipt_signature = execution["launcherSignature"]
        unsigned_execution = {
            key: value for key, value in execution.items()
            if key != "launcherSignature"
        }
        receipt_payload = (
            b"vaultfire-unlinkability-execution-receipt-v1\0"
            + canonical(unsigned_execution)
        )
        try:
            execution_public_key = base64.b64decode(
                execution_policy["executionSigner"]["publicKeyBase64"],
                validate=True,
            )
            execution_signature = base64.b64decode(
                receipt_signature["signatureBase64"], validate=True
            )
        except (ValueError, binascii.Error, TypeError) as exc:
            raise Blocked("unlinkability execution launcher signature encoding is invalid") from exc
        require(
            len(execution_public_key) == 32
            and receipt_signature["keyType"] == "Ed25519"
            and receipt_signature["publicKeySha256"]
            == execution_policy["executionSigner"]["publicKeySha256"]
            == hashlib.sha256(execution_public_key).hexdigest()
            and receipt_signature["signedPayloadSha256"]
            == hashlib.sha256(receipt_payload).hexdigest()
            and verify_ed25519(
                execution_public_key, execution_signature, receipt_payload
            ),
            "unlinkability execution record lacks the exact pinned launcher signature",
        )
        require(
            execution["candidateId"] == candidate_id
            and execution["sourceCommit"]
            == manifest["releaseCandidate"]["sourceCommit"]
            and execution["gitTree"] == manifest["releaseCandidate"]["gitTree"]
            and execution["selectionCommit"]
            == manifest["releaseCandidate"]["selectionCommit"]
            and execution["selectionTree"]
            == manifest["releaseCandidate"]["selectionTree"]
            and execution["scopeSha256"] == scope_hash
            and execution["chain"] == "base"
            and execution["testId"] == test_id
            and execution["protocolId"] == command_record["protocolId"]
            and execution["executablePath"] == command_record["executablePath"]
            and execution["executableSha256"]
            == command_record["executableSha256"]
            and execution["executionPolicySha256"]
            == command_record["executionPolicySha256"]
            and execution["candidateImplementationPath"]
            == command_record["candidateImplementationPath"]
            and execution["candidateImplementationSha256"]
            == command_record["candidateImplementationSha256"]
            and execution["candidateImplementationGitBlob"]
            == command_record["candidateImplementationGitBlob"]
            and execution["candidateInterfaceId"]
            == command_record["candidateInterfaceId"]
            and execution["independentOracleId"]
            == command_record["independentOracleId"]
            and execution["launcherArgv"] == expected_argv
            and execution["candidateArgv"] == [
                "/runtime/bin/python", "-I", "-B",
                "/candidate/implementation.py", "--request-jsonl",
                "/input/requests.jsonl", "--response-jsonl",
                "/output/responses.jsonl",
            ]
            and execution["isolationArgv"][0]
            == execution_policy["isolation"]["binaryPath"]
            and all(flag in execution["isolationArgv"] for flag in (
                "--unshare-all", "--die-with-parent", "--new-session",
                "--clearenv", "--ro-bind", "--ro-bind-data", "--chdir", "PWD",
            ))
            and execution["isolationArgv"][
                execution["isolationArgv"].index("--chdir") + 1
            ] == "/work"
            and execution["isolationArgv"][
                execution["isolationArgv"].index("PWD") + 1
            ] == "/work"
            and execution["exitCode"] == 0
            and execution["stdoutBase64"] == ""
            and execution["stdoutSha256"]
            == hashlib.sha256(b"").hexdigest()
            and execution["stderrBase64"] == ""
            and execution["stderrSha256"]
            == hashlib.sha256(b"").hexdigest()
            and execution["eventCount"] == len(derived_events)
            and [row["pairId"] for row in derived_events]
            == [
                pair_id for pair_id in selected_pair_ids
                if test_id == "privacy.combined"
                or corpus_rows[pair_id]["testId"] == test_id
            ]
            and {row["pairId"] for row in derived_events}
            == {
                pair_id for pair_id in selected_pair_ids
                for corpus_row in [corpus_rows[pair_id]]
                if test_id == "privacy.combined"
                or corpus_row["testId"] == test_id
            }
            and derived_events == transcript_events
            and max(input_created.values()) <= execution_started
            and execution_started == transcript_started
            and execution_ended == transcript_ended,
            "unlinkability outcomes are not derived from exact-commit execution evidence",
        )
        transcript_false_links = sum(
            row["expectedRelationship"] == "unlinked"
            and row["observedRelationship"] == "linked"
            for row in transcript_events
        )
        require(
            transcript["candidateId"] == candidate_id
            and transcript["sourceCommit"]
            == manifest["releaseCandidate"]["sourceCommit"]
            and transcript["gitTree"] == manifest["releaseCandidate"]["gitTree"]
            and transcript["scopeSha256"] == scope_hash
            and transcript["chain"] == "base"
            and transcript["testId"] == test_id
            and transcript["methodId"] == log["methodId"]
            and transcript["sampleCount"] == log["sampleCount"]
            and transcript["challengePairs"] == log["challengePairs"]
            and transcript["falseLinks"] == log["falseLinks"]
            and transcript["sampleCount"] == len(transcript_events)
            and transcript["challengePairs"] == len(transcript_events)
            and transcript["falseLinks"] == transcript_false_links
            and len({row["pairId"] for row in transcript_events})
            == len(transcript_events)
            and created_at <= transcript_started < transcript_ended <= as_of
            and transcript_ended - transcript_started <= timedelta(hours=24),
            "unlinkability transcript semantic, timing, or candidate binding mismatch",
        )
        resolved_logs[test_id] = log
        resolved_transcripts[test_id] = transcript
        refs.append(ref)
        transcript_refs.append(transcript_ref)
        execution_refs.append(execution_ref)
        execution_paths.add(transcript["executionOutputPath"])
        execution_digests.add(transcript["executionOutputSha256"])
    require(
        len({path for path, _ in transcript_refs}) == len(transcript_refs)
        and len({sha for _, sha in transcript_refs}) == len(transcript_refs)
        and not {path for path, _ in transcript_refs}
        & {path for path, _, _, _ in all_rows},
        "unlinkability transcripts must be unique and distinct from logs",
    )
    component_logs = [
        resolved_logs[row["testId"]] for row in tests
    ]
    component_transcripts = [
        resolved_transcripts[row["testId"]] for row in tests
    ]
    combined = resolved_logs["privacy.combined"]
    combined_transcript = resolved_transcripts["privacy.combined"]
    total_samples = sum(row["sampleCount"] for row in component_logs)
    total_pairs = sum(row["challengePairs"] for row in component_logs)
    total_false_links = sum(row["falseLinks"] for row in component_logs)
    observed_bps, upper_bps = unlinkability_upper_bound_bps(
        total_false_links, total_pairs, methodology["confidenceLevelBps"]
    )
    component_events = [
        event for transcript in component_transcripts
        for event in transcript["events"]
    ]
    component_event_map = {
        event["pairId"]: (
            event["expectedRelationship"], event["observedRelationship"]
        )
        for event in component_events
    }
    combined_event_map = {
        event["pairId"]: (
            event["expectedRelationship"], event["observedRelationship"]
        )
        for event in combined_transcript["events"]
    }
    positive_pairs = sum(
        event["expectedRelationship"] == "linked" for event in component_events
    )
    negative_pairs = sum(
        event["expectedRelationship"] == "unlinked" for event in component_events
    )
    def relationship_bounds(events: list[dict]) -> tuple[int, int, int]:
        linked = [
            event for event in events
            if event["expectedRelationship"] == "linked"
        ]
        unlinked = [
            event for event in events
            if event["expectedRelationship"] == "unlinked"
        ]
        require(
            linked and unlinked,
            "unlinkability verdict requires both linked and unlinked classes",
        )
        false_negatives = sum(
            event["observedRelationship"] != "linked" for event in linked
        )
        false_positives = sum(
            event["observedRelationship"] != "unlinked" for event in unlinked
        )
        _, false_negative_upper = unlinkability_upper_bound_bps(
            false_negatives, len(linked), methodology["confidenceLevelBps"]
        )
        _, false_positive_upper = unlinkability_upper_bound_bps(
            false_positives, len(unlinked), methodology["confidenceLevelBps"]
        )
        _, combined_upper = unlinkability_upper_bound_bps(
            false_negatives + false_positives,
            len(events),
            methodology["confidenceLevelBps"],
        )
        return false_negative_upper, false_positive_upper, combined_upper

    relationship_bound_sets = [
        relationship_bounds(transcript["events"])
        for transcript in component_transcripts
    ]
    relationship_bound_sets.append(
        relationship_bounds(combined_transcript["events"])
    )
    require(
        all(
            false_negative_upper <= methodology["maximumFalseLinkRateBps"]
            and false_positive_upper <= methodology["maximumFalseLinkRateBps"]
            and combined_upper <= methodology["maximumFalseLinkRateBps"]
            for (
                false_negative_upper,
                false_positive_upper,
                combined_upper,
            ) in relationship_bound_sets
        ),
        "unlinkability per-class or combined false-negative/false-positive "
        "confidence bound failed",
    )
    summary = document["summary"]
    require(
        combined["sampleCount"] == total_samples
        and combined["challengePairs"] == total_pairs
        and combined["falseLinks"] == total_false_links
        and combined["falseLinkRateBps"] == observed_bps
        and len(component_event_map) == len(component_events)
        and combined_event_map == component_event_map
        and methodology["sampleCount"] == total_samples
        and methodology["positivePairCount"] == positive_pairs
        and methodology["negativePairCount"] == negative_pairs
        and positive_pairs + negative_pairs == total_pairs
        and methodology["observedFalseLinkRateBps"] == observed_bps
        and methodology["calculatedUpperFalseLinkRateBps"] == upper_bps
        and summary["totalSamples"] == total_samples
        and summary["aggregateChallengePairs"] == total_pairs
        and summary["aggregateFalseLinks"] == total_false_links
        and summary["derivedObservedFalseLinkRateBps"] == observed_bps
        and summary["derivedUpperConfidenceBoundBps"] == upper_bps
        and observed_bps <= methodology["maximumFalseLinkRateBps"]
        and upper_bps <= methodology["maximumFalseLinkRateBps"],
        "unlinkability aggregate counts, rates, confidence bound, or conclusion "
        "is not derived from resolved evidence",
    )
    return additional_resolved_refs + refs + transcript_refs + execution_refs


def validate_objective_artifact(
    artifact: dict,
    evidence_id: str,
    manifest: dict,
    candidate_id: str,
    scope_hash: str,
    identities: dict[str, dict] | None = None,
    trust: dict | None = None,
) -> list[tuple[str, str]]:
    additional_resolved_refs: list[tuple[str, str]] = []
    exact = {
        "schemaVersion", "artifactId", "artifactType", "candidateId",
        "sourceCommit", "subjectOrganizationId", "partnerOrganizationId",
        "scopeSha256", "facts", "blobRefs",
    }
    require(set(artifact) == exact, f"artifact {evidence_id}: fields must be exact")
    require(artifact["schemaVersion"] == "1.0.0", f"artifact {evidence_id}: schema version mismatch")
    require(artifact["artifactId"] == evidence_id and artifact["artifactType"] == EVIDENCE_SPECS[evidence_id]["claim"], f"artifact {evidence_id}: type mismatch")
    require(artifact["candidateId"] == candidate_id, f"artifact {evidence_id}: candidate mismatch")
    require(artifact["sourceCommit"] == manifest["releaseCandidate"]["sourceCommit"], f"artifact {evidence_id}: source commit mismatch")
    require(artifact["subjectOrganizationId"] == manifest["subjectOrganizationId"], f"artifact {evidence_id}: subject organization mismatch")
    require(artifact["partnerOrganizationId"] == manifest["partnerOrganizationId"], f"artifact {evidence_id}: partner organization mismatch")
    require(artifact["scopeSha256"] == scope_hash, f"artifact {evidence_id}: scope mismatch")
    facts = artifact["facts"]
    require(type(facts) is dict and set(facts) == ARTIFACT_FACT_KEYS[evidence_id], f"artifact {evidence_id}: semantic fact keys mismatch")
    for key, value in facts.items():
        if key in {
            "entityVerified", "authorityVerified", "channelsControlTested",
            "evidenceReviewed", "candidateApproved", "noSurveillanceControlsApproved",
            "scopeAccepted", "candidateAccepted", "separationVerified",
            "subjectExecuted", "partnerExecuted", "subjectSignaturesVerified",
            "partnerSignaturesVerified", "intakeRouteControlTested",
            "coverageVerified", "staffingVerified", "responsibilitiesAccepted",
            "candidateIdMatched", "allStagesComplete", "allPassed",
            "singleStageMatched", "maximumLossBounded",
            "residualLiabilityAccepted", "forcedPushRejected",
            "pullSettlementVerified", "unknownDenied", "staleDenied",
            "malformedDenied", "unauthorizedDenied", "unlinkabilityVerified",
            "crossChainValueFlowAbsent", "allEvidenceTracked",
            "ignoredEvidenceAbsent", "uniqueBlobs", "pausedRefundPassed",
            "terminalExitPassed", "principalPreserved", "closedInputEnumVerified",
            "forbiddenConceptMutationsRejected",
        }:
            require(type(value) is bool and value is True, f"artifact {evidence_id}: fact {key} must be exact true")
        elif key.endswith("Sha256"):
            require(type(value) is str and SHA256.fullmatch(value), f"artifact {evidence_id}: fact {key} requires SHA-256")
        else:
            require(type(value) is str and len(value) > 0, f"artifact {evidence_id}: fact {key} requires a nonempty typed value")
    digest_facts = {key for key in facts if key.endswith("Sha256")}
    refs = artifact["blobRefs"]
    require(type(refs) is dict and set(refs) == digest_facts, f"artifact {evidence_id}: every digest fact requires one exact blob reference")
    require(
        len({ref["path"] for ref in refs.values()}) == len(refs)
        and len({ref["sha256"] for ref in refs.values()}) == len(refs),
        f"artifact {evidence_id}: typed source blobs and digests must be unique",
    )
    resolved = {}
    for fact_key, ref in refs.items():
        require(set(ref) == {"path", "sha256"}, f"artifact {evidence_id}: blob reference fields must be exact")
        require(ref["sha256"] == facts[fact_key], f"artifact {evidence_id}: blob reference/fact digest mismatch")
        blob_path = safe_repo_file(ref["path"], f"artifact {evidence_id} {fact_key}", suffix=".json")
        require_tracked_exact(ref["path"], blob_path, manifest["releaseCandidate"]["evidenceCommit"], f"artifact {evidence_id} {fact_key}")
        require(digest(blob_path) == ref["sha256"], f"artifact {evidence_id}: referenced blob digest mismatch")
        resolved[fact_key] = load_json(blob_path)
    source_record = resolved["sourceRecordSha256"]
    require(
        set(source_record) == {"schemaVersion", "recordType", "candidateId", "subjectOrganizationId", "partnerOrganizationId", "evidenceId", "assertions"},
        f"artifact {evidence_id}: typed source record fields must be exact",
    )
    require(source_record["schemaVersion"] == "1.0.0" and source_record["recordType"] == EVIDENCE_SPECS[evidence_id]["claim"], f"artifact {evidence_id}: typed source record mismatch")
    require(source_record["candidateId"] == candidate_id and source_record["evidenceId"] == evidence_id, f"artifact {evidence_id}: source record candidate/evidence mismatch")
    require(source_record["subjectOrganizationId"] == manifest["subjectOrganizationId"] and source_record["partnerOrganizationId"] == manifest["partnerOrganizationId"], f"artifact {evidence_id}: source record organization mismatch")
    nondigest_facts = {key: value for key, value in facts.items() if not key.endswith("Sha256")}
    require(json_equal(source_record["assertions"], nondigest_facts), f"artifact {evidence_id}: source record assertions do not prove typed facts")
    if evidence_id == "EXACT-COMMIT-TESTS":
        tests = resolved["testResultsSha256"]
        validate_test_results(
            tests, "exact-commit", manifest, candidate_id, scope_hash,
            facts["testSourceCommit"], facts["testGitTree"],
        )
    if evidence_id == "CANONICAL-OPERATIONS":
        require(refs["operationsSha256"]["path"] == CANONICAL_PATHS["operationsStatus"], "operations artifact must resolve canonical operations blob")
        operations = resolved["operationsSha256"]
        validate(operations, load_json(REPOSITORY / "v3-operations/schemas/release-status.schema.json"))
        require(all(operations.get(key) is True for key in ("sourceComplete", "evidenceComplete", "deploymentAuthorized", "deployed", "activated")), "operations blob does not prove completed stages")
    if evidence_id == "COMMERCIAL-AGREEMENT":
        agreement = resolved["agreementSha256"]
        validate(agreement, load_json(EVIDENCE_SCHEMA_DIR / "commercial-agreement.schema.json"))
        require(agreement["agreementType"] == "executed-pilot-commercial-agreement" and agreement["candidateId"] == candidate_id, "agreement candidate/type mismatch")
        require(
            agreement["subjectOrganizationId"] == manifest["subjectOrganizationId"]
            and agreement["partnerOrganizationId"] == manifest["partnerOrganizationId"],
            "agreement organization set mismatch",
        )
        require(
            {row["organizationId"] for row in agreement["legalParties"]}
            == {manifest["subjectOrganizationId"], manifest["partnerOrganizationId"]},
            "agreement legal-party set mismatch",
        )
        for party in agreement["legalParties"]:
            require_meaningful(party["legalName"], "agreement legal party")
        require(trust is not None, "agreement legal parties require an externally attested trust registry")
        trusted_legal_entities = {
            row["organizationId"]: row for row in trust.get("legalEntities", [])
        }
        require(
            set(trusted_legal_entities)
            == {manifest["subjectOrganizationId"], manifest["partnerOrganizationId"]},
            "agreement legal parties lack independent registry verification",
        )
        for party in agreement["legalParties"]:
            trusted_entity = trusted_legal_entities[party["organizationId"]]
            require(
                normalize_legal_name(party["legalName"])
                == normalize_legal_name(trusted_entity["legalName"]),
                "agreement legal name differs from independently verified registry name",
            )
        require_meaningful(agreement["governance"]["governingLaw"], "agreement governing law")
        require_meaningful(agreement["governance"]["exclusiveVenue"], "agreement exclusive venue")
        require(
            all("externalAttestationId" in row for row in agreement["signatories"]),
            "agreement signatories require externally attested named-person references",
        )
        relationship = scope_relationship(manifest)
        require(
            agreement["pilotScope"] == {
                "network": manifest["scope"]["network"],
                "chainId": manifest["scope"]["chainId"],
                "pilotType": manifest["scope"]["pilotType"],
                "activePartnerLimit": manifest["scope"]["activePartnerLimit"],
                "selectedModule": manifest["scope"]["selectedModule"],
                "selectedActionClass": manifest["scope"]["selectedActionClass"],
                "selectedRouteId": manifest["scope"]["selectedRouteId"],
                "requiredDeploymentContract": relationship["requiredDeploymentContract"],
                "rolloutStageId": relationship["rolloutStageId"],
                "productionClaim": False,
            },
            "agreement scope does not exactly match canonical selected pilot scope",
        )
        starts = parse_utc(agreement["term"]["effectiveAtUtc"], "agreement.term.effectiveAtUtc")
        ends = parse_utc(agreement["term"]["endsAtUtc"], "agreement.term.endsAtUtc")
        require(
            ends > starts
            and ends - starts == timedelta(days=agreement["term"]["durationDays"])
            and agreement["term"]["automaticRenewal"] is False,
            "agreement duration/termination ordering mismatch",
        )
        require(
            agreement["commercialTerms"]["paymentMode"] == "pull-only"
            and agreement["commercialTerms"]["rewardsConsumeCollateral"] is False
            and agreement["liability"]["bounded"] is True
            and agreement["privacy"]["explicitConsent"] is True
            and agreement["privacy"]["surveillanceRequired"] is False
            and agreement["privacy"]["dataMinimized"] is True
            and agreement["exitAndTermination"]["pauseSafeRefunds"] is True
            and agreement["exitAndTermination"]["terminalExitAvailable"] is True
            and agreement["exitAndTermination"]["principalSlashAllowed"] is False
            and agreement["support"]["maintenanceAndDeprecationAccepted"] is True
            and agreement["securityAndIncident"]["privateReportingRequired"] is True
            and agreement["securityAndIncident"]["incidentEscalationAccepted"] is True
            and agreement["changeControl"]["candidateRebindingRequired"] is True
            and agreement["changeControl"]["moduleByModuleOnly"] is True
            and agreement["subjectExecuted"] is True
            and agreement["partnerExecuted"] is True,
            "agreement omits mandatory commercial, privacy, exit, support, security, incident, or change terms",
        )
        validate_bound_approvals(
            agreement, "signatories",
            ["authorized-signatory", "partner-authorized-signatory"],
            manifest, identities,
            "vaultfire-executed-pilot-commercial-agreement-v2",
        )
    if evidence_id == "ACTUAL-CONTACTS":
        contacts = resolved["contactsArtifactSha256"]
        validate(contacts, load_json(EVIDENCE_SCHEMA_DIR / "contact-control.schema.json"))
        required_functions = sorted(CONTACT_FUNCTION_ROLES)
        require(
            contacts["candidateId"] == candidate_id
            and contacts["subjectOrganizationId"] == manifest["subjectOrganizationId"]
            and contacts["partnerOrganizationId"] == manifest["partnerOrganizationId"]
            and contacts["requiredFunctions"] == required_functions,
            "contact-control record candidate, organization, or required functions mismatch",
        )
        require(identities is not None, "contact-control record requires externally attested identities")
        manifest_roles = {row["roleId"]: row for row in manifest["roles"]}
        candidate_created = parse_utc(
            manifest["releaseCandidate"]["createdAtUtc"],
            "releaseCandidate.createdAtUtc",
        )
        as_of = parse_utc(manifest["asOfUtc"], "manifest.asOfUtc")
        seen_channels: set[str] = set()
        seen_receipt_paths: set[str] = set()
        seen_receipt_digests: set[str] = set()
        require(
            sorted(channel["function"] for channel in contacts["channels"]) == required_functions
            and all(channel["controlTested"] is True for channel in contacts["channels"]),
            "contact controls must uniquely cover and test every required function",
        )
        for channel in contacts["channels"]:
            function = channel["function"]; role = CONTACT_FUNCTION_ROLES[function]
            identity_id = assigned_identity(manifest, role)
            require(
                channel["roleId"] == role
                and channel["identityId"] == identity_id
                and identity_id in identities
                and role in identities[identity_id]["allowedRoles"],
                "contact function/role/identity binding mismatch",
            )
            expected_org = manifest["partnerOrganizationId"] if role == "partner-authorized-signatory" else manifest["subjectOrganizationId"]
            require(
                channel["organizationId"] == expected_org
                and identities[identity_id]["organizationId"] == expected_org,
                "contact organization separation mismatch",
            )
            require(
                channel["channelType"] in CONTACT_FUNCTION_CHANNEL_TYPES[function],
                "contact channel type is unsafe for its operational function",
            )
            if role != "partner-authorized-signatory":
                require(channel["channelId"] == manifest_roles[role]["contactChannelId"], "contact channel differs from exact manifest role channel")
            require(channel["channelId"] not in seen_channels, "contact channels must be distinct across required functions")
            seen_channels.add(channel["channelId"])
            reachability, nested_ref = resolve_candidate_json(
                channel["reachabilityTestPath"],
                channel["reachabilityTestSha256"],
                manifest,
                f"contact reachability {function}",
            )
            validate(
                reachability,
                load_json(EVIDENCE_SCHEMA_DIR / "contact-reachability-test.schema.json"),
            )
            require(
                reachability["candidateId"] == candidate_id
                and reachability["sourceCommit"]
                == manifest["releaseCandidate"]["sourceCommit"]
                and reachability["gitTree"]
                == manifest["releaseCandidate"]["gitTree"]
                and reachability["scopeSha256"] == scope_hash
                and reachability["function"] == function
                and reachability["roleId"] == role
                and reachability["identityId"] == identity_id
                and reachability["organizationId"] == expected_org
                and reachability["channelId"] == channel["channelId"]
                and reachability["channelType"] == channel["channelType"]
                and reachability["deliveryConfirmed"] is True
                and reachability["acknowledgmentConfirmed"] is True,
                "contact reachability evidence does not match exact channel/function/responder",
            )
            tested_at = parse_utc(
                reachability["testedAtUtc"], f"contactReachability.{function}.testedAtUtc"
            )
            require(
                parse_utc(manifest["releaseCandidate"]["createdAtUtc"], "releaseCandidate.createdAtUtc")
                <= tested_at
                <= parse_utc(manifest["asOfUtc"], "manifest.asOfUtc"),
                "contact reachability test is outside candidate readiness interval",
            )
            require(
                reachability["receiptPath"] not in seen_receipt_paths
                and reachability["receiptSha256"] not in seen_receipt_digests,
                "contact receipts must be unique across required functions",
            )
            seen_receipt_paths.add(reachability["receiptPath"])
            seen_receipt_digests.add(reachability["receiptSha256"])
            receipt, receipt_ref = resolve_candidate_json(reachability["receiptPath"],
                reachability["receiptSha256"],
                manifest,
                f"contact signed receipt {function}",
            )
            validate(
                receipt,
                load_json(EVIDENCE_SCHEMA_DIR / "contact-provider-receipt.schema.json"),
            )
            receipt_sent = parse_utc(
                receipt["sentAtUtc"], f"contactReceipt.{function}.sentAtUtc"
            )
            receipt_delivered = parse_utc(
                receipt["deliveredAtUtc"], f"contactReceipt.{function}.deliveredAtUtc"
            )
            receipt_ack = parse_utc(
                receipt["acknowledgedAtUtc"],
                f"contactReceipt.{function}.acknowledgedAtUtc",
            )
            require(
                receipt["candidateId"] == candidate_id
                and receipt["sourceCommit"]
                == manifest["releaseCandidate"]["sourceCommit"]
                and receipt["gitTree"] == manifest["releaseCandidate"]["gitTree"]
                and receipt["scopeSha256"] == scope_hash
                and receipt["function"] == function
                and receipt["roleId"] == role
                and receipt["identityId"] == identity_id
                and receipt["organizationId"] == expected_org
                and receipt["channelId"] == channel["channelId"]
                and receipt["channelType"] == channel["channelType"]
                and receipt["testNonce"] == reachability["testNonce"]
                and receipt["signerClass"] == "assigned-channel-controller"
                and receipt["deliveryConfirmed"] is True
                and receipt["acknowledgmentConfirmed"] is True
                and reachability["acknowledgmentSeconds"]
                == receipt["acknowledgmentSeconds"]
                and tested_at == receipt_sent
                and candidate_created <= receipt_sent
                <= receipt_delivered <= receipt_ack <= as_of
                and as_of - receipt_ack <= timedelta(days=30)
                and int((receipt_ack - receipt_sent).total_seconds())
                == receipt["acknowledgmentSeconds"],
                "contact receipt function, signer, channel, outcome, or timing mismatch",
            )
            receipt_unsigned = {
                key: value for key, value in receipt.items()
                if key not in {"signedPayloadSha256", "signatureBase64"}
            }
            receipt_payload = canonical({
                "domain": "vaultfire-contact-control-receipt-v1",
                "record": receipt_unsigned,
            })
            require(
                receipt["signedPayloadSha256"]
                == hashlib.sha256(receipt_payload).hexdigest(),
                "contact receipt signed payload mismatch",
            )
            try:
                receipt_signature = base64.b64decode(
                    receipt["signatureBase64"], validate=True
                )
            except (ValueError, binascii.Error) as exc:
                raise Blocked("invalid contact receipt signature encoding") from exc
            require(
                verify_ed25519(
                    identities[identity_id]["_public"],
                    receipt_signature,
                    receipt_payload,
                ),
                "contact receipt signature is not from exact assigned channel controller",
            )
            additional_resolved_refs.append(nested_ref)
            additional_resolved_refs.append(receipt_ref)
        require(contacts["channelReusePolicy"] == "prohibited-across-required-functions", "contact channel reuse is not safely prohibited")
    if evidence_id == "SIGNATURES":
        signatures = resolved["signatureSetSha256"]
        validate_signature_set(signatures, manifest, candidate_id, identities, trust)
    if evidence_id in {
        "PULL-PAYMENTS", "FAIL-CLOSED-APIS", "PAUSE-SAFE-EXITS",
        "PROTECTED-DECISION-INPUTS",
    }:
        validate_test_results(
            resolved["testResultsSha256"], EVIDENCE_SPECS[evidence_id]["claim"],
            manifest, candidate_id, scope_hash,
            manifest["releaseCandidate"]["sourceCommit"],
            manifest["releaseCandidate"]["gitTree"],
        )
    if evidence_id == "BOUNDED-LIABILITIES":
        caps = resolved["capsArtifactSha256"]
        validate(caps, load_json(EVIDENCE_SCHEMA_DIR / "bounded-liabilities.schema.json"))
        require(
            set(caps) == {
                "schemaVersion", "recordType", "candidateId",
                "subjectOrganizationId", "partnerOrganizationId", "currency",
                "amountUnit", "perEventCap", "aggregateCap", "maximumLoss",
                "reserveAmount", "maximumCoveredEvents",
                "remedies", "residualLiability", "acceptedBy",
            },
            "bounded-liability artifact fields must be exact",
        )
        require(
            caps["schemaVersion"] == "3.0.0"
            and caps["recordType"] == "bounded-liability-decision"
            and caps["candidateId"] == candidate_id
            and caps["subjectOrganizationId"] == manifest["subjectOrganizationId"]
            and caps["partnerOrganizationId"] == manifest["partnerOrganizationId"],
            "bounded-liability artifact candidate/organization mismatch",
        )
        require(
            all(
                type(caps[key]) is str and re.fullmatch(r"[1-9][0-9]{0,77}", caps[key])
                for key in ("perEventCap", "aggregateCap", "maximumLoss", "reserveAmount")
            )
            and caps["currency"] in {"USD", "USDC"}
            and caps["amountUnit"] == (
                "usd-cents" if caps["currency"] == "USD" else "usdc-micro-units"
            )
            and type(caps["maximumCoveredEvents"]) is int
            and type(caps["remedies"]) is list and caps["remedies"]
            and type(caps["residualLiability"]) is dict
            and type(caps["acceptedBy"]) is list,
            "bounded-liability artifact lacks meaningful numeric caps/remedies/acceptance",
        )
        per_event = int(caps["perEventCap"])
        aggregate = int(caps["aggregateCap"])
        maximum = int(caps["maximumLoss"])
        reserve = int(caps["reserveAmount"])
        require(
            per_event <= aggregate
            and aggregate == per_event * caps["maximumCoveredEvents"]
            and maximum == aggregate
            and reserve >= maximum,
            "bounded-liability cap arithmetic, maximum loss, or reserve adequacy is inconsistent",
        )
        require(
            len({row["remedyType"] for row in caps["remedies"]})
            == len(caps["remedies"]),
            "bounded-liability remedy types must be unique",
        )
        for remedy in caps["remedies"]:
            require_meaningful(remedy["description"], "bounded-liability remedy")
            require(
                remedy["amountUnit"] == caps["amountUnit"]
                and int(remedy["maximumAmount"]) <= aggregate,
                "bounded-liability remedy unit or maximum is inconsistent",
            )
        require(
            sum(int(remedy["maximumAmount"]) for remedy in caps["remedies"])
            <= aggregate,
            "cumulative bounded-liability remedy maxima exceed aggregate cap",
        )
        residual = caps["residualLiability"]
        require_meaningful(
            residual["description"],
            "bounded-liability residual terms",
        )
        category_caps = residual["categoryCaps"]
        require(
            residual["allocationBasis"]
            == "all-liability-categories-within-maximum-loss"
            and residual["stackingPolicy"] == "cumulative-within-aggregate-cap"
            and residual["remedyTreatment"]
            == "remedies-are-suballocations-not-additional-exposure"
            and residual["uncappedCategories"] == []
            and {row["category"] for row in category_caps}
            == {
                "general", "fraud", "willful-misconduct",
                "confidentiality-breach", "data-protection-breach",
            }
            and len({row["category"] for row in category_caps}) == 5
            and all(
                row["amountUnit"] == caps["amountUnit"]
                and int(row["maximumAmount"]) <= maximum
                for row in category_caps
            )
            and sum(int(row["maximumAmount"]) for row in category_caps)
            <= maximum,
            "residual-liability categories, units, stacking, or allocations "
            "contradict the asserted maximum loss",
        )
        validate_bound_approvals(
            caps, "acceptedBy",
            ["authorized-signatory", "partner-authorized-signatory"],
            manifest, identities,
            "vaultfire-bounded-liability-decision-v1",
        )
    if evidence_id == "PRIVACY-CROSS-CHAIN":
        privacy = resolved["privacyArtifactSha256"]
        validate(privacy, load_json(EVIDENCE_SCHEMA_DIR / "privacy-portability.schema.json"))
        require(
            set(privacy) == {
                "schemaVersion", "recordType", "candidateId",
                "subjectOrganizationId", "partnerOrganizationId", "chains",
                "consentMode", "portableCommitmentClasses",
                "unlinkabilityTestResultsSha256", "crossChainValueFlow",
            },
            "privacy-portability artifact fields must be exact",
        )
        require(
            privacy["schemaVersion"] == "1.0.0"
            and privacy["recordType"] == "chain-specific-trust-portability"
            and privacy["candidateId"] == candidate_id
            and privacy["subjectOrganizationId"] == manifest["subjectOrganizationId"]
            and privacy["partnerOrganizationId"] == manifest["partnerOrganizationId"]
            and privacy["chains"] == ["base"]
            and privacy["consentMode"] == "explicit"
            and type(privacy["portableCommitmentClasses"]) is list
            and privacy["portableCommitmentClasses"]
            and set(privacy["portableCommitmentClasses"])
            <= {"consent-receipt", "purpose-bound-commitment", "revocation-reference"}
            and SHA256.fullmatch(privacy["unlinkabilityTestResultsSha256"] or "")
            and privacy["crossChainValueFlow"] is False,
            "privacy-portability artifact semantic controls mismatch",
        )
        require(
            privacy["unlinkabilityTestResultsSha256"]
            == facts["unlinkabilityTestResultsSha256"],
            "privacy artifact unlinkability digest differs from objective evidence binding",
        )
        additional_resolved_refs.extend(validate_unlinkability_results(
            resolved["unlinkabilityTestResultsSha256"],
            manifest, candidate_id, scope_hash, identities,
        ))
    if evidence_id in OPERATIONAL_ACCEPTANCE_POLICIES:
        policy = OPERATIONAL_ACCEPTANCE_POLICIES[evidence_id]
        additional_resolved_refs.extend(validate_operational_acceptance(
            resolved[policy["digestFact"]],
            evidence_id, manifest, candidate_id, scope_hash, identities, facts,
            resolved.get("exerciseEvidenceSha256")
            if evidence_id == "INCIDENT-PLAN-ACCEPTANCE"
            else None,
        ))
    if evidence_id == "CANDIDATE-BINDING":
        require(facts["sourceCommit"] == manifest["releaseCandidate"]["sourceCommit"], "candidate-binding artifact source mismatch")
        require(facts["gitTree"] == manifest["releaseCandidate"]["gitTree"], "candidate-binding artifact tree mismatch")
    if evidence_id == "EXACT-COMMIT-TESTS":
        require(facts["testSourceCommit"] == manifest["releaseCandidate"]["sourceCommit"], "test artifact source commit mismatch")
        require(facts["testGitTree"] == manifest["releaseCandidate"]["gitTree"], "test artifact tree mismatch")
    return [(ref["path"], ref["sha256"]) for ref in refs.values()] + additional_resolved_refs


def post_commit_payload(manifest: dict) -> bytes:
    release = manifest["releaseCandidate"]
    return canonical({
        "domain": "vaultfire-partner-post-commit-attestation-v1",
        "envelopeId": release["envelopeId"],
        "candidateId": release["candidateId"],
        "sourceCommit": release["sourceCommit"],
        "gitTree": release["gitTree"],
        "evidenceCommit": release["evidenceCommit"],
        "evidenceTree": release["evidenceTree"],
        "artifactManifest": release["artifactManifest"],
    })


def validate_post_commit_signatures(
    manifest: dict, identities: dict[str, dict]
) -> None:
    attestation = manifest["attestation"]
    assignments = {row["roleId"]: row["identityId"] for row in manifest["roles"]}
    required = {
        "release-manager": assignments["release-manager"],
        "independent-reviewer": assignments["independent-reviewer"],
        "authorized-signatory": assignments["authorized-signatory"],
        "partner-authorized-signatory": attestation["partnerAcceptedByIdentityId"],
    }
    signatures = attestation["postCommitSignatures"]
    require(
        type(signatures) is list and len(signatures) == 4
        and {row["roleId"] for row in signatures} == set(required)
        and {row["identityId"] for row in signatures} == set(required.values()),
        "post-commit envelope requires exact four-role authority signature set",
    )
    payload = post_commit_payload(manifest)
    payload_sha = hashlib.sha256(payload).hexdigest()
    seen: set[str] = set()
    for row in signatures:
        role = row["roleId"]; identity_id = row["identityId"]
        require(
            set(row) == {
                "identityId", "roleId", "signedPayloadSha256", "signatureBase64"
            }
            and required[role] == identity_id
            and identity_id in identities
            and role in identities[identity_id]["allowedRoles"]
            and row["signedPayloadSha256"] == payload_sha
            and row["signatureBase64"] not in seen,
            "post-commit signature role/identity/payload binding mismatch",
        )
        seen.add(row["signatureBase64"])
        try:
            detached = base64.b64decode(row["signatureBase64"], validate=True)
        except (ValueError, binascii.Error) as exc:
            raise Blocked("post-commit signature encoding invalid") from exc
        require(
            verify_ed25519(identities[identity_id]["_public"], detached, payload),
            "post-commit envelope signature invalid",
        )


def validate_evidence(manifest: dict, candidate_id: str, scope_hash: str, as_of: datetime) -> None:
    identities, trust = load_trust(as_of)
    require(trust["subjectOrganizationId"] == manifest["subjectOrganizationId"], "trust registry subject organization mismatch")
    require(trust["partnerOrganizationId"] == manifest["partnerOrganizationId"], "trust registry partner organization mismatch")
    assignments = {row["roleId"]: row for row in manifest["roles"]}
    assigned_ids = []
    for role, row in assignments.items():
        require(IDENTITY.fullmatch(row["identityId"] or "") is not None, f"role {role}: trusted identity required")
        require(CHANNEL.fullmatch(row["contactChannelId"] or "") is not None, f"role {role}: controlled channel ID required")
        require(row["identityId"] in identities and role in identities[row["identityId"]]["allowedRoles"], f"role {role}: identity is not trusted/allowed")
        assigned_ids.append(row["identityId"])
    require(len(set(assigned_ids)) == len(assigned_ids), "mandatory internal roles must be held by distinct trusted identities")

    att = manifest["attestation"]
    att_roles = {
        "preparedByIdentityId": "release-manager",
        "reviewedByIdentityId": "independent-reviewer",
        "authorizedByIdentityId": "authorized-signatory",
        "partnerAcceptedByIdentityId": "partner-authorized-signatory",
    }
    att_ids = []
    for field, role in att_roles.items():
        identity_id = att[field]
        require(identity_id in identities and role in identities[identity_id]["allowedRoles"], f"{field}: trusted identity with exact role required")
        if role in assignments:
            require(identity_id == assignments[role]["identityId"], f"{field}: attestor must equal identity assigned to exact manifest role")
        att_ids.append(identity_id)
    require(len(set(att_ids)) == len(att_ids), "preparer, reviewer, authorizer, and partner acceptor must be separate identities")
    partner_id = att["partnerAcceptedByIdentityId"]
    require(partner_id not in assigned_ids, "partner identity must be separate from every internal role identity")
    require(identities[partner_id]["identityClass"] == "partner-human", "partner acceptor must be externally attested as a partner human")
    require(all(identities[i]["identityClass"] == "internal-human" for i in assigned_ids), "internal roles require externally attested internal humans")
    signed_at = parse_utc(att["signedAtUtc"], "attestation.signedAtUtc")
    require(att["signatureEvidenceId"] == "SIGNATURES", "signature evidence link required")
    require(signed_at <= as_of, "readiness signature cannot follow asOfUtc")

    evidence = manifest["evidence"]
    require(len(evidence) == len(MANDATORY_IDS) and {e["id"] for e in evidence} == MANDATORY_IDS, "exactly one evidence record per mandatory ID required")
    paths = [e["path"] for e in evidence]; hashes = [e["sha256"] for e in evidence]
    require(len(set(paths)) == len(paths), "evidence files must be unique")
    require(len(set(hashes)) == len(hashes), "evidence digests must be unique; generic reused files are prohibited")
    approved_times: list[datetime] = []
    objective_paths: list[str] = []
    objective_hashes: list[str] = []
    resolved_blob_paths: list[str] = []
    resolved_blob_hashes: list[str] = []
    objective_by_id: dict[str, dict] = {}
    objective_digest_by_id: dict[str, str] = {}
    expected_artifact_entries: dict[str, tuple[str, str]] = {
        CANONICAL_PATHS["trustedIdentities"]: (
            manifest["releaseCandidate"]["canonicalBindings"]["trustedIdentities"]["sha256"],
            "trust-registry",
        )
    }
    for row in evidence:
        eid = row["id"]; expected = EVIDENCE_SPECS[eid]
        require(row["claimType"] == expected["claim"], f"evidence {eid}: claim type mismatch")
        expected_path = f"{EVIDENCE_ROOT}/{eid.lower()}.json"
        require(row["path"] == expected_path, f"evidence {eid}: path must be type-specific")
        path = safe_repo_file(row["path"], f"evidence {eid}", EVIDENCE_ROOT, ".json")
        require_tracked_exact(row["path"], path, manifest["releaseCandidate"]["evidenceCommit"], f"evidence {eid}")
        require(row["sha256"] == digest(path), f"evidence {eid}: digest mismatch")
        expected_artifact_entries[row["path"]] = (row["sha256"], "evidence-claim")
        require(row["candidateId"] == candidate_id, f"evidence {eid}: not bound to exact candidate")
        claim = load_json(path)
        exact = {"schemaVersion", "evidenceId", "claimType", "candidateId", "scopeSha256", "subjectOrganizationId", "partnerOrganizationId", "issuedAtUtc", "approvedAtUtc", "expiresAtUtc", "approvedByIdentityId", "approvedByRole", "controlledSystemRef", "statement", "artifactRefs", "signedPayloadSha256", "signatureBase64"}
        require(set(claim) == exact, f"evidence {eid}: claim fields must be exact")
        require(claim["schemaVersion"] == "1.0.0" and claim["evidenceId"] == eid and claim["claimType"] == expected["claim"], f"evidence {eid}: typed identity mismatch")
        require(claim["candidateId"] == candidate_id and claim["scopeSha256"] == scope_hash, f"evidence {eid}: candidate/scope binding mismatch")
        require(claim["subjectOrganizationId"] == manifest["subjectOrganizationId"], f"evidence {eid}: subject organization mismatch")
        require(claim["partnerOrganizationId"] == manifest["partnerOrganizationId"], f"evidence {eid}: partner organization mismatch")
        require(SYSTEM_REF.fullmatch(claim["controlledSystemRef"] or "") is not None, f"evidence {eid}: controlled-system reference required")
        require(claim["statement"] == expected["statement"], f"evidence {eid}: semantic statement mismatch")
        identity_id = claim["approvedByIdentityId"]; role = claim["approvedByRole"]
        require(role in expected["roles"], f"evidence {eid}: approver role not allowed for claim type")
        require(identity_id in identities and role in identities[identity_id]["allowedRoles"], f"evidence {eid}: approver identity/role not trusted")
        if role == "partner-authorized-signatory":
            require(identity_id == att["partnerAcceptedByIdentityId"], f"evidence {eid}: partner approver differs from partner authority chain")
        else:
            require(role in assignments and identity_id == assignments[role]["identityId"], f"evidence {eid}: approver must equal identity assigned to exact manifest role")
        issued = parse_utc(claim["issuedAtUtc"], f"evidence {eid}.issuedAtUtc")
        approved = parse_utc(claim["approvedAtUtc"], f"evidence {eid}.approvedAtUtc")
        expires = parse_utc(claim["expiresAtUtc"], f"evidence {eid}.expiresAtUtc")
        created = parse_utc(manifest["releaseCandidate"]["createdAtUtc"], "releaseCandidate.createdAtUtc")
        require(created <= issued <= approved <= signed_at <= as_of, f"evidence {eid}: timestamp causality/order invalid")
        require(as_of - approved <= timedelta(days=30), f"evidence {eid}: approval stale")
        require(as_of < expires <= issued + timedelta(days=366), f"evidence {eid}: expiry invalid")
        approved_times.append(approved)
        refs = claim["artifactRefs"]
        require(isinstance(refs, list) and len({r["path"] for r in refs}) == len(refs), f"evidence {eid}: artifact references invalid/duplicated")
        for ref in refs:
            require(set(ref) == {"path", "sha256"}, f"evidence {eid}: artifact reference fields drift")
            artifact = safe_repo_file(ref["path"], f"evidence {eid} artifact")
            require_tracked_exact(ref["path"], artifact, manifest["releaseCandidate"]["evidenceCommit"], f"evidence {eid} artifact")
            require(ref["sha256"] == digest(artifact), f"evidence {eid}: artifact digest mismatch")
            expected_artifact_entries[ref["path"]] = (
                ref["sha256"],
                "objective-artifact"
                if ref["path"] == expected["prefixes"][0]
                else "supporting-artifact",
            )
        for required_path in expected["prefixes"]:
            require(any(ref["path"] == required_path for ref in refs), f"evidence {eid}: required semantic artifact absent")
        objective_path = expected["prefixes"][0]
        objective_ref = next(ref for ref in refs if ref["path"] == objective_path)
        objective_paths.append(objective_path)
        objective_hashes.append(objective_ref["sha256"])
        objective_artifact = load_json(REPOSITORY / objective_path)
        objective_by_id[eid] = objective_artifact
        objective_digest_by_id[eid] = objective_ref["sha256"]
        resolved_refs = validate_objective_artifact(
            objective_artifact, eid, manifest, candidate_id, scope_hash,
            identities, trust,
        )
        resolved_blob_paths.extend(path for path, _ in resolved_refs)
        resolved_blob_hashes.extend(sha256 for _, sha256 in resolved_refs)
        for resolved_path, resolved_sha256 in resolved_refs:
            expected_artifact_entries[resolved_path] = (
                resolved_sha256, "resolved-artifact"
            )
        unsigned = {k: v for k, v in claim.items() if k not in {"signedPayloadSha256", "signatureBase64"}}
        payload = canonical(unsigned)
        require(claim["signedPayloadSha256"] == hashlib.sha256(payload).hexdigest(), f"evidence {eid}: signed payload digest mismatch")
        try:
            signature = base64.b64decode(claim["signatureBase64"], validate=True)
        except (ValueError, binascii.Error) as exc:
            raise Blocked(f"evidence {eid}: invalid signature encoding") from exc
        require(verify_ed25519(identities[identity_id]["_public"], signature, payload), f"evidence {eid}: Ed25519 signature invalid")
    agreement_objective = objective_by_id["COMMERCIAL-AGREEMENT"]
    agreement_ref = agreement_objective["blobRefs"]["agreementSha256"]
    agreement = load_json(REPOSITORY / agreement_ref["path"])
    require(
        agreement["liability"]["capsArtifactSha256"]
        == objective_by_id["BOUNDED-LIABILITIES"]["facts"]["capsArtifactSha256"]
        and agreement["privacy"]["portabilityArtifactSha256"]
        == objective_by_id["PRIVACY-CROSS-CHAIN"]["facts"]["privacyArtifactSha256"]
        and agreement["support"]["supportAcceptanceSha256"]
        == objective_digest_by_id["SUPPORT-SLA-SELECTION"]
        and agreement["securityAndIncident"]["securityAcceptanceSha256"]
        == objective_digest_by_id["SECURITY-POLICY-ACCEPTANCE"]
        and agreement["securityAndIncident"]["incidentAcceptanceSha256"]
        == objective_digest_by_id["INCIDENT-PLAN-ACCEPTANCE"]
        and agreement["changeControl"]["raciAcceptanceSha256"]
        == objective_digest_by_id["CHANGE-RACI-ACCEPTANCE"]
        and agreement["linkedEvidence"]["signatureSetSha256"]
        == objective_by_id["SIGNATURES"]["facts"]["signatureSetSha256"],
        "commercial agreement evidence links do not cross-bind the exact candidate artifact set",
    )
    require(max(approved_times) <= signed_at, "attestation signature predates evidence approval")
    require(len(set(objective_paths)) == len(MANDATORY_IDS), "objective artifact paths must be unique per evidence type")
    require(len(set(objective_hashes)) == len(MANDATORY_IDS), "objective artifact blobs/digests must be unique per evidence type")
    require(
        len(set(resolved_blob_paths)) == len(resolved_blob_paths),
        "resolved typed evidence blob paths must be globally unique",
    )
    require(
        len(set(resolved_blob_hashes)) == len(resolved_blob_hashes),
        "resolved typed evidence blob digests must be globally unique",
    )
    artifact_manifest = load_json(
        REPOSITORY / manifest["releaseCandidate"]["artifactManifest"]["path"]
    )
    actual_entries = {
        entry["path"]: (entry["sha256"], entry["kind"])
        for entry in artifact_manifest["entries"]
    }
    require(
        actual_entries == expected_artifact_entries,
        "artifact manifest must exactly enumerate every claim, objective, supporting, resolved, and trust blob",
    )
    validate_post_commit_signatures(manifest, identities)


def run(path: Path) -> dict:
    try:
        manifest = load_json(path)
        require(isinstance(manifest, dict), "manifest top level must be an object")
        validate_shape(manifest)
    except StrictJSONError as exc:
        raise Blocked(str(exc)) from exc
    as_of = parse_utc(manifest["asOfUtc"], "asOfUtc")
    now = datetime.now(timezone.utc)
    require(as_of <= now + timedelta(minutes=5), "asOfUtc is in the future")
    if manifest["partnerReady"]:
        require(re.fullmatch(r"organization:[0-9a-f]{64}", manifest["subjectOrganizationId"] or "") is not None, "candidate subject organization required")
        require(re.fullmatch(r"organization:[0-9a-f]{64}", manifest["partnerOrganizationId"] or "") is not None, "candidate partner organization required")
        require(manifest["subjectOrganizationId"] != manifest["partnerOrganizationId"], "candidate subject and partner organizations must be distinct")
        require(now - as_of <= timedelta(hours=24), "ready manifest is stale")
        # Structural stop: no positive path exists until a reviewed tracked
        # policy pins a real external human authority.
        load_trust(as_of)
        scope_hash = validate_scope(manifest)
        _envelope_id, candidate_id, _, _, _ = validate_candidate(
            manifest, scope_hash, as_of, path
        )
        validate_evidence(manifest, candidate_id, scope_hash, as_of)
    else:
        validate_blocked(manifest)
    return {
        "verified": "Vaultfire organizational readiness manifest",
        "schemaValidation": "dependency-free Draft 2020-12 strict subset: passed",
        "manifest": str(path),
        "partnerReady": manifest["partnerReady"],
        "status": manifest["status"],
        "mandatoryEvidenceCount": len(MANDATORY_IDS),
        "externalHumanBlockerCount": len(EXTERNAL_IDS),
        "openBlockers": sorted(row["id"] for row in manifest["blockers"] if row["status"] == "open"),
        "networkActions": "none",
    }


if __name__ == "__main__":
    manifest_path = Path(sys.argv[1]).resolve() if len(sys.argv) == 2 else DEFAULT_MANIFEST
    try:
        print(json.dumps(run(manifest_path), indent=2))
    except (KeyError, TypeError, Blocked) as exc:
        print(f"ORGANIZATIONAL READINESS BLOCKED: {exc}", file=sys.stderr)
        raise SystemExit(1)
