OpenIslet

scripts/verify_iip0034_planar_and_portfolio.py

Deterministic Planar Route 3P Physics, Colony-Screening, Exact Decimal DEC-103 R3P-05 Thinning,

script Release v0.8.0 gen-eb955f8266035aba 111 KB · 8 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_iip0034_planar_and_portfolio.py · SHA-256: 24ff92056312d1e8…

        or set(observed_scope.keys()) != ASSEMBLED_DEVICE_LOT_SCOPE_KEY_SET
    ):
        return False, "NON_EXACT_7KEY_SCOPE_MISSING_OR_UNEXPECTED_EXTRA_KEYS", None
    for key in ASSEMBLED_DEVICE_LOT_SCOPE_KEYS:
        ev = expected_scope.get(key)
        ov = observed_scope.get(key)
        if not _is_canonical_identifier(ev) or not _is_canonical_identifier(ov) or ev != ov:
            return False, f"SCOPE_KEY_MISSING_NONCANONICAL_OR_MISMATCHED:{key}", None
    if expected_scope["physical_route_id"] != "ROUTE_3P_MODULAR_PLANAR_ENVELOPE":
        return False, "PHYSICAL_ROUTE_NOT_ROUTE_3P_MODULAR_PLANAR_ENVELOPE", None
    eligible_products = {
        pid: str(spec["donor_sha256"])
        for pid, spec in pc.DESIGN_Y_V2_DONOR_BINDINGS.items()
        if str(spec.get("role") or "") in ELIGIBLE_R3P05_FULLSTACK_ROLES
    }
    pvid = expected_scope["product_variant_id"]
    if pvid not in eligible_products:
        return False, f"PRODUCT_NOT_ELIGIBLE_FULLSTACK_DESIGN_Y_V2:{pvid}", None
    if expected_scope["construct_sha256"] != eligible_products[pvid]:
        return False, "CONSTRUCT_SHA256_MISMATCH_OR_NON_DIGEST", None
    return True, "OK", pvid


