OpenIslet

scripts/verify_iip0035_d1b_auto_and_portfolio.py

Deterministic Autologous D1b-Auto-C v2 Mode-B Registry, 45-Cell Stage-0 Contract,

script Release v0.8.0 gen-eb955f8266035aba 288 KB · 23 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_iip0035_d1b_auto_and_portfolio.py · SHA-256: fedb990aeaedd116…

        # 6. Emphasis delimiters (* or _)
        if ch in ("*", "_"):
            j = i
            while j < n and s[j] == ch:
                j += 1
            tokens.append(("delim", s[i:j]))
            i = j
            continue
        tokens.append(("text", ch))
        i += 1

    # Resolve matched emphasis delimiter runs (* and _) per CommonMark §6.2 flanking rules
    def _prev_char(idx: int) -> str:
        for k in range(idx - 1, -1, -1):
            if tokens[k][1]:
                return tokens[k][1][-1]
        return " "

    def _next_char(idx: int) -> str:
        for k in range(idx + 1, len(tokens)):
            if tokens[k][1]:
                return tokens[k][1][0]
        return " "

    def _is_ws_ch(c: str) -> bool:
        return c.isspace()

    def _is_punct_ch(c: str) -> bool:
        return c in _CM_ASCII_PUNCT

    delims: List[Dict[str, Any]] = []
    for idx, (tk, tv) in enumerate(tokens):
        if tk != "delim":
            continue
        dch = tv[0]
        pc_c = _prev_char(idx)
        nc_c = _next_char(idx)
        left_flank = (not _is_ws_ch(nc_c)) and (not _is_punct_ch(nc_c) or _is_ws_ch(pc_c) or _is_punct_ch(pc_c))
        right_flank = (not _is_ws_ch(pc_c)) and (not _is_punct_ch(pc_c) or _is_ws_ch(nc_c) or _is_punct_ch(nc_c))
        can_open = left_flank if dch == "*" else (left_flank and (not right_flank or _is_punct_ch(pc_c)))
        can_close = right_flank if dch == "*" else (right_flank and (not left_flank or _is_punct_ch(nc_c)))
        delims.append({
            "idx": idx,
            "ch": dch,
            "rem": len(tv),
            "orig": len(tv),
            "can_open": can_open,
            "can_close": can_close,
        })

    # Match closers against nearest valid openers
    ci = 0
    while ci < len(delims):
        closer = delims[ci]
        if closer["rem"] <= 0 or not closer["can_close"]:
            ci += 1
            continue
        matched_opener = None
        for oi in range(ci - 1, -1, -1):
            opener = delims[oi]
            if opener["rem"] <= 0 or not opener["can_open"] or opener["ch"] != closer["ch"]:
                continue
            if (opener["can_close"] or closer["can_open"]) and (opener["orig"] + closer["orig"]) % 3 == 0:
                if opener["orig"] % 3 != 0 or closer["orig"] % 3 != 0:
                    continue
            matched_opener = oi
            break
        if matched_opener is not None:
            opener = delims[matched_opener]
            use = 2 if (opener["rem"] >= 2 and closer["rem"] >= 2) else 1
            opener["rem"] -= use
            closer["rem"] -= use
            # Clear any intermediate unmatched delimiters between opener and closer
            for mi in range(matched_opener + 1, ci):
                delims[mi]["can_open"] = False
                delims[mi]["can_close"] = False
            if closer["rem"] == 0:
                ci += 1
        else:
            ci += 1

    delim_rem = {d["idx"]: d["rem"] for d in delims}
    out_parts: List[str] = []
    for idx, (tk, tv) in enumerate(tokens):
        if tk == "delim":
            rem = delim_rem.get(idx, len(tv))
            if rem > 0:
                out_parts.append(tv[:rem])
        else:
            out_parts.append(tv)
    return "".join(out_parts), has_link


