#!/usr/bin/env python3 """SQUIRCLE ROUTER v4 (round 5): the squircle run forward, then INVERTED and overlaid (Ben 2026-11-06: "run the squircle part and then have one that is inverted overlayed"; earlier: "a klein bottle with an inverted plane running through the diagonal"). The fold-paper fixed point x* = S(x*): a reply is kept only if reading it back lands on the turn it answers. FORWARD (turn -> replies). The TURN READER (turn_reader.py: speller + typed frame) reads the turn; `ground` binds it/this/that to the last frame's keys in this conversation; then EVERY port offers its candidate, none chosen yet: inform the head's checked answer (to the turn as written, and to the corrected turn); a cited record commissive a named command of the head, matched on the frame's verb + object: a read-only one RUNS (its output is the reply, its receipt goes to the ledger); one that changes state is offered as the exact command, kept open in the ledger until "go". A request for text (verb glossed as say/tell/explain/write, or an object glossed as a piece of writing) runs the essay command on the frame's topic. ledger a status turn ("did it work", "where are we", "is X live") is answered from the WORK LEDGER: what this Oracle7 ran in this conversation, each run's receipt, what is open hole the frame said back as a named hole: what was asked, of what, and that no operation of mine does it INVERTED (reply -> turn). Each candidate is read back with the same instruments: act fit its act (the relational instrument's act_of) against the human distribution P(reply act | turn act) aboutness the share of the frame's keys (IDF over Oracle7's records) that the candidate's lemmas carry A candidate whose read-back carries < 40% of the frame's key mass does not leave the circle (the lecture on one common word, the record that shares two words). Among those left: aboutness + act fit + 1 for substance (an answer, a run, a ledger report) over a named hole. Nothing is written about any turn. usage: module (SquircleRouterV4(..., reader=Reader))""" from __future__ import annotations import collections import math import re from squircle_reply import content_words from squircle_reply_v3 import SquircleRouterV3, SAFE, STATEFUL COVER = 0.40 MOOD_ACT = {"question": "question", "request": "directive", "commitment": "commissive", "statement": "inform", "social": "inform"} TEXT_NOUN = re.compile(r"\b(?:writing|written|text|narrative|article|essay|description|report|story|summary|" r"composition|message|publication)\b", re.I) SAY_VERB = re.compile(r"\b(?:communicate|express|say|tell|explain|describe|write|inform|narrate|speak|talk|recount|" r"summarize|summarise)\b", re.I) LECTURE = re.compile(r"^(?:capability:summarize|arb:explain_simply|arb:summarize|arb:definitional|resolve:topic)") GENERIC = {"need", "want", "get", "make", "give", "be", "do", "have", "let", "put", "like", "go", "see", "done", "continue", "keep", "can", "will", "try", "use", "work"} class SquircleRouterV4(SquircleRouterV3): def __init__(self, *a, reader=None, **k): super().__init__(*a, **k) self.reader = reader self.frames = collections.defaultdict(list) self.ledger = collections.defaultdict(list) # session -> [{"cmd", "receipt", "ok", "open", "turn"}] # ---------------- interior: ground the frame in this conversation def bind(self, session, fr): prev = [f for f in self.frames[session] if [k for k in f["keys"] if k not in GENERIC]] fr["bound"] = [] if fr["refs"] and prev: fr["bound"] = [k for k in prev[-1]["keys"] if k not in GENERIC][:4] return fr def kw(self, fr): ks = [k for k in fr["keys"] if k not in GENERIC] + [k for k in fr.get("bound", []) if k not in fr["keys"]] return ks def topic_words(self, fr): t = [w for w in fr["topic"] if w.isalnum() and not self.reader.is_closed(w)] if not t or all(w in ("this", "that", "it") for w in t): t = [w for w in fr["object"] if w.isalnum() and not self.reader.is_closed(w) and not self._is_text_noun(w)] if not t: t = fr.get("bound", []) return t # ---------------- dictionary classes (by gloss, never by list of words) def _glosses(self, w, pos): return [g for p, gs in self.reader.d.entries(w) if p == pos for g in gs] def _is_text_noun(self, w): return any(TEXT_NOUN.search(g) for g in self._glosses(w, "noun")[:12]) def _is_say_verb(self, v): return bool(v) and any(SAY_VERB.search(g) for g in self._glosses(v, "verb")[:6]) def is_text_request(self, fr): if fr["mood"] != "request": return False return self._is_say_verb(fr["verb"]) or any(self._is_text_noun(w) for w in fr["object"][:3]) # ---------------- the work ledger def ledger_report(self, session, fr): L = self.ledger[session] obj = [k for k in self.kw(fr)] if not L: return ("I have not run anything in this conversation yet, so I have no receipt of my own to report%s." % ((" on " + " ".join(obj)) if obj else ""), False) rel = [e for e in L if not obj or any(o in e["cmd"].lower() or o in e["receipt"].lower() for o in obj)] or L done = [e for e in rel if not e["open"]][-3:] open_ = [e for e in L if e["open"]][-3:] parts = [] if done: parts.append("What I ran here: " + "; ".join("`%s` (turn %d): %s" % (e["cmd"], e["turn"], e["receipt"]) for e in done) + ".") if open_: parts.append("Open, waiting on your go: " + "; ".join("`%s`" % e["cmd"] for e in open_) + ".") return " ".join(parts), True # ---------------- forward squircle: every port's candidate def candidates(self, turn, fr, session, cg, head): out = [] n = len(self.frames[session]) if self.check(head): out.append(("inform", "head", head["response"], True, str(head.get("path", "")))) if fr["changes"] and fr["fixed"].strip().lower() != turn.strip().lower(): h2 = self.head_chat(fr["fixed"], session) if self.check(h2): out.append(("inform", "head_fixed", h2["response"], True, str(h2.get("path", "")))) kw = self.kw(fr) if fr["status"]: txt, sub = self.ledger_report(session, fr) out.append(("inform", "ledger", txt, sub, "")) if self.is_text_request(fr): tw = self.topic_words(fr) if tw: r = self.run_safe("essay", tw, set()) cmd = 'oracle7.py essay "%s"' % " ".join(tw) self.ledger[session].append({"cmd": cmd, "receipt": "wrote it" if r else "returned nothing checked", "ok": bool(r), "open": False, "turn": n}) if r: out.append(("commissive", "essay", r, True, "")) if fr["mood"] in ("request", "commitment") and kw: m = self.match(kw) if m: _, cmd, usage, desc, ov = m if cmd in SAFE and cmd != "essay": tw = self.topic_words(fr) r = self.run_safe(cmd, tw, set(ov)) self.ledger[session].append({"cmd": "oracle7.py %s %s" % (cmd, " ".join(tw)), "turn": n, "receipt": (r or "nothing")[:80], "ok": bool(r), "open": False}) if r: out.append(("commissive", "run", r, True, "")) elif cmd in STATEFUL: self.ledger[session].append({"cmd": "oracle7.py " + usage, "receipt": "", "ok": False, "open": True, "turn": n}) out.append(("commissive", "commit", "That is `oracle7.py %s`: %s. It changes state, so I run it on your go and keep its " "receipt." % (usage, desc[:160]), True, "")) hits = self.recall(kw) if kw else [] if hits: out.append(("inform", "records", " ".join("My records (%s): %s" % (f, s) for _, s, f, _ in hits), True, "")) out.append(("hole", "hole", self.hole_text(fr), False, "")) return out def hole_text(self, fr): obj = " ".join(w for w in fr["object"] if w not in ("it", "this", "that")) or " ".join(fr.get("bound", [])) top = " ".join(w for w in fr["topic"] if w not in ("it", "this", "that")) what = " ".join(x for x in [fr["verb"] or "", obj, ("on " + top) if top else ""] if x).strip() if fr["mood"] in ("request", "commitment"): return ("You asked me to %s. No operation of mine does that, so I can't do it from here; it goes to the " "builder as a named hole." % (what or "act on that")) if fr["mood"] == "question": return "You asked %s %s. I have no record that answers it, and I won't guess." % ( fr["wh"] if fr["wh"] and fr["wh"] != "yes/no" else "about", what or "that") if fr["mood"] == "social": return None return None # ---------------- inverted squircle: read each candidate back def inverse(self, fr, u, text, path=""): act_c = self.act_of(text) fit = (self.phi.get(u) or {}).get(act_c, 0.0) kw = self.kw(fr) if not kw: return fit, 1.0, act_c lem = self.reader.lemmas_of(re.sub(r"`[^`]*`", " ", text) if not path else text) wt = lambda w: self.rec.idf.get(w, 6.0) mass = sum(wt(k) for k in kw) agree = sum(wt(k) for k in kw if k in lem) / mass if mass > 0 else 1.0 return fit, agree, act_c def reply(self, turn, session="convo"): self._cur = turn self.turns[session].append(turn) self.reader.sp.observe(turn) cg = self.common[session] self.receive(cg, turn) fr = self.bind(session, self.reader.read(turn)) u = MOOD_ACT.get(fr["mood"], "inform") head = self.head_chat(turn, session) cands = self.candidates(turn, fr, session, cg, head) self.frames[session].append(fr) scored = [] for port, sub, text, substantive, hpath in cands: if not text: continue fit, agree, act_c = self.inverse(fr, u, text) # the head's own computed answer to a question keeps its own check (a value need not restate the question) if sub.startswith("head") and fr["mood"] == "question" and hpath and not LECTURE.match(hpath): agree = max(agree, COVER) if agree < COVER and port != "hole": continue scored.append((agree + fit + (1.0 if substantive else 0.0), port, sub, text, act_c, round(agree, 2))) frame = {k: fr[k] for k in ("mood", "verb", "object", "topic", "status", "keys", "bound", "changes")} if not scored: return {"status": "declined", "response": "I can't reply to that with anything I can check.", "path": "squircle4:%s>none" % u, "act_in": u, "frame": frame} scored.sort(key=lambda x: -x[0]) s, port, sub, text, act_c, agree = scored[0] return {"status": "answered", "response": text, "path": "squircle4:%s>%s:%s" % (u, port, sub), "act_in": u, "act_out": act_c, "agree": agree, "frame": frame, "considered": [(round(x[0], 2), x[1] + ":" + x[2], x[5]) for x in scored[:5]]}