def _parse_commonmark_headings(text: str) -> List[Dict[str, Any]]:
    """Stdlib CommonMark 0.31.2 block parser extracting all rendered ATX and multiline Setext headings.

    Properly ignores fenced code blocks (backtick/tilde >= 3 chars), indented code blocks (>= 4 spaces or tab),
    and HTML comments (<!-- ... -->), while recursively stripping blockquote ('>') and list-item container
    prefixes so headings inside blockquotes or list items are still detected as rendered headings.
    """
    norm = text.replace("\r\n", "\n").replace("\r", "\n")
    raw_lines = norm.split("\n")
    line_offsets: List[int] = []
    pos = 0
    for ln in raw_lines:
        line_offsets.append(pos)
        pos += len(ln) + 1

    headings: List[Dict[str, Any]] = []
    in_fence = False
    fence_char = ""
    fence_len = 0
    in_html_comment = False
    para_lines: List[tuple[int, str, int]] = []  # (line_idx, stripped_text, container_depth)

    atx_re = re.compile(r"^ {0,3}(#{1,6})(?:[ \t]+(.*?))?[ \t]*$")
    fence_open_re = re.compile(r"^ {0,3}(`{3,}|~{3,})(.*)$")
    setext_re = re.compile(r"^ {0,3}(=+|-+)[ \t]*$")
    bq_re = re.compile(r"^ {0,3}> ?(.*)$")
    ul_re = re.compile(r"^ {0,3}[-+*][ \t]+(.*)$")
    ol_re = re.compile(r"^ {0,3}\d{1,9}[.)][ \t]+(.*)$")

    def _strip_containers(line: str) -> tuple[str, int]:
        depth = 0
        cur = line
        while True:
            mb = bq_re.match(cur)
            if mb:
                depth += 1
                cur = mb.group(1)
                continue
            mu = ul_re.match(cur)
            if mu:
                depth += 1
                cur = mu.group(1)
                continue
            mo = ol_re.match(cur)
            if mo:
                depth += 1
                cur = mo.group(1)
                continue
            break
        return cur, depth

    def _clean_atx_title(raw_title: str) -> str:
        t = raw_title.strip()
        # Strip optional CommonMark closing '#' sequence preceded by space/tab
        t = re.sub(r"(?:^|[ \t])#+[ \t]*$", "", t).strip()
        return t

    def _render_cm_inline_text(raw_title: str) -> str:
        # Decode CommonMark backslash-escaped ASCII punctuation and HTML character references (&#46;, &#x2e;, etc.)
        unesc = re.sub(r'\\([!"#$%&\'()*+,\-./:;<=>?@\[\\\]^_`{|}~])', r"\1", raw_title)
        return html.unescape(unesc)

    for idx, raw_line in enumerate(raw_lines):
        # 1. Active HTML comment block (CommonMark Type 2)
        if in_html_comment:
            if "-->" in raw_line:
                in_html_comment = False
            para_lines.clear()
            continue

        # 2. Active fenced code block
        if in_fence:
            close_pat = rf"^ {{0,3}}{re.escape(fence_char)}{{{fence_len},}}[ \t]*$"
            if re.match(close_pat, raw_line):
                in_fence = False
            para_lines.clear()
            continue

        # Strip blockquote/list containers to inspect leaf block
        leaf, c_depth = _strip_containers(raw_line)

        # 3. Blank line resets paragraph buffer
        if not leaf.strip():
            para_lines.clear()
            continue

        # 4. Opening HTML comment block (0-3 spaces)
        if re.match(r"^ {0,3}<!--", leaf):
            para_lines.clear()
            if "-->" not in leaf[leaf.find("<!--") + 4 :]:
                in_html_comment = True
            continue

        # 5. Opening fenced code block (0-3 spaces; backtick info string may not contain backticks)
        mf = fence_open_re.match(leaf)
        if mf:
            f_tok, info = mf.group(1), mf.group(2)
            if f_tok[0] == "~" or "`" not in info:
                in_fence = True
                fence_char = f_tok[0]
                fence_len = len(f_tok)
                para_lines.clear()
                continue

        # 6. Indented code block (>= 4 spaces or leading tab, only when NOT interrupting a paragraph)
        if not para_lines and (leaf.startswith("    ") or leaf.startswith("\t")):
            continue

        # 7. Multiline Setext underline immediately following non-empty paragraph buffer at same container depth
        ms = setext_re.match(leaf)
        if ms and para_lines and para_lines[-1][2] == c_depth:
            level = 1 if ms.group(1)[0] == "=" else 2
            title = " ".join(x[1] for x in para_lines).strip()
            start_idx = para_lines[0][0]
            headings.append({
                "kind": "setext",
                "level": level,
                "title": title,
                "rendered_title": _render_cm_inline_text(title),
                "raw_first_line": raw_lines[start_idx],
                "start_line": start_idx,
                "end_line": idx,
                "start_offset": line_offsets[start_idx],
                "end_offset": line_offsets[idx] + len(raw_line),
                "container_depth": c_depth,
            })
            para_lines.clear()
            continue

        # 8. ATX heading (1-6 '#', 0-3 leading spaces)
        ma = atx_re.match(leaf)
        if ma:
            para_lines.clear()
            level = len(ma.group(1))
            title = _clean_atx_title(ma.group(2) or "")
            headings.append({
                "kind": "atx",
                "level": level,
                "title": title,
                "rendered_title": _render_cm_inline_text(title),
                "raw_first_line": raw_line,
                "start_line": idx,
                "end_line": idx,
                "start_offset": line_offsets[idx],
                "end_offset": line_offsets[idx] + len(raw_line),
                "container_depth": c_depth,
            })
            continue

        # 9. Otherwise accumulate paragraph line (for potential multiline Setext heading)
        if para_lines and para_lines[-1][2] != c_depth:
            para_lines.clear()
        para_lines.append((idx, leaf.strip(), c_depth))

    return headings


