OpenIslet

scripts/verify_iip0057_foundry_v2_shield_invvax_insl82i_cuffv2.py

W6-C3 (Provisional Next-Free IIP-0057 / DEC-138 / GATE-36 / GY-035; staging slot iip0057,

script Release v0.8.0 gen-eb955f8266035aba 412 KB · 32 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_iip0057_foundry_v2_shield_invvax_insl82i_cuffv2.py · SHA-256: 1c63dcf649c42be4…

    "TCCTCCTGTGTCCCTCTGCCTCGCCGCTGTTCCGGAACCTGCTCTGCGCGGCACGTCCTGGCAGTGGGGCAGGTGGAG"
    "CTGGGCGGGGGCCCTGGTGCAGGCAGCCTGCAGCCCTTGGCCCTGGAGGGGTCCCTGCAGAAGCGTGGCATTGTGGAA"
    "CAATGCTGTACCAGCATCTGCTCCCTCTACCAGCTGGAGAACTACTGCAACTAGACGCAGCCCGCAGGCAGCCCCACA"
    "CCCGCCGCC"
)

# Live-verified UniProt P01308 human preproinsulin (110 aa)
UNIPROT_P01308_PREPROINSULIN = (
    "MALWMRLLPLLALLALWGPDPAAAFVNQHLCGSHLVEALYLVCGERGFFYTPKTRREAEDLQVGQVELGGGPGAGSLQPL"
    "ALEGSLQKRGIVEQCCTSICSLYQLENYCN"
)

# Live-verified UniProt P01857-1 secreted human IgG1 Fc WT baseline (EU 221..446, VSP_061818 G446, K447 clipped, 226 aa)
UNIPROT_P01857_1_FC_WT_226AA = (
    "DKTHTCPPCPAPELLGGPSVFLFPPKPKDTLMISRTPEVTCVVVDVSHEDPEVKFNWYVDGVEVHNAKTKPREEQYNSTY"
    "RVVSVLTVLHQDWLNGKEYKCKVSNKALPAPIEKTISKAKGQPREPQVYTLPPSRDELTKNQVSLTCLVKGFYPSDIAVE"
    "WESNGQPENNYKTTPPVLDSDGSFFLYSKLTVDKSRWQQGNVFSCSVMHEALHNHYTQKSLSLSPG"
)

# Live-verified ClinicalTrials.gov v2 registry snapshot (queried 2026-11-30; indication/sponsor terms audited)
PINNED_CLINICAL_TRIALS_SNAPSHOT: dict[str, dict[str, Any]] = {
    "NCT06783309": {
        "platform": "CNP-103 (COUR PLGA multi-Ag: preproinsulin, GAD65, IGRP, ZnT8)",
        "indication": "Newly diagnosed Type 1 Diabetes (NOT islet transplant recipients)",
        "status": "RECRUITING",
        "phases": ["PHASE1", "PHASE2"],
        "enrollment": 72,
        "posted_results": False,
        "whyStopped": None,
    },
    "NCT06001177": {
        "platform": "KAN-101 (Anokion pGal Ph2 SYNNERGY)",
        "indication": "Celiac disease (gluten challenge; NOT T1D)",
        "status": "COMPLETED",
        "phases": ["PHASE2"],
        "enrollment": 55,
        "posted_results": True,
        "primary_outcome_note": "Primary histological outcome did NOT show statistically significant benefit.",
        "whyStopped": None,
    },
    "NCT04248855": {
        "platform": "KAN-101 (Anokion pGal Ph1 ACeD)",
        "indication": "Celiac disease (gluten challenge; NOT T1D)",
        "status": "COMPLETED",
        "phases": ["PHASE1"],
        "enrollment": 41,
        "posted_results": True,
        "pk_note": "Celiac cohort plasma t1/2 geometric mean 31.72 min with high variability (PMID:37329900).",
        "whyStopped": None,
    },
    "NCT05574010": {
        "platform": "KAN-101 (ACeD-it)",
        "indication": "Celiac disease",
        "status": "TERMINATED",
        "phases": ["PHASE1", "PHASE2"],
        "enrollment": 128,
        "posted_results": False,
        "whyStopped": "Sponsor decision",
    },
    "NCT06798454": {
        "platform": "PVT201 (Parvus Navacim Ph1)",
        "indication": "Primary Biliary Cholangitis / Primary Sclerosing Cholangitis (PBC/PSC — NOT T1D)",
        "status": "COMPLETED",
        "phases": ["PHASE1"],
        "enrollment": 24,
        "posted_results": False,
        "whyStopped": None,
    },
    "NCT05018585": {
        "platform": "DIAGNODE-3 (rhGAD65-alum)",
        "indication": "Type 1 Diabetes (HLA-DR3-DQ2)",
        "status": "TERMINATED",
        "phases": ["PHASE3"],
        "enrollment": 321,
        "posted_results": False,
        "whyStopped": "Stopped for futility.",
    },
    "NCT04524949": {
        "platform": "IMCY-0098 (IMPACT proinsulin)",
        "indication": "Type 1 Diabetes",
        "status": "TERMINATED",
        "phases": ["PHASE2"],
        "enrollment": 110,
        "posted_results": True,
        "whyStopped": "No efficacy at primary analysis after 1 year. Long term follow-up stopped.",
    },
    "NCT05425446": {
        "platform": "DONQ52 (Chugai anti-HLA-DQ2.5/gluten Fab Ph1)",
        "indication": "Celiac disease (domain-transfer comparator)",
        "status": "COMPLETED",
        "phases": ["PHASE1"],
        "enrollment": 56,
        "posted_results": False,
        "whyStopped": None,
    },
    "NCT07239336": {
        "platform": "DONQ52 (Chugai anti-HLA-DQ2.5/gluten Fab Ph2)",
        "indication": "Celiac disease (domain-transfer comparator)",
        "status": "RECRUITING",
        "phases": ["PHASE2"],
        "enrollment": 92,
        "posted_results": False,
        "whyStopped": None,
    },
    "NCT05937581": {
        "platform": "CSL040 (CSL Behring sCR1 Ph1)",
        "indication": "Healthy volunteers (complement inhibition)",
        "status": "COMPLETED",
        "phases": ["PHASE1"],
        "enrollment": 62,
        "posted_results": False,
        "whyStopped": None,
    },
}