def _cm_render_inline_visible_text(raw: str, link_refs: set[str] | None = None) -> str:
    """Render visible plain text of a CommonMark 0.31.2 inline heading string."""
    txt, _ = _cm_render_inline_with_meta(raw, link_refs)
    return txt


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

    Tracks exact 4-column absolute tab stops across nested blockquotes and list items (§2.2/§5.1/§5.2),
    strictly checks open fenced/HTML leaf blocks before opening new containers, uses ASCII-only blank
    lines, parses full §4.7 link-reference definitions (nested parens, multi-line titles, non-blank labels),
    and renders visible inline heading text (code spans, backslash escapes before semicolon-required HTML5
    entities, links/images, and emphasis).
    """
    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]] = []
    doc_link_refs: set[str] = set()
    in_fence = False
    fence_char = ""
    fence_len = 0
    fence_depth = 0
    in_html_block_type = 0
    html_block_depth = 0
    para_lines: List[tuple[int, str, int]] = []

    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]*$")
    thematic_re = re.compile(r"^[ ]{0,3}(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$")
    ul_re = re.compile(r"^( {0,3})([-+*])(?:([ \t]+)(.*)|([ \t]*))$")
    ol_re = re.compile(r"^( {0,3})([0-9]{1,9}[.)])(?:([ \t]+)(.*)|([ \t]*))$", re.ASCII)
    # CommonMark 0.31.2 §4.6 HTML block start/end rules (Types 1-7)
    html_t1_start_re = re.compile(r"^ {0,3}<(?:pre|script|style|textarea)(?:[ \t>]|$)", re.IGNORECASE)
    html_t1_end_re = re.compile(r"</(?:pre|script|style|textarea)>", re.IGNORECASE)
    html_t2_start_re = re.compile(r"^ {0,3}<!--")
    html_t3_start_re = re.compile(r"^ {0,3}<\?")
    html_t4_start_re = re.compile(r"^ {0,3}<![A-Za-z]")
    html_t5_start_re = re.compile(r"^ {0,3}<!\[CDATA\[")
    html_t6_start_re = re.compile(
        r"^ {0,3}</?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|"
        r"dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|"
        r"h1|h2|h3|h4|h5|h6|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|"
        r"noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|"
        r"thead|title|tr|track|ul)(?:[ \t>]|/>|$)",
        re.IGNORECASE,
    )
    html_t7_start_re = re.compile(
        r"^ {0,3}(?:<[A-Za-z][A-Za-z0-9-]*(?:[ \t]+[A-Za-z_:][A-Za-z0-9_.:-]*(?:[ \t]*=[ \t]*(?:[^ \t\"'=<>`]+|'[^']*'|\"[^\"]*\"))?)*[ \t]*/?>|"
        r"</[A-Za-z][A-Za-z0-9-]*[ \t]*>)[ \t]*$"
    )

    container_stack: List[tuple[str, int]] = []

    def _flush_para_for_refs() -> None:
        if not para_lines:
            return
        p_text = "\n".join(p[1] for p in para_lines)
        found_refs, _ = _parse_cm_link_ref_defs_from_text(p_text)
        if found_refs:
            doc_link_refs.update(found_refs)
        para_lines.clear()

    def _count_leading_indent(s: str, start_col: int) -> tuple[int, int]:
        """Return (indent_cols, char_index_of_first_non_ws) with 4-col tab stops from absolute `start_col`."""
        col = start_col
        i = 0
        n_s = len(s)
        while i < n_s:
            ch = s[i]
            if ch == " ":
                col += 1
                i += 1
            elif ch == "\t":
                col += 4 - (col % 4)
                i += 1
            else:
                break
        return col - start_col, i

    def _consume_cols_abs(s: str, cols: int, start_col: int) -> tuple[bool, str, int]:
        """Consume `cols` display columns starting at absolute column `start_col` (CommonMark §2.2)."""
        col = start_col
        target = start_col + cols
        i = 0
        n_s = len(s)
        while i < n_s and col < target:
            ch = s[i]
            if ch == " ":
                col += 1
                i += 1
            elif ch == "\t":
                step = 4 - (col % 4)
                if col + step > target:
                    rem = (col + step) - target
                    return True, (" " * rem) + s[i + 1 :], target
                col += step
                i += 1
            else:
                return False, s, start_col
        if col >= target:
            return True, s[i:], col
        return False, s, start_col

    def _try_match_bq(s: str, start_col: int) -> tuple[bool, str, int]:
        """Match CommonMark §5.1 blockquote marker ` {0,3}>[optional 1-col space/tab]` at absolute `start_col`."""
        ind_cols, idx_ns = _count_leading_indent(s, start_col)
        if ind_cols > 3 or idx_ns >= len(s) or s[idx_ns] != ">":
            return False, s, start_col
        after_gt_col = start_col + ind_cols + 1
        rest = s[idx_ns + 1 :]
        if not rest:
            return True, "", after_gt_col
        if rest[0] == " ":
            return True, rest[1:], after_gt_col + 1
        if rest[0] == "\t":
            # Optional space after '>' consumes 1 column of the tab; remaining columns become spaces!
            tab_w = 4 - (after_gt_col % 4)
            rem_sp = tab_w - 1
            return True, (" " * rem_sp) + rest[1:], after_gt_col + 1
        return True, rest, after_gt_col

    def _try_match_list(s: str, start_col: int, *, interrupting_same_depth_para: bool) -> tuple[bool, int, str, int]:
        """Match CommonMark §5.2 list item marker at absolute `start_col`."""
        ind_cols, idx_ns = _count_leading_indent(s, start_col)
        if ind_cols > 3 or idx_ns >= len(s):
            return False, 0, s, start_col
        sub = s[idx_ns:]
        if thematic_re.match((" " * ind_cols) + sub):
            return False, 0, s, start_col
        m_ul = ul_re.match(sub)
        m_ol = None if m_ul else ol_re.match(sub)
        if not m_ul and not m_ol:
            return False, 0, s, start_col
        m = m_ul or m_ol
        mark_s = m.group(2)
        sep_s = m.group(3)
        rest_s = m.group(4) if sep_s is not None else ""
        mark_end_col = start_col + ind_cols + len(mark_s)
        if sep_s is None:
            if interrupting_same_depth_para:
                return False, 0, s, start_col
            content_indent = ind_cols + len(mark_s) + 1
            return True, content_indent, "", mark_end_col + 1
        is_empty_content = _cm_is_blank(rest_s)
        if interrupting_same_depth_para:
            if is_empty_content:
                return False, 0, s, start_col
            if m_ol is not None and mark_s not in ("1.", "1)"):
                return False, 0, s, start_col