OpenIslet

scripts/verify_iip0041_clinical_h1_cd64t_siglec.py

EXP-028 (CAND-031 / Target IIP-0041 — Bucket 2A) Remediated Verification Suite

script Release v0.8.0 gen-eb955f8266035aba 984 KB · 69 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0041_clinical_h1_cd64t_siglec.py · SHA-256: f004cf6d8259b8b4…

    return hashlib.sha256(
        json.dumps(body, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
    ).hexdigest()


def compute_gate28a_attestation_sha256(attestation: dict[str, Any]) -> str:
    """Canonical SHA-256 digest of a Gate 28-A attestation excluding `attestation_sha256` and `record_sha256`."""
    return compute_gate28a_record_sha256(attestation)


def build_gate28a_prespecification_attestation(
    *,
    cohort_id: str,
    cohort_canonical_sha256: str,
    protocol_or_sap_id: str = "SAP-GATE28A-2026-V1",
    prespecified_before_unblinding: bool = True,
    single_compatible_cohort_confirmed: bool = True,
    issuer_authority_id: str = "OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
) -> dict[str, Any]:
    """Build a SHA-256-authenticated PRESPECIFICATION_ATTESTATION record bound to cohort_id and full cohort_canonical_sha256."""
    rec: dict[str, Any] = {
        "record_type": "PRESPECIFICATION_ATTESTATION",
        "cohort_id": cohort_id,
        "cohort_canonical_sha256": cohort_canonical_sha256,
        "cohort_ledger_sha256": cohort_canonical_sha256,
        "protocol_or_sap_id": protocol_or_sap_id,
        "prespecified_before_unblinding": prespecified_before_unblinding,
        "single_compatible_cohort_confirmed": single_compatible_cohort_confirmed,
        "issuer_authority_id": issuer_authority_id,
    }
    digest = compute_gate28a_record_sha256(rec)
    rec["record_sha256"] = digest
    rec["attestation_sha256"] = digest
    return rec


def build_gate28a_source_verification_attestation(
    *,
    cohort_id: str,
    cohort_canonical_sha256: str,
    parallel_cmc_readiness_ledger_sha256: str,
    primary_source_citation_id: str = "PMID:99999999",
    primary_peer_reviewed_full_text_verified: bool = True,
    parallel_cmc_readiness_ledger_disclosed: bool = True,
    issuer_authority_id: str = "OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
) -> dict[str, Any]:
    """Build a SHA-256-authenticated SOURCE_VERIFICATION_ATTESTATION record bound to full cohort_canonical_sha256 and CMC ledger SHA-256."""
    rec: dict[str, Any] = {
        "record_type": "SOURCE_VERIFICATION_ATTESTATION",
        "cohort_id": cohort_id,
        "cohort_canonical_sha256": cohort_canonical_sha256,
        "cohort_ledger_sha256": cohort_canonical_sha256,
        "primary_source_citation_id": primary_source_citation_id,
        "primary_peer_reviewed_full_text_verified": primary_peer_reviewed_full_text_verified,
        "parallel_cmc_readiness_ledger_disclosed": parallel_cmc_readiness_ledger_disclosed,
        "parallel_cmc_readiness_ledger_sha256": parallel_cmc_readiness_ledger_sha256,
        "parallel_cmc_ledger_sha256": parallel_cmc_readiness_ledger_sha256,
        "issuer_authority_id": issuer_authority_id,
    }
    digest = compute_gate28a_record_sha256(rec)
    rec["record_sha256"] = digest
    rec["attestation_sha256"] = digest
    return rec


def build_gate28a_verified_lot_to_bank_manifest(
    *,
    cohort_id: str,
    lot_to_mcb_manifest: dict[str, str],
    lot_to_wcb_manifest: dict[str, str] | None = None,
    manifest_source_id: str = "QA-BANK-MANIFEST-2026-V1",
    issuer_authority_id: str = "OPENISLET_QA_RELEASE_BOARD_V1",
) -> dict[str, Any]:
    """Build a SHA-256-authenticated VERIFIED_LOT_TO_BANK_MANIFEST store record."""
    mcb_norm, eff_wcb, any_wcb, man_errs = _merge_and_validate_bank_manifests(
        lot_to_mcb_manifest,
        lot_to_wcb_manifest,
        context="VERIFIED_LOT_TO_BANK_MANIFEST",
    )
    if man_errs or mcb_norm is None:
        raise ValueError(f"Invalid lot/bank manifest for store record: {man_errs}")
    merged_wcb: dict[str, str] | None = dict(sorted(eff_wcb.items())) if (any_wcb and eff_wcb) else None
    rec: dict[str, Any] = {
        "record_type": "VERIFIED_LOT_TO_BANK_MANIFEST",
        "cohort_id": cohort_id,
        "manifest_source_id": manifest_source_id,
        "issuer_authority_id": issuer_authority_id,
        "lot_to_mcb_manifest": dict(sorted(mcb_norm.items())),
        "lot_to_wcb_manifest": merged_wcb,
    }
    rec["record_sha256"] = compute_gate28a_record_sha256(rec)
    return rec


def build_gate28a_parallel_cmc_ledger_bytes(
    *,
    cohort_id: str,
    lot_ledger: list[dict[str, Any]],
    issuer_authority_id: str = "OPENISLET_QA_RELEASE_BOARD_V1",
) -> tuple[bytes, str]:
    """Build canonical UTF-8 payload bytes and exact SHA-256 for a PARALLEL_CMC_READINESS_LEDGER store artifact."""
    payload_obj = {
        "record_type": "PARALLEL_CMC_READINESS_LEDGER",
        "cohort_id": cohort_id,
        "issuer_authority_id": issuer_authority_id,
        "lot_ledger": copy.deepcopy(lot_ledger),
    }
    raw_bytes = (json.dumps(payload_obj, indent=2, sort_keys=True, ensure_ascii=False) + "\n").encode("utf-8")
    return raw_bytes, sha256_bytes(raw_bytes)


def write_gate28a_trusted_clinical_store(
    store_path: pathlib.Path | str,
    *,
    prespecification_attestations: list[dict[str, Any]] | None = None,
    source_verification_attestations: list[dict[str, Any]] | None = None,
    verified_lot_to_bank_manifests: list[dict[str, Any]] | None = None,
    parallel_cmc_readiness_ledgers: list[bytes | dict[str, Any]] | None = None,
    store_authority_id: str = "OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
) -> pathlib.Path:
    """
    Persist Gate 28-A clinical attestations, verified lot->bank manifests, and raw PARALLEL_CMC_READINESS_LEDGER
    payload bytes into an independent external trusted clinical store (JSON registry file OR directory layout).
    """
    sp = pathlib.Path(store_path)
    prespecs = list(prespecification_attestations or [])
    sources = list(source_verification_attestations or [])
    manifests = list(verified_lot_to_bank_manifests or [])
    cmc_items = list(parallel_cmc_readiness_ledgers or [])

    for rec in prespecs + sources + manifests:
        if not isinstance(rec, dict) or not _is_valid_sha256_hex(rec.get("record_sha256")):
            raise ValueError("Every JSON record written to trusted_clinical_store must carry a valid 64-hex record_sha256")

    cmc_bytes_pairs: list[tuple[str, bytes]] = []
    for item in cmc_items:
        if isinstance(item, bytes):
            rb = item
        elif isinstance(item, dict):
            rb = (json.dumps(item, indent=2, sort_keys=True, ensure_ascii=False) + "\n").encode("utf-8")
        else:
            raise ValueError("parallel_cmc_readiness_ledgers items must be bytes or dict")
        cmc_bytes_pairs.append((sha256_bytes(rb), rb))

    if sp.suffix.lower() == ".json":
        if sp.is_file():
            doc = load_strict_json_bytes(sp.read_bytes(), f"trusted_clinical_store:{sp.name}")
        else:
            doc = {
                "schema_version": TRUSTED_CLINICAL_STORE_SCHEMA_VERSION,
                "store_authority_id": store_authority_id,
                "prespecification_attestations": {},
                "source_verification_attestations": {},
                "verified_lot_to_bank_manifests": {},
                "parallel_cmc_readiness_ledgers": {},
            }
        for rec in prespecs:
            doc.setdefault("prespecification_attestations", {})[rec["record_sha256"]] = copy.deepcopy(rec)
        for rec in sources:
            doc.setdefault("source_verification_attestations", {})[rec["record_sha256"]] = copy.deepcopy(rec)
        for rec in manifests:
            doc.setdefault("verified_lot_to_bank_manifests", {})[rec["record_sha256"]] = copy.deepcopy(rec)
        for digest, rb in cmc_bytes_pairs:
            doc.setdefault("parallel_cmc_readiness_ledgers", {})[digest] = {
                "payload_sha256": digest,
                "raw_payload_utf8": rb.decode("utf-8"),
            }
        sp.parent.mkdir(parents=True, exist_ok=True)
        sp.write_text(json.dumps(doc, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8")
        return sp

    # Directory store layout
    for sub in (
        "prespecification_attestations",
        "source_verification_attestations",
        "verified_lot_to_bank_manifests",
        "parallel_cmc_readiness_ledgers",
    ):
        (sp / sub).mkdir(parents=True, exist_ok=True)
    meta_file = sp / "store_metadata.json"
    if not meta_file.is_file():
        meta_file.write_text(
            json.dumps(
                {"schema_version": TRUSTED_CLINICAL_STORE_SCHEMA_VERSION, "store_authority_id": store_authority_id},
                indent=2,
                sort_keys=True,
            ) + "\n",
            encoding="utf-8",
        )
    for rec in prespecs:
        (sp / "prespecification_attestations" / f"{rec['record_sha256']}.json").write_text(
            json.dumps(rec, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8"
        )
    for rec in sources:
        (sp / "source_verification_attestations" / f"{rec['record_sha256']}.json").write_text(
            json.dumps(rec, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8"
        )
    for rec in manifests:
        (sp / "verified_lot_to_bank_manifests" / f"{rec['record_sha256']}.json").write_text(
            json.dumps(rec, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8"
        )
    for digest, rb in cmc_bytes_pairs:
        (sp / "parallel_cmc_readiness_ledgers" / f"{digest}.json").write_bytes(rb)
    return sp


def _lookup_gate28a_trusted_record(
    store_path: pathlib.Path | str | None,
    *,
    category: str,
    expected_sha256: Any,
    allowed_issuers: frozenset[str] | set[str],
) -> tuple[dict[str, Any] | None, str | None, str | None]:
    """Resolve a Gate 28-A JSON record STRICTLY from an independent external trusted_clinical_store."""
    if store_path is None:
        return None, "trusted_clinical_store not provided", None
    if not isinstance(store_path, (pathlib.Path, str)):
        return None, "trusted_clinical_store has invalid path type", None
    sp = pathlib.Path(store_path)
    if not sp.exists():
        return None, f"trusted_clinical_store path missing: {sp.name}", f"missing:{sp.name}"
    if not _is_valid_sha256_hex(expected_sha256):
        return None, f"Invalid 64-hex reference digest for {category}: {expected_sha256!r}", f"store:{sp.name}"

    try:
        if sp.is_file():
            doc = load_strict_json_bytes(sp.read_bytes(), f"trusted_clinical_store:{sp.name}")
            if not isinstance(doc, dict):
                return None, "Trusted clinical store registry JSON must be an object", f"registry_file:{sp.name}"
            if doc.get("schema_version") != TRUSTED_CLINICAL_STORE_SCHEMA_VERSION:
                return None, f"Trusted clinical store schema_version mismatch: {doc.get('schema_version')!r}", f"registry_file:{sp.name}"
            if _strict_literal_id(doc.get("store_authority_id")) not in allowed_issuers:
                return None, f"Trusted clinical store authority {doc.get('store_authority_id')!r} not in allowlist", f"registry_file:{sp.name}"
            bucket = doc.get(category)
            if not isinstance(bucket, dict):
                return None, f"Trusted clinical store missing bucket {category!r}", f"registry_file:{sp.name}"
            rec = bucket.get(expected_sha256)
            if not isinstance(rec, dict):
                return None, f"Record {expected_sha256[:16]}... not found in trusted clinical store bucket {category!r}", f"registry_file:{sp.name}"
            return rec, None, f"registry_file:{sp.name}"

        if sp.is_dir():
            meta_file = sp / "store_metadata.json"
            if meta_file.is_file():
                meta = load_strict_json_bytes(meta_file.read_bytes(), "store_metadata.json")
                if (
                    not isinstance(meta, dict)
                    or meta.get("schema_version") != TRUSTED_CLINICAL_STORE_SCHEMA_VERSION
                    or _strict_literal_id(meta.get("store_authority_id")) not in allowed_issuers
                ):