# ---------------------------------------------------------------------------
# Fail-Closed Core Helpers & Strict JSON Decoding (ZERO assert statements!)
# ---------------------------------------------------------------------------
def require_cond(cond: bool, msg: str) -> None:
    if not cond:
        raise RuntimeError(msg)


def sha256_bytes(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def sha256_str(text: str) -> str:
    return sha256_bytes(text.encode("utf-8"))


def sha256_file(path: Path) -> str:
    return sha256_bytes(path.read_bytes())


def _canonical_json_sha256(obj: Any) -> str:
    return sha256_str(json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False))


def compute_canonical_record_sha256(record: dict[str, Any]) -> str:
    """Compute canonical JSON SHA-256 of the COMPLETE evidence record body excluding archive_sha256."""
    body = {k: v for k, v in record.items() if k != "archive_sha256"}
    return _canonical_json_sha256(body)


def seal_evidence_record(record_body: dict[str, Any]) -> dict[str, Any]:
    """Return a deep copy sealed with exact canonical JSON SHA-256 archive_sha256."""
    check_strictly_finite(record_body, "evidence_record")
    body = copy.deepcopy({k: v for k, v in record_body.items() if k != "archive_sha256"})
    body["archive_sha256"] = compute_canonical_record_sha256(body)
    return body


def _clopper_pearson_upper_95_pct(k: int, n: int) -> float:
    """Exact one-sided 95% Clopper-Pearson upper confidence bound (percent) for k/n."""
    require_cond(isinstance(k, int) and isinstance(n, int) and 0 <= k <= n and n > 0, f"Invalid Clopper-Pearson args: {k}/{n}")
    if k == 0:
        return (1.0 - (0.05 ** (1.0 / n))) * 100.0
    if k == n:
        return 100.0
    log_n_fact = math.lgamma(n + 1)

    def _lower_tail(p: float) -> float:
        if p <= 0.0:
            return 1.0
        if p >= 1.0:
            return 0.0
        lp = math.log(p)
        lq = math.log1p(-p)
        log_terms = [
            log_n_fact - math.lgamma(i + 1) - math.lgamma(n - i + 1) + i * lp + (n - i) * lq
            for i in range(k + 1)
        ]
        m = max(log_terms)
        return math.exp(m) * sum(math.exp(t - m) for t in log_terms)

    lo, hi = k / n, 1.0
    for _ in range(80):
        mid = 0.5 * (lo + hi)
        if _lower_tail(mid) > 0.05:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi) * 100.0


def _is_valid_nonzero_sha256(val: Any) -> bool:
    if not isinstance(val, str) or len(val) != 64:
        return False
    if any(ch not in "0123456789abcdef" for ch in val):
        return False
    return len(set(val)) > 1


def _reject_nonfinite_constant(token: str) -> Any:
    raise ValueError(f"Non-finite JSON constant rejected fail-closed: {token!r}")


def _parse_strict_finite_float(token: str) -> float:
    try:
        dec = Decimal(token)
    except InvalidOperation as exc:
        raise ValueError(f"Invalid JSON float token: {token!r}") from exc
    if not dec.is_finite() or dec.copy_abs() > Decimal("1e300"):
        raise ValueError(f"Non-finite or overflowing JSON decimal token: {token!r}")
    val = float(token)
    if not math.isfinite(val) or abs(val) > 1e300:
        raise ValueError(f"Non-finite or overflowing JSON float: {token!r}")
    return val


def _parse_strict_finite_int(token: str) -> int:
    val = int(token)
    if abs(val) > 10 ** 300:
        raise ValueError(f"Overflowing JSON integer token: {token[:32]!r}")
    return val


def _reject_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
    out: dict[str, Any] = {}
    for k, v in pairs:
        if k in out:
            raise ValueError(f"Duplicate JSON object key rejected fail-closed: {k!r}")
        out[k] = v
    return out


def check_strictly_finite(obj: Any, label: str, path: str = "$") -> None:
    if isinstance(obj, bool) or obj is None or isinstance(obj, str):
        return
    if isinstance(obj, int):
        if abs(obj) > 10 ** 300:
            raise ValueError(f"Overflowing int in {label} at {path}")
        return
    if isinstance(obj, float):
        if not math.isfinite(obj) or abs(obj) > 1e300:
            raise ValueError(f"Non-finite or overflowing float in {label} at {path}: {obj!r}")
        return
    if isinstance(obj, dict):
        for k, v in obj.items():
            if not isinstance(k, str):
                raise ValueError(f"Non-string dict key in {label} at {path}: {type(k).__name__}")
            check_strictly_finite(v, label, f"{path}.{k}")
        return
    if isinstance(obj, (list, tuple)):
        for i, v in enumerate(obj):
            check_strictly_finite(v, label, f"{path}[{i}]")
        return
    raise ValueError(f"Unsupported non-JSON type in {label} at {path}: {type(obj).__name__}")