#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ readpath_gate.py v1 -- a machine-judgeable gate for batch-read receipts (spill text). Scope: Windows / IDBots spill files that carry a batch-read receipt of the shape - RECEIPT read_metaweb_pins_batch: {...} caliber api/metaweb/pins:batch;text-cap=8000runes;host-budget=18000chars. Five sections, each machine-judgeable: [1] FIELDS requested / readable_upstream / returned / truncated / omitted / bytes_written, plus tpc (truncation_point_count) and len(tp) (len(truncation_points)) as TWO numbers, never one. The tpc != len(tp) state is printed as one of: EQUAL tpc == len(tp) CAP-CONSISTENT tpc > len(tp) and len(tp) == cap (legal array cap) INCONSISTENT tpc > len(tp) and len(tp) < cap (count not explained) IMPOSSIBLE len(tp) > tpc INCONSISTENT / IMPOSSIBLE are FAIL. [2] KEPT per-item kept_chars, distinct-value histogram, N, baseline, d = kept - baseline, d=1 count and share, r = sum(kept) - N*baseline. [3] LAW r landing law: order key = total_chars DESC, tie -> index DESC (index = 0-based position in truncation_points). Every +1 (d>0) must sit inside the first r positions. Prints PASS/FAIL plus the boundary pair (last included / first excluded). [4] DIMENSION per item cut_at_bytes / kept_chars (bytes per char) and a suspect class. A HINT only: never a verdict, never a mechanism claim. [5] INTERVAL the same spill measured under two different intervals. Equal numbers => "interval-not-effective / declaration invalid" (FAIL). Verdict vocabulary: PASS / FAIL / UNKNOWN / N/A / HINT. FAIL the section was checked and violated. UNKNOWN attempted, could not judge (bad data / broken premise). N/A structurally nothing to judge -- and therefore NOT a pass. HINT descriptive only (section 4). Exit: 0 PASS / 2 FAIL / 3 UNKNOWN. Pure standard library. ASCII-only stdout, safe on a Windows console. """ import argparse import hashlib import json import os import sys from collections import Counter, OrderedDict VERSION = "readpath_gate.py v1 (2026-11-23)" RECEIPT_PREFIX = "- RECEIPT read_metaweb_pins_batch:" CONTENT_OPEN = "" CONTENT_CLOSE = "" FOOTER_START = "When you cite this on-chain content" FOOTER_END = "its built-in Bot Browser." DEFAULT_CAP = 12 CALIBER = "api/metaweb/pins:batch;text-cap=8000runes;host-budget=18000chars" RATIO_LATIN = 1.5 RATIO_CJK = 2.0 HEADER_TEXT = '4 MetaWeb result(s) for query "batch read receipt":\n\n' FOOTER_TEXT = ( "When you cite this on-chain content in your reply, keep it as a clickable " "MetaWeb URI markdown link with the scheme shown below. Scheme contract: pin:// is the " "universal reference for ANY pin and the correct one for readable text content " "(simplenote notes, buzz posts, ...); metafile:// is ONLY for pins on /file whose payload " "is a binary file (image, video, audio, PDF, archive) -- never cite a text pin as " "metafile://; metaapp:// for MetaApp packages; metaid:// for people. ALWAYS show the URI " "in FULL as the link text -- never abbreviate or truncate it with an ellipsis; a shortened " "URI is neither clickable nor copyable. NEVER construct Web2 viewer URLs (metaid.io, " "openagentinternet.org, ...) for on-chain content -- the app opens MetaWeb URIs directly " "in its built-in Bot Browser." ) TRAIL_TEXT = ( "Judge these candidates by title + summary, then open the 1-3 most promising pins with " "read_metaweb_pin (use the pin: ids above verbatim). Answer only from what you actually " "read, and cite the pins you used. Reuse these bullet lines in your reply (titles stay " "pin:// links, authors stay metaid:// links, pinIds stay intact)." ) # --------------------------------------------------------------------------- # # helpers # --------------------------------------------------------------------------- # def _sha256_hex(data): if isinstance(data, str): data = data.encode("utf-8") return hashlib.sha256(data).hexdigest() def _fake_pinid(seed): """Deterministic 66-char pinId (64 lowercase hex + 'i0') for fixtures.""" return hashlib.sha256(("readpath-gate:" + seed).encode("utf-8")).hexdigest() + "i0" def _line_of(text, off): return text.count("\n", 0, off) + 1 def _scan_json_object(text, start): """Return (raw_json_text, end_index) for a balanced {...} at text[start] == '{'.""" if start >= len(text) or text[start] != "{": return None, start depth = 0 in_str = False esc = False i = start while i < len(text): ch = text[i] if in_str: if esc: esc = False elif ch == "\\": esc = True elif ch == '"': in_str = False else: if ch == '"': in_str = True elif ch == "{": depth += 1 elif ch == "}": depth -= 1 if depth == 0: return text[start:i + 1], i + 1 i += 1 return None, start def _int_or_none(v): if isinstance(v, bool): return None if isinstance(v, int): return v if isinstance(v, str): try: return int(v) except ValueError: return None return None def content_spans(text): """Spans of bodies: receipts quoted there are transcriptions.""" spans = [] pos = 0 while True: a = text.find(CONTENT_OPEN, pos) if a < 0: break b = text.find(CONTENT_CLOSE, a) if b < 0: spans.append((a, len(text))) break spans.append((a, b)) pos = b + len(CONTENT_CLOSE) return spans def _inside(spans, off): for a, b in spans: if a <= off < b: return True return False def find_frames(text): """Find native receipt frames anchored on RECEIPT_PREFIX. Occurrences inside a body are transcriptions of someone else's receipt, not frames of this spill: they are collected into `skipped` with a reason, never counted. A non-transcription occurrence that cannot be parsed is kept as a broken frame (UNKNOWN), so a genuinely broken receipt is still visible. """ frames = [] skipped = [] spans = content_spans(text) pos = 0 while True: j = text.find(RECEIPT_PREFIX, pos) if j < 0: break k = j + len(RECEIPT_PREFIX) while k < len(text) and text[k] in " \t\r\n": k += 1 if k >= len(text) or text[k] != "{": skipped.append({"offset": j, "line": _line_of(text, j), "reason": "prefix mentioned in prose (no JSON object follows)"}) pos = k if k > j else j + len(RECEIPT_PREFIX) continue raw = None end = k if k < len(text) and text[k] == "{": raw, end = _scan_json_object(text, k) rec = {"offset": j, "line": _line_of(text, j), "obj": None, "error": None, "raw": raw, "end": end} if _inside(spans, j): skipped.append({"offset": j, "line": rec["line"], "reason": "quoted inside (transcription)"}) pos = j + len(RECEIPT_PREFIX) continue if raw is None: rec["error"] = "unbalanced or missing JSON object" frames.append(rec) pos = j + len(RECEIPT_PREFIX) continue if raw.startswith("{..."): skipped.append({"offset": j, "line": rec["line"], "reason": "literal placeholder {...}, not a receipt"}) pos = end continue try: rec["obj"] = json.loads(raw) except Exception as exc: # noqa: BLE001 - report, never crash rec["error"] = "JSON parse error: %s" % exc frames.append(rec) pos = end continue if not isinstance(rec["obj"], dict) or "truncation_points" not in rec["obj"]: skipped.append({"offset": j, "line": rec["line"], "reason": "parsed JSON lacks truncation_points (not a receipt)"}) pos = end continue frames.append(rec) pos = end return {"frames": frames, "skipped": skipped} def _ratio_class(bpc): if bpc is None: return "n/a" if bpc < RATIO_LATIN: return "suspect-latin" if bpc > RATIO_CJK: return "suspect-CJK" return "mixed/undetermined" def _worst(verdicts): vs = [v for v in verdicts if v] if "FAIL" in vs: return "FAIL" if "UNKNOWN" in vs: return "UNKNOWN" return "PASS" class Options(object): def __init__(self): self.cap = DEFAULT_CAP self.baseline = None self.frame = None self.interval_pair = "footer" self.no_interval = False self.interval_force_equal = False # --------------------------------------------------------------------------- # # [1]..[4] per-frame evaluation # --------------------------------------------------------------------------- # def evaluate_frame(obj, opts, frame_no, offset=0, line=0): res = OrderedDict() res["frame"] = frame_no res["line"] = line res["offset"] = offset sec1 = OrderedDict() sec2 = OrderedDict() sec3 = OrderedDict() sec4 = OrderedDict() res["fields"] = sec1 res["kept"] = sec2 res["law"] = sec3 res["dimension"] = sec4 tp_raw = obj.get("truncation_points") if not isinstance(tp_raw, list): res["error"] = "truncation_points missing or not a list" res["overall"] = "UNKNOWN" for sec in (sec1, sec2, sec3, sec4): sec["verdict"] = "UNKNOWN" return res n_tp = len(tp_raw) # ---- [1] FIELDS sec1["requested"] = obj.get("requested") sec1["readable_upstream"] = obj.get("readable_upstream") sec1["returned"] = obj.get("returned") sec1["truncated"] = obj.get("truncated") sec1["omitted"] = obj.get("omitted") sec1["bytes_written"] = obj.get("bytes_written") sec1["tpc"] = obj.get("truncation_point_count") sec1["len_tp"] = n_tp tpc_i = _int_or_none(sec1["tpc"]) if tpc_i is None: sec1["tpc_state"] = "UNKNOWN" sec1["tpc_note"] = "truncation_point_count missing or not an int" sec1["verdict"] = "UNKNOWN" elif tpc_i == n_tp: sec1["tpc_state"] = "EQUAL" sec1["tpc_note"] = "tpc == len(tp)" sec1["verdict"] = "PASS" elif tpc_i > n_tp and n_tp >= opts.cap: sec1["tpc_state"] = "CAP-CONSISTENT" sec1["tpc_note"] = ("tpc>len(tp) and len(tp)==cap(%d): legal array cap, " "not an inconsistency" % opts.cap) sec1["verdict"] = "PASS" elif tpc_i > n_tp: sec1["tpc_state"] = "INCONSISTENT" sec1["tpc_note"] = ("tpc>len(tp) and len(tp) 0] dge2 = [i for i in range(N) if d[i] >= 2] dneg = [i for i in range(N) if d[i] < 0] distinct = Counter(kept) sec2["baseline"] = baseline sec2["baseline_source"] = source sec2["kept_distinct"] = ["%d x%d" % (v, c) for v, c in sorted(distinct.items())] sec2["d_list"] = d sec2["r"] = r sec2["d1_count"] = len(d1) sec2["d1_share"] = "%d/%d = %.2f%%" % (len(d1), N, 100.0 * len(d1) / N) sec2["dpos_count"] = len(dpos) sec2["dge2_count"] = len(dge2) sec2["dneg_count"] = len(dneg) if dge2 or dneg or len(d1) != r: sec2["premise"] = "broken (d>=2, d<0, or #d1 != r)" sec2["verdict"] = "UNKNOWN" sec2["note"] = "kept is not two-valued around the baseline; r is not a +1 count" else: sec2["premise"] = "two-valued (d in {0,1})" sec2["verdict"] = "PASS" sec2["note"] = "d=1 count == r by construction on a two-valued batch" # ---- [3] ORDERING LAW order = sorted(range(N), key=lambda i: (-totals[i], -i)) sec3["order_key"] = "total_chars DESC, tie -> index(0-based) DESC" sec3["r"] = r if r < 0: top = [] sec3["verdict"] = "UNKNOWN" sec3["checked"] = False sec3["note"] = "r<0: baseline above min(kept_chars); bad --baseline" else: top = order[:r] sec3["note"] = "" top_set = set(top) outside = [i for i in dpos if i not in top_set] sec3["topr_indices"] = top sec3["dpos_indices"] = dpos sec3["d1_indices"] = d1 sec3["outside_topr"] = outside if top: bi = top[-1] sec3["boundary_in"] = "total_chars=%s idx=%d kept=%s" % (totals[bi], bi, kept[bi]) else: sec3["boundary_in"] = "n/a (r=0)" if 0 <= r < len(order): bo = order[r] sec3["boundary_out"] = "total_chars=%s idx=%d kept=%s" % (totals[bo], bo, kept[bo]) else: sec3["boundary_out"] = "n/a (no excluded item)" if not sec3.get("verdict"): if len(dpos) != r: sec3["placement"] = "n/a" sec3["completeness"] = "FAIL" sec3["verdict"] = "UNKNOWN" sec3["checked"] = False sec3["note"] = ("#(+1)=%d != r=%d: premise broken (d>=2 or mixed batch); " "law not applicable as stated" % (len(dpos), r)) elif r == 0: sec3["placement"] = "n/a" sec3["completeness"] = "n/a" sec3["verdict"] = "N/A" sec3["checked"] = False sec3["note"] = "r=0: no +1 to place (vacuous; NOT counted as a pass)" elif outside: sec3["placement"] = "FAIL" sec3["completeness"] = "PASS" sec3["verdict"] = "FAIL" sec3["checked"] = True sec3["note"] = "%d +1 item(s) outside top-%d: law violated" % (len(outside), r) else: sec3["placement"] = "PASS" sec3["completeness"] = "PASS" sec3["verdict"] = "PASS" sec3["checked"] = True sec3["note"] = "all %d +1 item(s) inside top-%d" % (len(dpos), r) else: sec3["placement"] = "n/a" sec3["completeness"] = "n/a" # ---- [4] DIMENSION HINT rows = [] counts = OrderedDict([("suspect-latin", 0), ("suspect-CJK", 0), ("mixed/undetermined", 0), ("n/a", 0)]) for i in range(N): k = kept[i] c = cuts[i] if k and c is not None: bpc = c / float(k) cls = _ratio_class(bpc) rows.append((i, k, c, "%.3f" % bpc, cls)) else: rows.append((i, k, c, "n/a", "n/a")) cls = "n/a" counts[cls] += 1 sec4["rows"] = rows sec4["thresholds"] = "<%.1f suspect-latin, >%.1f suspect-CJK, else mixed" % ( RATIO_LATIN, RATIO_CJK) sec4["summary"] = ", ".join("%s %d/%d" % (k, v, N) for k, v in counts.items() if v) sec4["verdict"] = "HINT" sec4["note"] = ("hint only: byte/char ratio is a text-composition cue, " "not a mechanism claim") res["overall"] = _worst([sec1["verdict"], sec2["verdict"], sec3["verdict"]]) return res # --------------------------------------------------------------------------- # # [5] interval harness # --------------------------------------------------------------------------- # def _span_footer_to_eof(text): s = text.find(FOOTER_START) if s < 0: return None return (s, len(text)) def _span_footer_block(text): s = text.find(FOOTER_START) if s < 0: return None e = text.find(FOOTER_END, s) if e < 0: return None return (s, e + len(FOOTER_END)) def _span_receipt_line(text): j = text.find(RECEIPT_PREFIX) if j < 0: return None e = text.find("\n", j) if e < 0: e = len(text) return (j, e) def _span_receipt_json(text): j = text.find(RECEIPT_PREFIX) if j < 0: return None k = j + len(RECEIPT_PREFIX) while k < len(text) and text[k] in " \t": k += 1 raw, end = _scan_json_object(text, k) if raw is None: return None return (k, end) def _measure(text, span): if span is None: return None a, b = span seg = text[a:b] return OrderedDict([("chars", len(seg)), ("bytes", len(seg.encode("utf-8"))), ("start", a), ("end", b)]) def interval_harness(text, opts): res = OrderedDict() res["pair"] = opts.interval_pair res["forced_equal"] = bool(opts.interval_force_equal) if opts.no_interval: res["verdict"] = "N/A" res["note"] = "skipped by --no-interval: section not measured (N/A is not a pass)" return res if opts.interval_pair == "receipt": name_a, name_b = "receipt_line_to_eol", "receipt_json_braces" sa = _span_receipt_line(text) sb = _span_receipt_json(text) else: name_a, name_b = "footer_marker_to_eof", "footer_start_end_block" sa = _span_footer_to_eof(text) sb = _span_footer_block(text) a = _measure(text, sa) b = _measure(text, sb) res["name_a"] = name_a res["name_b"] = name_b res["A"] = a res["B"] = b if a is None or b is None: res["verdict"] = "N/A" res["note"] = ("interval markers absent: section not measured " "(N/A is not a pass)") return res if opts.interval_force_equal: b = OrderedDict(a) res["B"] = b res["name_b"] = name_a + " [forced copy]" same = (a["chars"] == b["chars"] and a["bytes"] == b["bytes"]) res["delta_chars"] = a["chars"] - b["chars"] res["delta_bytes"] = a["bytes"] - b["bytes"] if opts.interval_force_equal: res["verdict"] = "FAIL" res["note"] = ("control arm: forced equal numbers -> the " "'interval-not-effective / declaration invalid' branch") elif same: if b["end"] == len(text): res["verdict"] = "N/A" res["note"] = ("two intervals coincide structurally (no text after the END " "marker): equality is ambiguous, NOT a pass") else: res["verdict"] = "FAIL" res["note"] = ("two different intervals give the same numbers: " "interval-not-effective / declaration invalid") else: res["verdict"] = "PASS" if opts.interval_pair == "receipt": res["note"] = ("two numbers differ; delta = the '- RECEIPT ...' prefix " "overhead outside the brace-matched JSON") else: res["note"] = ("two numbers differ; delta = text inside A and outside B " "(the tool-appended tail after the block)") return res # --------------------------------------------------------------------------- # # whole-text evaluation # --------------------------------------------------------------------------- # def evaluate_text(text, opts, label="", file_bytes=None): res = OrderedDict() res["tool"] = VERSION res["label"] = label res["bytes"] = file_bytes if file_bytes is not None else len(text.encode("utf-8")) res["sha256"] = _sha256_hex(text) found = find_frames(text) frames = found["frames"] res["frames_found"] = len(frames) res["occurrences_skipped"] = found["skipped"] res["skipped_count"] = len(found["skipped"]) fevals = [] for n, fr in enumerate(frames, 1): if opts.frame and n != opts.frame: continue if fr.get("error") and fr.get("obj") is None: ev = OrderedDict([("frame", n), ("line", fr["line"]), ("offset", fr["offset"]), ("error", fr["error"]), ("overall", "UNKNOWN")]) else: ev = evaluate_frame(fr["obj"], opts, n, fr["offset"], fr["line"]) fevals.append(ev) res["frames"] = fevals res["interval"] = interval_harness(text, opts) if not frames: res["error"] = "no receipt frame found (anchor: %r)" % RECEIPT_PREFIX verdicts = [ev.get("overall") for ev in fevals] verdicts.append(res["interval"].get("verdict")) overall = _worst(verdicts) if not fevals or (res.get("error") and not fevals): overall = "UNKNOWN" res["overall"] = overall fields_checked = sum(1 for ev in fevals if (ev.get("fields") or {}).get("verdict") in ("PASS", "FAIL")) law_checked = sum(1 for ev in fevals if (ev.get("law") or {}).get("checked")) iv_checked = 1 if res["interval"].get("verdict") in ("PASS", "FAIL") else 0 if fields_checked + law_checked + iv_checked == 0: res["overall"] = "UNKNOWN" res["coverage"] = OrderedDict([ ("frames", len(fevals)), ("fields_checked", fields_checked), ("law_checked", law_checked), ("interval_checked", iv_checked), ("line", "frames=%d fields_checked=%d law_checked=%d interval_checked=%d" % (len(fevals), fields_checked, law_checked, iv_checked)), ]) return res # --------------------------------------------------------------------------- # # rendering # --------------------------------------------------------------------------- # def _render_fields(ev): s = ev["fields"] L = ["[1] FIELDS (tpc and len(tp) are two numbers, never one)"] for k in ("requested", "readable_upstream", "returned", "truncated", "omitted", "bytes_written", "tpc", "len_tp", "tpc_state", "tpc_note", "verdict"): L.append(" %-20s %s" % (k, s.get(k, ""))) return L def _render_kept(ev): s = ev["kept"] L = ["[2] KEPT DISTRIBUTION"] L.append(" %-20s %s" % ("N(=len tp)", s.get("N"))) L.append(" %-20s %s" % ("kept_list", s.get("kept_list"))) L.append(" %-20s %s" % ("kept_distinct", s.get("kept_distinct"))) L.append(" %-20s %s (%s)" % ("baseline", s.get("baseline"), s.get("baseline_source"))) L.append(" %-20s %s" % ("r=sum(kept)-N*base", s.get("r"))) L.append(" %-20s %s" % ("d1_count", s.get("d1_count"))) L.append(" %-20s %s" % ("d1_share", s.get("d1_share"))) L.append(" %-20s %s" % ("dge2_count", s.get("dge2_count"))) L.append(" %-20s %s" % ("dneg_count", s.get("dneg_count"))) L.append(" %-20s %s" % ("premise", s.get("premise"))) L.append(" %-20s %s" % ("verdict", s.get("verdict"))) if s.get("note"): L.append(" %-20s %s" % ("note", s["note"])) return L def _render_law(ev): s = ev["law"] L = ["[3] ORDERING LAW (r landing)"] L.append(" %-20s %s" % ("order_key", s.get("order_key"))) L.append(" %-20s %s" % ("r", s.get("r"))) L.append(" %-20s %s" % ("dpos_indices", s.get("dpos_indices"))) L.append(" %-20s %s" % ("topr_indices", s.get("topr_indices"))) L.append(" %-20s %s" % ("outside_topr", s.get("outside_topr"))) L.append(" %-20s %s" % ("boundary_in", s.get("boundary_in"))) L.append(" %-20s %s" % ("boundary_out", s.get("boundary_out"))) L.append(" %-20s %s" % ("placement", s.get("placement"))) L.append(" %-20s %s" % ("completeness", s.get("completeness"))) L.append(" %-20s %s" % ("checked", s.get("checked"))) L.append(" %-20s %s" % ("verdict", s.get("verdict"))) if s.get("note"): L.append(" %-20s %s" % ("note", s["note"])) return L def _render_dim(ev): s = ev["dimension"] L = ["[4] DIMENSION HINT (bytes per char; hint only, no mechanism claim)"] L.append(" %-20s %s" % ("thresholds", s.get("thresholds"))) L.append(" %5s %8s %12s %9s %s" % ("idx", "kept", "cut_at_bytes", "B/C", "class")) for row in s.get("rows", []): L.append(" %5d %8s %12s %9s %s" % (row[0], row[1], row[2], row[3], row[4])) L.append(" %-20s %s" % ("summary", s.get("summary"))) L.append(" %-20s %s" % ("verdict", s.get("verdict"))) if s.get("note"): L.append(" %-20s %s" % ("note", s["note"])) return L def _render_interval(s): L = ["[5] INTERVAL HARNESS (same spill, two intervals)"] if s.get("name_a"): L.append(" %-20s %s" % ("interval_A", s.get("name_a"))) L.append(" %-20s %s" % ("A chars/bytes", _fmt_span(s.get("A")))) if s.get("name_b"): L.append(" %-20s %s" % ("interval_B", s.get("name_b"))) L.append(" %-20s %s" % ("B chars/bytes", _fmt_span(s.get("B")))) if "delta_chars" in s: L.append(" %-20s chars=%s bytes=%s" % ("delta(A-B)", s.get("delta_chars"), s.get("delta_bytes"))) L.append(" %-20s %s" % ("verdict", s.get("verdict"))) if s.get("note"): L.append(" %-20s %s" % ("note", s["note"])) return L def _fmt_span(m): if not m: return "n/a" return "chars=%d bytes=%d span=[%d,%d]" % (m["chars"], m["bytes"], m["start"], m["end"]) def render(res): L = ["=== %s ===" % res.get("tool")] if res.get("label"): L.append("label: %s" % res["label"]) L.append("file_bytes: %s" % res.get("bytes")) L.append("sha256: %s" % res.get("sha256")) L.append("frames_found: %s" % res.get("frames_found")) L.append("occurrences_skipped: %s" % res.get("skipped_count", 0)) for sk in res.get("occurrences_skipped", []): L.append(" skipped @line %s: %s" % (sk.get("line"), sk.get("reason"))) if res.get("error"): L.append("error: %s" % res["error"]) for ev in res.get("frames", []): L.append("") L.append("--- frame %s (line %s, offset %s) ---" % (ev.get("frame"), ev.get("line"), ev.get("offset"))) if ev.get("error") and not ev.get("fields"): L.append(" error: %s" % ev["error"]) L.append(" verdict UNKNOWN") continue L.extend(_render_fields(ev)) L.extend(_render_kept(ev)) L.extend(_render_law(ev)) L.extend(_render_dim(ev)) L.append("") L.extend(_render_interval(res.get("interval") or {})) L.append("") L.append("overall: %s" % res.get("overall")) L.append("coverage: %s" % ((res.get("coverage") or {}).get("line", ""))) return "\n".join(L) # --------------------------------------------------------------------------- # # fixtures # --------------------------------------------------------------------------- # def fixture_specs(): """Four fixtures. All synthetic, deterministic, ASCII.""" specs = [] f1 = OrderedDict() f1["name"] = "f1_positive_n12_r8" f1["desc"] = ("N=12, tpc=12, kept 456x8 + 455x4, r=8, the 8 longest carry " "the +1; one Latin item at idx=11 (ratio 1.000)") f1["expect"] = "PASS" f1["meta"] = OrderedDict([("requested", 12), ("readable_upstream", 12), ("returned", 12), ("truncated", True), ("omitted", 0), ("tpc", 12)]) f1["entries"] = [ ("f1-01", 456, 2600, 1368, 7800), ("f1-02", 456, 2500, 1368, 7500), ("f1-03", 456, 2400, 1368, 7200), ("f1-04", 456, 2300, 1368, 6900), ("f1-05", 456, 2200, 1368, 6600), ("f1-06", 456, 2100, 1368, 6300), ("f1-07", 456, 2000, 1368, 6000), ("f1-08", 456, 1900, 1368, 5700), ("f1-09", 455, 1800, 1365, 5400), ("f1-10", 455, 1700, 1365, 5100), ("f1-11", 455, 1600, 1365, 4800), ("f1-12", 455, 1500, 455, 1500), ] specs.append(f1) f2 = OrderedDict() f2["name"] = "f2_tpc12_len11" f2["desc"] = ("MUST-RED #1: tpc=12 but the array carries 11 entries " "(tpc>len(tp) and len(tp)<12). The +1 placement itself is clean, " "so the only red is section 1.") f2["expect"] = "FAIL" f2["meta"] = OrderedDict([("requested", 12), ("readable_upstream", 12), ("returned", 11), ("truncated", True), ("omitted", 0), ("tpc", 12)]) f2["entries"] = [ ("f2-01", 456, 2200, 1368, 6600), ("f2-02", 456, 2100, 1368, 6300), ("f2-03", 456, 2000, 1368, 6000), ("f2-04", 456, 1900, 1368, 5700), ("f2-05", 456, 1800, 1368, 5400), ("f2-06", 455, 1700, 1365, 5100), ("f2-07", 455, 1600, 1365, 4800), ("f2-08", 455, 1500, 1365, 4500), ("f2-09", 455, 1400, 1365, 4200), ("f2-10", 455, 1300, 1365, 3900), ("f2-11", 455, 1200, 1365, 3600), ] specs.append(f2) f3 = OrderedDict() f3["name"] = "f3_fake_plus1_nonlongest" f3["desc"] = ("MUST-RED #2 / fake frame: N=12, tpc=12, kept 455x10 + 456x2, r=2, " "but the two +1 items are the two SHORTEST. Section 1 is clean; " "section 3 must go red on placement.") f3["expect"] = "FAIL" f3["meta"] = OrderedDict([("requested", 12), ("readable_upstream", 12), ("returned", 12), ("truncated", True), ("omitted", 0), ("tpc", 12)]) f3["entries"] = [ ("f3-01", 455, 3000, 1365, 9000), ("f3-02", 455, 2900, 1365, 8700), ("f3-03", 455, 2800, 1365, 8400), ("f3-04", 455, 2700, 1365, 8100), ("f3-05", 455, 2600, 1365, 7800), ("f3-06", 455, 2500, 1365, 7500), ("f3-07", 455, 2400, 1365, 7200), ("f3-08", 455, 2300, 1365, 6900), ("f3-09", 455, 2200, 1365, 6600), ("f3-10", 455, 2100, 1365, 6300), ("f3-11", 456, 1000, 1368, 3000), ("f3-12", 456, 900, 1368, 2700), ] specs.append(f3) f4 = OrderedDict() f4["name"] = "f4_positive_latin_r0" f4["desc"] = ("N=8 Latin batch, kept flat at 400 (r=0), ratios ~1.000. " "Exercises the r=0 degenerate state and the Latin classifier.") f4["expect"] = "PASS" f4["meta"] = OrderedDict([("requested", 8), ("readable_upstream", 8), ("returned", 8), ("truncated", True), ("omitted", 0), ("tpc", 8)]) f4["entries"] = [ ("f4-01", 400, 1200, 400, 1200), ("f4-02", 400, 1100, 400, 1100), ("f4-03", 400, 1000, 400, 1000), ("f4-04", 400, 900, 400, 900), ("f4-05", 400, 800, 400, 800), ("f4-06", 400, 700, 400, 700), ("f4-07", 400, 600, 400, 600), ("f4-08", 400, 500, 400, 500), ] specs.append(f4) return specs def _make_entry(seed, kept, total, cut, tb, reason="trimmed", unit="utf16-char"): d = OrderedDict() d["pin_id"] = _fake_pinid(seed) d["reason"] = reason d["kept_chars"] = kept d["total_chars"] = total d["cut_at_bytes"] = cut d["total_bytes"] = tb d["unit"] = unit return d def make_spill(spec, bytes_written=0): entries = [_make_entry(*e) for e in spec["entries"]] m = spec["meta"] obj = OrderedDict() obj["requested"] = m["requested"] obj["readable_upstream"] = m["readable_upstream"] obj["returned"] = m["returned"] obj["truncated"] = m["truncated"] obj["omitted"] = m["omitted"] obj["omitted_ids"] = [] obj["unreadable"] = 0 obj["unreadable_ids"] = [] obj["truncation_point_count"] = m["tpc"] obj["truncation_points"] = entries obj["caliber"] = CALIBER obj["bytes_written"] = bytes_written body = json.dumps(obj, ensure_ascii=True, separators=(",", ":")) parts = [HEADER_TEXT, RECEIPT_PREFIX + " " + body + "\n", FOOTER_TEXT + "\n", TRAIL_TEXT + "\n"] return "".join(parts) def build_spill(spec): """Build a spill text whose bytes_written equals the real file byte length.""" bw = 0 text = make_spill(spec, 0) for _ in range(6): text = make_spill(spec, bw) real = len(text.encode("utf-8")) if real == bw: break bw = real return text def emit_fixtures(dirpath): if not os.path.isdir(dirpath): os.makedirs(dirpath) out = [] for spec in fixture_specs(): text = build_spill(spec) path = os.path.join(dirpath, spec["name"] + ".spill.txt") with open(path, "wb") as fh: fh.write(text.encode("utf-8")) out.append((path, len(text.encode("utf-8")), _sha256_hex(text))) return out # --------------------------------------------------------------------------- # # selftest # --------------------------------------------------------------------------- # def _red_sections(res): reds = [] for ev in res.get("frames", []): for key, label in (("fields", "1"), ("kept", "2"), ("law", "3"), ("dimension", "4")): sec = ev.get(key) or {} if sec.get("verdict") == "FAIL": reds.append("[%s] %s" % (label, key.upper())) iv = res.get("interval") or {} if iv.get("verdict") == "FAIL": reds.append("[5] INTERVAL") return reds def run_selftest(): specs = fixture_specs() rows = [] for spec in specs: text = build_spill(spec) opts = Options() res = evaluate_text(text, opts, spec["name"]) rows.append((spec["name"], spec["expect"], res)) text = build_spill(specs[0]) opts = Options() opts.interval_force_equal = True res = evaluate_text(text, opts, specs[0]["name"] + " [interval forced-equal control]") rows.append(("i2_interval_forced_equal", "FAIL", res)) print("=== SELFTEST MATRIX ===") print("%-32s %-8s %-8s %-5s %-22s %s" % ("case", "expect", "got", "exit", "red", "status")) ok = 0 for name, expect, res in rows: got = res["overall"] reds = _red_sections(res) exit_code = {"PASS": 0, "FAIL": 2, "UNKNOWN": 3}.get(got, 3) good = (got == expect) if good: ok += 1 print("%-32s %-8s %-8s %-5d %-22s %s" % (name, expect, got, exit_code, ",".join(reds) if reds else "-", "OK" if good else "MISMATCH")) total = len(rows) required = rows[:3] req_ok = sum(1 for _, e, r in required if r["overall"] == e) f2 = rows[1] f2_ok = 1 if f2[2]["overall"] == f2[1] else 0 print("") print("selftest: %d/%d as designed | required fixtures (f1,f2,f3) %d/3 | " "required must-red (f2 tpc12/len11) %d/1 | control arms %d/%d" % (ok, total, req_ok, f2_ok, sum(1 for _, e, r in rows[3:] if r["overall"] == e), len(rows) - 3)) return 0 if ok == total else 2 # --------------------------------------------------------------------------- # # main # --------------------------------------------------------------------------- # def main(argv=None): ap = argparse.ArgumentParser( prog="readpath_gate.py", description="Machine-judgeable gate for batch-read receipts in spill text.") ap.add_argument("--file", help="spill text file to evaluate (omit to read stdin)") ap.add_argument("--frame", type=int, default=None, help="evaluate only this 1-based frame") ap.add_argument("--baseline", type=int, default=None, help="override the kept baseline (default: min(kept_chars))") ap.add_argument("--cap", type=int, default=DEFAULT_CAP, help="declared truncation_points array cap (default 12)") ap.add_argument("--json", action="store_true", help="emit JSON instead of the text table") ap.add_argument("--selftest", action="store_true", help="run the built-in arms") ap.add_argument("--emit-fixtures", metavar="DIR", help="write the four fixture spill files into DIR") ap.add_argument("--interval-pair", choices=("footer", "receipt"), default="footer", help="which two intervals section 5 compares") ap.add_argument("--no-interval", action="store_true", help="skip section 5 (reported N/A, not a pass)") ap.add_argument("--interval-force-equal", action="store_true", help="control arm: force the two interval numbers equal") ap.add_argument("--version", action="version", version=VERSION) args = ap.parse_args(argv) if args.selftest: return run_selftest() if args.emit_fixtures: for path, nbytes, sha in emit_fixtures(args.emit_fixtures): print("%s bytes=%d sha256=%s" % (path, nbytes, sha)) return 0 opts = Options() opts.cap = args.cap opts.baseline = args.baseline opts.frame = args.frame opts.interval_pair = args.interval_pair opts.no_interval = args.no_interval opts.interval_force_equal = args.interval_force_equal if args.file: with open(args.file, "rb") as fh: raw = fh.read() text = raw.decode("utf-8", "replace") label = args.file file_bytes = len(raw) else: raw = sys.stdin.buffer.read() text = raw.decode("utf-8", "replace") label = "" file_bytes = len(raw) res = evaluate_text(text, opts, label, file_bytes) if args.json: print(json.dumps(res, ensure_ascii=True, indent=2)) else: print(render(res)) return {"PASS": 0, "FAIL": 2, "UNKNOWN": 3}.get(res["overall"], 3) if __name__ == "__main__": sys.exit(main())