def evaluate_r3p05_dec103_thinning(
    *,
    k: Any,
    n_raw: Any,
    eta_spike_recovery_l95: Any,
    f_clonogenic: Any = None,
    f_clonogenic_provenance: Any = None,
    alpha_obs: Any = None,
    alpha_f_clonogenic: Any = None,
    alpha_eta_recovery: Any = None,
    max_u95_fraction: Any = R3P05_MAX_U95_CEILING,
    expected_scope: Dict[str, Any] | None = None,
    observed_scope: Dict[str, Any] | None = None,
    sampling_independence_model: Any = None,
    clustered_sampling: Any = None,
    backup_gate0v_primary_failed: Any = None,
) -> Dict[str, Any]:
    """Fail-closed exact 50-digit conservative Decimal DEC-103 independent detection-thinning subgate for R3P-05.

    Enforces:
      - Unconditional k >= 1 observed-zero hard veto FIRST (with separate attribution_status field).
      - Strict hard ceiling max_u95_fraction in (0, 1e-6] evaluated in exact 50-digit Decimal.
      - Canonical exact 7-key DEC-103 ASSEMBLED_DEVICE_LOT_SCOPE (exact key set, control/zero-width/whitespace
        rejection, eligible full-stack Design Y v2 chr15 donor_sha256 binding, ROUTE_3P_MODULAR_PLANAR_ENVELOPE,
        and explicit backup_gate0v_primary_failed is True for backup CD55+CFH).
      - Strict isinstance(sampling_independence_model, str) check BEFORE equality (blocks NumPy 1-elem/2-elem arrays).
      - Mandatory explicit f_clonogenic_provenance:
          * 'KNOWN_OR_CONSERVATIVELY_ESTABLISHED': uses alpha_obs = 0.05 (unless stricter explicit alpha_obs given),
            yielding >= 90% Bonferroni joint coverage with 95% LCB recovery.
          * 'INDEPENDENTLY_ESTIMATED_WITH_ALPHA_ALLOCATION': requires explicit alpha_obs and alpha_f_clonogenic
            such that conservative ROUND_CEILING sum alpha_obs + alpha_eta_recovery + alpha_f_clonogenic <= 0.10.
      - Exact 50-digit conservative Decimal upper bound (ROUND_FLOOR on ln(alpha)/n, exp, and f*eta; ROUND_CEILING on
        1 - exp and division) comparing exact integer n_raw without binary64 ULP false PASS or 0.0 underflow display.
      - Mathematical count subgate ONLY: empirical_clearance_status always reports retrieval/whole-product pending.
    """
    is_int_k = isinstance(k, int) and not isinstance(k, bool)
    is_int_n = isinstance(n_raw, int) and not isinstance(n_raw, bool)
    cap_d = _safe_exact_decimal(max_u95_fraction)
    scope_ok, scope_reason, pvid = _check_canonical_scope_integrity(expected_scope, observed_scope)

    # 1. Observed-zero hard veto latches FIRST with separate attribution status
    if is_int_k and k > 0:
        cap_out = float(cap_d) if (cap_d is not None and Decimal(0) < cap_d <= R3P05_MAX_U95_CEILING_DEC) else None
        valid_count_rel = is_int_n and n_raw > 0 and k <= n_raw
        attr_status = (
            "EXACT_7KEY_SCOPE_ATTRIBUTED"
            if (scope_ok and valid_count_rel)
            else f"UNATTRIBUTED_OR_INVALID_AUX_INPUTS_UNCONDITIONAL_STOP:{scope_reason if not scope_ok else 'INVALID_N_OR_K_GT_N'}"
        )
        return {
            "status": "FAIL_HARD_STOP",
            "reason": "OBSERVED_NONZERO_VIABLE_ESCAPE_HARD_VETO",
            "attribution_status": attr_status,
            "empirical_clearance_status": "FAIL_HARD_STOP_OBSERVED_ESCAPE",
            "k": k,
            "n_raw": n_raw if is_int_n else None,
            "cap_fraction": cap_out,
        }

    # 2. Strict hard ceiling cap validation (exact Decimal <= 1e-6)
    if cap_d is None or not (Decimal(0) < cap_d <= R3P05_MAX_U95_CEILING_DEC):
        return {
            "status": "HOLD_RELAXED_OR_INVALID_CAP_FRACTION",
            "k": k if is_int_k else None,
            "n_raw": n_raw if is_int_n else None,
            "preregistered_max_cap_fraction": R3P05_MAX_U95_CEILING,
        }
    cap_float = float(cap_d)

    # 3. Canonical exact 7-key DEC-103 ASSEMBLED_DEVICE_LOT_SCOPE + registered eligible full-stack product/digest binding