if not d.is_finite(): raise ValueError(f"Non-finite JSON decimal token rejected: {token!r}") return d def parse_stage0_observation_json_exact(raw_json: str) -> Dict[str, Any]: """Decode raw Stage-0 observation JSON preserving exact decimal numeric lexemes (zero binary64 drift).""" obj = json.loads( raw_json, object_pairs_hook=_reject_duplicate_json_keys, parse_constant=_reject_nonfinite_json, parse_float=_parse_exact_decimal_json_float, ) if not isinstance(obj, dict): raise ValueError("Stage-0 observation JSON must decode to a top-level JSON object") return obj def _load_json_strict(path: Path) -> Any: return json.loads( path.read_text(encoding="utf-8"), object_pairs_hook=_reject_duplicate_json_keys, parse_constant=_reject_nonfinite_json, parse_float=_parse_finite_json_float, ) def _safe_exact_decimal(val: Any) -> Decimal | None: """Convert non-bool int/float/Decimal/numeric-str to exact finite Decimal without binary64 boundary drift. Uses Decimal(str(val)) for finite Python floats (shortest round-trip decimal representation via dtoa) so ordinary decoded JSON numbers like 0.1 compare equal to exact decimal string "0.1" at inclusive thresholds, while numeric strings parse directly via Decimal(s) with zero binary64 underflow/rounding. """ if isinstance(val, bool): return None if isinstance(val, Decimal): return val if val.is_finite() else None if isinstance(val, int): return Decimal(val) if isinstance(val, float): if not math.isfinite(val): return None try: d = Decimal(str(val)) except Exception: return None return d if d.is_finite() else None if isinstance(val, str): if val != val.strip() or not _DECIMAL_STR_RE.fullmatch(val): return None try: d = Decimal(val) except Exception: return None return d if d.is_finite() else None return None def _has_surrogate(val: str) -> bool: return any(0xD800 <= ord(ch) <= 0xDFFF for ch in val) def _is_canonical_identifier(val: Any) -> bool: return ( isinstance(val, str) and bool(val) and val == val.strip() and not _has_surrogate(val) and _FORBIDDEN_ID_CHARS_RE.search(val) is None ) def _cm_is_blank(s: str) -> bool: """CommonMark 0.31.2 §2.2: a blank line contains ONLY ASCII spaces (U+0020) and tabs (U+0009).""" return all(ch in (" ", "\t") for ch in s) def _cm_strip_ascii_ws(s: str) -> str: return s.strip(" \t") def _cm_normalize_link_label(label: str) -> str: return re.sub(r"[ \t\n]+", " ", label.strip(" \t\n")).casefold() def _parse_cm_link_ref_defs_from_text(text: str) -> tuple[set[str], int]: """Consume zero or more leading CommonMark 0.31.2 §4.7 link reference definitions from `text`. Returns (normalized_labels_found, number_of_leading_lines_consumed). Handles balanced nested parentheses in destinations (depth <= 32), multi-line quoted/parenthesized titles, and rejects whitespace-only labels like `[ ]` per CommonMark §4.7. """ n = len(text) pos = 0 labels: set[str] = set() lines_consumed = 0 def _skip_spaces_tabs(p: int) -> int: while p < n and text[p] in (" ", "\t"): p += 1 return p def _skip_opt_ws_and_one_nl(p: int) -> int: p = _skip_spaces_tabs(p) if p < n and text[p] == "\n": p += 1 p = _skip_spaces_tabs(p) return p while pos < n: save_pos = pos # Up to 3 leading spaces sp = 0 while pos < n and text[pos] == " " and sp < 3: pos += 1 sp += 1 if pos >= n or text[pos] != "[": pos = save_pos break pos += 1 lbl_start = pos lbl_chars = 0 found_close = False while pos < n and lbl_chars <= 999: ch = text[pos] if ch == "\\" and pos + 1 < n: pos += 2 lbl_chars += 2 continue if ch == "[": break if ch == "]": found_close = True break pos += 1 lbl_chars += 1 if not found_close: pos = save_pos break raw_label = text[lbl_start:pos] # §4.7: label must contain at least one non-whitespace character (ASCII space/tab/newline) if not re.search(r"[^ \t\n]", raw_label): pos = save_pos break pos += 1 # consume ']' if pos >= n or text[pos] != ":": pos = save_pos break pos += 1 # consume ':' pos = _skip_opt_ws_and_one_nl(pos) if pos >= n: pos = save_pos break # Parse link destination (§4.7 / §6.3) if text[pos] == "<": pos += 1 dest_ok = False while pos < n: ch = text[pos] if ch == "\n" or ch == "<": break if ch == "\\" and pos + 1 < n and text[pos + 1] != "\n": pos += 2 continue if ch == ">": pos += 1 dest_ok = True break pos += 1 if not dest_ok: pos = save_pos break else: dest_start = pos paren_depth = 0 dest_bad = False while pos < n: ch = text[pos] oc = ord(ch) if ch in (" ", "\t", "\n") or oc < 0x20 or oc == 0x7F: break if ch == "\\" and pos + 1 < n and text[pos + 1] not in (" ", "\t", "\n"): pos += 2 continue if ch == "(": paren_depth += 1 if paren_depth > 32: dest_bad = True break pos += 1 continue if ch == ")": if paren_depth == 0: dest_bad = True break paren_depth -= 1 pos += 1 continue pos += 1 if dest_bad or paren_depth != 0 or pos == dest_start: pos = save_pos break # After destination, check optional title or end-of-line after_dest_pos = pos ws_after_dest_start = pos p_ws = _skip_spaces_tabs(pos) had_nl_after_dest = False if p_ws < n and text[p_ws] == "\n": had_nl_after_dest = True p_title_start = _skip_spaces_tabs(p_ws + 1) else: p_title_start = p_ws has_ws_before_title = (p_title_start > ws_after_dest_start) def _try_parse_title(tp: int) -> int | None: if tp >= n or text[tp] not in ('"', "'", "("): return None delim = ")" if text[tp] == "(" else text[tp] tp += 1 while tp < n: ch = text[tp] if ch == "\\" and tp + 1 < n: tp += 2 continue if delim == ")" and ch == "(": return None if ch == "\n": # Blank line inside title is forbidden nl_next = _skip_spaces_tabs(tp + 1) if nl_next < n and text[nl_next] == "\n": return None if ch == delim: tp += 1 tp = _skip_spaces_tabs(tp) if tp == n: return tp if text[tp] == "\n": return tp + 1 return None tp += 1 return None title_end = _try_parse_title(p_title_start) if has_ws_before_title else None if title_end is not None: pos = title_end labels.add(_cm_normalize_link_label(raw_label)) lines_consumed = text[:pos].count("\n") if pos < n else (text.count("\n") + 1) continue