"""seal - the judge at the one exit every reply leaves through (12.5, round-2 design section 1.1; organ 1 of 4). A reply is said only as far as its receipts read back. The seal splits the delivered text into sentences, each with the receipts its producer attached, and reads every receipt back against its record with its own code: [wd:Q P

Q] the relation store holds (s, p, o) and the sentence says the object's name and the subject's (or a pronoun standing for it); [hole:] the hole record holds that id (a hole says what is not held; it is never an assertion). Other receipt families (a page record [n], a proving path, a reading receipt) are counted by family; until the seal reads a family back it is "not read by the seal" and changes nothing. Sentences with no receipt are counted. The seal only lowers: a reply's label is the lower of what its producer said and what its receipts bear. It never raises a hole to an answer, never adds a sentence, and never rewrites one. No language model; no hand-written list about data. This module is pure: it is given the stores and the reply and returns the verdict; wiring it at the one exit is step 3.""" import json import os import re RECEIPT = re.compile(r"\[([^\[\]]{1,200})\]") # a receipt has a shape: family:value (wd:, hole:, scene:, turn:, enwiki_...:) or page record numbers; a bracket holding code or # a list ([x for x in xs], ['a', 'b']) is text, not a receipt SHAPE = re.compile(r"^(?:[A-Za-z][\w-]{0,40}:\S.*|\d+(?:\s*,\s*\d+)*)$") WD = re.compile(r"^wd:Q(\d+)\s+P(\d+)\s+Q(\d+)$") HOLE = re.compile(r"^hole:([\w-]+)$") PRONOUN = {"it", "he", "she", "they", "its", "his", "her", "their", "this", "these"} ORDER = {"answered": 3, "offered": 2, "hole": 1} def sentences(text): """the body as [(sentence, [receipts])]: a sentence ends at . ! ? followed by its receipt group; sections a reply marks as sources or how it was made are not sentences of the body""" body, fence = [], False for ln in str(text or "").splitlines(): if ln.strip().startswith("```"): fence = not fence # code shown in a reply is not a sentence of it continue if fence: continue s = ln.strip() if re.match(r"^(?:#+\s*|\*\*|_)?(?:sources|how this was made)\b", s, re.I): break if s and not s.startswith(("#", "```")): body.append(s) text = re.sub(r"`[^`]*`", "", " ".join(body)) # inline code is not a sentence's content or a receipt out, pos = [], 0 for m in re.finditer(r"[.!?][\"')\]]*((?:\s*\[[^\[\]]{1,200}\])*)(?=\s+[A-Z0-9\"(]|\s*$)", text): seg = text[pos:m.end()].strip() pos = m.end() if seg: out.append((RECEIPT.sub("", seg).strip(), [x for x in RECEIPT.findall(seg) if SHAPE.match(x.strip())])) tail = text[pos:].strip() if tail: out.append((RECEIPT.sub("", tail).strip(), [x for x in RECEIPT.findall(tail) if SHAPE.match(x.strip())])) return [(s, rc) for s, rc in out if s or rc] def _words(s): return {w for w in re.findall(r"[a-z0-9]+", s.lower()) if len(w) > 2} def read_back(sentence, receipts, store, holes): """-> (family, ok or None). ok None = a family the seal does not read yet""" if not receipts: return "none", None fams = [] for rc in receipts: rc = rc.strip() m = WD.match(rc) if m: s, p, o = (int(x) for x in m.groups()) ok = bool(store.holds(s, p, o)) if ok: ow, sw, ws = _words(store.label(o) or ""), _words(store.label(s) or ""), _words(sentence) ok = (not ow or bool(ow & ws)) and (not sw or bool(sw & ws) or bool(PRONOUN & set(sentence.lower().split()))) fams.append(("wd", ok)) continue m = HOLE.match(rc) if m: fams.append(("hole", m.group(1) in holes)) continue if re.fullmatch(r"\d+(?:\s*,\s*\d+)*", rc): fams.append(("page", None)) continue fams.append(("other:" + rc.split(":")[0][:20].lower(), None)) known = [ok for _f, ok in fams if ok is not None] fam = fams[0][0] if len({f for f, _ in fams}) == 1 else "+".join(sorted({f for f, _ in fams})) if not known: return fam, None return fam, all(known) def holes_of(state_dir): p = os.path.join(state_dir, "holes.jsonl") if state_dir else None out = set() if p and os.path.isfile(p): for ln in open(p, encoding="utf-8", errors="replace"): try: out.add(str(json.loads(ln)["id"])) except (ValueError, KeyError): continue return out def registry(tree): """the names of this release's verified parts (RELEASE_HASHES.json, the registry verify_install checks); empty when absent""" try: return set(json.load(open(os.path.join(tree, "RELEASE_HASHES.json"), encoding="utf-8")).get("parts") or {}) except (OSError, ValueError): return set() def proof_reads(reply, parts): """-> (ok, why) for a proving-path receipt: every part it names is a part of this release's registry""" pr = reply.get("proof") or {} names = list(pr.get("parts") or []) if not names: return None, None missing = [n for n in names if n not in parts] if missing: return False, "its proof names %s, which %s not a part of this release" % (", ".join(missing), "is" if len(missing) == 1 else "are") return True, "proved by %s" % ", ".join(names) def executed(reply): """a record of what ran: the bench's receipt (state) or the workspace tools' run receipt (started, returncode)""" ex = reply.get("execution") or {} return isinstance(ex, dict) and (bool(ex.get("state")) or (ex.get("started") is True and "returncode" in ex)) def seal(reply, store, holes=frozenset(), parts=frozenset()): """-> the verdict: each sentence's family and read-back, the label the receipts bear (never above the producer's), and what would be lowered and why. Pure: the reply is not changed here.""" status = reply.get("status") or "hole" rows = [] for s, rc in sentences(reply.get("response")): fam, ok = read_back(s, rc, store, holes) rows.append({"text": s, "receipts": rc, "family": fam, "ok": ok}) asserted = [r for r in rows if r["family"] not in ("hole",)] failed = [r for r in asserted if r["ok"] is False] bare = [r for r in asserted if r["family"] == "none"] unread = [r for r in asserted if r["ok"] is None and r["family"] != "none"] label = status why = [] pok, pwhy = proof_reads(reply, parts) if status == "answered": if failed: label, why = "offered", ["%d receipted sentence(s) do not read back" % len(failed)] elif pok is False: label, why = "offered", [pwhy] elif (bare and not any(r["ok"] for r in asserted) and not unread and pok is None and not executed(reply)): label, why = "offered", ["no sentence carries a receipt, a proof or a record of what ran"] if ORDER.get(label, 0) > ORDER.get(status, 0): label = status # the seal only lowers return {"status": status, "label": label, "lowered": label != status, "why": why, "proof": pwhy, "rows": rows, "counts": {"sentences": len(rows), "read_back": sum(1 for r in rows if r["ok"]), "failed": len(failed), "bare": len(bare), "unread_family": len(unread)}}