Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- root/wander-train/appraisal_v1.pyAdded+194
- root/wander-train/chat_context_v1.pyAdded+372
- root/wander-train/chem_agents_v1.pyAdded+586
- root/wander-train/code_organ_v2.pyAdded+474
- root/wander-train/code_organ_v3.pyAdded+488
- root/wander-train/exact_router_v1.pyAdded+143
- root/wander-train/general_reader_v1.pyAdded+471
- root/wander-train/math_organ_v2.pyAdded+508
- root/wander-train/oracle_cube_reader_v1_3.pyAdded+447
- root/wander-train/oracle_game_combine_v1.pyAdded+209
- root/wander-train/oracle_program_ir_v1.pyAdded+256
- root/wander-train/oracle_release_conceptnet.pyAdded+142
- root/wander-train/oracle_release_runtime_aa.pyAdded+135
- root/wander-train/oracle_release_runtime_ac.pyAdded+140
- root/wander-train/oracle_release_runtime_ag.pyAdded+104
- root/wander-train/oracle_release_runtime_ah.pyAdded+76
- root/wander-train/oracle_release_runtime_aj.pyAdded+72
- root/wander-train/oracle_release_runtime_am.pyAdded+55
- root/wander-train/oracle_release_runtime_c.pyAdded+113
- root/wander-train/oracle_release_runtime_e.pyAdded+126
- root/wander-train/oracle_release_runtime_h.pyAdded+70
- root/wander-train/oracle_release_runtime_k.pyAdded+73
- root/wander-train/oracle_release_runtime_n.pyAdded+17
- root/wander-train/oracle_release_runtime_p.pyAdded+34
- root/wander-train/oracle_release_runtime_q.pyAdded+148
- root/wander-train/oracle_release_runtime_s.pyAdded+50
- root/wander-train/oracle_release_runtime_u.pyAdded+44
- root/wander-train/oracle_release_runtime_w58.pyAdded+212
- root/wander-train/oracle_release_runtime_w59.pyAdded+164
- root/wander-train/oracle_release_runtime_w60.pyAdded+64
- root/wander-train/oracle_release_runtime_w71.pyAdded+245
- root/wander-train/oracle_sibling_evidential_v3.pyAdded+92
- root/wander-train/oracle_tritree_v1.pyAdded+473
- root/wander-train/oracle_tritree_v2.pyAdded+479
- root/wander-train/organ_dialogue_v1.pyAdded+125
- root/wander-train/organ_self_v1.pyAdded+308
- root/wander-train/path_memory_v1.pyAdded+171
- root/wander-train/pubchem_periodic_table.csvAdded+119
- root/wander-train/relation_forms_v2.pyAdded+118
- root/wander-train/stage5c58_cycling_cognitive_substrate.pyAdded+480
- root/wander-train/stage5h1_generic_dataset_expert.pyAdded+377
- root/wander-train/stage5h3_hrr_relational_state_transducer.pyAdded+363
- root/wander-train/stage5k102_persistent_typed_discourse_agent.pyAdded+1614
- root/wander-train/stage5k104_relational_ingress_equivalence_agent.pyAdded+228
- root/wander-train/stage5k108_universal_terminal_proof_projection_agent.pyAdded+127
- root/wander-train/stage5k115_copular_definition_equivalence_agent.pyAdded+229
- root/wander-train/stage5k117_caller_context_isolation_agent.pyAdded+175
- root/wander-train/stage5k11_quadratic_inverse_solver.pyAdded+348
- root/wander-train/stage5k121_authenticated_context_operator_agent.pyAdded+243
- root/wander-train/stage5k131_registered_source_action_ingress_agent.pyAdded+210
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194#!/usr/bin/env python3"""appraisal_v1 - APPRAISAL of a turn from what Oracle7 knows, not from emotion words.
Scherer's component-process checks, each computed from structure: EVENT CLASS every noun/verb in the turn is walked up WordNet's hypernym graph; the classes it reaches (illness, damage, loss, failure, danger, crime/deception, obstruction, gain, praise, reunion, surprise) are the event's appraisal - "toothache" -> ill_health, "fire" -> danger, "cheated" -> deception, with no cue for those words anywhere in this file AGENCY whose doing: the speaker's own ("I broke", "I overslept") vs another's ("you", "he", "they", a passive "I've been cheated") - another's obstruction appraises to anger, one's own loss to sadness NOVELTY explicit unexpectedness markers EMOTION the class those checks produce: fear (danger), anger (another's obstruction / norm violation), sadness (own loss, illness, damage, failure, regret), surprise (unexpected), happiness (gain, praise, reunion), disgust (revulsion)Direct emotion words still count (they are evidence too), but the event walk is what generalises.usage (dev tuning only): appraisal_v1.py dev"""import reimport sysfrom functools import lru_cache
try: from nltk.corpus import wordnet as wn wn.synsets("dog")except Exception: # noqa: BLE001 wn = None
# WordNet anchor synsets -> appraisal class (a word appraises to a class when one of its senses reaches the anchor)ANCHORS = { "danger": ["danger.n.01", "fire.n.04", "emergency.n.01", "accident.n.01", "disaster.n.02", "attack.n.01", "injury.n.01", "threat.n.01", "violence.n.01"], "ill_health": ["ill_health.n.01", "illness.n.01", "pain.n.01", "ache.n.01", "symptom.n.01", "infection.n.01", "wound.n.01"], "damage": ["damage.n.01", "breakage.n.02", "break.v.02", "break.v.03", "destroy.v.01", "spill.v.01", "malfunction.n.01"], "loss": ["loss.n.01", "lose.v.01", "lose.v.02", "death.n.01", "die.v.01", "misplace.v.01", "forget.v.01"], "failure": ["failure.n.01", "fail.v.02", "fail.v.04", "mistake.n.01", "delay.n.01", "oversleep.v.01"], "deception": ["deception.n.01", "cheat.v.01", "cheat.v.02", "deceive.v.01", "rip_off.v.01", "crime.n.01", "rob.v.01", "steal.v.01"], "obstruction": ["obstruction.n.01", "traffic_jam.n.01", "wait.v.01", "trap.v.01", "block.v.01", "pollution.n.01", "noise.n.01"], "gain": ["gain.n.01", "win.v.01", "promotion.n.01", "success.n.01", "prize.n.01", "gift.n.01", "celebration.n.01"], "praise": ["praise.n.01", "compliment.n.01", "congratulation.n.01"],}EMOTION_OF_CLASS = {"danger": "fear", "ill_health": "sadness", "damage": "sadness", "loss": "sadness", "failure": "sadness", "deception": "anger", "obstruction": "anger", "gain": "happiness", "praise": "happiness"}DIRECT = { "fear": r"\b(?:scared|frighten\w*|terrified|worried|nervous|anxious|panic\w*|butterflies|dread\w*|help me|save (?:my|me)|" r"(?:i'?m|i am) (?:so |really |very )?afraid of)\b", "anger": r"\b(?:angry|furious|mad at|annoy\w*|irritat\w*|fed up|sick of|i hate|ridiculous|outrageous|unacceptable|" r"how dare|damn|can'?t (?:stand|bear)|hundred times|stupid|terrible|horrendous|awful|rude)\b", "disgust": r"\b(?:disgust\w*|gross|revolting|yuck|nasty|filthy|sickening)\b", "sadness": r"\b(?:sad|unhappy|depress\w*|lonely|i miss|sorry to hear|so sorry about|heartbroken|upset|cry\w*|" r"(?:so|very) tired|not up to|against me|(?:i'?m|i am) sorry,? (?:i|sir|madam))\b", "surprise": r"(?:\bwhat a surprise\b|\bno way\b|\breally\?|\bwow\b|\byikes\b|\bcan'?t believe\b|\bnever believe\b|" r"\bsurpris\w*|\bfancy meeting\b|\bunbelievable\b|\bwhat happened\b|\balmost didn'?t recogni[sz]e\b|" r"\bhow come\b|\bis that you\b)", "happiness": r"\b(?:happy|glad|wonderful|fantastic|excited|delighted|congratulations|thank you so much|can'?t wait|" r"nice to (?:see|meet)|great news|lovely|beautiful|magnificent|cute|proud|impressed|good job|enjoy|" r"in heaven|smells good|finally (?:here|back))\b",}OTHER_AGENT = re.compile(r"\b(?:you|he|she|they|someone|somebody|that guy|the (?:driver|waiter|company|shop|landlord))\b" r"|\b(?:been|got|was|were) (?:\w+ed|cheated|robbed|stolen|hit|fired|dumped)\b", re.I)STOP = set("be have do get go make take come see know say think want like feel look give use find tell ask seem " "try leave call keep let begin show hear play run move live believe bring happen write sit stand lose pay " "meet include continue set learn change lead understand watch follow stop create speak read spend grow " "open walk win offer remember love consider appear buy wait serve die send build stay fall cut reach kill " "raise pass sell decide return explain hope develop carry break receive agree support hit produce eat " "cover catch draw choose wear thing time way day man woman people year".split())
@lru_cache(maxsize=None)def _anchors(): if wn is None: return {} out = {} for cls, names in ANCHORS.items(): for n in names: try: out[wn.synset(n)] = cls except Exception: # noqa: BLE001 pass return out
@lru_cache(maxsize=20000)def word_class(word): """the appraisal class reached by the word's MOST FREQUENT sense (WordNet usage counts), walked only when that sense is a noun - "going" (verb), "down" (adverb), "still" (adverb) are not events; "toothache", "fire" are""" if wn is None: return None anchors = _anchors() syns = wn.synsets(word.lower()) if not syns: return None top = max(syns, key=lambda x: (sum(l.count() for l in x.lemmas() if l.name().lower() == word.lower()), -syns.index(x))) if top.pos() != "n": return None seen, frontier = set(), [top] for _ in range(8): nxt = [] for x in frontier: if x in anchors: return anchors[x] for h in x.hypernyms() + x.instance_hypernyms(): if h not in seen: seen.add(h) nxt.append(h) frontier = nxt if not frontier: break return None
# events carried by VERBS are named explicitly (a verb's most frequent sense is rarely the eventful one)EVENT_VERBS = {"deception": r"\b(?:cheated|robbed|stolen|stole|ripped off|scammed|lied to)\b", "damage": r"\b(?:broke|broken|smashed|spilled|crashed|ruined|wrecked)\b", "loss": r"\b(?:lost (?:my|our|the|his|her)|left my|passed away|died)\b", "failure": r"\b(?:overslept|failed|missed (?:the|my)|didn'?t (?:accomplish|finish|make it|pass|win)|forgot)\b", "obstruction": r"\b(?:stuck|waiting (?:for )?(?:quite|so|such) (?:a )?(?:long|time)|almost hit|traffic jam)\b", "gain": r"\b(?:won(?!')|promoted|got the job|finally (?:lost|got|finished|passed)|new baby|just bought)\b"}
def appraise(text): """{"emotion", "classes", "agent", "novel", "evidence"} - evidence names the words and the checks that fired""" t = str(text or "").replace("’", "'").replace(" ' ", "'") direct = [e for e, rx in DIRECT.items() if re.search(rx, t, re.I)] classes, ev = [], [] for c, rx in EVENT_VERBS.items(): m = re.search(rx, t, re.I) if m: classes.append(c) ev.append("%s->%s" % (m.group(0).lower(), c)) for w in re.findall(r"[A-Za-z][A-Za-z'-]{2,}", t): wl = w.lower().strip("'") if wl in STOP or len(wl) < 4: continue c = word_class(wl) if c: classes.append(c) ev.append("%s->%s" % (wl, c)) other = bool(OTHER_AGENT.search(t)) novel = "surprise" in direct emo = "none" if "fear" in direct or "danger" in classes: emo = "fear" elif "anger" in direct or "deception" in classes or ("obstruction" in classes and other): emo = "anger" elif "disgust" in direct: emo = "disgust" elif "gain" in classes and "finally" in t.lower(): emo = "happiness" elif "sadness" in direct or any(c in classes for c in ("ill_health", "loss", "damage", "failure")): emo = "sadness" elif novel: emo = "surprise" elif "happiness" in direct or any(c in classes for c in ("gain", "praise")): emo = "happiness" return {"emotion": emo, "classes": classes, "agent": "other" if other else "self", "novel": novel, "evidence": ev + ["direct:%s" % d for d in direct]}
def _dev(): import collections sys.path.insert(0, "/root/w240") from relational_instrument_v1 import dd tp, hu, pr, fp, nn, miss = collections.Counter(), collections.Counter(), collections.Counter(), 0, 0, [] fps = collections.Counter() for r in dd("dev"): g, a = r["e0"], appraise(r["opener"]) p = a["emotion"] if g != "none": hu[g] += 1 else: nn += 1 if p != "none": fp += 1 fps[(p, tuple(a["evidence"][:3]))] += 1 if p != "none": pr[p] += 1 if g == p and g != "none": tp[g] += 1 elif g != "none" and len(miss) < 25: miss.append((g, p, a["evidence"][:4], r["opener"][:80])) for e in ("anger", "disgust", "fear", "happiness", "sadness", "surprise"): print(" %-9s %3d / %3d human / %3d predicted" % (e, tp[e], hu[e], pr[e])) print(" DEV recall %d/%d | false positives on neutral %d/%d" % (sum(tp.values()), sum(hu.values()), fp, nn)) print(" top false-positive evidence:", fps.most_common(12)) for m in miss: print(" miss", m)
if __name__ == "__main__": _dev()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372#!/usr/bin/env python3"""chat_context_v1 - Oracle7's CONVERSATION engine (Ben 2026-10-09: "we have what we need for a proper chat model").
Chat failed by REFUSAL, not by error: a follow-up ("Where was he born?", "And its currency?", "And of Denmark?", "What doesthat cost?") reached the core without the conversation, and the core either refused or - worse - read the pronoun as thetopic ("he" -> an article about the word "he"). This engine never asserts anything itself. It keeps a small DIALOGUE STATEper session and REWRITES a turn that only makes sense through the conversation into the standalone question it standsfor; the whole verified chain (router, 210 specialists, fusion, maths) then answers that question exactly as it would ifit had been asked outright. The rewrite is shown in the reply's path and provenance, so the reading can be checked.
STATE (per session): the previous standalone question; its SUBJECT entity (the entity asked about) and its ANSWER entity (the entity the reply named), each with whether it is a person; the previous numeric RESULT (value + unit); solved variables ("x = 5"); the previous question's material phrase ("burning 5 kg of coal"). PRONOUNS he/she/him/his/her -> the person in play (the answer if it is a person - "Who wrote Frankenstein? / Who was her mother?" - else the subject); it/its -> the THING asked about ("Which planet does Titan orbit? / Who discovered it?" is Titan); "that country / that city ..." -> the entity just named; possessives become "the <noun> of <E>". ELLIPSIS "And its currency?" (relation swap), "And of Denmark?" / "And Doctor Zhivago?" (entity swap in the previous question), "And on the Moon?" / "And with radius 10 m?" (modifier swap or addition), "Where?" / "In what year?" (question-word swap, active -> passive when needed: "Who discovered Titan?" -> "In what year was Titan discovered?"). RESULTS "What does that cost at $0.20 per kWh?" -> the previous result ("300 kWh"); "What is x squared?" -> the solved x; "How much CO2 does that emit?" -> the previous material phrase ("burning 5 kg of coal"). MULTI "What is the capital of Austria and what is its currency?" -> two questions, each resolved and answered.A turn with nothing to resolve is passed through untouched. If a rewrite cannot be made with confidence, nothing isrewritten (the chain's own reply stands)."""import re
import relation_spec_v1 as RS
PRON_PERSON = r"he|she|him|his|her|hers"PRON_THING = r"it|its"REL_NOUNS = r"capital(?: city)?|currency|population|official language|national anthem|anthem|continent|calling code|highest point|" \ r"leader|president|prime minister|author|director|composer|creator|founder|headquarters|nationality|religion|" \ r"spouse|wife|husband|father|mother|birthplace|place of birth|date of birth|birthday"WH = r"who|what|which|where|when|how"STATE_CAP = 2000UNRESOLVED = "__unresolved__" # rewrite() -> (UNRESOLVED, pronoun): a short turn whose pronoun has nothing to refer to
class Turn: def __init__(self): self.q = None # previous standalone question self.subj = None # (qid, label, is_person, surface) self.ans = None # (qid, label, is_person) self.result = None # (value, unit) self.solved = {} # variable -> value self.material = None # "burning 5 kg of coal" / "5 kg of coal"
_STATES = {}
def state(sid): st = _STATES.get(sid) if st is None: if len(_STATES) > STATE_CAP: _STATES.clear() st = _STATES[sid] = Turn() return st
def _is_person(qid): try: return 5 in RS.classes_of(qid)[0] except Exception: # noqa: BLE001 return False
def _entity_of_question(q): a = RS.analyse(q) if not a or not a["cands"]: return None qid = a["cands"][0] return (qid, RS._rs().label(qid) or a["span"], _is_person(qid), a["span"])
RECEIPT_ENDS = re.compile(r"From the Wikidata relation store: (.+?)(?: \(Q(\d+)\))? - [^()]*? \(P\d+\) - (.+?)(?: \(Q(\d+)\))?\.\s*(?:\[|$)")TYPED = re.compile(r"\(typed relations: wd:Q(\d+) P\d+ wd:Q(\d+)\)")RECEIPT = re.compile(r"From the Wikidata relation store: .*? - .*? \(P\d+\) - (.+?)(?: \(Q(\d+)\))?\.\s*(?:\[|$)")
def _entity_of_reply(reply, prefer_person=False): """the entity the reply named; after a WHO question the answer is a person, so a person among the name's top candidates is preferred (the linker's popularity order put a song called "Pablo Picasso" before the painter)""" text = re.sub(r"^\s*\[ev:[a-z_]+\]\s*", "", str(reply or "")) m = RECEIPT_ENDS.search(text) if m: # the receipt reads subject - property - value, in the direction of the STORE: an inverse read ("Who painted # Guernica?" -> "Pablo Picasso (Q5593) - wrote - Guernica (Q175036)") puts the answer FIRST. The answer is the end # whose label the reply leads with. lead = text.split(". From the Wikidata relation store:", 1)[0].strip().lower() ends = [(m.group(1), m.group(2)), (m.group(3), m.group(4))] pick = [e for e in ends if e[1] and e[0].strip().lower() == lead] or [e for e in ends[::-1] if e[1]] if pick: qid = int(pick[0][1]) return (qid, RS._rs().label(qid) or pick[0][0], _is_person(qid)) m = RECEIPT.search(text) if m and m.group(2): qid = int(m.group(2)) return (qid, RS._rs().label(qid) or m.group(1), _is_person(qid)) # a sentence ends at . ! ? - but not after an initial ("J. R. R. Tolkien") first = re.split(r"(?<![\s.][A-Z]\.)(?<!^[A-Z]\.)(?<=[.!?])\s", text, 1)[0].rstrip(".") m = TYPED.search(text) if m: # the reply's typed relation names the exact entities; the answer is the end the reply leads with lead = re.sub(r"\s*\[[^\]]*\]\s*", " ", first).strip().lower() for q in (int(m.group(2)), int(m.group(1))): lab = RS._rs().label(q) if lab and lab.lower() == lead: return (q, lab, _is_person(q)) first = re.sub(r"\s*\[[^\]]*\]\s*", " ", first).strip() if not first or len(first) > 160: return None try: sp = RS.X.L.link(first, 3) except Exception: # noqa: BLE001 return None if not sp: return None span, cs = sp[0] qid = cs[0][0] if prefer_person: people = [c[0] for c in cs[:3] if _is_person(c[0])] if people: qid = people[0] return (qid, RS._rs().label(qid) or span, _is_person(qid))
NUM_UNIT = re.compile(r"(?:is|about|=|of)\s+\$?(-?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?)\s*(kwh|kj|mj|j|kg|g|m|km|s|n|pa|kpa|w|kw|litres?|liters?|l|m³|m3|°c|%)?", re.I)SOLVED = re.compile(r"\b([a-z])\s*=\s*(-?\d+(?:\.\d+)?)\b")MATERIAL = re.compile(r"\b((?:burning\s+)?\d[\d,]*(?:\.\d+)?\s*(?:kg|g|tonnes?|litres?|liters?|m3)\s+of\s+[a-z][a-z ]{1,24}?)(?=\s+(?:release|emit|produce|give|make|weigh)|[?.,]|$)", re.I)
def _result_of_reply(reply): text = re.sub(r"^\s*\[ev:[a-z_]+\]\s*", "", str(reply or "")) m = re.search(r"(?:answer is|is about|takes about|cost(?:s)? (?:is |about )?)\s*\$?(-?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?)\s*([a-zA-Z³%°]+)?", text) if not m: m = NUM_UNIT.search(text) if not m: return None try: v = float(m.group(1).replace(",", "")) except ValueError: return None unit = (m.group(2) or "").lower() if "$" in text[:max(0, m.start(1)) + 2] and not unit: unit = "$" return (v, unit)
def update(sid, standalone, reply): """after the chain answered (or declined) the standalone question: remember what the conversation is about""" st = state(sid) numeric = bool(re.search(r"\d", standalone)) and isinstance(reply, dict) and reply.get("status") == "answered" \ and _result_of_reply(reply.get("response")) is not None if not recognised(standalone) and not numeric: return # context comes from FACTUAL turns only st.q = standalone # an entity the conversation already resolved KEEPS its identity when the rewrite names it (relinking "Pablo Picasso" # by popularity picked a song, Q7121722, over the painter the previous answer named, Q5593) subj = next((tuple(e[:3]) + (e[1],) for e in (st.ans, st.subj) if e and len(e[1] or "") >= 3 and e[1] in standalone), None) \ or _entity_of_question(standalone) typed = TYPED.search(str(reply.get("response", ""))) if isinstance(reply, dict) else None if subj and typed: for q in (int(typed.group(1)), int(typed.group(2))): if q != subj[0] and (RS._rs().label(q) or "").lower() == subj[1].lower(): subj = (q, subj[1], _is_person(q), subj[3]) # the reply's own typed relation names the exact entity if subj: st.subj = subj if isinstance(reply, dict) and reply.get("status") == "answered": ans = _entity_of_reply(reply.get("response"), prefer_person=bool(re.match(r"^\s*(?:who|whom|whose)\b", standalone, re.I))) st.ans = ans if ans and (not subj or ans[0] != subj[0]) else None r = _result_of_reply(reply.get("response")) st.result = r for var, val in SOLVED.findall(str(reply.get("response", ""))): st.solved[var] = val mm = MATERIAL.search(standalone) if mm: st.material = mm.group(1).strip()
def _person(st): if st.ans and st.ans[2]: return st.ans[1] if st.subj and st.subj[2]: return st.subj[1] return None
def _thing(st): if st.subj and not st.subj[2]: return st.subj[1] if st.ans and not st.ans[2]: return st.ans[1] return None
def _cap(s): s = s.strip() return s[:1].upper() + s[1:] if s else s
def _q(s): s = s.strip().rstrip("?.! ") return _cap(s) + "?"
def _swap_wh(prev, wh): """'When was Alfred Hitchcock born?' + 'Where' -> 'Where was Alfred Hitchcock born?'; active 'Who discovered Titan?' -> 'In what year was Titan discovered?'""" p = prev.strip().rstrip("?") m = re.match(r"^(?:who|what|which|where|when|how)\b(?:\s+year)?\s+((?:was|were|is|are|did|does|do)\b.*)$", p, re.I) if m: return _q("%s %s" % (wh, m.group(1))) m = re.match(r"^who\s+(\w+ed)\s+(.+)$", p, re.I) if m: return _q("%s was %s %s" % (wh, m.group(2), m.group(1))) return None
def _rewrite_raw(sid, text): """-> (kind, standalone question) with kind "num" | "rel", (UNRESOLVED, pronoun), or None""" st = state(sid) t = " ".join(str(text or "").split()) low = t.lower().rstrip("?.! ") if not t: return None pron = re.search(r"\b(he|she|him|his|her|it|its|they|them|their)\b", low) short_bare = pron is not None and len(low.split()) <= 12 and re.search(r"(?<=\s)[A-Z][a-z]+", t) is None if not st.q: return (UNRESOLVED, pron.group(1)) if short_bare and pron.group(1) not in ("it", "its") else None # results and variables m = re.search(r"\bwhat is ([a-z]) (squared|cubed)\b", low) if m and m.group(1) in st.solved: power = "2" if m.group(2) == "squared" else "3" return ("num", _q(re.sub(r"\b%s (squared|cubed)\b" % m.group(1), "%s^%s" % (st.solved[m.group(1)], power), t, flags=re.I))) if re.search(r"\b(?:that|this)\b", low) and (st.result or st.material): if re.search(r"\b(?:co2|carbon dioxide|emit|emission|release|weigh)", low) and st.material: return ("num", _q(re.sub(r"\b(?:that|this)\b", st.material, t, count=1, flags=re.I))) if st.result and st.result[1] and re.search(r"per\s+%s\b" % re.escape(st.result[1]), low): return ("num", _q(re.sub(r"\b(?:that|this)\b", "%s %s" % (_fmt(st.result[0]), st.result[1]), t, count=1, flags=re.I))) # bare question word: "Where?", "When?", "In what year?" m = re.match(r"^(?:and\s+)?(where|when|in what year|what year)$", low) if m: r = _swap_wh(st.q, {"what year": "In what year"}.get(m.group(1), _cap(m.group(1)))) return ("rel", r) if r else None # ellipsis with "And ..." m = re.match(r"^(?:and|what about|how about)\s+(.+)$", low) if m: rest = t[len(t) - len(m.group(1)) - (len(t) - len(t.rstrip("?.! "))):].rstrip("?.! ") rest_low = rest.lower() mr = re.match(r"^(?:the\s+|its\s+|his\s+|her\s+|their\s+)?(%s)$" % REL_NOUNS, rest_low) if mr: ent = _thing(st) if not re.match(r"^(his|her)\b", rest_low) else _person(st) ent = ent or _thing(st) or _person(st) return ("rel", _q("What is the %s of %s" % (mr.group(1), ent))) if ent else None mp = re.match(r"^(on|in|at|with|for|of)\s+(.+)$", rest, re.I) if mp and mp.group(1).lower() in ("of", "for") and st.subj and st.subj[3]: r = _replace_subject(st, mp.group(2)) return ("rel", r) if r else None if mp and mp.group(1).lower() in ("on", "in", "at", "with"): prep, phrase = mp.group(1).lower(), mp.group(2) pm = re.search(r"\b%s\s+[^?]*?\d[^?]*?(?=$|\?|,)" % prep, st.q, re.I) if re.search(r"\d", phrase) else None if not st.result: return None # a modifier swap continues a COMPUTATION only if pm: return ("num", _q(st.q[:pm.start()] + "%s %s" % (prep, phrase) + st.q[pm.end():])) return ("num", _q(st.q.rstrip("?.! ") + " %s %s" % (prep, phrase))) if rest[:1].isupper() and st.subj and st.subj[3]: r = _replace_subject(st, rest) return ("rel", r) if r else None return None # "that country" / possessive and personal pronouns out = t changed = False m = re.search(r"\bthat\s+(country|city|state|planet|nation|island|river|band|team|company|book|film|novel|place)\b", out, re.I) if m: ent = (st.ans[1] if st.ans and not st.ans[2] else None) or _thing(st) if not ent: return None out = out[:m.start()] + ent + out[m.end():] changed = True # a turn that names its own subject (a capitalised name after the first word) keeps its own pronouns names_own = re.search(r"(?<=\s)[A-Z][a-z]+", out) is not None and not changed for pron, getter in (() if names_own else ((PRON_PERSON, _person), (PRON_THING, _thing))): for pm in list(re.finditer(r"\b(%s)\b(\s+[a-z]+(?:\s+[a-z]+)?)?" % pron, out, re.I))[::-1]: ent = getter(st) if not ent: return (UNRESOLVED, pm.group(1).lower()) if short_bare else None word = pm.group(1).lower() if word in ("his", "her", "its") and pm.group(2): noun = pm.group(2).strip() if re.match(r"^(%s)\b" % REL_NOUNS, noun, re.I) or word in ("his", "its"): rep = "the %s of %s" % (noun, ent) out = out[:pm.start()] + rep + out[pm.end():] changed = True continue out = out[:pm.start(1)] + ent + out[pm.end(1):] changed = True if not changed: return None return ("rel", _q(out))
def recognised(q): """a question the verified relation layer can READ: it matches one of the hand-written relation readers whole""" try: import relation_spec_v2 as S2 _, low = S2.normalise(q) for key in S2.RD.PROPS: c = S2.compiled(key) if any(rx.match(low) for d in ("fwd", "inv") for rx in c[d]): return True except Exception: # noqa: BLE001 return False return False
def rewrite(sid, text): """-> the standalone question this turn stands for, (UNRESOLVED, pronoun), or None. A rewrite is ACCEPTED only when it is exactly right for the verified layer: a relation rewrite must be a question the relation readers recognise; a numeric rewrite must continue a numeric answer. Anything else goes to the core untouched - the core has its own conversation acts ("got it", "why?", "did you run it?", "how does it work?") that a rewrite would break (m52 replay, 2026-10-09).""" r = _rewrite_raw(sid, text) if r is None: return None if r[0] == UNRESOLVED: return r if recognised(text) else None kind, q = r if not q: return None if kind == "num": return q if state(sid).result or state(sid).solved else None return q if recognised(q) else None
def _replace_subject(st, new): surface = st.subj[3] if surface and surface in st.q: return _q(st.q.replace(surface, new, 1)) lab = st.subj[1] if lab and lab in st.q: return _q(st.q.replace(lab, new, 1)) return None
def _fmt(v): return ("%d" % v) if abs(v - round(v)) < 1e-9 else ("%.6g" % v)
SPLIT = re.compile(r"\s+and\s+(?=(?:%s)\b)" % WH, re.I)
def split_parts(text): """'What is the capital of Austria and what is its currency?' -> two questions (only when the second part is itself a question starting with a question word)""" t = " ".join(str(text or "").split()).rstrip("?") parts = SPLIT.split(t) if len(parts) < 2: return None # split ONLY when every part is a question the relation readers can read (panel v27 2026-10-09: a reading passage # containing "... and Where to Find Them" and "Everything is fine, and how are you?" were split and lost) return [_q(p) for p in parts] if all(_shape_ok(_q(p)) for p in parts) else None
def _shape_ok(p): """the part reads as a relation question - as written, or with its pronoun standing for a named thing""" if recognised(p): return True s = re.sub(r"\b(?:its|his|her|their)\s+(\w+(?:\s+\w+)?)", r"the \1 of Peru", p, flags=re.I) s = re.sub(r"\b(?:he|she|it|they|him|them)\b", "Peru", s, flags=re.I) return s != p and recognised(s)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586#!/usr/bin/env python3"""chem_agents_v1 - five chemistry agents (Oracle7 specialists) that compute exactly what a question asks, from the values itgives, with every constant stated. Built for the university-chemistry questions the benchmark curriculum showed the familycould not reach (MMLU-Pro chemistry, development rows 3400-3999 only). GasAgent ideal gas: density, molar mass from density, one unknown of P V n T (mass + formula -> n) PhAgent pH / pOH / [H+] of strong acids and bases, weak acid or base from Ka / Kb / pKa, Henderson-Hasselbalch PhotonAgent photon energy / wavelength / frequency (per photon, per mole, eV), de Broglie, hydrogen-like transitions ColligativeAgent freezing-point depression, boiling-point elevation, molality, molar mass from a shift, osmotic pressure KineticsAgent first-order decay: half-life, rate constant, time to a fraction, fraction leftLAW (from the specialist network): EVERY number in the question must be read by the computation, or the agent declines -an unread number means a condition the formula does not know about. Each agent also declines what it cannot type(unknown formula, missing value, multi-part questions). Returns {kind, status, response, value}."""from __future__ import annotations
import csvimport mathimport osimport re
HERE = os.path.dirname(os.path.abspath(__file__))R_LATM = 0.082057366 # L atm / (mol K)R_J = 8.314462618 # J / (mol K)H = 6.62607015e-34 # J s (exact)C = 2.99792458e8 # m / s (exact)NA = 6.02214076e23 # 1 / mol (exact)EV = 1.602176634e-19 # J (exact)ME = 9.1093837015e-31 # kgRH = 1.09677583e7 # m^-1, Rydberg constant for hydrogen
def _table(): for p in (os.path.join(HERE, "pubchem_periodic_table.csv"), __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/specialists/chemistry-v3/pubchem_periodic_table.csv"): if os.path.exists(p): return {r["Symbol"]: float(r["AtomicMass"]) for r in csv.DictReader(open(p, encoding="utf-8"))} return {}
EL = _table()
# ---------------------------------------------------------------- textdef clean(t): t = " ".join(str(t or "").split()) t = t.replace("−", "-").replace("–", "-").replace("\\times", "×").replace("\\cdot", "·").replace("°", " deg ") t = re.sub(r"\\(?:mathrm|text|mathbf|operatorname)\s*\{([^{}]*)\}", r"\1", t) t = re.sub(r"\\(?:mathrm|text)\s*\{([^{}]*)\}", r"\1", t) t = t.replace("$", " ").replace("~", " ").replace("\\,", " ").replace("{", "").replace("}", "") t = re.sub(r"\^\s*\\circ|\\circ", " deg ", t) t = re.sub(r"_(\d)", r"\1", t) # CO_2 -> CO2, H_2SO_4 -> H2SO4 t = re.sub(r"(?<![\d.×x*])(?<![\d.]\s)\b10\s*\^\s*\(?([-+]?\d+)\)?", r"1×10^\1", t) # a bare power of ten is a number t = re.sub(r"(\d)\s+(?=10\^)", r"\1×", t) # "2 10^-15" -> "2×10^-15" t = re.sub(r"\s+", " ", t) return t.strip()
NUMRE = re.compile(r"(?<![A-Za-z\d.])([-+]?\d+(?:,\d{3})*(?:\.\d+)?|[-+]?\.\d+)\s*(?:(?:×|x|\*)\s*10\s*\^?\s*\(?\s*([-+]?\d+)\)?|[eE]([-+]?\d+))?")
def num(s): m = NUMRE.fullmatch(s.strip()) if not m: raise ValueError(s) return _val(m)
def _val(m): v = float(m.group(1).replace(",", "")) e = m.group(2) or m.group(3) return v * 10 ** int(e) if e else v
def numbers(t): """every number in the question with its span (formula subscripts excluded: H2SO4, CO2 are names, not values)""" out = [] for m in NUMRE.finditer(t): a = m.start() if a > 0 and re.match(r"[A-Z)\]a-z]", t[a - 1]) and not re.match(r"[a-z]{2,}", t[max(0, a - 3):a]): continue if re.match(r"\d", t[a]) and a > 0 and t[a - 1] == "(" and re.match(r"\(\d+\)\s*[A-Z]", t[a - 1:]): continue out.append((m.start(), m.end(), _val(m))) return out
class Reader: """reads typed quantities off the question; records which number spans it used"""
def __init__(self, text): self.t = clean(text) self.low = self.t.lower() self.nums = numbers(self.t) self.used = set()
def _take(self, pattern, flags=re.I): found = [] for m in re.finditer(pattern, self.t, flags): found.append(m) return found
def q(self, units, conv): """all quantities whose unit is one of `units`; conv(value, unit) -> SI-ish value""" res = [] pat = r"(" + NUMRE.pattern + r")\s*(" + units + r")(?![a-z])" for m in re.finditer(pat, self.t, re.I): nm = NUMRE.match(m.group(1)) v = _val(nm) res.append((conv(v, m.group(m.lastindex).lower()), m.start(), m.start() + len(m.group(1)))) # one value stated twice in two units ("720 mm Hg or 720 torr") is one quantity: keep it once, read both spans if len(res) > 1 and all(abs(x[0] - res[0][0]) <= 1e-9 * max(abs(res[0][0]), 1e-300) for x in res): for x in res[1:]: self.used.add(x[1]) res = res[:1] return res
def use(self, item): self.used.add(item[1]) return item[0]
def all_read(self, also=()): starts = set(self.used) | set(also) return all(any(abs(s - a) <= 1 for s in starts) for a, _, _ in self.nums)
P_UNITS = r"atm(?:ospheres?)?|torr|mm\s*hg|mmhg|kpa|pa|bar|psi"V_UNITS = r"liters?|litres?|l|ml|milliliters?|cm3|cm\^3|dm3|dm\^3|m3|m\^3"T_UNITS = r"deg\s*c|deg\s*k|deg\s*f|k(?![a-z])|kelvin|celsius|c(?![a-z])"M_UNITS = r"kg|g|mg|grams?|kilograms?|milligrams?"
def p_atm(v, u): u = u.replace(" ", "") return v * {"atm": 1, "atmosphere": 1, "atmospheres": 1, "torr": 1 / 760, "mmhg": 1 / 760, "kpa": 1 / 101.325, "pa": 1 / 101325, "bar": 1 / 1.01325, "psi": 1 / 14.6959}[u]
def v_l(v, u): u = u.replace("^", "") if u in ("ml", "milliliter", "milliliters", "cm3"): return v / 1000 if u == "m3": return v * 1000 return v
def t_k(v, u): u = u.replace(" ", "") if u in ("degc", "c", "celsius"): return v + 273.15 if u == "degf": return (v - 32) * 5 / 9 + 273.15 return v
def m_g(v, u): return v * 1000 if u.startswith("k") else v / 1000 if u.startswith("m") else v
def molar_mass(f): """H2SO4, Ca(OH)2, CuSO4·5H2O -> g/mol; None if any symbol is unknown""" f = f.replace("·", ".").replace("*", ".") total = 0.0 for part in f.split("."): k = re.match(r"(\d+)(.*)", part) mult, part = (int(k.group(1)), k.group(2)) if k else (1, part) stack, cur, i = [], {}, 0 while i < len(part): ch = part[i] if ch == "(": stack.append(cur) cur = {} i += 1 elif ch == ")": j = i + 1 while j < len(part) and part[j].isdigit(): j += 1 n = int(part[i + 1:j] or 1) prev = stack.pop() for s, c in cur.items(): prev[s] = prev.get(s, 0) + c * n cur, i = prev, j else: m = re.match(r"([A-Z][a-z]?)(\d*)", part[i:]) if not m: return None s = m.group(1) if s not in EL: return None cur[s] = cur.get(s, 0) + int(m.group(2) or 1) i += len(m.group(0)) if stack: return None total += mult * sum(EL[s] * c for s, c in cur.items()) return total
FORMULA = re.compile(r"(?<![A-Za-z])((?:[A-Z][a-z]?\d*|\((?:[A-Z][a-z]?\d*)+\)\d*){1,8}(?:[.·]\d*(?:[A-Z][a-z]?\d*)+)?)(?![a-z])")NAMES = {"oxygen": "O2", "nitrogen": "N2", "hydrogen": "H2", "chlorine": "Cl2", "fluorine": "F2", "helium": "He", "neon": "Ne", "argon": "Ar", "carbon dioxide": "CO2", "carbon monoxide": "CO", "methane": "CH4", "ammonia": "NH3", "water": "H2O", "ethane": "C2H6", "propane": "C3H8", "butane": "C4H10", "sulfur dioxide": "SO2", "nitrogen dioxide": "NO2", "hydrogen chloride": "HCl", "glucose": "C6H12O6", "sucrose": "C12H22O11", "urea": "CH4N2O", "ethanol": "C2H5OH", "methanol": "CH3OH", "benzene": "C6H6", "sodium chloride": "NaCl", "acetic acid": "CH3COOH", "xenon": "Xe", "krypton": "Kr"}
def formulas(t): out = [] for m in FORMULA.finditer(t): f = m.group(1) syms = re.findall(r"[A-Z][a-z]?", f) if (re.search(r"\d|\(", f) or len(syms) >= 2) and all(s in EL for s in syms): out.append((f, m.start(), m.end())) for name, f in NAMES.items(): for m in re.finditer(r"\b%s\b" % name, t, re.I): out.append((f, m.start(), m.end())) return out
def sig(x): return "%.4g" % x
def say(kind, text, value=None, status="answered"): return {"kind": kind, "status": status, "response": text, "value": value}
def multi_part(low): return bool(re.search(r"\(a\)|\(b\)|\ba\)\s|\bb\)\s|\band (?:also |then )?(?:calculate|find|determine|compute)\b", low))
# ---------------------------------------------------------------- agentsclass GasAgent: def answer(self, text, session_id="default"): r = Reader(text) low = r.low if multi_part(low) or not re.search(r"\bgas\b|\bdensity\b|\bmolar mass\b|\bmolecular weight\b|\bideal\b|\batm\b|\btorr\b|\bmm ?hg\b|\bkpa\b", low): return None if re.search(r"van ?der ?waals|real gas|effus|diffus|mean free|root.mean|rms|compressib|adiabat|isotherm|work|heat|" r"partial pressure|mole fraction|mixture|reaction|react|produced|collected over water|vapor pressure|" r"balloon|leak|graham|kinetic energy|speed|velocity|collision", low): return None P, V, T, M = r.q(P_UNITS, p_atm), r.q(V_UNITS, v_l), r.q(T_UNITS, t_k), r.q(M_UNITS, m_g) D = r.q(r"g\s*/\s*(?:l|liters?|litres?|dm3)|g\s*l\^?-1|grams? per liter", lambda v, u: v) N = r.q(r"moles?|mol(?![a-z])", lambda v, u: v) if any(len(x) > 1 for x in (P, V, T, M, D, N)): return None stp = bool(re.search(r"\bstp\b|standard (?:temperature and pressure|conditions)", low)) fs = formulas(r.t) ask = None for k, pat in (("density", r"what is the density|calculate the density|find the density|determine the density|density of .* (?:at|under)"), ("molar", r"molar mass|molecular weight|molecular mass"), ("pressure", r"what (?:is the )?pressure|calculate the pressure|find the pressure|what pressure"), ("volume", r"what (?:is the )?volume|calculate the volume|find the volume|what volume|occupy"), ("temperature", r"what (?:is the )?temperature|at what temperature|calculate the temperature|find the temperature"), ("moles", r"how many moles|number of moles|moles of gas"), ("mass", r"what (?:is the )?mass|how many grams|mass of gas")): if re.search(pat, low): ask = k break if ask is None: return None Tk = r.use(T[0]) if T else (273.15 if stp else None) Pa = r.use(P[0]) if P else (1.0 if stp else None) f = fs[0][0] if len({x[0] for x in fs}) == 1 else None Mm = molar_mass(f) if f else None if ask == "density": if D or not (Tk and Pa and Mm): return None d = Pa * Mm / (R_LATM * Tk) out = say("gas_density", "The density of %s is %s g/L (d = PM/RT = %s atm × %s g/mol / (0.082057 L·atm/(mol·K) × %s K))." % (f, sig(d), sig(Pa), sig(Mm), sig(Tk)), d) elif ask == "molar": if not (D and Tk and Pa): return None d = r.use(D[0]) mm = d * R_LATM * Tk / Pa out = say("gas_molar_mass", "The molar mass is %s g/mol (M = dRT/P = %s g/L × 0.082057 × %s K / %s atm)." % (sig(mm), sig(d), sig(Tk), sig(Pa)), mm) else: n = r.use(N[0]) if N else None if n is None and M and Mm: n = r.use(M[0]) / Mm Vl = r.use(V[0]) if V else None known = {"pressure": Pa, "volume": Vl, "temperature": Tk, "moles": n} if ask == "mass": if not (Pa and Vl and Tk and Mm) or N or M: return None nn = Pa * Vl / (R_LATM * Tk) out = say("gas_mass", "The mass is %s g (n = PV/RT = %s mol; × %s g/mol for %s)." % (sig(nn * Mm), sig(nn), sig(Mm), f), nn * Mm) else: others = {k: v for k, v in known.items() if k != ask} if any(v is None for v in others.values()): return None if ask == "pressure": v = n * R_LATM * Tk / Vl out = say("gas_pressure", "The pressure is %s atm (P = nRT/V)." % sig(v), v) elif ask == "volume": v = n * R_LATM * Tk / Pa out = say("gas_volume", "The volume is %s L (V = nRT/P)." % sig(v), v) elif ask == "temperature": v = Pa * Vl / (n * R_LATM) out = say("gas_temperature", "The temperature is %s K (T = PV/nR)." % sig(v), v) else: v = Pa * Vl / (R_LATM * Tk) out = say("gas_moles", "The amount is %s mol (n = PV/RT)." % sig(v), v) return out if r.all_read() else None
STRONG_ACID = {"HCl": 1, "HBr": 1, "HI": 1, "HNO3": 1, "HClO4": 1}STRONG_BASE = {"NaOH": 1, "KOH": 1, "LiOH": 1, "Ba(OH)2": 2, "Ca(OH)2": 2, "Sr(OH)2": 2}
class PhAgent: def answer(self, text, session_id="default"): r = Reader(text) low = r.low if multi_part(low) or not re.search(r"\bph\b|\bpoh\b|\[h\+\]|\[h3o\+\]|hydrogen ion|hydronium", low): return None if re.search(r"titrat|added|adding|mix|mixed|after|equivalence|polyprotic|diprotic|ksp|solubility|hydroly[sz]|salt|" r"percent|degree of|ionization constant of water|at \d+ deg|temperature", low): return None conc = r.q(r"m(?![a-z])|molar|mol/l|moles? per liter|n(?![a-z])", lambda v, u: v) ka = [(m, m.start()) for m in re.finditer(r"\b(k_?a|k_?b|pk_?a|pk_?b)\s*(?:=|is|of|value of)?\s*(" + NUMRE.pattern + ")", r.t, re.I)] ask = "pH" if re.search(r"what is the ph|calculate the ph|find the ph|determine the ph|ph of|the ph\b", low) else \ "pOH" if re.search(r"\bpoh\b", low) and not re.search(r"\bph\b(?! ?=)", low.replace("poh", "")) else \ "H" if re.search(r"\[h\+\]|\[h3o\+\]|hydrogen ion concentration|hydronium ion concentration", low) else None if ask is None: return None hgiven = re.search(r"(?:hydrogen ion|hydronium(?: ion)?|\[h\+\]|\[h3o\+\])\s*(?:concentration\s*)?(?:is|of|=|equal to)\s*(" + NUMRE.pattern + r")\s*m\b", r.t, re.I) if ask == "pH" and hgiven and not ka: h = num(hgiven.group(1)) r.used.add(hgiven.start(1)) if not (0 < h <= 10): return None return say("ph_from_h", "The pH is %s (pH = -log10[H+] = -log10 %s)." % ("%.2f" % -math.log10(h), sig(h)), -math.log10(h)) if r.all_read() else None phgiven = re.search(r"\bph (?:of|is|=)\s*(" + NUMRE.pattern + ")", r.t, re.I) if ask == "H" and phgiven and not conc and not ka: p = num(phgiven.group(1)) r.used.add(phgiven.start(1)) h = 10 ** -p return say("h_from_ph", "[H+] is %s M (10^-pH with pH %s)." % (sig(h), sig(p)), h) if r.all_read() else None fs = [x[0] for x in formulas(r.t)] if len(conc) != 1: return None c = r.use(conc[0]) if not ka: acid = [f for f in fs if f in STRONG_ACID] base = [f for f in fs if f in STRONG_BASE] if len(set(acid + base)) != 1 or c <= 1e-7: return None if acid: h = c * STRONG_ACID[acid[0]] ph = -math.log10(h) what = "%s is a strong acid, fully ionized: [H+] = %s M" % (acid[0], sig(h)) else: oh = c * STRONG_BASE[base[0]] ph = 14 + math.log10(oh) what = "%s is a strong base, fully dissociated: [OH-] = %s M" % (base[0], sig(oh)) else: if len(ka) != 1: return None m, pos = ka[0] r.used.add(m.start(2)) kind, kv = m.group(1).lower().replace("_", ""), num(m.group(2)) k = 10 ** -kv if kind.startswith("p") else kv if not (0 < k < 1): return None x = (-k + math.sqrt(k * k + 4 * k * c)) / 2 # exact quadratic: x^2 / (c - x) = K if kind.endswith("b"): ph = 14 + math.log10(x) what = "weak base, Kb = %s: [OH-] = %s M from x^2/(C - x) = Kb" % (sig(k), sig(x)) else: ph = -math.log10(x) what = "weak acid, Ka = %s: [H+] = %s M from x^2/(C - x) = Ka" % (sig(k), sig(x)) h = 10 ** -ph if not r.all_read(): return None if ask == "pH": return say("ph", "The pH is %s (%s)." % ("%.2f" % ph, what), ph) if ask == "pOH": return say("poh", "The pOH is %s (%s)." % ("%.2f" % (14 - ph), what), 14 - ph) return say("h", "[H+] is %s M (%s)." % (sig(10 ** -ph), what), 10 ** -ph)
class PhotonAgent: LEN = {"nm": 1e-9, "nanometers": 1e-9, "nanometer": 1e-9, "a": 1e-10, "angstroms": 1e-10, "angstrom": 1e-10, "å": 1e-10, "m": 1, "meters": 1, "cm": 1e-2, "um": 1e-6, "μm": 1e-6, "micrometers": 1e-6, "microns": 1e-6, "pm": 1e-12, "mm": 1e-3}
def answer(self, text, session_id="default"): r = Reader(text) low = r.low if multi_part(low) or not re.search(r"photon|wavelength|frequency|light|radiation|de ?broglie|transition|emitted|absorbed|quantum", low): return None if re.search(r"work function|photoelectric|threshold|stopping|intensity|power|watt|lamp|laser|per second|uncertainty|" r"box|particle in|harmonic|rotational|vibrational|bond|spin|nmr|esr|epr|zeeman|doppler", low): return None if re.search(r"black ?body", low) and re.search(r"(?:maximum|peak|most intense).{0,30}wavelength|wavelength.{0,30}(?:maximum|peak)", low): T = r.q(T_UNITS, t_k) if len(T) != 1: return None lm = 2.897771955e-3 / r.use(T[0]) return say("wien", "The peak wavelength is %s m (Wien: λmax = b/T, b = 2.8978e-3 m·K)." % sig(lm), lm) if r.all_read() else None lam = r.q(r"nm|nanometers?|angstroms?|å|pm|um|μm|micrometers?|microns?|cm(?![-^\d])|mm(?![a-z])|m(?![a-z/^\-])", lambda v, u: v * self.LEN[u]) nu = r.q(r"hz|s\^?-1|sec\^?-1|/s", lambda v, u: v) # de Broglie if re.search(r"de ?broglie|wavelength of (?:an?|the) (?:electron|proton|neutron|particle|ball)", low): vel = r.q(r"m/s|m s\^?-1|meters? per second", lambda v, u: v) mass = r.q(M_UNITS, lambda v, u: m_g(v, u) / 1000) ke = r.q(r"ev|electron ?volts?", lambda v, u: v * EV) m_ = ME if "electron" in low and not mass else (r.use(mass[0]) if len(mass) == 1 else None) if m_ is None or len(vel) + len(ke) != 1: return None p = m_ * r.use(vel[0]) if vel else math.sqrt(2 * m_ * r.use(ke[0])) lam_ = H / p return say("de_broglie", "The de Broglie wavelength is %s m (λ = h/p, p = %s kg·m/s)." % (sig(lam_), sig(p)), lam_) if r.all_read() else None # hydrogen-like transitions ns = re.findall(r"n\s*=\s*(\d+)", low) if len(ns) == 2 and re.search(r"hydrogen|he\+|li2\+|transition|electron (?:falls|drops|jumps|moves)", low): z = 2 if re.search(r"\bhe\+|helium ion|ionized helium", low) else 3 if re.search(r"li2\+|li\+\+", low) else 1 if z == 1 and not re.search(r"hydrogen", low): return None for m in re.finditer(r"n\s*=\s*(\d+)", r.t, re.I): r.used.add(m.start(1)) n1, n2 = sorted(int(x) for x in ns) if n1 == n2: return None wn = RH * z * z * (1 / n1 ** 2 - 1 / n2 ** 2) # m^-1 E = H * C * wn if re.search(r"wavelength", low): v, txt = 1 / wn, "The wavelength is %s m (%s nm), from 1/λ = R_H Z² (1/%d² − 1/%d²)." % (sig(1 / wn), sig(1e9 / wn), n1, n2) elif re.search(r"frequency", low): v, txt = wn * C, "The frequency is %s Hz (ν = c R_H Z² (1/%d² − 1/%d²))." % (sig(wn * C), n1, n2) elif re.search(r"energy", low): v, txt = E, "The energy is %s J per photon (%s eV), ΔE = hc R_H Z² (1/%d² − 1/%d²)." % (sig(E), sig(E / EV), n1, n2) elif re.search(r"wave ?number", low): v, txt = wn / 100, "The wavenumber is %s cm^-1." % sig(wn / 100) else: return None return say("transition", txt, v) if r.all_read() else None # photon: energy <-> wavelength <-> frequency if len(lam) + len(nu) != 1: return None if lam: L = r.use(lam[0]) f = C / L else: f = r.use(nu[0]) L = C / f E = H * f if re.search(r"(?:energy|kj|kilojoules?).*(?:per mole|/mol|a mole|one mole|mole of photons)|per mole of photons|einstein", low): v, txt = E * NA / 1000, "The energy is %s kJ/mol (E = N_A hc/λ)." % sig(E * NA / 1000) elif re.search(r"\bev\b|electron ?volts?", low) and re.search(r"energy", low): v, txt = E / EV, "The energy is %s eV (E = hc/λ)." % sig(E / EV) elif re.search(r"energy", low): v, txt = E, "The energy is %s J per photon (E = hc/λ = %s J·s × %s m/s / %s m)." % (sig(E), H, C, sig(L)) elif re.search(r"frequency", low) and lam: v, txt = f, "The frequency is %s Hz (ν = c/λ)." % sig(f) elif re.search(r"wavelength", low) and nu: v, txt = L, "The wavelength is %s m (λ = c/ν)." % sig(L) else: return None return say("photon", txt, v) if r.all_read() else None
KF = {"water": 1.86, "benzene": 5.12, "camphor": 37.7, "cyclohexane": 20.0}KB = {"water": 0.512, "benzene": 2.53}NONELECTROLYTE = ("glucose", "sucrose", "urea", "sugar", "ethylene glycol", "glycerol", "C6H12O6", "C12H22O11", "CH4N2O", "nonelectrolyte", "non-electrolyte")
class ColligativeAgent: def answer(self, text, session_id="default"): r = Reader(text) low = r.low if multi_part(low) or not re.search(r"freezing|boiling|osmotic|molality|molal", low): return None if re.search(r"vapor pressure|raoult|percent|dissociat|association|degree|van.t hoff factor of|dimer|ionized|electrolyte(?! )|" r"activity|ideal solution", low): return None solv = [s for s in KF if s in low] nonel = any(s.lower() in low for s in NONELECTROLYTE) if not nonel or len(set(solv)) > 1: return None Kf_given = re.search(r"\bk_?f\b[^\d]{0,20}(" + NUMRE.pattern + ")", r.t, re.I) Kb_given = re.search(r"\bk_?b\b[^\d]{0,20}(" + NUMRE.pattern + ")", r.t, re.I) masses = r.q(M_UNITS, m_g) molal = r.q(r"m(?![a-z])|molal", lambda v, u: v) s = solv[0] if solv else "water" if "osmotic" in low: conc = r.q(r"m(?![a-z])|molar|mol/l", lambda v, u: v) T = r.q(T_UNITS, t_k) if len(conc) != 1 or len(T) != 1: return None pi = r.use(conc[0]) * R_LATM * r.use(T[0]) return say("osmotic", "The osmotic pressure is %s atm (π = MRT, nonelectrolyte)." % sig(pi), pi) if r.all_read() else None freezing = "freezing" in low K = None if freezing: if Kf_given: K = num(Kf_given.group(1)) r.used.add(Kf_given.start(1)) else: K = KF.get(s) else: if Kb_given: K = num(Kb_given.group(1)) r.used.add(Kb_given.start(1)) else: K = KB.get(s) if K is None: return None if len(molal) == 1 and not masses: m = r.use(molal[0]) elif len(masses) == 2: fs = [x[0] for x in formulas(r.t) if x[0] in ("C6H12O6", "C12H22O11", "CH4N2O") or x[0] not in ("H2O",)] solute = [f for f in fs if f != {"water": "H2O"}.get(s)] mm = molar_mass(solute[0]) if len(set(solute)) == 1 else None if mm is None: return None a, b = sorted(masses, key=lambda x: x[0]) m = (r.use(a) / mm) / (r.use(b) / 1000) else: return None dT = K * m if freezing: base = {"water": 0.0, "benzene": 5.5, "cyclohexane": 6.5, "camphor": 179.8}[s] if re.search(r"freezing point (?:of the solution|will be|is)|new freezing|at what temperature.*freez|freezes at", low): return say("freezing_point", "The freezing point is %s deg C (ΔTf = Kf·m = %s × %s = %s deg C below %s deg C)." % (sig(base - dT), K, sig(m), sig(dT), base), base - dT) if r.all_read() else None if re.search(r"depression|lowered|by how much|change in", low): return say("freezing_depression", "The freezing point is lowered by %s deg C (ΔTf = Kf·m = %s × %s)." % (sig(dT), K, sig(m)), dT) if r.all_read() else None else: base = {"water": 100.0, "benzene": 80.1}[s] if re.search(r"boiling point (?:of the solution|will be|is)|new boiling|boils at", low): return say("boiling_point", "The boiling point is %s deg C (ΔTb = Kb·m = %s × %s = %s deg C above %s deg C)." % (sig(base + dT), K, sig(m), sig(dT), base), base + dT) if r.all_read() else None if re.search(r"elevation|raised|by how much|change in", low): return say("boiling_elevation", "The boiling point rises by %s deg C (ΔTb = Kb·m)." % sig(dT), dT) if r.all_read() else None return None
class KineticsAgent: T = {"s": 1, "sec": 1, "seconds": 1, "second": 1, "min": 60, "minutes": 60, "minute": 60, "h": 3600, "hr": 3600, "hours": 3600, "hour": 3600, "days": 86400, "day": 86400, "d": 86400, "years": 3.15576e7, "year": 3.15576e7, "yr": 3.15576e7, "y": 3.15576e7}
def answer(self, text, session_id="default"): r = Reader(text) low = r.low if multi_part(low) or not re.search(r"half-?life|first-?order|decay", low): return None if re.search(r"second-?order|zero-?order|activation|arrhenius|temperature|catalyst|equilibrium|counts|dpm|" r"age of|dating|carbon-14|c-14|14c", low): return None tq = r.q(r"seconds?|sec|s(?![a-z])|minutes?|min(?![a-z])|hours?|hrs?|h(?![a-z])|days?|d(?![a-z])|years?|yrs?|y(?![a-z])", lambda v, u: v * self.T[u]) pct = r.q(r"%|percent", lambda v, u: v / 100) frac = re.search(r"\b(one|a) (half|third|fourth|quarter|tenth|eighth|sixteenth)\b", low) half = re.search(r"half-?life (?:of|is|=)", low) amt = r.q(r"mci|μci|uci|ci(?![a-z])|bq|mg|kg|g(?![a-z])|grams?", lambda v, u: v) unit = re.search(r"(" + NUMRE.pattern + r")\s*(mCi|μCi|uCi|Ci|Bq|mg|kg|g|grams?)(?![a-z])", r.t) if len(tq) == 2 and half and len(amt) == 1 and re.search(r"how much.*(?:remain|left)|(?:remain|left) after", low): a, b = tq th, t = (a, b) if a[1] < b[1] else (b, a) th_v, t_v = r.use(th), r.use(t) left = r.use(amt[0]) * 0.5 ** (t_v / th_v) return say("amount_left", "The amount remaining is %s %s (× (1/2)^(t/t½) = (1/2)^%s)." % (sig(left), unit.group(unit.lastindex), sig(t_v / th_v)), left) if r.all_read() else None if len(tq) == 2 and half and re.search(r"(?:what|how much|what fraction|what percent).*(?:remain|left)", low): a, b = tq th, t = (a, b) if a[1] < b[1] else (b, a) th_v, t_v = r.use(th), r.use(t) f = 0.5 ** (t_v / th_v) return say("fraction_left", "The fraction remaining is %s (%s%%), (1/2)^(t/t½)." % (sig(f), sig(100 * f)), f) if r.all_read() else None if len(tq) == 1 and half and (pct or frac) and re.search(r"how long|how much time|what time", low): th_v = r.use(tq[0]) if pct: p = r.use(pct[0]) f = p if re.search(r"remain|left", low) else 1 - p else: f = {"half": .5, "third": 1 / 3, "fourth": .25, "quarter": .25, "tenth": .1, "eighth": .125, "sixteenth": 1 / 16}[frac.group(2)] if not re.search(r"remain|left", low): return None if not (0 < f < 1): return None t = th_v * math.log(f) / math.log(0.5) return say("time_to_fraction", "It takes %s s (t = t½ · log(f)/log(1/2), f = %s)." % (sig(t), sig(f)), t) if r.all_read() else None if len(tq) == 1 and half and re.search(r"rate constant|\bk\b", low): k = math.log(2) / r.use(tq[0]) return say("rate_constant", "The rate constant is %s s^-1 (k = ln 2 / t½)." % sig(k), k) if r.all_read() else None return None
AGENTS = {"chem-gas": GasAgent, "chem-ph": PhAgent, "chem-photon": PhotonAgent, "chem-colligative": ColligativeAgent, "chem-kinetics": KineticsAgent}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474"""code_organ_v2 - v1 (MBPP-frozen b2e52a1d) + STRICT mode for a single example: every move named by therequest. Programs as specified free moves over a verified function library, checked by execution; everyverified program joins the library (the stored final forms - continuous learning without retraining).
REQUEST description + input/output examples (asserts) -> function name, argument values and types, expected outputs, constants the description names ("at least 4 characters", "the character 'l'")MOVES typed library functions. The TYPE SYSTEM is the specified structure: a function applies only where its argument types connect; within that the choice is free. The description's words rank the moves.SEARCH bottom-up enumeration with OBSERVATIONAL EQUIVALENCE: programs that behave identically on the examples are kept once, so compositions of 3-4 moves stay tractable.CHECK the rendered source is executed against every example; nothing is released that did not run and pass.STORE a verified program becomes a library function (its description words are its keywords, its signature its type); later requests compose it - measured as the library-growth curve.Only library templates are ever evaluated; no text from the request is executed."""from __future__ import annotations
import astimport itertoolsimport jsonimport mathimport refrom collections import Counter
# ----------------------------------------------------------------------------------------------------------- typesdef tyof(v): if isinstance(v, bool): return "bool" if isinstance(v, int): return "int" if isinstance(v, float): return "float" if isinstance(v, str): return "str" if isinstance(v, list): return "list" if isinstance(v, tuple): return "tuple" if isinstance(v, dict): return "dict" if isinstance(v, set): return "set" return "any"
GROUP = {"num": {"int", "float"}, "seq": {"list", "tuple", "str"}, "coll": {"list", "tuple", "set"}, "any": {"bool", "int", "float", "str", "list", "tuple", "dict", "set", "any"}}
def fits(t, want): return t == want or t in GROUP.get(want, ())
# ------------------------------------------------------------------------------------------------------ primitivesclass Prim: __slots__ = ("name", "ins", "out", "fn", "src", "kw")
def __init__(self, name, ins, out, fn, src, kw): self.name, self.ins, self.out, self.fn, self.src = name, ins, out, fn, src self.kw = {w.lower().rstrip("s") for w in kw.split()} # v2: normalised exactly like the request words
def _big(x): if isinstance(x, int) and abs(x) > 10 ** 7: raise ValueError("too large") return x
def _is_prime(n): if n < 2: return False return all(n % d for d in range(2, int(n ** 0.5) + 1))
def _uniq(xs): out = [] for x in xs: if x not in out: out.append(x) return out
def _flatten(xs): out = [] for x in xs: out += list(x) if isinstance(x, (list, tuple)) else [x] return out
P_ = [ # numbers Prim("add", ("num", "num"), "num", lambda a, b: a + b, "({0} + {1})", "add sum plus total"), Prim("sub", ("num", "num"), "num", lambda a, b: a - b, "({0} - {1})", "subtract difference minus"), Prim("mul", ("num", "num"), "num", lambda a, b: _big(a * b), "({0} * {1})", "multiply product times"), Prim("fdiv", ("num", "num"), "num", lambda a, b: a // b, "({0} // {1})", "divide quotient integer"), Prim("div", ("num", "num"), "float", lambda a, b: a / b, "({0} / {1})", "divide ratio average"), Prim("mod", ("num", "num"), "num", lambda a, b: a % b, "({0} % {1})", "remainder modulo divisible"), Prim("pow", ("num", "num"), "num", lambda a, b: _big(a ** b) if b < 64 else 1 / 0, "({0} ** {1})", "power square cube exponent"), Prim("sq", ("num",), "num", lambda a: a * a, "({0} ** 2)", "square squares"), Prim("cube", ("num",), "num", lambda a: a ** 3, "({0} ** 3)", "cube cubes"), Prim("abs", ("num",), "num", abs, "abs({0})", "absolute"), Prim("neg", ("num",), "num", lambda a: -a, "(-{0})", "negative negate"), Prim("half", ("num",), "float", lambda a: a / 2, "({0} / 2)", "half area triangle"), Prim("sqrt", ("num",), "float", math.sqrt, "math.sqrt({0})", "root square"), Prim("isqrt", ("int",), "int", math.isqrt, "math.isqrt({0})", "root square integer"), Prim("fact", ("int",), "int", lambda n: math.factorial(n) if 0 <= n <= 30 else 1 / 0, "math.factorial({0})", "factorial"), Prim("gcd", ("int", "int"), "int", math.gcd, "math.gcd({0}, {1})", "gcd greatest common divisor"), Prim("lcm", ("int", "int"), "int", lambda a, b: a * b // math.gcd(a, b) if a and b else 0, "({0} * {1} // math.gcd({0}, {1}))", "lcm least common multiple"), Prim("isprime", ("int",), "bool", _is_prime, "(({0}) > 1 and all(({0}) % d for d in range(2, int(({0}) ** 0.5) + 1)))", "prime"), Prim("even", ("int",), "bool", lambda n: n % 2 == 0, "({0} % 2 == 0)", "even"), Prim("odd", ("int",), "bool", lambda n: n % 2 == 1, "({0} % 2 == 1)", "odd"), Prim("digits", ("int",), "list", lambda n: [int(c) for c in str(abs(n))], "[int(c) for c in str(abs({0}))]", "digits digit"), Prim("revnum", ("int",), "int", lambda n: int(str(abs(n))[::-1]), "int(str(abs({0}))[::-1])", "reverse number"), Prim("bin", ("int",), "str", lambda n: bin(n)[2:], "bin({0})[2:]", "binary"), Prim("frombin", ("str",), "int", lambda s: int(s, 2), "int({0}, 2)", "binary decimal convert"), Prim("popcount", ("int",), "int", lambda n: bin(n).count("1"), "bin({0}).count('1')", "set bits count ones"), Prim("xor", ("int", "int"), "int", lambda a, b: a ^ b, "({0} ^ {1})", "xor bit differ"), Prim("ispow2", ("int",), "bool", lambda n: n > 0 and n & (n - 1) == 0, "({0} > 0 and {0} & ({0} - 1) == 0)", "power two bit"), Prim("eq", ("any", "any"), "bool", lambda a, b: a == b, "({0} == {1})", "equal same"), Prim("lt", ("num", "num"), "bool", lambda a, b: a < b, "({0} < {1})", "less smaller"), Prim("gt", ("num", "num"), "bool", lambda a, b: a > b, "({0} > {1})", "greater larger"), Prim("not", ("bool",), "bool", lambda a: not a, "(not {0})", "not"), Prim("and", ("bool", "bool"), "bool", lambda a, b: a and b, "({0} and {1})", "and both"), Prim("or", ("bool", "bool"), "bool", lambda a, b: a or b, "({0} or {1})", "or either"), Prim("maxn", ("num", "num"), "num", max, "max({0}, {1})", "maximum largest bigger"), Prim("minn", ("num", "num"), "num", min, "min({0}, {1})", "minimum smallest"), Prim("round2", ("num",), "float", lambda a: round(a, 2), "round({0}, 2)", "round"), Prim("int", ("any",), "int", int, "int({0})", "integer convert"), Prim("str", ("any",), "str", str, "str({0})", "string convert"), Prim("float", ("num",), "float", float, "float({0})", "float"), Prim("tri", ("int",), "int", lambda n: n * (n + 1) // 2, "({0} * ({0} + 1) // 2)", "triangular sum natural"), Prim("pi_r2", ("num",), "float", lambda r: math.pi * r * r, "(math.pi * {0} * {0})", "area circle"), Prim("circ", ("num",), "float", lambda r: 2 * math.pi * r, "(2 * math.pi * {0})", "circumference perimeter circle"), # sequences Prim("len", ("seq",), "int", len, "len({0})", "length count number size"), Prim("sum", ("coll",), "num", lambda xs: sum(xs), "sum({0})", "sum total add"), Prim("max", ("coll",), "any", max, "max({0})", "maximum largest biggest max longest"), Prim("min", ("coll",), "any", min, "min({0})", "minimum smallest min"), Prim("sorted", ("coll",), "list", sorted, "sorted({0})", "sort sorted ascending order"), Prim("sorted_desc", ("coll",), "list", lambda xs: sorted(xs, reverse=True), "sorted({0}, reverse=True)", "sort descending largest"), Prim("rev", ("seq",), "seq", lambda xs: xs[::-1], "{0}[::-1]", "reverse reversed"), Prim("first", ("seq",), "any", lambda xs: xs[0], "{0}[0]", "first"), Prim("last", ("seq",), "any", lambda xs: xs[-1], "{0}[-1]", "last"), Prim("take", ("seq", "int"), "seq", lambda xs, n: xs[:n], "{0}[:{1}]", "first n smallest largest take"), Prim("drop", ("seq", "int"), "seq", lambda xs, n: xs[n:], "{0}[{1}:]", "remove first skip"), Prim("at", ("seq", "int"), "any", lambda xs, i: xs[i], "{0}[{1}]", "nth index element second third"), Prim("tolist", ("any",), "list", list, "list({0})", "list convert"), Prim("totuple", ("any",), "tuple", tuple, "tuple({0})", "tuple convert"), Prim("toset", ("coll",), "set", set, "set({0})", "unique distinct set"), Prim("uniq", ("coll",), "list", _uniq, "list(dict.fromkeys({0}))", "unique distinct duplicates remove"), Prim("inter", ("coll", "coll"), "tuple", lambda a, b: tuple(sorted(set(a) & set(b))), "tuple(sorted(set({0}) & set({1})))", "common shared similar intersection"), Prim("union", ("coll", "coll"), "tuple", lambda a, b: tuple(sorted(set(a) | set(b))), "tuple(sorted(set({0}) | set({1})))", "union combine"), Prim("diff", ("coll", "coll"), "list", lambda a, b: [x for x in a if x not in b], "[x for x in {0} if x not in {1}]", "difference not in"), Prim("concat", ("seq", "seq"), "seq", lambda a, b: a + b, "({0} + {1})", "concatenate join append combine merge"), Prim("count", ("seq", "any"), "int", lambda xs, x: xs.count(x), "{0}.count({1})", "count occurrences frequency"), Prim("index", ("seq", "any"), "int", lambda xs, x: xs.index(x), "{0}.index({1})", "index position find"), Prim("contains", ("any", "seq"), "bool", lambda x, xs: x in xs, "({0} in {1})", "contains present exists check"), Prim("allsame", ("coll",), "bool", lambda xs: len(set(xs)) <= 1, "(len(set({0})) <= 1)", "same equal all identical"), Prim("alluniq", ("coll",), "bool", lambda xs: len(set(xs)) == len(xs), "(len(set({0})) == len(list({0})))", "unique distinct duplicate"), Prim("issorted", ("coll",), "bool", lambda xs: list(xs) == sorted(xs), "(list({0}) == sorted({0}))", "sorted order check"), Prim("prod", ("coll",), "num", lambda xs: _big(math.prod(xs)), "math.prod({0})", "product multiply"), Prim("mean", ("coll",), "float", lambda xs: sum(xs) / len(xs), "(sum({0}) / len({0}))", "average mean"), Prim("map_sq", ("coll",), "list", lambda xs: [x * x for x in xs], "[x * x for x in {0}]", "square squares each"), Prim("map_cube", ("coll",), "list", lambda xs: [x ** 3 for x in xs], "[x ** 3 for x in {0}]", "cube cubes each"), Prim("map_neg", ("coll",), "list", lambda xs: [-x for x in xs], "[-x for x in {0}]", "negative"), Prim("map_abs", ("coll",), "list", lambda xs: [abs(x) for x in xs], "[abs(x) for x in {0}]", "absolute"), Prim("map_str", ("coll",), "list", lambda xs: [str(x) for x in xs], "[str(x) for x in {0}]", "string convert"), Prim("map_int", ("coll",), "list", lambda xs: [int(x) for x in xs], "[int(x) for x in {0}]", "integer convert"), Prim("map_len", ("coll",), "list", lambda xs: [len(x) for x in xs], "[len(x) for x in {0}]", "length each"), Prim("map_first", ("coll",), "list", lambda xs: [x[0] for x in xs], "[x[0] for x in {0}]", "first each"), Prim("map_last", ("coll",), "list", lambda xs: [x[-1] for x in xs], "[x[-1] for x in {0}]", "last each"), Prim("map_sum", ("coll",), "list", lambda xs: [sum(x) for x in xs], "[sum(x) for x in {0}]", "sum each"), Prim("map_add", ("coll", "num"), "list", lambda xs, k: [x + k for x in xs], "[x + {1} for x in {0}]", "add each"), Prim("map_mul", ("coll", "num"), "list", lambda xs, k: [x * k for x in xs], "[x * {1} for x in {0}]", "multiply each double doubled twice"), Prim("zipadd", ("coll", "coll"), "list", lambda a, b: [x + y for x, y in zip(a, b)], "[x + y for x, y in zip({0}, {1})]", "add two lists elementwise"), Prim("zipmul", ("coll", "coll"), "list", lambda a, b: [x * y for x, y in zip(a, b)], "[x * y for x, y in zip({0}, {1})]", "multiply two lists"), Prim("zipsub", ("coll", "coll"), "list", lambda a, b: [x - y for x, y in zip(a, b)], "[x - y for x, y in zip({0}, {1})]", "subtract two lists"), Prim("zipdiv", ("coll", "coll"), "list", lambda a, b: [x / y for x, y in zip(a, b)], "[x / y for x, y in zip({0}, {1})]", "divide two lists"), Prim("zip", ("coll", "coll"), "list", lambda a, b: list(zip(a, b)), "list(zip({0}, {1}))", "pair zip"), Prim("f_even", ("coll",), "list", lambda xs: [x for x in xs if x % 2 == 0], "[x for x in {0} if x % 2 == 0]", "even"), Prim("f_odd", ("coll",), "list", lambda xs: [x for x in xs if x % 2 == 1], "[x for x in {0} if x % 2 == 1]", "odd"), Prim("f_pos", ("coll",), "list", lambda xs: [x for x in xs if x > 0], "[x for x in {0} if x > 0]", "positive"), Prim("f_neg", ("coll",), "list", lambda xs: [x for x in xs if x < 0], "[x for x in {0} if x < 0]", "negative"), Prim("f_gt", ("coll", "num"), "list", lambda xs, k: [x for x in xs if x > k], "[x for x in {0} if x > {1}]", "greater than"), Prim("f_lenge", ("coll", "int"), "list", lambda xs, k: [x for x in xs if len(x) >= k], "[x for x in {0} if len(x) >= {1}]", "at least long characters"), Prim("f_neq", ("coll", "any"), "list", lambda xs, k: [x for x in xs if x != k], "[x for x in {0} if x != {1}]", "remove all"), Prim("cumsum", ("coll",), "list", lambda xs: list(itertools.accumulate(xs)), "list(itertools.accumulate({0}))", "cumulative running sum"), Prim("flatten", ("coll",), "list", _flatten, "[y for x in {0} for y in (x if isinstance(x, (list, tuple)) else [x])]", "flatten nested"), Prim("mostcommon", ("coll",), "any", lambda xs: Counter(xs).most_common(1)[0][0], "collections.Counter({0}).most_common(1)[0][0]", "most common frequent maximum occurrences"), Prim("freq", ("coll",), "dict", lambda xs: dict(Counter(xs)), "dict(collections.Counter({0}))", "frequency count each"), Prim("sortkey1", ("coll",), "list", lambda xs: sorted(xs, key=lambda t: t[1]), "sorted({0}, key=lambda t: t[1])", "sort second element"), Prim("maxkey_len", ("coll",), "any", lambda xs: max(xs, key=len), "max({0}, key=len)", "longest maximum length"), Prim("minkey_len", ("coll",), "any", lambda xs: min(xs, key=len), "min({0}, key=len)", "shortest minimum length"), Prim("range1", ("int",), "list", lambda n: list(range(1, n + 1)) if n <= 10 ** 5 else 1 / 0, "list(range(1, {0} + 1))", "first n natural numbers range"), Prim("range0", ("int",), "list", lambda n: list(range(n)) if n <= 10 ** 5 else 1 / 0, "list(range({0}))", "range"), # strings Prim("upper", ("str",), "str", str.upper, "{0}.upper()", "upper uppercase capital"), Prim("lower", ("str",), "str", str.lower, "{0}.lower()", "lower lowercase"), Prim("title", ("str",), "str", str.title, "{0}.title()", "title capitalize first letter each word"), Prim("capitalize", ("str",), "str", str.capitalize, "{0}.capitalize()", "capitalize"), Prim("swapcase", ("str",), "str", str.swapcase, "{0}.swapcase()", "toggle swap case"), Prim("strip", ("str",), "str", str.strip, "{0}.strip()", "strip trim whitespace spaces"), Prim("nospace", ("str",), "str", lambda s: s.replace(" ", ""), "{0}.replace(' ', '')", "remove spaces whitespace"), Prim("words", ("str",), "list", str.split, "{0}.split()", "words split"), Prim("splitby", ("str", "str"), "list", lambda s, d: s.split(d), "{0}.split({1})", "split delimiter"), Prim("joinsp", ("coll",), "str", lambda xs: " ".join(xs), "' '.join({0})", "join words"), Prim("join", ("coll",), "str", lambda xs: "".join(xs), "''.join({0})", "join concatenate characters"), Prim("replace", ("str", "str", "str"), "str", lambda s, a, b: s.replace(a, b), "{0}.replace({1}, {2})", "replace"), Prim("remove", ("str", "str"), "str", lambda s, a: s.replace(a, ""), "{0}.replace({1}, '')", "remove delete"), Prim("remove1", ("str", "str"), "str", lambda s, a: s.replace(a, "", 1), "{0}.replace({1}, '', 1)", "remove first occurrence"), Prim("removelast", ("str", "str"), "str", lambda s, a: (s[:s.rfind(a)] + s[s.rfind(a) + 1:]) if a in s else s, "(({0}[:{0}.rfind({1})] + {0}[{0}.rfind({1}) + 1:]) if {1} in {0} else {0})", "remove last occurrence"), Prim("chars", ("str",), "list", list, "list({0})", "characters chars"), Prim("isdigit", ("str",), "bool", str.isdigit, "{0}.isdigit()", "digit numeric integer"), Prim("isalpha", ("str",), "bool", str.isalpha, "{0}.isalpha()", "alphabet letters"), Prim("isupper", ("str",), "bool", str.isupper, "{0}.isupper()", "upper"), Prim("islower", ("str",), "bool", str.islower, "{0}.islower()", "lower"), Prim("startswith", ("str", "str"), "bool", str.startswith, "{0}.startswith({1})", "starts begins"), Prim("endswith", ("str", "str"), "bool", str.endswith, "{0}.endswith({1})", "ends"), Prim("find", ("str", "str"), "int", str.find, "{0}.find({1})", "find position index occurrence"), Prim("f_upper", ("str",), "str", lambda s: "".join(c for c in s if c.isupper()), "''.join(c for c in {0} if c.isupper())", "uppercase characters extract"), Prim("f_lower", ("str",), "str", lambda s: "".join(c for c in s if c.islower()), "''.join(c for c in {0} if c.islower())", "lowercase characters remove"), Prim("f_digit", ("str",), "str", lambda s: "".join(c for c in s if c.isdigit()), "''.join(c for c in {0} if c.isdigit())", "digits numbers extract"), Prim("f_alpha", ("str",), "str", lambda s: "".join(c for c in s if c.isalpha()), "''.join(c for c in {0} if c.isalpha())", "letters remove non alphabet"), Prim("f_alnum", ("str",), "str", lambda s: "".join(c for c in s if c.isalnum()), "''.join(c for c in {0} if c.isalnum())", "alphanumeric remove special characters"), Prim("vowels", ("str",), "int", lambda s: sum(c in "aeiouAEIOU" for c in s), "sum(c in 'aeiouAEIOU' for c in {0})", "vowels count"), Prim("ispal", ("seq",), "bool", lambda s: s == s[::-1], "({0} == {0}[::-1])", "palindrome"), Prim("sortchars", ("str",), "str", lambda s: "".join(sorted(s)), "''.join(sorted({0}))", "sort characters"), Prim("rev_words", ("str",), "str", lambda s: " ".join(s.split()[::-1]), "' '.join({0}.split()[::-1])", "reverse words"), Prim("ord", ("str",), "int", lambda s: ord(s) if len(s) == 1 else 1 / 0, "ord({0})", "ascii value character"), Prim("chr", ("int",), "str", lambda n: chr(n) if 0 <= n < 1114111 else 1 / 0, "chr({0})", "character ascii"), Prim("strlen_words", ("str",), "list", lambda s: [len(w) for w in s.split()], "[len(w) for w in {0}.split()]", "length words"), Prim("firstchar", ("str",), "str", lambda s: s[0], "{0}[0]", "first character"), Prim("lastchar", ("str",), "str", lambda s: s[-1], "{0}[-1]", "last character"), Prim("upper_first_last", ("str",), "str", lambda s: " ".join((w[0].upper() + w[1:-1] + w[-1].upper()) if len(w) > 1 else w.upper() for w in s.split()), "' '.join((w[0].upper() + w[1:-1] + w[-1].upper()) if len(w) > 1 else w.upper() for w in {0}.split())", "capitalize first last letters each word"),]# v2 library entries added from the gate panel's FAILURE CLASSES (general-purpose operations; checked on MBPP dev)P_ += [ Prim("c2f", ("num",), "float", lambda c: c * 9 / 5 + 32, "({0} * 9 / 5 + 32)", "celsius fahrenheit convert temperature"), Prim("f2c", ("num",), "float", lambda f: (f - 32) * 5 / 9, "(({0} - 32) * 5 / 9)", "fahrenheit celsius convert temperature"), Prim("isleap", ("int",), "bool", lambda y: y % 4 == 0 and (y % 100 != 0 or y % 400 == 0), "({0} % 4 == 0 and ({0} % 100 != 0 or {0} % 400 == 0))", "leap year"), Prim("joincomma", ("coll",), "str", lambda xs: ",".join(xs), "','.join({0})", "join comma separated"), Prim("nwords", ("str",), "int", lambda s: len(s.split()), "len({0}.split())", "count words number"),]IMPORTS = "import math\nimport itertools\nimport collections\n"
# --------------------------------------------------------------------------------------------------------- requestdef parse_tests(tests, setup=""): """'assert f(a, b) == v' -> (fname, [(args, expected)], wrapper-src or None)""" fname, cases, wrap = None, [], None for t in tests: try: node = ast.parse(t.strip()).body[0] except SyntaxError: return None if not isinstance(node, ast.Assert): return None test = node.test if isinstance(test, ast.Call) or (isinstance(test, ast.UnaryOp) and isinstance(test.operand, ast.Call)): neg = isinstance(test, ast.UnaryOp) call = test.operand if neg else test exp = not neg lhs = call elif isinstance(test, ast.Compare) and len(test.ops) == 1 and isinstance(test.ops[0], ast.Eq): lhs = test.left try: exp = ast.literal_eval(test.comparators[0]) except Exception: # noqa: BLE001 return None else: return None call, w = lhs, None if isinstance(lhs, ast.Call) and isinstance(lhs.func, ast.Name) and lhs.func.id in ("set", "sorted", "list", "tuple", "round", "abs") and lhs.args and isinstance(lhs.args[0], ast.Call): w, call = lhs.func.id, lhs.args[0] if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Name)): return None try: args = [ast.literal_eval(a) for a in call.args] except Exception: # noqa: BLE001 return None if fname and call.func.id != fname: return None fname, wrap = call.func.id, w or wrap cases.append((args, exp)) return (fname, cases, wrap) if fname and cases else None
WRAP = {None: lambda v: v, "set": set, "sorted": sorted, "list": list, "tuple": tuple, "round": round, "abs": abs}
ORDINAL = {"first": 0, "second": 1, "third": 2, "fourth": 3, "last": -1, "double": 2, "doubled": 2, "twice": 2, "triple": 3, "tripled": 3, "half": 2, "halve": 2, "halved": 2}
def consts_of(desc, cases, strict=False): """constants a program may use. STRICT (one example): only what the request itself names - its numbers, its quoted characters and its ordinals (first=0, second=1, last=-1) - so no positional coincidence is reachable""" text = re.split(r"\bso\b", desc or "")[0] if strict else (desc or "") named = [int(n) for n in re.findall(r"\b(\d{1,4})\b", text)] named += re.findall(r"'([^']{1,3})'", text) named += [v for w, v in ORDINAL.items() if re.search(r"\b%s\b" % w, text, re.I)] out = named if strict else [0, 1, 2, -1, "", " "] + named return list(dict.fromkeys(out))
GENERIC = {"write", "function", "python", "find", "given", "number", "numbers", "integer", "list", "string", "element", "elements", "value", "values", "check", "whether", "two", "the", "and", "from", "all", "using", "which", "that", "with", "into", "for", "each", "array", "tuple", "item", "items", "get", "given", "not", "out", "sequence"}
def words_of(desc): return {w.lower().rstrip("s") for w in re.findall(r"[A-Za-z]+", desc or "") if len(w) >= 3 and w.lower() not in GENERIC and w.lower().rstrip("s") not in GENERIC}
# ----------------------------------------------------------------------------------------------------------- searchclass CodeOrgan: def __init__(self, library=None, max_size=4, cap=60000): self.prims = list(P_) + list(library or []) self.max_size, self.cap = max_size, cap self.why = ""
def learn(self, name, prog, arity_types, out_t, desc): """STORE: a verified program becomes a library function; later requests compose it""" fnc = prog["fn"] src = "%s(%s)" % (name, ", ".join("{%d}" % i for i in range(len(arity_types)))) p = Prim("lib_" + name, tuple(arity_types), out_t, lambda *vals: fnc(vals), src, " ".join(words_of(desc))) self.prims.append(p) self.library_src = getattr(self, "library_src", {}) self.library_src[name] = prog["def"].replace(IMPORTS, "") return p
def solve(self, desc, tests, setup="", visible=None, strict=False): self.why = "" pt = parse_tests(tests, setup) if not pt: self.why = "the examples are not simple asserts" return None fname, cases, wrap = pt vis = cases if visible is None else cases[:visible] if not vis: return None W = WRAP[wrap] nargs = len(vis[0][0]) if any(len(a) != nargs for a, _ in cases): self.why = "varying arity" return None target = [W(e) if wrap else e for _, e in vis] kw = words_of(desc) # the request SPECIFIES the moves: rank by the description's words; keep the whole library but try relevant first # a stored program is a move only with >= 2 examples, and never inside its own definition; with ONE example # (strict) only the base library composes - forms verified on one example are too weak to build on from one more pool = [p for p in self.prims if p.name != "lib_" + fname and not (strict and p.name.startswith("lib_"))] prims = sorted(pool, key=lambda p: -len(p.kw & kw)) # terminals: arguments and constants; a term = (src, type, outputs-tuple, fn) terms_by_size = {1: []} seen = set()
def add(size, src, outs, fnc, used=frozenset()): key = repr(outs) try: match = [W(o) if wrap else o for o in outs] == target except Exception: # noqa: BLE001 match = False if match: # the request SPECIFIES the moves: a fit made only of moves the description never names is a # coincidence of three examples, not an answer - it is not accepted and does not claim the signature. # A fit must also READ its inputs: every argument is used, except an 'n' that only restates a length. reads = all(argn[i] in re.findall(r"a\d+", src) or restates_len[i] for i in range(nargs)) # STRICT (one example): EVERY operation must be named by the request - the description specifies the # program and the single example only checks it named = all(pr.kw & kw for pr in used) if strict else any(pr.kw & kw for pr in used) if used and reads and named: return (src, fnc) self.coincidences = getattr(self, "coincidences", 0) + 1 return None if key in seen or len(key) > 1500 or len(seen) > self.cap: return None # bounded memory: huge values and past-budget terms are not kept seen.add(key) ty = tyof(outs[0]) if any(tyof(o) != ty for o in outs): ty = "any" terms_by_size.setdefault(size, []).append((src, ty, outs, fnc, used)) return None
argn = ["a%d" % i for i in range(nargs)] restates_len = [all(isinstance(a[i], int) and any(isinstance(a[j], (list, tuple, str)) and len(a[j]) == a[i] for j in range(nargs) if j != i) for a, _ in vis) for i in range(nargs)] for i in range(nargs): hit = add(1, argn[i], tuple(a[i] for a, _ in vis), (lambda i: lambda xs: xs[i])(i)) if hit: return self._emit(fname, argn, hit, cases, wrap, desc) for c in consts_of(desc, vis, strict): add(1, repr(c), tuple(c for _ in vis), (lambda c: lambda xs: c)(c)) n_terms = 0 best = None for size in range(2, self.max_size + 1): for p in prims: k = len(p.ins) # child sizes summing to size-1 for parts in _compositions(size - 1, k): pools = [terms_by_size.get(s, []) for s in parts] pools = [[t for t in pool if fits(t[1], want) or t[1] == "any"] for pool, want in zip(pools, p.ins)] if any(not pool for pool in pools): continue for combo in itertools.product(*pools): n_terms += 1 if n_terms > self.cap: self.why = "search budget exhausted" return None try: outs = tuple(p.fn(*[t[2][j] for t in combo]) for j in range(len(vis))) except Exception: # noqa: BLE001 continue if any(_oversize(o) for o in outs): continue # bounded memory: never represent a huge intermediate value src = p.src.format(*[t[0] for t in combo]) fnc = (lambda p, combo: lambda xs: p.fn(*[t[3](xs) for t in combo]))(p, combo) used = frozenset([p]).union(*[t[4] for t in combo]) hit = add(size, src, outs, fnc, used) if hit: if not strict: return self._emit(fname, argn, hit, cases, wrap, desc) # COVERAGE: how much of what the request says the program's moves account for, jointly named = len(set().union(*[pr.kw for pr in used]) & kw) if best is None or named > best[0]: best = (named, hit) if strict and best: # v2 STRICT: the fit covering most of the request, any size return self._emit(fname, argn, best[1], cases, wrap, desc) self.why = "no program of size <= %d fits the examples" % self.max_size return None
def _emit(self, fname, argn, hit, cases, wrap, desc): src, fnc = hit lib = getattr(self, "library_src", {}) used = [n for n in lib if re.search(r"\b%s\(" % re.escape(n), src)] deps = "".join(lib[n] for n in used) # stored forms this program composes body = "%s%sdef %s(%s):\n return %s\n" % (IMPORTS, deps, fname, ", ".join(argn), src) # CHECK: execute the RENDERED source (not the in-memory closure) against every example given ns = {} exec(compile(body, "<organ>", "exec"), ns) # noqa: S102 - composed only of library templates W = WRAP[wrap] passed = 0 for a, e in cases: try: out = ns[fname](*a) ok = (W(out) if wrap else out) == e except Exception: # noqa: BLE001 ok = False passed += ok return {"def": body, "fname": fname, "expr": src, "passed": passed, "cases": len(cases), "fn": fnc, "arity": len(argn), "reused": used}
def _oversize(o): if isinstance(o, bool): return False if isinstance(o, int): return abs(o) > 10 ** 12 if isinstance(o, str): return len(o) > 400 if isinstance(o, (list, tuple, set, dict)): return len(o) > 200 or any(_oversize(x) for x in list(o)[:50]) return False
def _compositions(total, k): if k == 1: yield (total,) return for first in range(1, total - k + 2): for rest in _compositions(total - first, k - 1): yield (first,) + rest123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488"""code_organ_v3 - v2 (admitted in w482, immutable) + cover mode for conversation (coverage selection at any sizewith stored programs allowed). v2: v1 (MBPP-frozen b2e52a1d) + STRICT mode for a single example: every move named by therequest. Programs as specified free moves over a verified function library, checked by execution; everyverified program joins the library (the stored final forms - continuous learning without retraining).
REQUEST description + input/output examples (asserts) -> function name, argument values and types, expected outputs, constants the description names ("at least 4 characters", "the character 'l'")MOVES typed library functions. The TYPE SYSTEM is the specified structure: a function applies only where its argument types connect; within that the choice is free. The description's words rank the moves.SEARCH bottom-up enumeration with OBSERVATIONAL EQUIVALENCE: programs that behave identically on the examples are kept once, so compositions of 3-4 moves stay tractable.CHECK the rendered source is executed against every example; nothing is released that did not run and pass.STORE a verified program becomes a library function (its description words are its keywords, its signature its type); later requests compose it - measured as the library-growth curve.Only library templates are ever evaluated; no text from the request is executed."""from __future__ import annotations
import astimport itertoolsimport jsonimport mathimport refrom collections import Counter
# ----------------------------------------------------------------------------------------------------------- typesdef tyof(v): if isinstance(v, bool): return "bool" if isinstance(v, int): return "int" if isinstance(v, float): return "float" if isinstance(v, str): return "str" if isinstance(v, list): return "list" if isinstance(v, tuple): return "tuple" if isinstance(v, dict): return "dict" if isinstance(v, set): return "set" return "any"
GROUP = {"num": {"int", "float"}, "seq": {"list", "tuple", "str"}, "coll": {"list", "tuple", "set"}, "any": {"bool", "int", "float", "str", "list", "tuple", "dict", "set", "any"}}
def fits(t, want): return t == want or t in GROUP.get(want, ())
# ------------------------------------------------------------------------------------------------------ primitivesclass Prim: __slots__ = ("name", "ins", "out", "fn", "src", "kw")
def __init__(self, name, ins, out, fn, src, kw): self.name, self.ins, self.out, self.fn, self.src = name, ins, out, fn, src self.kw = {w.lower().rstrip("s") for w in kw.split()} # v2: normalised exactly like the request words
def _big(x): if isinstance(x, int) and abs(x) > 10 ** 7: raise ValueError("too large") return x
def _is_prime(n): if n < 2: return False return all(n % d for d in range(2, int(n ** 0.5) + 1))
def _uniq(xs): out = [] for x in xs: if x not in out: out.append(x) return out
def _flatten(xs): out = [] for x in xs: out += list(x) if isinstance(x, (list, tuple)) else [x] return out
P_ = [ # numbers Prim("add", ("num", "num"), "num", lambda a, b: a + b, "({0} + {1})", "add sum plus total"), Prim("sub", ("num", "num"), "num", lambda a, b: a - b, "({0} - {1})", "subtract difference minus"), Prim("mul", ("num", "num"), "num", lambda a, b: _big(a * b), "({0} * {1})", "multiply product times"), Prim("fdiv", ("num", "num"), "num", lambda a, b: a // b, "({0} // {1})", "divide quotient integer"), Prim("div", ("num", "num"), "float", lambda a, b: a / b, "({0} / {1})", "divide ratio average"), Prim("mod", ("num", "num"), "num", lambda a, b: a % b, "({0} % {1})", "remainder modulo divisible"), Prim("pow", ("num", "num"), "num", lambda a, b: _big(a ** b) if b < 64 else 1 / 0, "({0} ** {1})", "power square cube exponent"), Prim("sq", ("num",), "num", lambda a: a * a, "({0} ** 2)", "square squares"), Prim("cube", ("num",), "num", lambda a: a ** 3, "({0} ** 3)", "cube cubes"), Prim("abs", ("num",), "num", abs, "abs({0})", "absolute"), Prim("neg", ("num",), "num", lambda a: -a, "(-{0})", "negative negate"), Prim("half", ("num",), "float", lambda a: a / 2, "({0} / 2)", "half area triangle"), Prim("sqrt", ("num",), "float", math.sqrt, "math.sqrt({0})", "root square"), Prim("isqrt", ("int",), "int", math.isqrt, "math.isqrt({0})", "root square integer"), Prim("fact", ("int",), "int", lambda n: math.factorial(n) if 0 <= n <= 30 else 1 / 0, "math.factorial({0})", "factorial"), Prim("gcd", ("int", "int"), "int", math.gcd, "math.gcd({0}, {1})", "gcd greatest common divisor"), Prim("lcm", ("int", "int"), "int", lambda a, b: a * b // math.gcd(a, b) if a and b else 0, "({0} * {1} // math.gcd({0}, {1}))", "lcm least common multiple"), Prim("isprime", ("int",), "bool", _is_prime, "(({0}) > 1 and all(({0}) % d for d in range(2, int(({0}) ** 0.5) + 1)))", "prime"), Prim("even", ("int",), "bool", lambda n: n % 2 == 0, "({0} % 2 == 0)", "even"), Prim("odd", ("int",), "bool", lambda n: n % 2 == 1, "({0} % 2 == 1)", "odd"), Prim("digits", ("int",), "list", lambda n: [int(c) for c in str(abs(n))], "[int(c) for c in str(abs({0}))]", "digits digit"), Prim("revnum", ("int",), "int", lambda n: int(str(abs(n))[::-1]), "int(str(abs({0}))[::-1])", "reverse number"), Prim("bin", ("int",), "str", lambda n: bin(n)[2:], "bin({0})[2:]", "binary"), Prim("frombin", ("str",), "int", lambda s: int(s, 2), "int({0}, 2)", "binary decimal convert"), Prim("popcount", ("int",), "int", lambda n: bin(n).count("1"), "bin({0}).count('1')", "set bits count ones"), Prim("xor", ("int", "int"), "int", lambda a, b: a ^ b, "({0} ^ {1})", "xor bit differ"), Prim("ispow2", ("int",), "bool", lambda n: n > 0 and n & (n - 1) == 0, "({0} > 0 and {0} & ({0} - 1) == 0)", "power two bit"), Prim("eq", ("any", "any"), "bool", lambda a, b: a == b, "({0} == {1})", "equal same"), Prim("lt", ("num", "num"), "bool", lambda a, b: a < b, "({0} < {1})", "less smaller"), Prim("gt", ("num", "num"), "bool", lambda a, b: a > b, "({0} > {1})", "greater larger"), Prim("not", ("bool",), "bool", lambda a: not a, "(not {0})", "not"), Prim("and", ("bool", "bool"), "bool", lambda a, b: a and b, "({0} and {1})", "and both"), Prim("or", ("bool", "bool"), "bool", lambda a, b: a or b, "({0} or {1})", "or either"), Prim("maxn", ("num", "num"), "num", max, "max({0}, {1})", "maximum largest bigger"), Prim("minn", ("num", "num"), "num", min, "min({0}, {1})", "minimum smallest"), Prim("round2", ("num",), "float", lambda a: round(a, 2), "round({0}, 2)", "round"), Prim("int", ("any",), "int", int, "int({0})", "integer convert"), Prim("str", ("any",), "str", str, "str({0})", "string convert"), Prim("float", ("num",), "float", float, "float({0})", "float"), Prim("tri", ("int",), "int", lambda n: n * (n + 1) // 2, "({0} * ({0} + 1) // 2)", "triangular sum natural"), Prim("pi_r2", ("num",), "float", lambda r: math.pi * r * r, "(math.pi * {0} * {0})", "area circle"), Prim("circ", ("num",), "float", lambda r: 2 * math.pi * r, "(2 * math.pi * {0})", "circumference perimeter circle"), # sequences Prim("len", ("seq",), "int", len, "len({0})", "length count number size"), Prim("sum", ("coll",), "num", lambda xs: sum(xs), "sum({0})", "sum total add"), Prim("max", ("coll",), "any", max, "max({0})", "maximum largest biggest max longest"), Prim("min", ("coll",), "any", min, "min({0})", "minimum smallest min"), Prim("sorted", ("coll",), "list", sorted, "sorted({0})", "sort sorted ascending order"), Prim("sorted_desc", ("coll",), "list", lambda xs: sorted(xs, reverse=True), "sorted({0}, reverse=True)", "sort descending largest"), Prim("rev", ("seq",), "seq", lambda xs: xs[::-1], "{0}[::-1]", "reverse reversed"), Prim("first", ("seq",), "any", lambda xs: xs[0], "{0}[0]", "first"), Prim("last", ("seq",), "any", lambda xs: xs[-1], "{0}[-1]", "last"), Prim("take", ("seq", "int"), "seq", lambda xs, n: xs[:n], "{0}[:{1}]", "first n smallest largest take"), Prim("drop", ("seq", "int"), "seq", lambda xs, n: xs[n:], "{0}[{1}:]", "remove first skip"), Prim("at", ("seq", "int"), "any", lambda xs, i: xs[i], "{0}[{1}]", "nth index element second third"), Prim("tolist", ("any",), "list", list, "list({0})", "list convert"), Prim("totuple", ("any",), "tuple", tuple, "tuple({0})", "tuple convert"), Prim("toset", ("coll",), "set", set, "set({0})", "unique distinct set"), Prim("uniq", ("coll",), "list", _uniq, "list(dict.fromkeys({0}))", "unique distinct duplicates remove"), Prim("inter", ("coll", "coll"), "tuple", lambda a, b: tuple(sorted(set(a) & set(b))), "tuple(sorted(set({0}) & set({1})))", "common shared similar intersection"), Prim("union", ("coll", "coll"), "tuple", lambda a, b: tuple(sorted(set(a) | set(b))), "tuple(sorted(set({0}) | set({1})))", "union combine"), Prim("diff", ("coll", "coll"), "list", lambda a, b: [x for x in a if x not in b], "[x for x in {0} if x not in {1}]", "difference not in"), Prim("concat", ("seq", "seq"), "seq", lambda a, b: a + b, "({0} + {1})", "concatenate join append combine merge"), Prim("count", ("seq", "any"), "int", lambda xs, x: xs.count(x), "{0}.count({1})", "count occurrences frequency"), Prim("index", ("seq", "any"), "int", lambda xs, x: xs.index(x), "{0}.index({1})", "index position find"), Prim("contains", ("any", "seq"), "bool", lambda x, xs: x in xs, "({0} in {1})", "contains present exists check"), Prim("allsame", ("coll",), "bool", lambda xs: len(set(xs)) <= 1, "(len(set({0})) <= 1)", "same equal all identical"), Prim("alluniq", ("coll",), "bool", lambda xs: len(set(xs)) == len(xs), "(len(set({0})) == len(list({0})))", "unique distinct duplicate"), Prim("issorted", ("coll",), "bool", lambda xs: list(xs) == sorted(xs), "(list({0}) == sorted({0}))", "sorted order check"), Prim("prod", ("coll",), "num", lambda xs: _big(math.prod(xs)), "math.prod({0})", "product multiply"), Prim("mean", ("coll",), "float", lambda xs: sum(xs) / len(xs), "(sum({0}) / len({0}))", "average mean"), Prim("map_sq", ("coll",), "list", lambda xs: [x * x for x in xs], "[x * x for x in {0}]", "square squares each"), Prim("map_cube", ("coll",), "list", lambda xs: [x ** 3 for x in xs], "[x ** 3 for x in {0}]", "cube cubes each"), Prim("map_neg", ("coll",), "list", lambda xs: [-x for x in xs], "[-x for x in {0}]", "negative"), Prim("map_abs", ("coll",), "list", lambda xs: [abs(x) for x in xs], "[abs(x) for x in {0}]", "absolute"), Prim("map_str", ("coll",), "list", lambda xs: [str(x) for x in xs], "[str(x) for x in {0}]", "string convert"), Prim("map_int", ("coll",), "list", lambda xs: [int(x) for x in xs], "[int(x) for x in {0}]", "integer convert"), Prim("map_len", ("coll",), "list", lambda xs: [len(x) for x in xs], "[len(x) for x in {0}]", "length each"), Prim("map_first", ("coll",), "list", lambda xs: [x[0] for x in xs], "[x[0] for x in {0}]", "first each"), Prim("map_last", ("coll",), "list", lambda xs: [x[-1] for x in xs], "[x[-1] for x in {0}]", "last each"), Prim("map_sum", ("coll",), "list", lambda xs: [sum(x) for x in xs], "[sum(x) for x in {0}]", "sum each"), Prim("map_add", ("coll", "num"), "list", lambda xs, k: [x + k for x in xs], "[x + {1} for x in {0}]", "add each"), Prim("map_mul", ("coll", "num"), "list", lambda xs, k: [x * k for x in xs], "[x * {1} for x in {0}]", "multiply each double doubled twice"), Prim("zipadd", ("coll", "coll"), "list", lambda a, b: [x + y for x, y in zip(a, b)], "[x + y for x, y in zip({0}, {1})]", "add two lists elementwise"), Prim("zipmul", ("coll", "coll"), "list", lambda a, b: [x * y for x, y in zip(a, b)], "[x * y for x, y in zip({0}, {1})]", "multiply two lists"), Prim("zipsub", ("coll", "coll"), "list", lambda a, b: [x - y for x, y in zip(a, b)], "[x - y for x, y in zip({0}, {1})]", "subtract two lists"), Prim("zipdiv", ("coll", "coll"), "list", lambda a, b: [x / y for x, y in zip(a, b)], "[x / y for x, y in zip({0}, {1})]", "divide two lists"), Prim("zip", ("coll", "coll"), "list", lambda a, b: list(zip(a, b)), "list(zip({0}, {1}))", "pair zip"), Prim("f_even", ("coll",), "list", lambda xs: [x for x in xs if x % 2 == 0], "[x for x in {0} if x % 2 == 0]", "even"), Prim("f_odd", ("coll",), "list", lambda xs: [x for x in xs if x % 2 == 1], "[x for x in {0} if x % 2 == 1]", "odd"), Prim("f_pos", ("coll",), "list", lambda xs: [x for x in xs if x > 0], "[x for x in {0} if x > 0]", "positive"), Prim("f_neg", ("coll",), "list", lambda xs: [x for x in xs if x < 0], "[x for x in {0} if x < 0]", "negative"), Prim("f_gt", ("coll", "num"), "list", lambda xs, k: [x for x in xs if x > k], "[x for x in {0} if x > {1}]", "greater than"), Prim("f_lenge", ("coll", "int"), "list", lambda xs, k: [x for x in xs if len(x) >= k], "[x for x in {0} if len(x) >= {1}]", "at least long characters"), Prim("f_neq", ("coll", "any"), "list", lambda xs, k: [x for x in xs if x != k], "[x for x in {0} if x != {1}]", "remove all"), Prim("cumsum", ("coll",), "list", lambda xs: list(itertools.accumulate(xs)), "list(itertools.accumulate({0}))", "cumulative running sum"), Prim("flatten", ("coll",), "list", _flatten, "[y for x in {0} for y in (x if isinstance(x, (list, tuple)) else [x])]", "flatten nested"), Prim("mostcommon", ("coll",), "any", lambda xs: Counter(xs).most_common(1)[0][0], "collections.Counter({0}).most_common(1)[0][0]", "most common frequent maximum occurrences"), Prim("freq", ("coll",), "dict", lambda xs: dict(Counter(xs)), "dict(collections.Counter({0}))", "frequency count each"), Prim("sortkey1", ("coll",), "list", lambda xs: sorted(xs, key=lambda t: t[1]), "sorted({0}, key=lambda t: t[1])", "sort second element"), Prim("maxkey_len", ("coll",), "any", lambda xs: max(xs, key=len), "max({0}, key=len)", "longest maximum length"), Prim("minkey_len", ("coll",), "any", lambda xs: min(xs, key=len), "min({0}, key=len)", "shortest minimum length"), Prim("range1", ("int",), "list", lambda n: list(range(1, n + 1)) if n <= 10 ** 5 else 1 / 0, "list(range(1, {0} + 1))", "first n natural numbers range"), Prim("range0", ("int",), "list", lambda n: list(range(n)) if n <= 10 ** 5 else 1 / 0, "list(range({0}))", "range"), # strings Prim("upper", ("str",), "str", str.upper, "{0}.upper()", "upper uppercase capital"), Prim("lower", ("str",), "str", str.lower, "{0}.lower()", "lower lowercase"), Prim("title", ("str",), "str", str.title, "{0}.title()", "title capitalize first letter each word"), Prim("capitalize", ("str",), "str", str.capitalize, "{0}.capitalize()", "capitalize"), Prim("swapcase", ("str",), "str", str.swapcase, "{0}.swapcase()", "toggle swap case"), Prim("strip", ("str",), "str", str.strip, "{0}.strip()", "strip trim whitespace spaces"), Prim("nospace", ("str",), "str", lambda s: s.replace(" ", ""), "{0}.replace(' ', '')", "remove spaces whitespace"), Prim("words", ("str",), "list", str.split, "{0}.split()", "words split"), Prim("splitby", ("str", "str"), "list", lambda s, d: s.split(d), "{0}.split({1})", "split delimiter"), Prim("joinsp", ("coll",), "str", lambda xs: " ".join(xs), "' '.join({0})", "join words"), Prim("join", ("coll",), "str", lambda xs: "".join(xs), "''.join({0})", "join concatenate characters"), Prim("replace", ("str", "str", "str"), "str", lambda s, a, b: s.replace(a, b), "{0}.replace({1}, {2})", "replace"), Prim("remove", ("str", "str"), "str", lambda s, a: s.replace(a, ""), "{0}.replace({1}, '')", "remove delete"), Prim("remove1", ("str", "str"), "str", lambda s, a: s.replace(a, "", 1), "{0}.replace({1}, '', 1)", "remove first occurrence"), Prim("removelast", ("str", "str"), "str", lambda s, a: (s[:s.rfind(a)] + s[s.rfind(a) + 1:]) if a in s else s, "(({0}[:{0}.rfind({1})] + {0}[{0}.rfind({1}) + 1:]) if {1} in {0} else {0})", "remove last occurrence"), Prim("chars", ("str",), "list", list, "list({0})", "characters chars"), Prim("isdigit", ("str",), "bool", str.isdigit, "{0}.isdigit()", "digit numeric integer"), Prim("isalpha", ("str",), "bool", str.isalpha, "{0}.isalpha()", "alphabet letters"), Prim("isupper", ("str",), "bool", str.isupper, "{0}.isupper()", "upper"), Prim("islower", ("str",), "bool", str.islower, "{0}.islower()", "lower"), Prim("startswith", ("str", "str"), "bool", str.startswith, "{0}.startswith({1})", "starts begins"), Prim("endswith", ("str", "str"), "bool", str.endswith, "{0}.endswith({1})", "ends"), Prim("find", ("str", "str"), "int", str.find, "{0}.find({1})", "find position index occurrence"), Prim("f_upper", ("str",), "str", lambda s: "".join(c for c in s if c.isupper()), "''.join(c for c in {0} if c.isupper())", "uppercase characters extract"), Prim("f_lower", ("str",), "str", lambda s: "".join(c for c in s if c.islower()), "''.join(c for c in {0} if c.islower())", "lowercase characters remove"), Prim("f_digit", ("str",), "str", lambda s: "".join(c for c in s if c.isdigit()), "''.join(c for c in {0} if c.isdigit())", "digits numbers extract"), Prim("f_alpha", ("str",), "str", lambda s: "".join(c for c in s if c.isalpha()), "''.join(c for c in {0} if c.isalpha())", "letters remove non alphabet"), Prim("f_alnum", ("str",), "str", lambda s: "".join(c for c in s if c.isalnum()), "''.join(c for c in {0} if c.isalnum())", "alphanumeric remove special characters"), Prim("vowels", ("str",), "int", lambda s: sum(c in "aeiouAEIOU" for c in s), "sum(c in 'aeiouAEIOU' for c in {0})", "vowels count"), Prim("ispal", ("seq",), "bool", lambda s: s == s[::-1], "({0} == {0}[::-1])", "palindrome"), Prim("sortchars", ("str",), "str", lambda s: "".join(sorted(s)), "''.join(sorted({0}))", "sort characters"), Prim("rev_words", ("str",), "str", lambda s: " ".join(s.split()[::-1]), "' '.join({0}.split()[::-1])", "reverse words"), Prim("ord", ("str",), "int", lambda s: ord(s) if len(s) == 1 else 1 / 0, "ord({0})", "ascii value character"), Prim("chr", ("int",), "str", lambda n: chr(n) if 0 <= n < 1114111 else 1 / 0, "chr({0})", "character ascii"), Prim("strlen_words", ("str",), "list", lambda s: [len(w) for w in s.split()], "[len(w) for w in {0}.split()]", "length words"), Prim("firstchar", ("str",), "str", lambda s: s[0], "{0}[0]", "first character"), Prim("lastchar", ("str",), "str", lambda s: s[-1], "{0}[-1]", "last character"), Prim("upper_first_last", ("str",), "str", lambda s: " ".join((w[0].upper() + w[1:-1] + w[-1].upper()) if len(w) > 1 else w.upper() for w in s.split()), "' '.join((w[0].upper() + w[1:-1] + w[-1].upper()) if len(w) > 1 else w.upper() for w in {0}.split())", "capitalize first last letters each word"),]# v2 library entries added from the gate panel's FAILURE CLASSES (general-purpose operations; checked on MBPP dev)P_ += [ Prim("c2f", ("num",), "float", lambda c: c * 9 / 5 + 32, "({0} * 9 / 5 + 32)", "celsius fahrenheit convert temperature"), Prim("f2c", ("num",), "float", lambda f: (f - 32) * 5 / 9, "(({0} - 32) * 5 / 9)", "fahrenheit celsius convert temperature"), Prim("isleap", ("int",), "bool", lambda y: y % 4 == 0 and (y % 100 != 0 or y % 400 == 0), "({0} % 4 == 0 and ({0} % 100 != 0 or {0} % 400 == 0))", "leap year"), Prim("joincomma", ("coll",), "str", lambda xs: ",".join(xs), "','.join({0})", "join comma separated"), Prim("nwords", ("str",), "int", lambda s: len(s.split()), "len({0}.split())", "count words number"),]IMPORTS = "import math\nimport itertools\nimport collections\n"
# --------------------------------------------------------------------------------------------------------- requestdef parse_tests(tests, setup=""): """'assert f(a, b) == v' -> (fname, [(args, expected)], wrapper-src or None)""" fname, cases, wrap = None, [], None for t in tests: try: node = ast.parse(t.strip()).body[0] except SyntaxError: return None if not isinstance(node, ast.Assert): return None test = node.test if isinstance(test, ast.Call) or (isinstance(test, ast.UnaryOp) and isinstance(test.operand, ast.Call)): neg = isinstance(test, ast.UnaryOp) call = test.operand if neg else test exp = not neg lhs = call elif isinstance(test, ast.Compare) and len(test.ops) == 1 and isinstance(test.ops[0], ast.Eq): lhs = test.left try: exp = ast.literal_eval(test.comparators[0]) except Exception: # noqa: BLE001 return None else: return None call, w = lhs, None if isinstance(lhs, ast.Call) and isinstance(lhs.func, ast.Name) and lhs.func.id in ("set", "sorted", "list", "tuple", "round", "abs") and lhs.args and isinstance(lhs.args[0], ast.Call): w, call = lhs.func.id, lhs.args[0] if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Name)): return None try: args = [ast.literal_eval(a) for a in call.args] except Exception: # noqa: BLE001 return None if fname and call.func.id != fname: return None fname, wrap = call.func.id, w or wrap cases.append((args, exp)) return (fname, cases, wrap) if fname and cases else None
WRAP = {None: lambda v: v, "set": set, "sorted": sorted, "list": list, "tuple": tuple, "round": round, "abs": abs}
ORDINAL = {"first": 0, "second": 1, "third": 2, "fourth": 3, "last": -1, "double": 2, "doubled": 2, "twice": 2, "triple": 3, "tripled": 3, "half": 2, "halve": 2, "halved": 2}
def consts_of(desc, cases, strict=False): """constants a program may use. STRICT (one example): only what the request itself names - its numbers, its quoted characters and its ordinals (first=0, second=1, last=-1) - so no positional coincidence is reachable""" text = re.split(r"\bso\b", desc or "")[0] if strict else (desc or "") named = [int(n) for n in re.findall(r"\b(\d{1,4})\b", text)] named += re.findall(r"'([^']{1,3})'", text) named += [v for w, v in ORDINAL.items() if re.search(r"\b%s\b" % w, text, re.I)] out = named if strict else [0, 1, 2, -1, "", " "] + named return list(dict.fromkeys(out))
GENERIC = {"write", "function", "python", "find", "given", "number", "numbers", "integer", "list", "string", "element", "elements", "value", "values", "check", "whether", "two", "the", "and", "from", "all", "using", "which", "that", "with", "into", "for", "each", "array", "tuple", "item", "items", "get", "given", "not", "out", "sequence"}
def words_of(desc): return {w.lower().rstrip("s") for w in re.findall(r"[A-Za-z]+", desc or "") if len(w) >= 3 and w.lower() not in GENERIC and w.lower().rstrip("s") not in GENERIC}
# ----------------------------------------------------------------------------------------------------------- searchclass CodeOrgan: def __init__(self, library=None, max_size=4, cap=60000): self.prims = list(P_) + list(library or []) self.max_size, self.cap = max_size, cap self.why = ""
def learn(self, name, prog, arity_types, out_t, desc): """STORE: a verified program becomes a library function; later requests compose it""" fnc = prog["fn"] src = "%s(%s)" % (name, ", ".join("{%d}" % i for i in range(len(arity_types)))) p = Prim("lib_" + name, tuple(arity_types), out_t, lambda *vals: fnc(vals), src, " ".join(words_of(desc))) self.prims.append(p) self.library_src = getattr(self, "library_src", {}) self.library_src[name] = prog["def"].replace(IMPORTS, "") return p
def solve(self, desc, tests, setup="", visible=None, strict=False, cover=False, allow_lib=True): """strict: request-named constants only + coverage selection (one example); cover: coverage selection at any size (conversation); allow_lib: stored programs may compose (needs >= 2 examples)""" cover = cover or strict self.why = "" pt = parse_tests(tests, setup) if not pt: self.why = "the examples are not simple asserts" return None fname, cases, wrap = pt vis = cases if visible is None else cases[:visible] if not vis: return None W = WRAP[wrap] nargs = len(vis[0][0]) if any(len(a) != nargs for a, _ in cases): self.why = "varying arity" return None target = [W(e) if wrap else e for _, e in vis] kw = words_of(desc) self._req_kw, self._cover, self._n_visible = kw, None, len(vis) # the request SPECIFIES the moves: rank by the description's words; keep the whole library but try relevant first # a stored program is a move only with >= 2 examples, and never inside its own definition; with ONE example # (strict) only the base library composes - forms verified on one example are too weak to build on from one more pool = [p for p in self.prims if p.name != "lib_" + fname and not ((strict or not allow_lib) and p.name.startswith("lib_"))] prims = sorted(pool, key=lambda p: -len(p.kw & kw)) # terminals: arguments and constants; a term = (src, type, outputs-tuple, fn) terms_by_size = {1: []} seen = set()
def add(size, src, outs, fnc, used=frozenset()): key = repr(outs) try: match = [W(o) if wrap else o for o in outs] == target except Exception: # noqa: BLE001 match = False if match: # the request SPECIFIES the moves: a fit made only of moves the description never names is a # coincidence of three examples, not an answer - it is not accepted and does not claim the signature. # A fit must also READ its inputs: every argument is used, except an 'n' that only restates a length. reads = all(argn[i] in re.findall(r"a\d+", src) or restates_len[i] for i in range(nargs)) # STRICT (one example): EVERY operation must be named by the request - the description specifies the # program and the single example only checks it named = all(pr.kw & kw for pr in used) if strict else any(pr.kw & kw for pr in used) if used and reads and named: return (src, fnc) self.coincidences = getattr(self, "coincidences", 0) + 1 return None if key in seen or len(key) > 1500 or len(seen) > self.cap: return None # bounded memory: huge values and past-budget terms are not kept seen.add(key) ty = tyof(outs[0]) if any(tyof(o) != ty for o in outs): ty = "any" terms_by_size.setdefault(size, []).append((src, ty, outs, fnc, used)) return None
argn = ["a%d" % i for i in range(nargs)] restates_len = [all(isinstance(a[i], int) and any(isinstance(a[j], (list, tuple, str)) and len(a[j]) == a[i] for j in range(nargs) if j != i) for a, _ in vis) for i in range(nargs)] for i in range(nargs): hit = add(1, argn[i], tuple(a[i] for a, _ in vis), (lambda i: lambda xs: xs[i])(i)) if hit: return self._emit(fname, argn, hit, cases, wrap, desc) for c in consts_of(desc, vis, strict): add(1, repr(c), tuple(c for _ in vis), (lambda c: lambda xs: c)(c)) n_terms = 0 best = None first_hit_size = None for size in range(2, self.max_size + 1): if cover and best and first_hit_size is None: first_hit_size = size - 1 if cover and first_hit_size is not None and size > first_hit_size + 1: break # v3: look at most ONE size beyond the first fit (bounded time) for p in prims: k = len(p.ins) # child sizes summing to size-1 for parts in _compositions(size - 1, k): pools = [terms_by_size.get(s, []) for s in parts] pools = [[t for t in pool if fits(t[1], want) or t[1] == "any"] for pool, want in zip(pools, p.ins)] if any(not pool for pool in pools): continue for combo in itertools.product(*pools): n_terms += 1 if n_terms > self.cap: if cover and best: # v3: a found fit is never discarded by the budget return self._emit(fname, argn, best[1], cases, wrap, desc) self.why = "search budget exhausted" return None try: outs = tuple(p.fn(*[t[2][j] for t in combo]) for j in range(len(vis))) except Exception: # noqa: BLE001 continue if any(_oversize(o) for o in outs): continue # bounded memory: never represent a huge intermediate value src = p.src.format(*[t[0] for t in combo]) fnc = (lambda p, combo: lambda xs: p.fn(*[t[3](xs) for t in combo]))(p, combo) used = frozenset([p]).union(*[t[4] for t in combo]) hit = add(size, src, outs, fnc, used) if hit: if not cover: return self._emit(fname, argn, hit, cases, wrap, desc) # COVERAGE: how much of what the request says the program's moves account for, jointly named = len(set().union(*[pr.kw for pr in used]) & kw) if best is None or named > best[0]: best = (named, hit) self._cover = named if cover and best: # v2 STRICT: the fit covering most of the request, any size return self._emit(fname, argn, best[1], cases, wrap, desc) self.why = "no program of size <= %d fits the examples" % self.max_size return None
def _emit(self, fname, argn, hit, cases, wrap, desc): src, fnc = hit lib = getattr(self, "library_src", {}) used = [n for n in lib if re.search(r"\b%s\(" % re.escape(n), src)] deps = "".join(lib[n] for n in used) # stored forms this program composes body = "%s%sdef %s(%s):\n return %s\n" % (IMPORTS, deps, fname, ", ".join(argn), src) # CHECK: execute the RENDERED source (not the in-memory closure) against every example given ns = {} exec(compile(body, "<organ>", "exec"), ns) # noqa: S102 - composed only of library templates W = WRAP[wrap] passed = 0 for a, e in cases: try: out = ns[fname](*a) ok = (W(out) if wrap else out) == e except Exception: # noqa: BLE001 ok = False passed += ok return {"def": body, "fname": fname, "expr": src, "passed": passed, "cases": len(cases), "fn": fnc, "arity": len(argn), "reused": used, "cover": getattr(self, "_cover", None), "req_words": len(getattr(self, "_req_kw", ()) or ()), "n_visible": getattr(self, "_n_visible", None)}
def _oversize(o): if isinstance(o, bool): return False if isinstance(o, int): return abs(o) > 10 ** 12 if isinstance(o, str): return len(o) > 400 if isinstance(o, (list, tuple, set, dict)): return len(o) > 200 or any(_oversize(x) for x in list(o)[:50]) return False
def _compositions(total, k): if k == 1: yield (total,) return for first in range(1, total - k + 2): for rest in _compositions(total - first, k - 1): yield (first,) + rest123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143#!/usr/bin/env python3"""exact_router_v1 - Oracle7's EXACT relation router (runtime form). No similarity, no learned weights: a question is answeredonly when an ADMITTED pattern names the relation it asks and the linked entities agree on one stored value.
Patterns (router_mine_v3, 2026-10-06): (asked noun or wh-word, one content word) -> Wikidata property, mined over 124,000TriviaQA train questions; admitted when the answer given through that property is right >= 90% of the time on BOTH md5halves with >= 8 firings in each (32 patterns, 13 properties). Never-read holdout (TriviaQA train offset 82,000): 33 right,1 wrong (the wrong one was a Wikidata unknown-value blank node - now refused, rule 3 below).Answer: entity_linker_v2 top span -> its candidates (<= 3) -> every candidate carrying the routed property must agree onONE value. Refused: (1) yes/no questions; (2) a hidden hop - an unnamed intermediate between the named entity and theanswer ("an artist who also directed", "the brother-in-law of X"), the guard measured 2026-10-06; (3) blank-node values;(4) every matching pattern must name the SAME property.use: answer(question) -> {"answer", "property", "subject_qid", "pattern"} or None"""import jsonimport re
import entity_linker_v2 as Limport oracle_relstore_v1 as RS
PATTERNS = __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/relstore/router_patterns_v4.json"STORE = __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/relstore/relations_v2.sqlite3"_PATS, _RS = None, Nonenorm = L.normHEAD = re.compile(r"\b(?:which|what)\s+((?:[a-z]+\s+){0,2}?[a-z]+)(?:\s+(?:is|was|are|were|did|does|do|has|had|in|of|for|from|" r"to|by|named|called|founded|created|directed|wrote|won|became)\b|\s*,)", re.I)WH = re.compile(r"\b(who|whom|whose|where|when|which|what|how)\b", re.I)POLAR = re.compile(r"^\s*(is|are|was|were|do|does|did|has|have|had|can|could|will|would|should)\b", re.I)HOP = re.compile(r"\b(a|an|the)\s+([\w'–-]+\s+){0,3}(who|whom|whose|which|that)\b(?!\s*\?)" r"|\b(a|an|the)\s+([\w'–-]+\s+){0,5}(created|directed|written|founded|coached|owned|produced|hosted|led|played|named)\s+by\b" r"|\bthe\s+(illustrator|author|director|founder|creator|wife|husband|father|mother|son|daughter|brother|sister|" r"brother-in-law|sister-in-law|father-in-law|mother-in-law|son-in-law|daughter-in-law|nephew|niece|uncle|aunt|" r"owner|composer|producer|writer|singer|star|team|club|band|company|capital|leader|coach|manager)\s+of\b", re.I)
def _load(): global _PATS, _RS if _PATS is None: _PATS = {tuple(k.split("|", 1)): v[0] for k, v in json.load(open(PATTERNS)).items()} _RS = RS.RelStore() if STORE is None else RS.RelStore(STORE) return _PATS, _RS
def features(q, span): m = HEAD.search(q) head = norm(m.group(1)).split()[-1] if m else None w = WH.search(q) key = head or (w.group(1).lower() if w else "-") ent = set(norm(span).split()) words = {x for x in norm(q).split() if x not in L.STOP and x not in ent and not x.isdigit() and len(x) >= 3} return {(key, x) for x in words} | {(key, "*")}
DOMINANCE = 10 # a name whose top sense is >= 10x more linked refers to it
def hop(q, span): """a hidden hop - but "the capital of France" is no hop when France is the named entity right after "of" """ for m in HOP.finditer(q): if m.group(0).lower().endswith(" of"): after = norm(q[m.end():]) if after.startswith(norm(span)) or after.startswith("the " + norm(span)): continue return True return False
# the store holds CURRENT values: a past-time qualifier on a relation that changes over time is not answerable from itTIME_VARIANT = {36, 35, 6, 54, 159, 27, 17, 131, 286, 488, 1037, 108, 39, 463, 102, 26}PAST = re.compile(r"\b(between|until|till|before|after|during|in|from|by)\s+(the\s+)?(\d{3,4}s?|\d{1,2}(st|nd|rd|th)\s+century)\b" r"|\b(formerly|former|originally|once|previously|ancient|old)\b", re.I)QUOTED = re.compile(r"[‘“\"']([^’”\"']{3,80})[’”\"']")
def subject_ok(q, span): """the linked span must be the question's subject: a quoted title must BE the span; a later "of <Name>" means the subject is further along the "of" chain ("the capital of the U.S. state of Connecticut")""" s = q.strip() if len(s) > 2 and s[0] == '"' and s[-1] == '"': s = s[1:-1] # CSV-wrapped question: "Who ... ""Citizen Kane""?" m = QUOTED.search(s.replace('""', '"')) if m and norm(m.group(1)) != norm(span): return False i = q.find(span) if i >= 0 and re.search(r"\bof\s+(the\s+)?[A-Z]", q[i + len(span):]): return False return True
def answer(q): pats, rs = _load() q = str(q) if POLAR.search(q): return None sp = L.link(q, 3) if not sp: return None span, cs = sp[0] if hop(q, span) or not subject_ok(q, span): return None if DOMINANCE and len(cs) > 1 and cs[0][1] >= DOMINANCE * max(1, max(c[1] for c in cs[1:])): cs = cs[:1] matched = {f: pats[f] for f in features(q, span) if f in pats} props = set(matched.values()) if len(props) != 1: return None p = props.pop() if p in TIME_VARIANT and PAST.search(q): return None sets, subj = [], None for qid, _, _ in cs[:3]: vals = {rs.label(o) if o else lit for pp, o, lit in rs.props_of(qid) if pp == p} vals = {v for v in vals if v and ".well-known/genid" not in v} if vals: sets.append(frozenset(vals)) subj = subj or qid if not sets or len(set(sets)) != 1 or len(sets[0]) != 1: return None aw = [w for w in norm(next(iter(sets[0]))).split() if w not in L.STOP] if aw and all(w in set(norm(q).split()) for w in aw): return None # the answer restates the question: not an answer return {"answer": _show(next(iter(sets[0])), q), "property": p, "subject_qid": subj, "pattern": "|".join(sorted(matched)[0])}
MONTHS = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
def _show(v, q): """a stored time "1034-03-27T00:00:00Z" reads as "1034" when the year is asked, else "27 March 1034"; BCE years keep their sign as "BC" """ m = re.match(r"^([+-]?)(\d{1,4})-(\d\d)-(\d\d)T", v) if not m: return v y = str(int(m.group(2))) + (" BC" if m.group(1) == "-" else "") if re.search(r"\byear\b", q, re.I) or m.group(3) == "00" or (m.group(3) == "01" and m.group(4) == "01"): return y return "%d %s %s" % (int(m.group(4)), MONTHS[int(m.group(3)) - 1], y)
if __name__ == "__main__": import sys for q in sys.argv[1:]: print(q, "->", answer(q))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471#!/usr/bin/env python3"""general_reader_v1 - a relation reader that does not depend on how a question is phrased (Box C).For a question the release declines: find the entities it names (exact Wikipedia titles), read every fact one step from them inthe Wikidata relation store, and answer ONLY when all three agree: (1) CUE - the relation is named by the question's own words (property label stems, or a measured router cue pair) (2) TYPE - the answer is the kind of thing asked for (who -> a person; where -> a place; "which comedian" -> a comedian) (3) UNIQUE- exactly one candidate survives (two different answers -> decline)The answer is never an entity the question itself names. Every answer carries its receipt (subject, property, value, ids).usage (dev measurement): general_reader_v1.py eval <trivia json ...> | general_reader_v1.py ask "<question>" """import jsonimport reimport sqlite3import sysimport unicodedata
STORE = __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/relstore/relations_v2.sqlite3"db = sqlite3.connect("file:%s?mode=ro&immutable=1" % STORE, uri=True, check_same_thread=False)
STOP = set("a an the of in on at to for by with from and or is was were are be been being who whom whose what which when where why how " "did does do has have had this that these those it its he she they his her their as into than then there here one".split())AUX = set("is was were are did does do has have had can could will would should may might".split())HUMAN_Q = ("who", "whom", "whose")PLACE_WORDS = set("city town village country state province region county island capital place municipality commune borough " "district settlement port river mountain lake sea ocean continent area".split())GENERIC_TYPE = set("one name person people thing year type kind part title area word term number".split())# qualifiers the reader cannot evaluate from one fact: order, extremes, time, fiction or a work's own worldQUALIFIER = re.compile(r"\b(first|last|only|second|third|fourth|fifth|oldest|youngest|largest|smallest|biggest|longest|shortest|" r"highest|lowest|tallest|most|least|best|worst|original|former|current|currently|previous|next|latest|earliest|" r"famous|famously|nicknamed|known as|better known|called|real name|in the (?:bible|film|movie|novel|book|play|" r"series|show|song|opera|musical|game|tv|story|poem|legend)|in (?:greek|roman|norse) mythology|" r"(?:1[0-9]|20)[0-9]{2}|century|decade|year|when|during|at the time|outbreak|battle|war|preceded|succeeded|before|after|" r"between|same|other|also|both|nickname|setting|set in|according to)\b", re.I)
PROP, PROPNAMES = {}, {}for p, lab in db.execute("SELECT p, label FROM prop_src"): if lab: PROP[p] = labfor line in open(__import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/relstore/prop_labels.tsv", encoding="utf-8"): m = re.match(r'<http://www\.wikidata\.org/entity/P(\d+)>\t"(.*)"@en', line.strip()) if m: p = int(m.group(1)) PROPNAMES.setdefault(p, []).append(m.group(2)) # the file holds the label AND its aliases, one per line PROP.setdefault(p, m.group(2))# everyday words for common relations (question wording differs from Wikidata's label); measured on dev like everything elseALIASES = {26: "married marry wife husband spouse", 25: "mother", 22: "father", 3373: "sister brother sibling", 40: "son daughter child", 50: "writer author novelist", 57: "directed director", 86: "composed composer music", 170: "created creator", 112: "founded founder", 36: "capital", 19: "born birthplace", 20: "died death", 569: "born", 570: "died", 175: "singer performer", 161: "starred", 69: "studied attended educated", 108: "worked employer", 54: "played team", 166: "won awarded award", 131: "located situated", 138: "named", 37: "language spoken official", 38: "currency", 6: "prime minister mayor premier", 35: "president king queen monarch emperor", 27: "nationality citizen", 800: "known work", 61: "discovered discoverer", 397: "orbits orbit", 30: "continent", 140: "religion", 102: "party", 127: "owned owner owns", 176: "made built manufactured manufacturer", 84: "designed architect", 674: "characters character", 1441: "appears appear", 136: "genre", 264: "label", 98: "edited editor", 162: "produced producer", 58: "screenplay screenwriter", 710: "participant participated", 1346: "won winner", 17: "country", 495: "country", 159: "headquarters based", 740: "formed", 571: "founded established formed", 576: "dissolved abolished", 1037: "director manager", 488: "chairman chairperson", 169: "chief executive ceo", 286: "head coach manager", 451: "partner", 1038: "relative", 1327: "partner", 413: "position played", 118: "league", 641: "sport", 115: "home stadium ground venue", 361: "part", 150: "contains", 206: "located", 1376: "capital"}ALIAS_STEMS = {}try: ALLOW = set(json.load(open(__import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/relstore/reader_prop_allowlist.json"))) # relations the admitted relation specialists readexcept Exception: # noqa: BLE001 ALLOW = set()ALLOW -= {102, 1082} # party membership changes; population is a numberSKIP_PROPS = {21, 971, 735, 734, 1343, 910, 4224, 1889, 31, 279, 373, 646, 214, 227, 244, 213, 268, 269, 349, 434, 435, 436, 1006, 1015, 1017, 1263, 2671, 3417, 5008, 1424, 1151, 1792, 3876, 361, 527, 5869, 2184, 8402, 1482, 3222}
def norm(s): s = unicodedata.normalize("NFKD", str(s)).encode("ascii", "ignore").decode("ascii") return " ".join(re.sub(r"[^a-z0-9 ]+", " ", s.lower()).split())
def stem(w): w = w.lower() if w.endswith("ied") and len(w) <= 5: # died -> die, lied -> lie return w[:-1] for suf in ("ations", "ation", "ings", "ing", "ers", "ors", "er", "or", "ed", "es", "s", "ion"): if len(w) > len(suf) + 3 and w.endswith(suf): return w[: -len(suf)] return w
_lab, _cls = {}, {}
def label(q): if q not in _lab: r = db.execute("SELECT label, enwiki FROM entity WHERE qid=?", (q,)).fetchone() _lab[q] = (r[0] or r[1]) if r else None return _lab[q]
def classes(q): if q in _cls: return _cls[q] out, frontier, seen = set(), [o for (o,) in db.execute("SELECT o FROM fact WHERE s=? AND p=31", (q,)) if o], set() for d in range(2): # its class and one parent: higher superclasses name things it is not nxt = [] for c in frontier: if c in seen: continue seen.add(c) lab = label(c) if lab: ws = norm(lab).split() if ws: out.add(ws[-1]) # head noun: "town in Finland" is a town, not a Finland if d < 1: nxt += [o for (o,) in db.execute("SELECT o FROM fact WHERE s=? AND p=279", (c,)) if o] frontier = nxt _cls[q] = out return out
_cls0 = {}GEO_SYN = {"country": "country state kingdom republic nation monarchy federation empire principality sultanate emirate", "city": "city town capital metropolis municipality borough commune", "town": "town city municipality borough commune village", "state": "state province", "county": "county shire", "island": "island atoll", "river": "river stream tributary", "mountain": "mountain peak volcano massif summit", "lake": "lake reservoir", "sea": "sea", "ocean": "ocean"}GEO_SYN = {stem(k): set(stem(x) for x in v.split()) for k, v in GEO_SYN.items()}
def classes0(q): """head nouns of the thing's own classes (P31 only): a city is a city, not the country its classes sit under""" if q not in _cls0: out = set() for (o,) in db.execute("SELECT o FROM fact WHERE s=? AND p=31", (q,)): lab = label(o) if o else None ws = norm(lab).split() if lab else [] if ws: out.add(stem(ws[-1])) _cls0[q] = out return _cls0[q]
def is_human(q): return db.execute("SELECT 1 FROM fact WHERE s=? AND p=31 AND o=5 LIMIT 1", (q,)).fetchone() is not None
def ent(title): t = title.strip(" .,'\"") if not t: return None for v in dict.fromkeys((t, t[:1].upper() + t[1:], " ".join(w[:1].upper() + w[1:] for w in t.split()))): r = db.execute("SELECT qid FROM entity WHERE enwiki=? LIMIT 1", (v,)).fetchone() if r: return r[0] return None
def linked(q): words = re.findall(r"[A-Za-z0-9'\-\.&]+", q.replace('"', " ")) taken, out = set(), [] for n in (6, 5, 4, 3, 2, 1): for i in range(len(words) - n + 1): if any(j in taken for j in range(i, i + n)): continue span = words[i:i + n] if span[0].lower() in STOP or span[-1].lower() in STOP: continue if n == 1 and (not span[0][:1].isupper() or i == 0 or len(span[0]) < 3): continue if all(w.lower() in STOP for w in span): continue before = words[i - 1] if i > 0 else "" after = words[i + n] if i + n < len(words) else "" if (after[:1].isupper() and after.lower() not in STOP) or (i > 1 and before[:1].isupper() and before.lower() not in STOP): continue # part of a longer name ("Andrew Bonar" in "Andrew Bonar Law") qid = ent(" ".join(span)) if qid: out.append((" ".join(span), qid)) taken.update(range(i, i + n)) return out
def asked_type(q): ql = q.lower().strip() w = re.findall(r"[a-z]+", ql) if not w: return None, set() if w[0] in HUMAN_Q or " who " in " " + ql[:40] or re.search(r"\bto whom\b|\bwhom\b", ql): return "human", set() m = re.search(r"\b(?:which|what)\s+((?:[a-z\-]+\s+){0,2}?[a-z\-]+)\s*\?\s*$", ql) # "... the sister of which actor?" if m: nouns = set(stem(x) for x in m.group(1).split() if x not in STOP and x not in GENERIC_TYPE) if nouns: return "noun", nouns m = re.match(r"(?:in )?(?:which|what) (city|town|country|state|county|island|river|mountain|lake|sea|ocean)\b", ql) if m: return "noun", {stem(m.group(1))} if w[0] == "where": return "place", set() if w[0] == "when" or re.match(r"(in )?(what|which) year", ql): return "time", set() if re.match(r"how (many|much|long|old|far|tall|high)", ql): return "number", set() m = re.match(r"(?:what|which|who) (?:is|was|are|were) the ([a-z\-]+(?: [a-z\-]+)?) of\b", ql) # "what is the capital of ..." if m: head = m.group(1).split()[-1] if head not in STOP and head not in GENERIC_TYPE: return "rel", {stem(head)} m = re.search(r"\b(which|what)\s+((?:[a-z\-]+\s+){0,3}?)([a-z\-]+)\s+(?:" + "|".join(AUX) + r"|[a-z]+ed|[a-z]+s)\b", ql) if m: nouns = set(stem(x) for x in (m.group(2) + " " + m.group(3)).split() if x not in STOP and x not in GENERIC_TYPE) if nouns: return "noun", nouns return None, set()
_pw = {}
def prop_words(p): if p not in _pw: s = set() for name in PROPNAMES.get(p, [PROP.get(p, "")]): ws = [stem(x) for x in norm(name).split() if x not in STOP and len(x) > 2] if 0 < len(ws) <= 3: # long descriptive aliases are not cues s.update(ws) _pw[p] = s return _pw[p]
# words too loose to name a relation on their own (dev 10-14): "wrote" fits author, lyricist and publisher; "song" fits lyricist;# "found" (in "found in the museum") stems like "founded"STOPCUE = {stem(x) for x in ("write wrote written writ song songs theme found find make made play played sing sang known book books " "music musical film films movie movies national").split()}
def cued(p, qwords_stem, qwords): qwords_stem = qwords_stem - STOPCUE if prop_words(p) & qwords_stem: return True if p not in ALIAS_STEMS: ALIAS_STEMS[p] = set(stem(x) for x in ALIASES.get(p, "").split()) if ALIAS_STEMS[p] & qwords_stem: return True return False # cue pairs dropped: "which|city" is not a relation (dev 10-14)
FEMININE = {"actress": "actor", "authoress": "author", "poetess": "poet", "comedienne": "comedian", "sculptress": "sculptor", "heroine": "hero", "princess": "prince", "duchess": "duke", "empress": "emperor", "songstress": "singer"}
def type_ok(kind, nouns, cand_qid, lit, p=None): if kind == "rel": # the relation noun itself ("capital") must be the property: named by the property's own label or aliases return p is not None and bool(prop_words(p) & nouns) and (cand_qid is not None or lit is not None) if kind == "time": return lit is not None and bool(re.search(r"\b1?\d{3,4}\b", str(lit))) if cand_qid is None: return False if kind == "human": return is_human(cand_qid) if kind == "place": return bool(classes(cand_qid) & PLACE_WORDS) if kind == "noun": nouns = set(stem(FEMININE.get(x, x)) for x in nouns) | nouns cw = set(stem(x) for x in classes(cand_qid)) if "person" in nouns or "man" in nouns or "woman" in nouns: return is_human(cand_qid) geo = [n for n in nouns if n in GEO_SYN] if geo: # "which country": Nairobi is a city (held-out 10-14: Peter Hain) return any(classes0(cand_qid) & GEO_SYN[n] for n in geo) return bool(cw & nouns) or (is_human(cand_qid) and bool(nouns & occupations(cand_qid))) return False
_occ = {}
def occupations(q): if q not in _occ: s = set() for (o,) in db.execute("SELECT o FROM fact WHERE s=? AND p IN (106, 39) LIMIT 30", (q,)): if o and label(o): ws = norm(label(o)).split() if ws: s.add(stem(ws[-1])) # the head noun only: "film score composer" is a composer _occ[q] = s return _occ[q]
_gen = {}
def generic(e): """a class or concept, not a particular thing: it is a subclass of something, or many things are instances of it""" if e not in _gen: sub = db.execute("SELECT 1 FROM fact WHERE s=? AND p=279 LIMIT 1", (e,)).fetchone() is not None inst = len(db.execute("SELECT s FROM fact WHERE p=31 AND o=? LIMIT 30", (e,)).fetchall()) >= 30 occ = len(db.execute("SELECT s FROM fact WHERE p=106 AND o=? LIMIT 30", (e,)).fetchall()) >= 30 _gen[e] = sub or inst or occ return _gen[e]
_word_props = None
def inv_props(qwords_stem, qwords): """properties whose label/alias words or cue pairs appear in the question (index built once; was a scan of 38k per entity)""" global _word_props if _word_props is None: _word_props = {} for p in set(PROPNAMES) | set(PROP): if p in SKIP_PROPS: continue for w in prop_words(p) | set(stem(x) for x in ALIASES.get(p, "").split()): _word_props.setdefault(w, set()).add(p) ps = set() for w in qwords_stem - STOPCUE: ps |= _word_props.get(w, set()) ps = [p for p in ps if db.execute("SELECT 1 FROM fact WHERE p=? LIMIT 1", (p,)).fetchone()] return ps[:60]
SHORT_NAMES = {"uk": 145, "u k": 145, "britain": 145, "great britain": 145, "us": 30, "u s": 30, "usa": 30, "u s a": 30, "america": 30, "ussr": 15180, "soviet union": 15180, "uae": 878, "eu": 458, "holland": 55}
def echoed(q, val, ans): """the answer is already in the question: by its label, or by a common short name (dev-burned held-out 10-14: "Where are Akrotiri and Dhekelia, allocated by treaty to the UK" read the holder, the UK, as the place)""" qn = " %s " % norm(q) words = [w for w in norm(ans).split() if w not in STOP and w not in ("the", "of")] if words and all(" %s " % w in qn for w in words): return True return val is not None and any(" %s " % k in qn and v == val for k, v in SHORT_NAMES.items())
QWORDS = set("who whom whose what which where when why how in on at of the a an is was were are did does do name".split())
def unlinked_name(q, links): """a capitalised name or a quoted title in the question that no linked span covers""" covered = set() for t, _ in links: covered.update(w.lower() for w in re.findall(r"[A-Za-z0-9']+", t)) for quoted in re.findall(r"[\"“]([^\"”]{2,80})[\"”]", q): if not any(quoted.lower() in t.lower() or t.lower() in quoted.lower() for t, _ in links): return True words = re.findall(r"[A-Za-z][A-Za-z0-9'\-]*", q) for i, w in enumerate(words): if i == 0 or not w[:1].isupper() or w.lower() in QWORDS or w.lower() in STOP: continue if w.lower() not in covered: return True return False
def answer(q): if QUALIFIER.search(q): return None kind, nouns = asked_type(q) if kind in (None, "number"): return None ents = [(t, e) for t, e in linked(q) if not generic(e)] if not ents: return None if unlinked_name(q, linked(q)): return None # held-out 10-14: Jennings Brewery -> read Cumbria; Dismaland -> Banksy if q.count(",") >= 2 or (re.search(r"\band\b", q) and len(ents) >= 2): return None # several clues joined: one fact cannot answer it if kind == "rel": m = re.search(r"\bof (?:the )?(.+?)(?:\?|$| in | on | at )", q) if not m: return None first = [(t, e) for t, e in ents if m.group(1).lower().startswith(t.lower())] if not first: return None ents = first[:1] # "the capital of the Yukon Territory in Canada": the Yukon, not Canada named = {qid for _, qid in ents} qwords = set(re.findall(r"[a-z]+", q.lower())) qwords_stem = set(stem(x) for x in qwords if x not in STOP) if kind == "noun": qwords_stem -= nouns # the answer-type word is not the relation ("which country ... headquarters") cands = {} for span, e in ents: for p, o, lit in db.execute("SELECT p, o, lit FROM fact WHERE s=? LIMIT 4000", (e,)): if p in SKIP_PROPS or p not in ALLOW or (o is not None and o in named): continue if o is not None and (label(o) or "").startswith("Category:"): continue if not cued(p, qwords_stem, qwords): continue if type_ok(kind, nouns, o, lit, p): key = ("q", o) if o is not None else ("l", str(lit)) cands.setdefault(key, []).append((e, p, "fwd")) for p in [x for x in inv_props(qwords_stem, qwords) if x in ALLOW]: # reverse answers only when the relation's MAIN name is in the question: aliases such as "mother of" on the # child relation describe the relation backwards (dev 10-14: "mother of Achilles") main = set(stem(x) for x in norm(PROP.get(p, "")).split() if x not in STOP and len(x) > 2) if not (main & qwords_stem): continue subs = [s for (s,) in db.execute("SELECT s FROM fact WHERE p=? AND o=? LIMIT 6", (p, e))] if len(subs) > 5: # a big group (everyone who received an award): no reverse answer continue for s in subs: if s in named: continue if type_ok(kind, nouns, s, None, p): cands.setdefault(("q", s), []).append((e, p, "inv")) if len(cands) != 1: return None (kt, val), why = next(iter(cands.items())) if len(ents) >= 2 and len({w[0] for w in why}) < 2: # two or more named things: at least two must agree (held-out return None # 10-14: Jennings Brewery -> Cumbria's capital, Dismaland -> Banksy) if False: return None e, p, d = why[0] ans = label(val) if kt == "q" else val if not ans: return None if echoed(q, val if kt == "q" else None, ans): return None # the question already names it ("allocated to the UK": not where it is) if d == "fwd": receipt = "%s (Q%d) - %s (P%d) - %s" % (label(e), e, PROP.get(p, ""), p, ("%s (Q%d)" % (ans, val)) if kt == "q" else ans) else: receipt = "%s (Q%d) - %s (P%d) - %s (Q%d)" % (ans, val, PROP.get(p, ""), p, label(e), e) return {"answer": ans, "receipt": receipt, "prop": p, "dir": d, "kind": kind, "agree": len(why)}
def correct(ans, golds): """exact match after normalising, or one contains the other as whole words ("Lake Mead" / "Mead", "The Dirham" / "United Arab Emirates dirham"); articles dropped""" drop = lambda s: " ".join(w for w in norm(s).split() if w not in ("the", "a", "an")) a = drop(ans) for g in (drop(x) for x in golds if x): if not g: continue if a == g: return True if len(g) >= 4 and re.search(r"\b%s\b" % re.escape(g), a): return True if len(a) >= 4 and re.search(r"\b%s\b" % re.escape(a), g): return True return False
if __name__ == "__main__": if sys.argv[1] == "ask": print(json.dumps(answer(sys.argv[2]), indent=1)) sys.exit() import multiprocessing as mp
def one(item): q, golds = item try: r = answer(q) except Exception as e: # noqa: BLE001 return ("err", q[:80], str(e)[:80]) if not r: return None return ("right" if correct(r["answer"], golds) else "wrong", q[:110], r["answer"], golds[:2], r["receipt"][:130], r["kind"])
items = [it for f in sys.argv[2:] for it in json.load(open(f))] cnt = {"right": 0, "wrong": 0, "err": 0} rows = [] with mp.Pool(6) as pool: for i, res in enumerate(pool.imap_unordered(one, items, chunksize=4), 1): if res: cnt[res[0]] += 1 rows.append(res) if i % 250 == 0: print("progress %d/%d right %d wrong %d" % (i, len(items), cnt["right"], cnt["wrong"]), flush=True) fired = cnt["right"] + cnt["wrong"] print("questions %d fired %d right %d wrong %d errors %d precision %.3f" % (len(items), fired, cnt["right"], cnt["wrong"], cnt["err"], cnt["right"] / max(1, fired))) for r in rows: if r[0] != "right": print(" ", r[0].upper(), r[1:]) json.dump(rows, open("/root/w240/coverage_eval_last.json", "w"), indent=0)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508"""math_organ_v2 - v1 (admitted in w480, now immutable) + two fixes found on the gate panel: "factorial" is not arequest to factor, and a request for a PROGRAM is the code organ's, not a mathematical request.
exact mathematics as specified free moves, every result independently checked, the method cited.
REQUEST directive (solve / simplify / factor / expand / evaluate / differentiate / integrate / limit / decompose) + the expression(s), read from the question or from its exercise set's instructionMOVES SymPy operations legal for that directive and that expression's typeCHECK independent of the move that produced the answer: solve every solution substituted back satisfies every equation / inequality factor the product expands back to the input, and is a product simplify equivalent to the input at random points, and no more complex than the input evaluate recomputed by direct numeric substitution derivative agrees with a central difference at random points integral differentiates back to the integrand (definite: numeric quadrature agrees) limit agrees with evaluation near the pointSTORED FORM the textbook's own method for the directive (a howto or a worked example, textbook_store_v1) is citedNothing is asserted unless the check passes; a failed check is an abstention with the reason."""from __future__ import annotations
import randomimport reimport sqlite3
import sympy as spfrom sympy.parsing.sympy_parser import (convert_xor, implicit_multiplication_application, parse_expr, split_symbols_custom, standard_transformations)
STORE = __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/textbooks/textbook_store_v1.sqlite3"FUNCS = {"sin", "cos", "tan", "sec", "csc", "cot", "log", "ln", "exp", "sqrt", "root", "asin", "acos", "atan", "abs", "sinh", "cosh", "tanh", "pi", "oo", "theta", "alpha", "beta", "gamma", "Delta", "lambda", "mu", "sigma", "omega", "phi", "rho", "tau", "epsilon", "arcsin", "arccos", "arctan"}LOCAL = {"e": sp.E, "pi": sp.pi, "ln": sp.log, "log": sp.log, "root": lambda x, n: sp.root(x, n), "oo": sp.oo, "arcsin": sp.asin, "arccos": sp.acos, "arctan": sp.atan, "abs": sp.Abs, "theta": sp.Symbol("theta")}
def _split_ok(name): return name not in FUNCS and not name.startswith(("theta", "alpha", "beta", "gamma", "Delta", "lambda", "omega"))
TRANSF = standard_transformations + (split_symbols_custom(_split_ok), implicit_multiplication_application, convert_xor)DIRECTIVES = [ ("partial", r"partial fraction|decomposition"), ("derivative", r"\bderivative|differentiate|\bf'\(|d/dx|dy/dx"), ("integral", r"\bintegra(l|te)|antiderivative"), ("limit", r"\blimit|\blim_"), ("factor", r"\bfactor(?!ial)"), # v2: "factorial" is not a request to factor ("solve", r"\bsolve|\bsolution|find (?:the )?(?:value|zeros?|roots?)\b|\bfind x\b"), ("evaluate", r"\bevaluate|\bfind f\(|\bcompute|\bcalculate|\bwhat is\b|\bhow much is\b"), ("expand", r"\bmultiply|\bexpand|\bdistributive"), ("simplify", r"\bsimplif|\badd\b|\bsubtract|\bdivide|\bcombine|\breduce"),]
def clean_linear(s): s = s.replace("−", "-").replace("×", "*").replace("·", "*").replace("÷", "/").replace("^", "**") s = re.sub(r"(\d),(\d{3})\b", r"\1\2", s) s = re.sub(r"\s+", " ", s).strip().rstrip(".?,;") return s
def P(s, syms=None): s = clean_linear(s) s = re.sub(r"\bsqrt\s*\(", "sqrt(", s) return parse_expr(s, local_dict=dict(LOCAL, **(syms or {})), transformations=TRANSF, evaluate=True)
def directive_of(text): t = (text or "").lower() for name, rx in DIRECTIVES: if re.search(rx, t): return name return None
ENGLISH = {"of", "to", "is", "by", "at", "in", "on", "if", "an", "as", "the", "and", "for", "use", "let", "all", "are", "its", "how", "not", "or", "be", "it", "we", "find", "when", "each", "given", "then", "from", "with", "that", "this", "what", "which", "where", "your", "you", "into", "using", "value", "values", "following", "exercises", "expression", "expressions", "equation", "equations", "simplify", "solve", "factor", "evaluate", "multiply", "divide", "add", "subtract", "completely", "polynomial", "form", "write", "answer", "result", "greatest", "common", "number", "numbers", "term", "terms", "exact", "calculator", "round", "rule", "any", "one", "two", "has", "can", "our", "was", "per", "sum", "set", "get", "may", "see", "new", "own", "way", "out"}TOK = re.compile(r"[A-Za-z]+|\d+(?:\.\d+)?|\*\*|<=|>=|!=|->|\+-|[-+*/^=<>(){}\[\],|_;'!]|\.(?=\d)|\.|\s+")
def _is_math_word(w, prev, nxt): lw = w.lower() if lw in FUNCS or w == "C": return True if lw in ENGLISH: return False if len(w) == 1: return not (w in ("a", "A", "I") and nxt.isspace() and prev in ("", " ")) return len(w) <= 3 # implicit products "xy", "ah", "abc"
FUNC_RX = r"(sqrt|sin|cos|tan|sec|csc|cot|log|ln|exp)"
def normalize_request(text): """surface conventions -> linear mathematics: '2xsqrt(48)' -> '2x sqrt(48)', degrees, log bases, imaginary unit""" t = text or "" t = re.sub(r"(?<=[a-z0-9)])%s(?=[\s(])" % FUNC_RX, r" \1", t) # xsqrt( -> x sqrt( t = re.sub(r"(\d+(?:\.\d+)?)\s*°", r"(\1*pi/180)", t) # 120° -> radians t = re.sub(r"\blog\s*_\s*\{?(\d+)\}?\s*\(?([^()\s]+)\)?", r"log(\2,\1)", t) # log_5 25 -> log(25,5) if re.search(r"\bcomplex|\bimaginary|\d\s*i\b|[-+]\s*\d*\s*i\)", t, re.I): t = re.sub(r"(?<![A-Za-z])i(?![A-Za-z])", "I", t) # the imaginary unit return t
WORD_PROBLEM_WORDS = 7
def english_load(text): words = [w for w in re.findall(r"[A-Za-z]{3,}", text or "") if w.lower() not in ENGLISH and w.lower() not in FUNCS] return len(words)
def extract_math(text): """maximal runs of mathematical tokens (numbers, operators, brackets, variables, function names); English, a colon and a sentence end break a run""" toks = [m.group(0) for m in TOK.finditer((text or "").replace(":", " . "))] spans, cur = [], [] for i, t in enumerate(toks): prev = toks[i - 1] if i else "" nxt = toks[i + 1] if i + 1 < len(toks) else "" ok = _is_math_word(t, prev, nxt) if t.isalpha() else (t != ".") if ok: cur.append(t) else: if cur: spans.append("".join(cur)) cur = [] if cur: spans.append("".join(cur)) out = [] for s in spans: s = s.strip(" ,;:") s = re.sub(r"\|\s*([^|]+?)\s*\|", r"Abs(\1)", s) if s and (re.search(r"[0-9]", s) or re.search(r"[=^+*/<>()]", s)) and re.search(r"[a-z0-9]", s): out.append(s) return out
def assignments(text): """'when a=-4, b=6' / 'for x = 2 and y = 3' -> {a: -4, b: 6}""" out = {} m = re.search(r"\b(?:when|for|if|with|where|at)\s+((?:[a-z]\s*=\s*[-+]?[0-9./()]+\s*(?:,|\band\b)?\s*)+)", text or "") if m: for v, val in re.findall(r"\b([a-z])\s*=\s*([-+]?[0-9./()]+)", m.group(1)): try: out[sp.Symbol(v)] = P(val) except Exception: # noqa: BLE001 pass return out
def target_var(text): m = re.search(r"\bfor\s+([a-z])\b(?!\s*=)", text or "") return sp.Symbol(m.group(1)) if m else None
def rounding(text): t = (text or "").lower() m = re.search(r"round(?:ed)?\s+(?:your answer\s+)?to\s+(?:the\s+nearest\s+)?(\w+)", t) if not m: return None return {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "tenth": 1, "hundredth": 2, "thousandth": 3, "whole": 0, "integer": 0, "1": 1, "2": 2, "3": 3, "4": 4}.get(m.group(1))
def binary_phrase(text): """'the difference of A and B' -> (A)-(B); sum / product / quotient likewise; 'subtract A from B' -> (B)-(A)""" m = re.search(r"\bsubtract\s+(.+?)\s+from\s+(.+?)(?:\.\s|\.$|$)", text or "", re.I) if m: a, b = extract_math(m.group(1)), extract_math(m.group(2)) return "(%s)-(%s)" % (b[0], a[-1]) if a and b else None m = re.search(r"\b(sum|difference|product|quotient) of (.+?) and (.+?)(?:\.\s|\.$|$)", text or "", re.I) if not m: return None op = {"sum": "+", "difference": "-", "product": "*", "quotient": "/"}[m.group(1).lower()] a, b = extract_math(m.group(2)), extract_math(m.group(3)) return "(%s)%s(%s)" % (a[-1], op, b[0]) if a and b else None
def complexity(e): return sp.count_ops(e, visual=False) + len(str(e)) / 40.0
def rand_pts(syms, k=5): rng = random.Random(7) return [{s: sp.Rational(rng.randint(2, 29), rng.randint(3, 11)) for s in syms} for _ in range(k)]
def equiv(a, b): try: d = sp.simplify(a - b) if d == 0: return True syms = sorted((a.free_symbols | b.free_symbols), key=str) for pt in rand_pts(syms): va, vb = complex(a.subs(pt).evalf()), complex(b.subs(pt).evalf()) if abs(va - vb) > 1e-7 * max(1.0, abs(va)): return False return True except Exception: # noqa: BLE001 return False
class MathOrgan: def __init__(self, store=STORE): try: self.db = sqlite3.connect("file:%s?mode=ro" % store, uri=True, check_same_thread=False) except Exception: # noqa: BLE001 self.db = None self.why = ""
# ------------------------------------------------------------------ the stored form (method citation) def method(self, directive, hint=""): if not self.db: return None words = {"solve": "solve equation", "simplify": "simplify expression", "factor": "factor", "expand": "multiply", "evaluate": "evaluate", "derivative": "derivative", "integral": "integral", "limit": "limit", "partial": "partial fraction decomposition"}[directive] q = " OR ".join(w for w in words.split()) try: r = self.db.execute("SELECT item.book, item.section, item.title, item.kind, item.id FROM item_fts JOIN item " "ON item.id = item_fts.rowid WHERE item_fts MATCH ? AND item.kind IN ('howto','example') " "ORDER BY (item.kind='howto') DESC, rank LIMIT 1", ("title:(%s)" % q,)).fetchone() except Exception: # noqa: BLE001 r = None return {"book": r[0], "section": r[1], "title": r[2], "kind": r[3], "id": "tb:%d" % r[4]} if r else None
# ------------------------------------------------------------------ the solve def answer(self, question, instruction=None): self.why = "" # v2: a request for a PROGRAM ("write a Python function that returns the factorial ...") is the code organ's if re.search(r"\b(?:write|make|create|implement|code)\b.*\b(?:function|program|script|method)\b", question or "", re.I): self.why = "a request for a program, not for a mathematical result" return None # v1 reads LINEAR notation (the textbook store's form, and what people type). Typeset LaTeX ($...$, \frac, # \sqrt{}) is declined until a LaTeX reader exists: reading it with the linear reader would be luck, not reading. if re.search(r"\$|\\(?:frac|sqrt|cdot|left|right|begin|dfrac|tfrac|pi|times)\b", question or ""): self.why = "typeset (LaTeX) mathematics: this organ reads linear notation only" return None question = normalize_request(question) d = directive_of(question) or directive_of(instruction or "") # a WORD PROBLEM needs language -> equations (a later organ); reading numbers out of prose is guessing body = question[len(instruction):] if instruction and question.startswith(instruction) else question if english_load(body) > WORD_PROBLEM_WORDS: self.why = "a word problem: the quantities must be translated into equations first" return None bp = binary_phrase(question) spans = [bp] if bp else extract_math(question) # a request whose only mathematics is a bare number names an operation this organ does not hold # ("the lcm of 73 and 230", "452 in base 7", "803 in roman numerals"): echoing the number would be a guess if not any(re.search(r"[-+*/^=<>()]|[a-z]", s_) for s_ in spans): self.why = "no expression to operate on: the request names an operation this organ does not hold" return None if re.search(r"\b(?:lcm|gcd|gcf|base\s+\d|roman|numerals?|binary|hexadecimal|octal|convert|km|miles?|yards?|feet|" r"inch(?:es)?|meters?|kilograms?|pounds?|percent|%)\b", question, re.I) and d in ("evaluate", "simplify"): self.why = "a named operation or unit this organ does not hold" return None defined = {m.group(1) for s_ in spans for m in [re.match(r"^\s*([a-zA-Z])\s*\(\s*[a-z]\s*\)\s*=", s_)] if m} used = {m.group(1) for s_ in spans for m in re.finditer(r"(?<![A-Za-z])([fghFGHpqr])\(\s*[-a-z0-9]", s_)} if used - defined: self.why = "the request uses a function it does not define" return None if not spans: self.why = "no mathematics in the request" return None if not d: d = "solve" if any("=" in s or "<" in s or ">" in s for s in spans) else "simplify" try: res = getattr(self, "_" + d)(spans, question) except Exception as e: # noqa: BLE001 self.why = "%s failed: %s" % (d, repr(e)[:80]) return None if not res: self.why = self.why or "%s: no checked result" % d return None nd = rounding(question) if nd is not None and isinstance(res.get("value"), sp.Basic) and res["value"].is_number: v = round(float(res["value"].evalf()), nd) res["value"], res["answer"] = sp.Float(v), ("%d" % v if nd == 0 else ("%." + str(nd) + "f") % v) res["steps"] = res.get("steps", []) + ["round to %d decimal place%s" % (nd, "" if nd == 1 else "s")] res["directive"] = d res["method"] = self.method(d) return res
# --- solve: equations, inequalities, systems ------------------------------------------------------------------ def _solve(self, spans, q): eqs = [] for s in spans: for part in re.split(r";|\band\b", s): part = part.strip() m = re.match(r"^(.*?)(<=|>=|<|>|=)(.*)$", part) if not m: continue lhs, op, rhs = m.groups() if not lhs.strip() or not rhs.strip(): continue L_, R_ = P(lhs), P(rhs) eqs.append((L_, op, R_)) if not eqs: return None syms = sorted(set().union(*[(a.free_symbols | b.free_symbols) for a, _, b in eqs]), key=str) tv = target_var(q) if tv is not None and tv in syms: syms = [tv] elif len(eqs) < len(syms): self.why = "more unknowns than equations and no variable named" return None if not syms or len(syms) > 3: return None if all(op == "=" for _, op, _ in eqs): sols = sp.solve([sp.Eq(a, b) for a, _, b in eqs], syms, dict=True) if not sols: self.why = "no solution found" return None for sol in sols: # CHECK: substitute back for a, _, b in eqs: if not equiv(a.subs(sol), b.subs(sol)): self.why = "substitution check failed" return None out = [", ".join("%s = %s" % (k, sp.sstr(v)) for k, v in sorted(sol.items(), key=lambda kv: str(kv[0]))) for sol in sols] return {"answer": " or ".join(out), "value": sols, "check": "each solution substituted back satisfies every equation", "steps": ["read %s" % "; ".join("%s %s %s" % (sp.sstr(a), o, sp.sstr(b)) for a, o, b in eqs), "solve for %s" % ", ".join(map(str, syms))]} if len(eqs) == 1 and len(syms) == 1: a, op, b = eqs[0] rel = {"<": sp.Lt, ">": sp.Gt, "<=": sp.Le, ">=": sp.Ge}[op](a, b) sol = sp.solveset(rel, syms[0], domain=sp.S.Reals) # CHECK: a point inside satisfies, a point outside does not inside = sol.inf + 1 if sol.inf.is_finite else (sol.sup - 1 if sol.sup.is_finite else 0) if inside not in sol or not rel.subs(syms[0], inside): self.why = "inequality check failed" return None return {"answer": sp.sstr(sol), "value": sol, "check": "a point of the solution set satisfies the inequality", "steps": ["read %s %s %s" % (sp.sstr(a), op, sp.sstr(b)), "solve over the reals"]} return None
# --- factor --------------------------------------------------------------------------------------------------- def _factor(self, spans, q): e = P(max(spans, key=len)) f = sp.factor(e) if not equiv(sp.expand(f), sp.expand(e)): return None if not (isinstance(f, sp.Mul) or isinstance(f, sp.Pow)) and f == e: self.why = "does not factor over the rationals" return None return {"answer": sp.sstr(f), "value": f, "check": "the product expands back to the input", "steps": ["read %s" % sp.sstr(e), "factor completely"]}
# --- simplify / expand ---------------------------------------------------------------------------------------- def _simplify(self, spans, q, how="simplify"): e0 = P(max(spans, key=len)) # the textbook convention: variables under radicals and exponents are taken as positive pos = {s: sp.Symbol(str(s), positive=True) for s in e0.free_symbols} e = e0.xreplace(pos) s0 = sp.simplify(e) cands = [s0, sp.together(s0), sp.powsimp(s0), sp.powdenest(s0, force=True), sp.expand(e), sp.cancel(e), sp.factor(e), sp.radsimp(s0)] back = {v: k for k, v in pos.items()} cands = [c.xreplace(back) for c in cands] e = e0 if how == "expand": cands = [sp.expand(e)] + cands best = cands[0] else: best = min(cands, key=complexity) if not equiv(best, e): return None return {"answer": sp.sstr(best), "value": best, "check": "equivalent to the input at random points (variables positive, the textbook convention)", "steps": ["read %s" % sp.sstr(e), "%s" % ("expand" if how == "expand" else "simplify")]}
def _expand(self, spans, q): return self._simplify(spans, q, how="expand")
# --- evaluate ------------------------------------------------------------------------------------------------- def _evaluate(self, spans, q): fdef = next((s for s in spans if re.match(r"^\s*[a-zA-Z]\s*\(\s*[a-z]\s*\)\s*=", s)), None) if fdef: m = re.match(r"^\s*([a-zA-Z])\s*\(\s*([a-z])\s*\)\s*=(.*)$", fdef) fname, var, body = m.groups() f = P(body) x = sp.Symbol(var) args = [re.match(r"^\s*%s\s*\((.*)\)\s*$" % fname, s) for s in spans if s is not fdef] args = [a.group(1) for a in args if a] if not args: return None outs = [] for a in args: v = sp.simplify(f.subs(x, P(a))) chk = f.subs(x, P(a)) if not equiv(v, chk): return None outs.append("%s(%s) = %s" % (fname, a, sp.sstr(v))) return {"answer": "; ".join(outs), "value": outs, "check": "recomputed by direct substitution", "steps": ["read %s(%s) = %s" % (fname, var, sp.sstr(f))] + ["substitute %s" % a for a in args]} subs = assignments(q) cand = [s_ for s_ in spans if not re.match(r"^\s*[a-z]\s*=\s*[-+]?[0-9./()]+\s*$", s_)] or spans e = P(max(cand, key=len).split("=")[0]) if subs and e.free_symbols and e.free_symbols <= set(subs): v = sp.nsimplify(sp.simplify(e.subs(subs))) if not equiv(v, e.subs(subs)): return None return {"answer": sp.sstr(v), "value": v, "check": "recomputed by direct substitution", "steps": ["read %s" % sp.sstr(e), "substitute %s" % ", ".join("%s = %s" % kv for kv in subs.items())]} if e.free_symbols: return self._simplify(spans, q) v = sp.nsimplify(sp.simplify(e)) if not e.is_Float else e if abs(complex(v.evalf()) - complex(e.evalf())) > 1e-9 * max(1, abs(complex(e.evalf()))): return None return {"answer": sp.sstr(v), "value": v, "check": "recomputed numerically", "steps": ["read %s" % sp.sstr(e), "evaluate"]}
# --- calculus ------------------------------------------------------------------------------------------------- def _var(self, e, q): syms = sorted(e.free_symbols, key=str) m = re.search(r"with respect to ([a-z])|d/d([a-z])", q) if m: return sp.Symbol(m.group(1) or m.group(2)) for pref in ("x", "t", "u", "theta"): for s in syms: if str(s) == pref: return s return syms[0] if syms else sp.Symbol("x")
def _body(self, spans): s = max(spans, key=len) s = re.sub(r"^\s*[a-zA-Z]\s*\(\s*[a-z]\s*\)\s*=", "", s) s = re.sub(r"^\s*y\s*=", "", s) return s
def _derivative(self, spans, q): e = P(self._body(spans)) x = self._var(e, q) d = sp.simplify(sp.diff(e, x)) for pt in rand_pts([x], 3): # CHECK: central difference h = sp.Rational(1, 10 ** 6) num = (e.subs(x, pt[x] + h) - e.subs(x, pt[x] - h)) / (2 * h) if abs(complex(num.evalf()) - complex(d.subs(pt).evalf())) > 1e-4 * max(1, abs(complex(d.subs(pt).evalf()))): return None return {"answer": sp.sstr(d), "value": d, "check": "agrees with a central difference at random points", "steps": ["read %s" % sp.sstr(e), "differentiate with respect to %s" % x]}
def _integral(self, spans, q): s = max(spans, key=len) m = re.search(r"integral\s*_\s*\{?([^}^]+?)\}?\s*\^\s*\{?([^}]+?)\}?\s*(\(.*|[^(].*?)\s*(?:d([a-z]))?\s*$", s) fb = re.search(r"from\s+([-\w./()]+)\s+to\s+([-\w./()]+)", q) lo = hi = None if m: lo, hi, body, v = m.groups() e = P(body) elif fb: lo, hi = fb.groups() body = max([x for x in spans if x.strip() not in (lo, hi)] or spans, key=len) e = P(re.sub(r"\s*d[a-z]\s*$", "", self._body([body]).replace("integral", ""))) else: e = P(re.sub(r"\s*d([a-z])\s*$", "", self._body(spans).replace("integral", ""))) x = self._var(e, q) F = sp.integrate(e, x) if F.has(sp.Integral): return None if not equiv(sp.diff(F, x), e): # CHECK: differentiates back return None if lo is not None: val = sp.simplify(F.subs(x, P(hi)) - F.subs(x, P(lo))) quad = sp.Integral(e, (x, P(lo), P(hi))).evalf() if abs(complex(val.evalf()) - complex(quad)) > 1e-6 * max(1, abs(complex(quad))): return None return {"answer": sp.sstr(val), "value": val, "check": "antiderivative differentiates back; quadrature agrees", "steps": ["read integral of %s from %s to %s" % (sp.sstr(e), lo, hi), "antiderivative %s" % sp.sstr(F)]} return {"answer": sp.sstr(F) + " + C", "value": F, "check": "differentiates back to the integrand", "steps": ["read %s" % sp.sstr(e), "integrate with respect to %s" % x]}
def _limit(self, spans, q): s = max(spans, key=len) m = re.search(r"lim\s*_\s*\{?\s*([a-z])\s*->\s*([^}\s]+?)\s*\}?\s*(\S.*?)\s*(?:,.*)?$", s) or \ re.search(r"as ([a-z]) (?:approaches|->) ([-\w.]+)", q) if not m: return None if len(m.groups()) == 3: v, pt, body = m.groups() e = P(body) else: v, pt = m.groups() e = P(self._body([x for x in spans if "lim" not in x] or spans)) x, a = sp.Symbol(v), P(pt) L_ = sp.limit(e, x, a) if L_.is_finite: # CHECK: evaluation near the point near = complex(e.subs(x, a + sp.Rational(1, 10 ** 7)).evalf()) if abs(near - complex(L_.evalf())) > 1e-3 * max(1, abs(complex(L_.evalf()))): return None return {"answer": sp.sstr(L_), "value": L_, "check": "agrees with evaluation near the point", "steps": ["read the limit of %s as %s -> %s" % (sp.sstr(e), v, pt)]}
def _partial(self, spans, q): e = P(max(spans, key=len)) x = self._var(e, q) r = sp.apart(e, x) if not equiv(r, e): return None return {"answer": sp.sstr(r), "value": r, "check": "recombines to the input", "steps": ["read %s" % sp.sstr(e), "decompose into partial fractions"]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447"""oracle_cube_reader_v1 - the reasoning cube, Phase A: read -> frame -> link -> expand -> bind -> check -> verify.
Three graphs share one middle pillar (request, binding, evidence, surface). This module walks the first six moves:
Q Malkuth->Yesod READ the surface opens obligations Q Yesod->Tiferet FRAME the answer slot: its TYPE (person, year, date, number, place, or an instance of the question's head noun), the relation words, the constraints O Tiferet->Chokmah LINK the subject, by the store's own title index (longest word n-grams), never by guessing from capital letters K Chokmah->Chesed EXPAND the subject's own page, sentence by sentence, each with its claim id K Chesed->Tiferet BIND a candidate of the required type, drawn from a sentence that carries the relation O Geburah->Tiferet CHECK INDEPENDENT of the proposing sentence: an entity candidate's OWN page must say it is the asked-for kind; the question's constraints must be attested in the binding sentence or on the candidate's page; a value candidate (year, date, number) must be the only value of its type bound to a relation word in its sentence Q Tiferet->Keter VERIFY every obligation discharged, one candidate standing, or nothing is said
Laws obeyed (reach-is-not-answer, 2026-09-10): a candidate is proposed BECAUSE it could fill the open slot, carries atyped binding, and is checked by something that did not propose it. No hypernym bridging. Abstention is free; a wronganswer costs a right one. The store is ORACLE_DEEP_BUILD, read-only."""from __future__ import annotations
import osimport reimport sqlite3import unicodedata
DEEP = os.environ.get("ORACLE_DEEP_BUILD") or ( __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/fable-content/oracle-m-series-2026-08-15/" "m13e8_dbpedia_enslot_openstax_full_fable_bench_a_v1/wikipedia_specialist.sqlite3")
STOP = set("""a an the of and or for to in on at by with from into about as is are was were be been being it its this thatthese those which what who whom whose when where why how did does do has have had not no but if than so such also canwill would could should may might must shall there their his her he she they them we you your our i me my one firstlast name named called known""".split())MEASURES = {"capacity", "population", "height", "length", "area", "number", "size", "weight", "depth", "width", "age", "distance", "speed", "elevation", "altitude", "attendance", "budget", "revenue"}ANSWER_WORDS = {"day", "month", "year", "date", "time", "when", "first", "last", "name", "names", "called", "second", "number", "many", "much", "exact", "full", "people", "person", "two", "three"}FRAME_NOUNS = {"name", "type", "kind", "sort", "word", "term", "title", "one", "thing", "part", "member"}ACTION_BREAK = re.compile(r"^(is|was|were|are|did|does|do|has|had|have|won|played|made|became|served|wrote|directed|" r"founded|released|located|called|named|known|used|held|given|awarded|built|born|died|developed|" r"invented|created|published|produced|starred|in|of|for|by|to|at|on|from|with|that|whose|who|" r"which|as|after|before|during|and|or)$", re.I)MONTHS = "january february march april may june july august september october november december".split()MONTH_RE = "|".join(m.capitalize() for m in MONTHS)YEAR = re.compile(r"\b(1[0-9]{3}|20[0-2][0-9])\b")DATE = re.compile(r"\b(\d{1,2} (?:%s) \d{3,4}|(?:%s) \d{1,2}, \d{3,4})\b" % (MONTH_RE, MONTH_RE))MONTH_YEAR = re.compile(r"\b((?:%s) \d{4})\b" % MONTH_RE)COMPARE = re.compile(r"\b(or|out of|between|both|either|neither)\b.*\?$|\b(more|most|less|fewer|older|younger|earlier|later|" r"longer|shorter|larger|smaller|bigger|taller|first)\b.*\b(or|and)\b", re.I)NUMBER = re.compile(r"\b\d{1,3}(?:,\d{3})+\b|\b\d+(?:\.\d+)?\b")NUMWORDS = {w: i for i, w in enumerate("zero one two three four five six seven eight nine ten eleven twelve".split())}CAPSPAN = re.compile(r"\b([A-Z][\w'\.\-&]*(?:\s+(?:of|the|de|von|van|da|del|la|le|and|&)?\s*[A-Z0-9][\w'\.\-&]*){0,5})")TOK = re.compile(r"[A-Za-z0-9][A-Za-z0-9'\-\.&]*")# v1.2: a PERSON is shown by a birth/life-span parenthetical or an occupation predicate, never by a pronoun anywhere on the# page (v1.1 accepted "MA" - Massachusetts - as a person because the page said "her")OCCUPATIONS = (r"actor|actress|singer|songwriter|musician|composer|writer|author|poet|novelist|journalist|politician|" r"lawyer|judge|player|footballer|cricketer|athlete|coach|manager|painter|artist|sculptor|architect|" r"scientist|physicist|chemist|biologist|mathematician|astronomer|engineer|inventor|economist|philosopher|" r"historian|director|producer|businessman|businesswoman|entrepreneur|explorer|soldier|general|admiral|" r"officer|king|queen|emperor|prince|princess|pope|bishop|priest|monk|saint|president|minister|senator|" r"governor|diplomat|activist|comedian|dancer|model|designer|photographer|surgeon|physician|nurse|" r"professor|teacher|scholar|academic|chef|pilot|astronaut|wrestler|boxer|racing driver|cyclist|swimmer|" r"tennis player|golfer|chess player|rapper|drummer|guitarist|pianist|conductor|filmmaker|screenwriter|" r"cartoonist|illustrator|critic|editor|publisher|broadcaster|presenter|television personality|nobleman|" r"noblewoman|lord|lady|duke|earl|count|countess|baron|chief|leader|missionary|theologian|psychologist")PERSON_LEAD = re.compile(r"\(\s*born\b|\(\s*(?:c\.\s*)?\d{1,2}? ?\w* ?\d{3,4}\s*[–-]|\(\s*fl\.|" r"\b(?:is|was)\s+(?:a|an|the)\s+(?:[\w\-]+\s+){0,4}?(?:%s)s?\b" % OCCUPATIONS, re.I)NOUNISH = re.compile(r"(?:ers?|ors?|ions?|ments?|ness|ities|ity|ists?|ship)$", re.I)PLACE_LEAD = re.compile(r"\b(city|town|village|country|state|province|county|region|capital|municipality|island|" r"district|commune|borough|suburb|territory|nation|located in|metropolis|kingdom|republic)\b", re.I)
def norm(s): s = unicodedata.normalize("NFKD", str(s)).encode("ascii", "ignore").decode("ascii") return " ".join(re.sub(r"[^a-z0-9 ]+", " ", s.lower()).split())
IRREG = {"won": "win", "win": "win", "wins": "win", "wrote": "write", "written": "write", "writes": "write", "write": "write", "began": "begin", "begun": "begin", "became": "become", "become": "become", "led": "lead", "leads": "lead", "lead": "lead", "ran": "run", "run": "run", "sang": "sing", "sung": "sing", "sing": "sing", "held": "hold", "hold": "hold", "made": "make", "make": "make", "took": "take", "taken": "take", "take": "take", "gave": "give", "given": "give", "give": "give", "came": "come", "come": "come", "went": "go", "met": "meet", "meet": "meet", "left": "leave", "leave": "leave", "built": "build", "build": "build", "sold": "sell", "sell": "sell", "bought": "buy", "buy": "buy", "taught": "teach", "teach": "teach", "fought": "fight", "fight": "fight", "drew": "draw", "drawn": "draw", "draw": "draw", "flew": "fly", "fly": "fly", "grew": "grow", "grow": "grow", "spoke": "speak", "speak": "speak", "chose": "choose", "chosen": "choose", "choose": "choose", "drove": "drive", "drive": "drive", "born": "bear", "birth": "bear", "died": "die", "dies": "die", "die": "die", "death": "die", "beat": "beat", "beaten": "beat", "shot": "shoot", "hit": "hit", "set": "set", "put": "put"}BASE_VERBS = set("""play join attend marry appear found discover invent release direct compose coach serve elect awardsign command host produce publish open close design create capture defeat star record graduate study move live namescore represent debut premiere air launch establish introduce approve nominate appoint succeed replace kill murderretire resign own acquire merge sponsor manage train perform tour reach finish rank place qualify earn receive""".split())
def canon(w): w = w.lower() return IRREG.get(w) or stem(w)
def verbish(w): wl = w.lower() return wl in IRREG or wl in BASE_VERBS or (wl.endswith("ed") and len(wl) > 4) or stem(wl) in {stem(b) for b in BASE_VERBS}
def stem(w): w = w.lower() for suf in ("ing", "ers", "ed", "es", "er", "s"): if len(w) > len(suf) + 3 and w.endswith(suf): return w[: -len(suf)][:6] return w[:6]
class CubeReader: def __init__(self, path=DEEP): uri = "file:%s?mode=ro&immutable=1" % path self.db = sqlite3.connect(uri, uri=True, check_same_thread=False) self._lead = {}
# ---- K: the store ---- def pid_of(self, title): nt = norm(title) if not nt: return None r = self.db.execute("SELECT page_id FROM title_alias WHERE normalized_title=? LIMIT 1", (nt,)).fetchone() return r[0] if r else None
def page(self, pid, cap=40): out = [] for (rowid,) in self.db.execute("SELECT source_rowid FROM page_sentence WHERE page_id=? ORDER BY sentence_ordinal " "LIMIT ?", (pid, cap)).fetchall(): c = self.db.execute("SELECT c0, c1 FROM source_rows_content WHERE id=?", (rowid,)).fetchone() if not c: continue text = " ".join(str(c[1]).split()) # the store's sentence splitter breaks on initials ("discovered by A." / "Schwassmann on 11 September 1898"): # rejoin, keeping the first claim id and citing both if out and re.search(r"(?:^|\s)[A-Z]\.$", out[-1][1]): out[-1] = (out[-1][0], out[-1][1] + " " + text) else: out.append((c[0], text)) return out
def lead(self, pid, n=3): if pid not in self._lead: self._lead[pid] = " ".join(t for _, t in self.page(pid, n)) return self._lead[pid]
# ---- Q: FRAME ---- def frame(self, q): s = " ".join(str(q).split()) low = s.lower() if not s or "passage:" in low or "\noptions" in low or "options:" in low or re.search(r"\b(you|your)\b", low): return None if not (s.endswith("?") or re.match(r"^(who|whom|whose|what|which|when|where|how|in what|in which|name)\b", low)): return None atype, head = None, None if re.search(r"\bwhat (day|date)\b|\bday, month,? and year\b|\bexact date\b|\b(what|which) month and year\b", low): atype = "DATE" elif re.search(r"\b(what|which) year\b|\bin what year\b|^when\b|\bwhat year\b", low): atype = "YEAR" elif re.search(r"\bhow many\b", low): atype = "NUMBER" elif re.match(r"^(who|whom)\b", low) or re.search(r"\b(which|what) (person|man|woman|actor|actress|singer|player|" r"writer|author|politician|artist|director)\b", low): atype = "PERSON" elif re.match(r"^where\b", low): atype, head = "PLACE", None else: m = re.search(r"\b(?:which|what)\s+((?:[\w'\-]+\s+){0,5}?[\w'\-]+?)(?=\s+(?:is|was|were|are|did|does|do|has|had|" r"have|won|played|made|became|served|wrote|directed|founded|released|located|called|named|known|" r"used|held|given|awarded|built|born|died|developed|invented|created|published|produced|starred|" r"in|of|for|by|to|at|on|from|with|that|whose|who|which|as|after|before|during)\b|\s*\?|$)", s, re.I) if m: words = [w for w in m.group(1).split() if w] lower = [w for w in words if w.islower() and w.isalpha()] if lower: head = lower[-1].lower() if head in FRAME_NOUNS: m2 = re.search(r"\b(?:name|type|kind|sort|title) of (?:the |a |an )?((?:[\w'\-]+\s+){0,3}?[\w'\-]+?)" r"(?=\s+(?:in|of|for|by|that|which|who|whose|is|was|were)\b|\s*\?|$)", s, re.I) head = ([w for w in m2.group(1).split() if w.islower()] or [None])[-1] if m2 else None if head in MEASURES: atype = "NUMBER" elif head in ("city", "country", "town", "state", "place", "capital", "village", "nation", "province"): atype = "PLACE" elif head and head not in STOP and len(head) >= 3: atype = "INSTANCE" if atype is None: return None if COMPARE.search(s) and (" or " in low or " out of " in low or " between " in low or " both " in low): return None # a comparison: the COMPARE move is Phase 3, not this reader if re.search(r"\bthe (?:[a-z\-]+ ){0,2}(?:man|woman|person|composer|author|writer|director|actor|actress|singer|" r"player|team|band|company|film|city|country|village|town|artist|founder|creator|leader|president|" r"king|queen|school|university|group|album|show|series|book|novel|song|character|state|river)\s+" r"(?:who|whose|which|that|where)\b", low): return None # the subject is a DESCRIPTION: a bridge (two hops), Phase 3 if re.search(r"\bthe\b[^?]{0,90}?,?\s+(?:who|whose)\b", low): return None # v1.2: any described person ("the American lawyer ... who") is a bridge if re.search(r"\b(?:of|on|in|at|from|near)\s+the\s+(?:[a-z\-]+\s+){0,2}[a-z]+\s+(?:located|situated|based|founded|" r"built|named|called|known|found|owned|operated|run|held)\b", low): return None # v1.3: "the slopes of the hill located in what town" - the # asked thing is a described entity (a bridge), not the subject return {"q": s, "atype": atype, "head": head, "years": set(YEAR.findall(s)), "month_year": bool(re.search(r"\bmonth and year\b|\bmonth, and year\b", low)) and "day" not in low}
# ---- O: LINK (title index, longest non-overlapping n-grams) ---- def link(self, fr, maxn=7): toks = TOK.findall(fr["q"]) found = [] for n in range(min(maxn, len(toks)), 0, -1): for i in range(len(toks) - n + 1): words = toks[i:i + n] nt = norm(" ".join(words)) if not nt or all(w in STOP or w in FRAME_NOUNS for w in nt.split()) or nt == fr["head"]: continue if not words[0][:1].isupper() and not words[0][:1].isdigit(): continue # a subject starts with a capital (names, titles) or a digit if n == 1 and len(nt) < 4: continue if nt in MONTHS or nt.replace(" ", "").isdigit(): continue # a month or a bare number is a constraint, never the subject pid = self.pid_of(nt) if pid: found.append((i, i + n, " ".join(words), pid)) keep, used = [], set() for i, j, text, pid in sorted(found, key=lambda t: (-(t[1] - t[0]), t[0])): if used.isdisjoint(range(i, j)): keep.append({"span": (i, j), "text": text, "pid": pid}) used.update(range(i, j)) fr["tokens"] = toks fr["subjects"] = keep subj_tok = set(k for s in keep for k in range(*s["span"])) rel = [t for k, t in enumerate(toks) if k not in subj_tok and t.lower() not in STOP and t.lower() != fr["head"] and t.lower() not in ANSWER_WORDS and not YEAR.fullmatch(t) and t[:1].islower() and len(t) >= 3] fr["rel"] = [stem(t) for t in rel] # the PREDICATE: the question's verb(s). The binding sentence must carry one of them - a value bound through a # shared context word ("road" in "road running athlete") answers a different relation verbs = [(k, t) for k, t in enumerate(toks) if k not in subj_tok and t[:1].islower() and verbish(t) and t.lower() not in STOP] # only the verb GOVERNING the answer slot counts: the one nearest the wh-phrase ("founded in what year"), not a # participle describing something else ("a failed raid") wh = [k for k, t in enumerate(toks) if t.lower() in ("who", "whom", "whose", "what", "which", "when", "where", "how")] if verbs and wh: w0 = wh[0] k, t = min(verbs, key=lambda kt: (abs(kt[0] - w0), kt[0] < w0)) fr["pred"] = [canon(t)] else: fr["pred"] = sorted({canon(t) for _, t in verbs}) # every NAME in the question is an obligation: a capitalised token (not the first word) outside every linked span unlinked = [t for k, t in enumerate(toks) if k > 0 and k not in subj_tok and t[:1].isupper() and t.lower() not in STOP and len(t) >= 3] unlinked += [t for k, t in enumerate(toks) if k not in subj_tok and t.isdigit() and len(t) >= 2 and not YEAR.fullmatch(t)] # v1.2: an identifier ("gal56", "EURECA-1") is an obligation too: letters and digits together unlinked += [t for k, t in enumerate(toks) if k not in subj_tok and re.search(r"\d", t) and re.search(r"[A-Za-z]", t)] # v1.2: the ROLE the answer must play. "Who beat X" asks for the AGENT of the predicate # v1.3: "Who did X knock out?" asks for the PATIENT of X's action fr["patient"] = bool(re.match(r"^(?:who|whom|what|which [\w\-]+)\s+(?:did|does|do|has|had|have)\b", fr["q"].lower())) fr["agent"] = bool(re.match(r"^(?:who|which [\w\-]+(?: [\w\-]+)?)\s+(?!is\b|was\b|are\b|were\b|did\b|does\b|do\b|has\b|" r"had\b|have\b|will\b|would\b|can\b|could\b)[a-z]+", fr["q"].lower())) fr["constraints"] = [s["text"] for s in keep[1:]] + sorted(fr["years"]) + unlinked return keep
# ---- K: BIND ---- def _candidates(self, fr, sent, qnorm): at = fr["atype"] out = [] if at == "YEAR": out = [y for y in YEAR.findall(sent) if y not in fr["years"]] elif at == "DATE": out = DATE.findall(sent) if not out and fr.get("month_year"): out = MONTH_YEAR.findall(sent) elif at == "NUMBER": out = [n for n in NUMBER.findall(sent) if not YEAR.fullmatch(n) and n not in fr["q"]] else: for m in CAPSPAN.finditer(sent): span = m.group(1).strip(" .,;:") span = re.sub(r"^(The|A|An)\s+", "", span) if len(span) < 3 or (span.isupper() and len(span) <= 3) or norm(span) in qnorm or norm(span).split()[0] in STOP: continue if span.split()[0].capitalize() in MONTH_RE.split("|"): continue out.append(span) return out
def bind(self, fr): qnorm = norm(fr["q"]) rel = set(fr["rel"]) cands = [] for subj in fr["subjects"][:4]: sents = self.page(subj["pid"], 40) for idx, (cid, sent_full) in enumerate(sents): words = [p for t in TOK.findall(sent_full) for p in [t] + t.split("-")[1:]] # "co-founded" -> founded # v1.2: the predicate must appear as a VERB - "composers" is not "composed" verbs_here = {canon(t) for t in words if not NOUNISH.search(t)} if fr["pred"] and not (verbs_here & set(fr["pred"])): continue # the question's predicate is not in this sentence sent = sent_full if not ({"bear", "die"} & set(fr["pred"])): # a value inside "(born ...)" or a life span answers only a birth/death question sent = re.sub(r"\((?:[^()]*\b(?:born|died|b\.|d\.)\b[^()]*|\s*[^()]{0,30}\d{3,4}\s*[–-]\s*[^()]{0,30}\d{3,4}\s*)\)", "", sent_full) stoks = [stem(t) for t in TOK.findall(sent)] hits = len(rel & set(stoks)) cover = (hits / len(rel)) if rel else (1.0 if idx < 2 else 0.0) if rel and hits == 0: continue # the sentence must carry at least one of the question's relation words if not rel and idx >= 2: continue # no relation words: only the page's lead may bind for c in self._candidates(fr, sent, qnorm): # proximity: the candidate sits near a relation word in its sentence pos = sent.find(c) near = any(abs(sent.lower().find(r) - pos) < 90 for r in rel if sent.lower().find(r) >= 0) if rel else True if not near: continue cands.append({"value": c, "claim": cid, "sentence": sent_full, "subject": subj, "cover": cover, "lead": idx < 3, "score": cover + (0.3 if idx < 3 else 0.0)}) return cands
# ---- O: CHECK (independent of the proposing sentence) ---- def check(self, fr, c): at = fr["atype"] ev = {} if at in ("PERSON", "PLACE", "INSTANCE"): pid = self.pid_of(c["value"]) if not pid or pid == c["subject"]["pid"]: return False, {"why": "candidate has no page of its own"} lead = self.lead(pid) if at == "PERSON" and not PERSON_LEAD.search(lead): return False, {"why": "candidate page does not describe a person"} first = re.split(r"(?<=[.!?])\s+", lead, 1)[0] if at == "PLACE" and not fr["head"] and not PLACE_LEAD.search(first): return False, {"why": "candidate page does not describe a place"} if at == "INSTANCE" or (at == "PLACE" and fr["head"]): # IS-A, not mention: the first sentence must say the candidate IS a <head> ("... is a professional team") h = fr["head"] # ... and the head noun must END its phrase ("a film", not "a film producer") isa = (r"\b(?:is|was|are|were)\s+(?:a|an|the|one of the)\b[^.]{0,90}?\b%s(?:s|es)?\b" r"(?=\s*(?:[,.;:()]|$)|\s+(?:that|which|who|whose|based|in|of|from|and|or|founded|established|located|" r"with|by|for|released|directed|produced|written|set|created|developed|published|made|first|since|" r"owned|operated|consisting|starring|about|on|at|to|named|known|situated|headquartered)\b)") % re.escape(h) # the store's canonical title is also type evidence when its last word IS the head ("Crimean War") title_head = norm(c["value"]).split()[-1:] in ([h], [h + "s"]) if not re.search(isa, first, re.I) and not title_head: return False, {"why": "candidate page does not say it is a %s" % h} if fr.get("agent"): # v1.2 ROLE: "Who beat X?" needs the candidate as the predicate's AGENT. In active voice the agent stands # before the verb; after it, only a passive "by" makes it the agent ("discovered by Annibale de Gasparis"). # "Henman ... beating Roger Federer" puts Federer in the patient role and is refused. sl = c["sentence"] pos_c = sl.find(c["value"]) pv = next((m for m in TOK.finditer(sl) if not NOUNISH.search(m.group(0)) and canon(m.group(0)) in fr["pred"]), None) if pv is not None and pos_c > pv.start() and not re.search(r"\bby\b", sl[pv.end():pos_c]): return False, {"why": "candidate is not the agent of the predicate"} if fr.get("patient"): # v1.3 ROLE: the answer is the patient of the SUBJECT's action; a sentence where the subject is itself # the passive patient ("Douglas was knocked out ... Lou Savarese") names the agent, not the answer subj_words = [w for w in norm(c["subject"]["text"]).split() if len(w) >= 4] sl = c["sentence"] for w in subj_words: if re.search(r"\b%s\b[^.]{0,40}?\b(?:was|were|been|being)\s+(?:\w+\s+)?\w+(?:ed|en|out)\b" % re.escape(w), sl, re.I): return False, {"why": "the subject is the patient in this sentence"} ev = {"type_page": pid, "type_lead": lead[:240]} where = norm(c["sentence"] + " " + lead + " " + self.lead(c["subject"]["pid"])) else: if at == "DATE" and not fr.get("month_year"): # v1.3 CORROBORATION for day-precision dates: a single sentence can be wrong (FC Baltika: the store says # 23 August 1954, the key 22 December 1954). An exact date is committed only when a SECOND sentence - # different claim id - carries the same date string with the subject's distinctive word. subj_words = [w for w in norm(c["subject"]["text"]).split() if len(w) >= 4 and w not in STOP] word = max(subj_words, key=len) if subj_words else None n_other = 0 if word: try: rows = self.db.execute("SELECT claim_id FROM source_rows WHERE source_rows MATCH ? LIMIT 6", ('"%s" AND "%s"' % (c["value"].replace('"', ""), word),)).fetchall() n_other = len({r[0] for r in rows if r[0] != c["claim"]}) except sqlite3.OperationalError: n_other = 0 if n_other < 1: return False, {"why": "exact date not corroborated by a second sentence"} vals = self._candidates(fr, c["sentence"], norm(fr["q"])) if len(set(vals)) != 1: return False, {"why": "more than one %s in the binding sentence" % at.lower()} where = norm(c["sentence"] + " " + self.lead(c["subject"]["pid"])) # constraints: every OTHER name/number/year in the question. The subject whose page holds the sentence is attested # by the page itself; qualifiers of that subject ("El Santuario, Antioquia, Colombia") may be attested on its lead; # a person's name is attested by its surname own = norm(c["subject"]["text"]) cons = [x for x in fr["constraints"] if norm(x) and norm(x) != own and norm(x) not in own] linked_other = {norm(s["text"]) for s in fr["subjects"] if norm(s["text"]) != own} sent_n = norm(c["sentence"]) missing = [] for x in cons: nx = norm(x) sur = nx.split()[-1] if len(nx.split()) > 1 and len(nx.split()[-1]) >= 4 else None # another NAMED entity of the question must be in the binding sentence itself (not merely on a lead): the # prize page's "awarded since 1979" says nothing about the person the question asks about # v1.3: a YEAR in the question qualifies the event, so it must be in the binding sentence too scope = sent_n if (nx in linked_other or YEAR.fullmatch(x.strip())) else where if nx not in scope and not (sur and (" %s " % sur) in (" %s " % scope)): missing.append(x) if missing: return False, {"why": "constraint not attested: %s" % missing} return True, ev
# ---- Q: VERIFY + the whole cycle ---- def answer(self, q): self.stop = "frame" fr = self.frame(q) if not fr: return None self.stop = "link" if not self.link(fr): return None self.stop = "bind" cands = self.bind(fr) if not cands: return None self.stop = "check" best = {} for c in cands: k = norm(c["value"]) if k not in best or c["score"] > best[k]["score"]: best[k] = c ranked = sorted(best.values(), key=lambda c: -c["score"]) passed = [] self.why = [] for c in ranked[:6]: ok, ev = self.check(fr, c) if ok: c["check"] = ev passed.append(c) else: self.why.append((c["value"], ev.get("why"))) if not passed: return None top = passed[0] if len(passed) > 1 and passed[1]["score"] >= top["score"] - 1e-9: self.stop = "tie" return None # two checked candidates tie: nothing is said self.stop = "answered" return {"answer": top["value"], "claim": top["claim"], "sentence": top["sentence"], "subject": top["subject"]["text"], "type": fr["atype"], "head": fr["head"], "check": top["check"], "frame": {k: fr[k] for k in ("atype", "head", "rel")}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209#!/usr/bin/env python3"""ORACLE GAME COMBINATORS - operators that take games and return games.
Twelve categories with parameters is a large space. It is still a flat one: everygame it can build is one of twelve shapes wearing different numbers. The move thatmakes it genuinely open is HIGHER ORDER operators, which take a game and give backa different game, because then the space closes under its own operations.
Two of them, and they are chosen because both are real games people actually playrather than formal curiosities:
INVERT the win condition is flipped. Get three in a row and you LOSE, which is a real game (misere noughts and crosses) with completely different play from the one it inverts. Applied to any of the twelve, not just to take-away where it was hand-written.
COMPOUND play game A, then game B, and whoever won more takes the match. "Tic tac toe then nim" is not in any catalogue, is not a parameter setting of anything, and is a perfectly well defined game. This is what combining categories means.
Both come with their own referees, built by composing the referees underneaththem, so a combined game is checked the same way a simple one is: the engineplays, the referee replays, and the emitted program runs in a separate process.A combination is only allowed out if all three agree about it.
The count matters less than the closure. Twelve categories give twelve games; withINVERT that is twenty-four; with COMPOUND over ordered pairs it is 24 x 24 beforeany parameter is chosen, and the parameters are still free. Nothing in that spaceis stored."""
from __future__ import annotations
import re
from oracle_game_kernel_v1 import GameError, play
COMPOUND_BUDGET = 1200from oracle_game_vocab_v1 import CATS
_FLIP = {'first': 'second', 'second': 'first', 'draw': 'draw', 'solved': 'failed', 'failed': 'solved'}
# ── INVERT ───────────────────────────────────────────────────────────────────def invert_build(inner_name, params): inner = CATS[inner_name]['build'](params) base_outcome = inner['outcome']
def outcome(st): got = base_outcome(st) return _FLIP[got] if got is not None else None
return dict(inner, outcome=outcome)
def invert_referee(inner_name, params, log): got = CATS[inner_name]['referee'](params, log) return _FLIP[got]
# ── COMPOUND ─────────────────────────────────────────────────────────────────def compound_build(a_name, b_name, a_params, b_params): """Play A to a result, then B, then compare. One game, two halves.""" ga = CATS[a_name]['build'](a_params) gb = CATS[b_name]['build'](b_params)
def score_of(res): return {'first': 1, 'solved': 1, 'second': -1, 'failed': -1, 'draw': 0}[res]
# Every move is TAGGED with the half it belongs to, so the kernel's own move # log is already splittable by the referee. The first version kept a private # tagged log inside the state and handed the referee the kernel's untagged # one, which is why every compound died on unpacking. def init(): return ('a', ga['init'](), None, 0)
def moves(st): leg, inner = st[0], st[1] g = ga if leg == 'a' else gb legal = [(leg, m) for m in g['moves'](inner)] if not legal and leg == 'a': # the first half ran out of legal moves without declaring a result. # Returning nothing here makes the KERNEL call the whole compound a # draw and the second half never happens, which the referee then # rightly refuses. Hand back a marker so the transition still occurs. return [('a', None)] return legal
def apply(st, tagged, t): leg, inner, first_res, count = st _tag, m = tagged if m is None: # the exhaustion marker from moves() return ('b', gb['init'](), ga['outcome'](inner) or 'draw', 0) g = ga if leg == 'a' else gb inner2 = g['apply'](inner, m, count) # the INNER half's own turn done = g['outcome'](inner2) if done is not None and leg == 'a': return ('b', gb['init'](), done, 0) return (leg, inner2, first_res, count + 1)
def outcome(st): leg, inner, first_res, _count = st if leg == 'a': return None done = gb['outcome'](inner) if done is None: return None total = score_of(first_res) + score_of(done) return 'first' if total > 0 else 'second' if total < 0 else 'draw'
def policy(st, legal, t): return legal[0] if st[3] % 2 == 0 else legal[-1]
return {'init': init, 'moves': moves, 'apply': apply, 'outcome': outcome, 'policy': policy}
def compound_referee(a_name, b_name, a_params, b_params, log): """Split the tagged log and hand each half to the referee that owns it.""" a_log = [m for leg, m in log if leg == 'a' and m is not None] b_log = [m for leg, m in log if leg == 'b' and m is not None] if not a_log or not b_log: raise GameError('referee: one half of the compound never happened') ra = CATS[a_name]['referee'](a_params, a_log) rb = CATS[b_name]['referee'](b_params, b_log) sc = {'first': 1, 'solved': 1, 'second': -1, 'failed': -1, 'draw': 0} total = sc[ra] + sc[rb] return 'first' if total > 0 else 'second' if total < 0 else 'draw'
# ── routing the combinations ─────────────────────────────────────────────────_INVERT_CUE = re.compile( r'\b(?:misere|mis[eè]re)\b|you lose|makes you lose|loses instead' r'|whoever .{0,24}loses|reverse(?:d)? (?:rules|win)|inverted' r'|the loser wins|last one loses', re.I)_COMPOUND_CUE = re.compile( r'\bthen\b|\bfollowed by\b|\band then\b|\bboth\b.{0,20}\bgames?\b' r'|combin(?:e|ed|ation) of', re.I)
def find_categories(surface): """Every category the surface names, in the order it names them.""" hits = [] for name, c in CATS.items(): for rx in c['cues']: m = rx.search(surface) if m: hits.append((m.start(), name)) break hits.sort() out = [] for _pos, name in hits: if name not in out: out.append(name) return out
def parse_combination(surface): """(kind, payload) or None if this is not a combination request.
kind is 'invert' or 'compound'. Raises GameError when the request clearly wants a combination but the pieces do not resolve, so it can decline with a reason rather than quietly build one half. """ names = find_categories(surface) wants_compound = bool(_COMPOUND_CUE.search(surface)) wants_invert = bool(_INVERT_CUE.search(surface))
if wants_compound: real = [n for n in names if n != 'misere_take_away'] if len(real) < 2: raise GameError('that asks for two games joined together and I can ' 'only find one of them in it') a, b = real[0], real[1] pa = CATS[a]['params'](surface) pb = CATS[b]['params'](surface) return 'compound', (a, b, pa, pb)
if wants_invert and names: base = [n for n in names if n != 'misere_take_away'] if not base: return None # plain misere nim, already a category n = base[0] return 'invert', (n, CATS[n]['params'](surface)) return None
def describe(kind, payload): if kind == 'invert': n, p = payload return ('%s, with the win condition inverted: doing the thing that ' 'normally wins LOSES' % CATS[n]['describe'](p)) a, b, pa, pb = payload return ('two games in one match: first %s, then %s, and whoever wins more ' 'takes it' % (CATS[a]['describe'](pa), CATS[b]['describe'](pb)))
def build_and_referee(kind, payload): if kind == 'invert': n, p = payload return (invert_build(n, p), lambda _params, log: invert_referee(n, p, log), p) a, b, pa, pb = payload return (compound_build(a, b, pa, pb), lambda _params, log: compound_referee(a, b, pa, pb, log), {'a': a, 'b': b})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256#!/usr/bin/env python3"""oracle_program_ir_v1 - one intermediate representation; every request compiles to a bounded relational program.
The five things that looked like separate engineering tracks - corpus reach, coding, conversation, prose,self-repair - are one missing operation. A request must compile into explicit semantic OBLIGATIONS, thoseobligations into a bounded relational PROGRAM over stores, operators, discourse state and permitted inference,and the completed result must be verified AGAINST THE OBLIGATIONS before anything is rendered.
I found this while working on coding and then confined it to coding. The coding fold says: the request containsits own specification, and testing a program against its own behaviour verifies the wrong proposition. Every othercapability makes the identical error. Asked why a compiler needs a parser, the model checks whether retrievedsentences match the surface wording. Asked whether oxygen is a cause or a result, it checks a taxonomic exclusion.Asked to compare photosynthesis with respiration, it retrieves individually warranted fragments and loses thecomparison subject. In each case the local claims are valid and the executed answer is not bound to what wasasked - the same failure as returning a bank-account class for a stack and reporting that it executed.
THE CONSEQUENCE THAT MATTERS MOST: an answer need not exist as a stored sentence. It exists as a warranted paththrough stored relations. No sentence anywhere says why a compiler needs a parser; the answer is a join acrosswhat a compiler consumes and what a parser produces. Measuring whether the answer STRING is in the store - whichis what every coverage probe here has done, mine included - can only ever report a coverage problem. That is thedifference between possessing documents and possessing knowledge.
utterance -> obligations -> relational program -> execution trace -> answer-state -> expression
A successful answer is a verified execution trace satisfying every obligation, not a collection of valid sentences.
This module is the representation and the obligation compiler. It executes nothing: an obligation it cannot buildis itself a finding, and is recorded as `unbuildable` rather than quietly dropped.
usage: oracle_program_ir_v1.py [--packet PATH] compile the diagnostic prompts and print their programs"""
from __future__ import annotations
import jsonimport reimport sysfrom dataclasses import dataclass, field, asdictfrom pathlib import Path
WORD = re.compile(r"[A-Za-z][A-Za-z'-]{1,}")PROPER = re.compile(r"\b([A-Z][\w'-]+(?:\s+(?:of|the|de)\s+[A-Z][\w'-]+|\s+[A-Z][\w'-]+)*)")PRONOUN = re.compile(r"\b(it|its|that|this|they|them|those|these|one)\b", re.I)NEGATION = re.compile(r"\b(not|isn't|aren't|doesn't|don't|never|no longer|rather than|instead of)\b", re.I)PAST = re.compile(r"\b(was|were|did|had|used to|formerly|originally)\b", re.I)QUANTIFIER = re.compile(r"\b(all|every|each|some|any|most|three|two|both|several|many|few|\d+)\b", re.I)# A capital letter at the start of a sentence is not a name. Taking "What", "Compare", "Is" as entities is the# same head-word disease this whole line exists to fix, and the first version of this file had it.NOT_A_NAME = {'what', 'which', 'who', 'when', 'where', 'why', 'how', 'is', 'are', 'was', 'were', 'do', 'does', 'did', 'can', 'could', 'will', 'would', 'should', 'tell', 'give', 'list', 'name', 'compare', 'explain', 'describe', 'summarize', 'summarise', 'correct', 'the', 'a', 'an', 'so', 'and', 'but', 'if', 'that', 'this', 'it', 'they', 'in', 'on', 'at', 'for', 'write', 'solve', 'find'}# word-bounded and applied to the LOWERCASED utterance (fixed 2026-09-23): unbounded, it matched the tail of every# capitalised word, so "Summarize the Internet" yielded the subjects 'ummarize' and 'nternet'CONTENT = re.compile(r"\b([a-z][a-z'-]{3,})\b")FUNCTION = {'about', 'from', 'with', 'into', 'than', 'then', 'have', 'been', 'does', 'made', 'more', 'most', 'much', 'many', 'some', 'such', 'like', 'also', 'just', 'over', 'under', 'between', 'because', 'there', 'here', 'them', 'their', 'your', 'mine', 'ours', 'wrong', 'right', 'mean', 'means'}
@dataclassclass Obligation: """something the answer must satisfy to BE an answer. Verification is against these, never against fragments.""" name: str kind: str # resolve | retrieve | relate | join | compute | contrast | decide | explain argument: str = '' satisfied_by: str = '' # filled at execution: what satisfied it satisfied: bool | None = None # None until executed note: str = ''
@dataclassclass Request: """the intermediate representation. One shape; the program TYPE varies over it.""" utterance: str program_type: str = 'unknown' entities: list = field(default_factory=list) discourse_referents: list = field(default_factory=list) # pronouns needing binding from prior turns requested_relation: str = '' requested_operation: str = '' quantifiers: list = field(default_factory=list) polarity: str = 'positive' tense: str = 'present' obligations: list = field(default_factory=list) completion_criteria: list = field(default_factory=list) content_subjects: list = field(default_factory=list) unbuildable: list = field(default_factory=list)
# Each program type declares the obligations its answers must satisfy. These are the SHAPES of questions, and a# kernel slot is an executable question-shape rather than a prose template: definition, constitution, mechanism,# contrast, criterion, limitation, consequence.PROGRAM_TYPES = { 'definition': ['resolve:subject', 'retrieve:genus', 'retrieve:differentia', 'explain:definition'], 'constitution': ['resolve:subject', 'relate:part_of', 'explain:composition'], 'mechanism': ['resolve:subject', 'relate:process', 'join:steps', 'explain:mechanism'], 'cause': ['resolve:subject', 'relate:causal_edge', 'decide:cause_vs_result', 'explain:causation'], 'dependence': ['resolve:dependent', 'resolve:dependency', 'retrieve:consumes', 'retrieve:produces', 'join:through_intermediate', 'decide:dependency_follows', 'explain:why_needed'], 'comparison': ['resolve:left', 'resolve:right', 'retrieve:left_properties', 'retrieve:right_properties', 'contrast:shared_dimension', 'explain:difference'], 'counterfactual': ['resolve:subject', 'relate:causal_edge', 'decide:antecedent_removed', 'explain:consequence'], 'enumeration': ['resolve:subject', 'retrieve:n_facts', 'decide:distinctness', 'explain:list'], 'summarization': ['resolve:scope', 'retrieve:claims_in_scope', 'contrast:redundancy', 'explain:summary'], 'correction': ['resolve:prior_claim', 'retrieve:contrary_evidence', 'decide:which_holds', 'explain:correction'], 'coding': ['resolve:specification', 'compute:program', 'decide:satisfies_specification', 'explain:program'], 'computation': ['resolve:operands', 'resolve:operation', 'compute:exact', 'explain:steps'], 'argumentation': ['resolve:thesis', 'retrieve:premises', 'join:dependency_graph', 'contrast:objections', 'decide:thesis_supported', 'explain:argument'],}
# surface cues -> program type. Deliberately small and readable: this is a claim about which question is being# asked, and a wrong claim here should be legible in the trace rather than buried.CUES = [ ('dependence', re.compile(r"\bwhy (?:does|do|is|are|would).{0,40}\b(?:need|require|depend|use)\b", re.I)), ('dependence', re.compile(r"\b(?:need|require|depend on)\b.{0,30}\?", re.I)), ('counterfactual', re.compile(r"\bwhat if\b|\bwould happen if\b|\bhad .{0,20} not\b|\bwithout\b.{0,30}\?", re.I)), ('cause', re.compile(r"\bwhat causes?\b|\bwhy (?:does|do|is|are)\b|\bcause or (?:a )?result\b", re.I)), ('comparison', re.compile(r"\bcompare\b|\bdifference between\b|\bhow is .{0,30} different\b|\bversus\b|\bvs\.?\b", re.I)), ('correction', re.compile(r"\bcorrect me\b|\bthat'?s wrong\b|\bactually,?\b|\bisn'?t it\b", re.I)), ('summarization', re.compile(r"\bsummari[sz]e\b|\bwhat have we\b|\bso far\b|\brecap\b", re.I)), ('enumeration', re.compile(r"\blist\b|\bname (?:three|two|\d+)\b|\bgive me (?:three|two|\d+)\b", re.I)), ('mechanism', re.compile(r"\bhow does\b|\bhow do\b|\bhow is .{0,20} made\b|\bwork\b\s*\?", re.I)), ('constitution', re.compile(r"\bmade of\b|\bcomposed of\b|\bparts of\b|\bconsists? of\b", re.I)), ('computation', re.compile(r"\d.{0,20}(?:%|percent|times|plus|minus|divided)|\bsquare root\b|\bsolve for\b", re.I)), ('coding', re.compile(r"\bwrite a (?:python|javascript|java|c|go|sql)\b|\bfunction that\b|\bclass for\b", re.I)), ('definition', re.compile(r"^\s*what (?:is|are|was|were)\b|\btell me about\b|\bwhat'?s\b", re.I)),]
def classify(utterance): for name, rx in CUES: if rx.search(utterance or ''): return name return 'unknown'
def compile_request(utterance, discourse_topics=()): """utterance -> Request with its obligations. Executes nothing.""" u = ' '.join(str(utterance or '').split()) r = Request(utterance=u) r.program_type = classify(u) # names, minus anything that is only capitalised because it began the sentence r.entities = [m.group(1) for m in PROPER.finditer(u) if m.group(1).split()[0].lower() not in NOT_A_NAME] # lowercase content nouns are subjects too - "compare photosynthesis with respiration" names two things and # capitalises neither r.content_subjects = [w for w in CONTENT.findall(u.lower()) if w not in FUNCTION and w not in NOT_A_NAME] r.discourse_referents = sorted({m.group(1).lower() for m in PRONOUN.finditer(u)}) r.quantifiers = sorted({m.group(1).lower() for m in QUANTIFIER.finditer(u)}) r.polarity = 'negative' if NEGATION.search(u) else 'positive' r.tense = 'past' if PAST.search(u) else 'present'
# the requested relation is what the answer must ESTABLISH, not what the words resemble if r.program_type == 'dependence': r.requested_relation = 'functional_dependence' elif r.program_type in ('cause', 'counterfactual'): r.requested_relation = 'causal' elif r.program_type == 'comparison': r.requested_relation = 'contrast_on_shared_dimension' elif r.program_type in ('definition', 'constitution'): r.requested_relation = 'taxonomic' r.requested_operation = r.program_type
template = PROGRAM_TYPES.get(r.program_type) if not template: r.unbuildable.append('no program type recognised for this utterance') return r
# the SUBJECTS of the program: named entities, else the discourse referents that must be bound from prior turns subjects = list(r.entities) + [c for c in r.content_subjects if c not in {e.lower() for e in r.entities}] for step in template: kind, _, arg = step.partition(':') ob = Obligation(name=step, kind=kind, argument=arg) if kind == 'resolve': if r.discourse_referents and not subjects: # THE FAILURE THE TRACES KEEP SHOWING: the act is identified and its subject is a pronoun that # nothing binds. Recorded as an obligation with a named source, not as a dead end. ob.note = 'subject is a discourse referent (%s); must bind from prior turns' % ', '.join(r.discourse_referents) elif subjects: ob.note = 'candidate: %s' % subjects[0] else: ob.note = 'no subject available in the utterance' r.obligations.append(ob)
r.completion_criteria = ['every obligation satisfied', 'the established relation is the one requested (%s)' % (r.requested_relation or 'n/a'), 'each claim carries a warrant', 'no two admitted claims contradict'] if r.program_type == 'comparison' and len(subjects) < 2: r.unbuildable.append('comparison needs two subjects; found %d' % len(subjects)) return r
def verify(request, trace): """check the completed trace against the OBLIGATIONS - never against the fragments it produced.""" got = {str(k) for k in (trace or {}).keys()} unmet = [] for ob in request.obligations: ob.satisfied = ob.name in got ob.satisfied_by = str((trace or {}).get(ob.name, ''))[:120] if not ob.satisfied: unmet.append(ob.name) return {'satisfied': len(request.obligations) - len(unmet), 'total': len(request.obligations), 'unmet': unmet, 'answerable': not unmet}
def main(): a = sys.argv[1:] packet = a[a.index('--packet') + 1] if '--packet' in a else '/root/fresh_conv_test.json' prompts = [] try: d = json.loads(Path(packet).read_text(encoding='utf-8')) for name, turns in d.items(): for t in (turns if isinstance(turns, list) else []): q = t[0] if isinstance(t, (list, tuple)) and t else (t if isinstance(t, str) else '') if q: prompts.append((name, q)) except Exception as exc: # noqa: BLE001 print('packet unreadable (%s); using built-in examples' % exc) prompts = [('example', 'Why does a compiler need a parser?'), ('example', 'Is oxygen a cause or a result of photosynthesis?'), ('example', 'Compare photosynthesis with respiration.'), ('example', 'List three facts about it.')]
print('%d prompts\n' % len(prompts)) unknown = 0 unbound = 0 for name, q in prompts: r = compile_request(q) if r.program_type == 'unknown': unknown += 1 needs_binding = [o for o in r.obligations if 'discourse referent' in o.note] if needs_binding: unbound += 1 print('%-14s %-46s -> %s' % (name, q[:44], r.program_type)) print(' relation : %s | entities: %s | referents: %s' % (r.requested_relation or '-', ', '.join(r.entities[:3]) or '-', ', '.join(r.discourse_referents) or '-')) print(' program : %s' % ' -> '.join(o.name for o in r.obligations)) for o in needs_binding: print(' UNBOUND : %s (%s)' % (o.name, o.note)) for u in r.unbuildable: print(' UNBUILDABLE: %s' % u) print() print('%d prompts | %d had no recognised program type | %d have an unbound subject' % (len(prompts), unknown, unbound)) return 0
if __name__ == '__main__': raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142#!/usr/bin/env python3"""R1 — ConceptNet commonsense adapter for the release runtime.
Typed edge retrieval over the sealed M13e5 ConceptNet specialist(m13e5_conceptnet_build_a_v1, index sha 5e28406c...), rendered with provenance.Zero-model: SQL + deterministic rendering only. Speech uses ConceptNet's owncrowd-authored surface_text where present (attributed), otherwise a typedrelation template. Every released line carries its edge provenance; emptyretrieval is an explicit abstention, never a guess."""
from __future__ import annotations
import reimport sqlite3from pathlib import Pathfrom typing import Any
PHASE = Path(__file__).resolve().parents[1] / "fable-content" / "oracle-m-series-2026-08-15"DEFAULT_BUILD = PHASE / "m13e5_conceptnet_build_a_v1" / "conceptnet_specialist.sqlite3"
# Relation -> (question forms it answers, deterministic template)RELATION_TEMPLATES: dict[str, str] = { "IsA": "{start} is a kind of {end}", "PartOf": "{start} is part of {end}", "HasA": "{start} has {end}", "UsedFor": "{start} is used for {end}", "CapableOf": "{start} can {end}", "AtLocation": "{start} is typically found at {end}", "Causes": "{start} causes {end}", "HasSubevent": "{start} involves {end}", "HasPrerequisite": "{start} requires {end}", "MotivatedByGoal": "{start} is motivated by {end}", "Desires": "{start} desires {end}", "MadeOf": "{start} is made of {end}", "ReceivesAction": "{start} can be {end}", "HasProperty": "{start} is {end}", "Synonym": "{start} is a synonym of {end}", "Antonym": "{start} is an antonym of {end}", "DistinctFrom": "{start} is distinct from {end}", "SimilarTo": "{start} is similar to {end}", "RelatedTo": "{start} is related to {end}",}
QUESTION_ROUTES: list[tuple[re.Pattern[str], list[str]]] = [ (re.compile(r"^what is (?:a |an |the )?(.+?) used for\??$", re.I), ["UsedFor"]), (re.compile(r"^what can (?:a |an |the )?(.+?) do\??$", re.I), ["CapableOf"]), (re.compile(r"^where (?:would you |do you |can you )?find (?:a |an |the )?(.+?)\??$", re.I), ["AtLocation"]), (re.compile(r"^where is (?:a |an |the )?(.+?) (?:usually |typically )?found\??$", re.I), ["AtLocation"]), (re.compile(r"^what (?:does|do) (?:a |an |the )?(.+?) have\??$", re.I), ["HasA"]), (re.compile(r"^what is (?:a |an |the )?(.+?) made of\??$", re.I), ["MadeOf"]), (re.compile(r"^what causes (?:a |an |the )?(.+?)\??$", re.I), ["Causes:end"]), (re.compile(r"^what (?:does|do) (?:a |an |the )?(.+?) cause\??$", re.I), ["Causes"]), (re.compile(r"^what kind of thing is (?:a |an |the )?(.+?)\??$", re.I), ["IsA"]), (re.compile(r"^what (?:is|are) (?:a |an |the )?(.+?) (?:a )?(?:kind|type|sort) of\??$", re.I), ["IsA"]), (re.compile(r"^what is (?:a |an |the )?(.+?) part of\??$", re.I), ["PartOf"]), (re.compile(r"^what (?:is|are) (?:the )?parts? of (?:a |an |the )?(.+?)\??$", re.I), ["PartOf:end", "HasA"]), (re.compile(r"^what do(?:es)? (?:a |an |the )?(.+?) require\??$", re.I), ["HasPrerequisite"]), (re.compile(r"^what is (?:a |an |the )?(.+?) similar to\??$", re.I), ["SimilarTo", "Synonym"]), (re.compile(r"^what is (?:the )?opposite of (?:a |an |the )?(.+?)\??$", re.I), ["Antonym"]),]
_SURFACE_BRACKETS = re.compile(r"\[\[|\]\]")
class ConceptNetAdapter: def __init__(self, build_path: Path | str = DEFAULT_BUILD): build_path = Path(build_path) if not build_path.is_file(): raise FileNotFoundError(str(build_path)) uri = build_path.resolve().as_uri() + "?mode=ro&immutable=1" self.connection = sqlite3.connect(uri, uri=True)
# ── retrieval ──────────────────────────────────────────────────────── def edges(self, concept: str, relation: str, *, reverse: bool = False, limit: int = 6) -> list[dict[str, Any]]: concept = concept.strip().lower() column, other = ("end", "start") if reverse else ("start", "end") rows = self.connection.execute( f"SELECT rel, start, end, weight, surface_text, dataset FROM edge " f"WHERE {column}=? AND rel=? ORDER BY weight DESC, start, end LIMIT ?", (concept, relation, limit)).fetchall() return [{"rel": r[0], "start": r[1], "end": r[2], "weight": r[3], "surface_text": r[4], "dataset": r[5], "provenance": f"conceptnet57:{r[0]}:{r[1]}->{r[2]}"} for r in rows]
def neighborhood(self, concept: str, *, limit_per_relation: int = 4) -> dict[str, list[dict[str, Any]]]: out: dict[str, list[dict[str, Any]]] = {} for relation in RELATION_TEMPLATES: if relation == "RelatedTo": continue # too diffuse for a summary; available via edges() found = self.edges(concept, relation, limit=limit_per_relation) if found: out[relation] = found return out
# ── rendering ──────────────────────────────────────────────────────── @staticmethod def render_edge(edge: dict[str, Any]) -> str: surface = (edge.get("surface_text") or "").strip() if surface: text = _SURFACE_BRACKETS.sub("", surface).lstrip("*").strip() if text: return text[0].upper() + text[1:].rstrip(".") + "." template = RELATION_TEMPLATES.get(edge["rel"], "{start} relates to {end}") text = template.format(start=edge["start"], end=edge["end"]) return text[0].upper() + text[1:] + "."
def answer(self, question: str) -> dict[str, Any]: """Route a commonsense question form; abstain explicitly otherwise.""" text = " ".join(question.strip().split()) for pattern, relations in QUESTION_ROUTES: match = pattern.match(text) if not match: continue concept = match.group(1).strip().lower() collected: list[dict[str, Any]] = [] for spec in relations: relation, _, direction = spec.partition(":") collected.extend(self.edges(concept, relation, reverse=(direction == "end"))) if not collected: return {"status": "withheld", "operation": "conceptnet_no_admitted_edges", "concept": concept, "response": f"The commonsense index has no admitted edges answering that about {concept}.", "claims": []} seen: set[str] = set() lines = [] claims = [] for edge in collected: rendered = self.render_edge(edge) if rendered in seen: continue seen.add(rendered) lines.append(rendered) claims.append({"provenance": edge["provenance"], "weight": edge["weight"], "dataset": edge["dataset"]}) if len(lines) >= 5: break return {"status": "answered", "operation": "conceptnet_commonsense", "concept": concept, "response": " ".join(lines), "claims": claims} return {"status": "unrouted", "operation": "conceptnet_form_not_registered", "response": "", "claims": []}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135#!/usr/bin/env python3"""Runtime AA — evidence-mined tiered cues for the explanatory routes (additive over Z).
M24's cue inventories were authored by guessing and the route stress test showedthe cost: how 10%, what_causes 28%, when 65% answer-rate. Iteration 4 mined400,000 admitted sentences to find the forms the corpus ACTUALLY uses, and theguesses had missed the most frequent ones outright:
cause : "led to" 1,117 · "so that" 1,012 · "as a result" 372 · "result of" 340 process : "uses" 3,647 · "when the" 3,580 · "is called" 3,108 · "is/are formed" 263 date : "was released" 1,038 · "was built" 560 · "took place" 323 ("built" was in the question regex but NOT in the inception cues at all)
Widening naively would trade precision for recall, so the cues are TIERED: aspecific form is preferred, and a broad one is consulted only when no specificform matches. Frequency alone does not promote a cue — "makes" is frequent butweakly causal, so it sits in the last tier.
Also fixes a sentence-quality defect the harness surfaced: sentence extractionsometimes yields a fragment starting mid-parenthetical ("1938) is a psychologist..."), which is cited and correct but reads as broken. Such fragments areskipped in favour of the next admitted sentence."""
from __future__ import annotations
import reimport time
from oracle_release_runtime_z import OracleReleaseRuntimeZ
# tier 1 = explicitly the relation; tier 2 = strongly indicative; tier 3 = weak fallbackCAUSE_TIERS = [ re.compile(r"\b(caused by|is caused|are caused|due to|results? from|triggered by|produced by)\b", re.I), re.compile(r"\b(because|led to|leads to|as a result|result of|gives rise to)\b", re.I), re.compile(r"\b(causes|makes|so that|therefore|happens when|occurs when)\b", re.I),]PROCESS_TIERS = [ re.compile(r"\b(happens when|occurs when|forms? when|is formed|are formed|works? by|by which|through which)\b", re.I), re.compile(r"\b(process|is made|are made|begins when|starts when|when there is)\b", re.I), re.compile(r"\b(uses|when the|is called|moves|produces)\b", re.I),]# Date cues are conditioned on the VERB ACTUALLY ASKED, not a fixed tier order.# A flat specific-first ordering regressed "When did WWII start?" to "The Tanggu# Truce ... was signed in 1933" because `was signed` outranked `began`. The asked# verb is the correct selector: it says which event the questioner means.VERB_CUES = { "start": [r"\b(began|begun|started|broke out|was launched)\b", r"\b(was founded|was established|was created)\b"], "begin": [r"\b(began|begun|started|broke out|was launched)\b", r"\b(was founded|was established|was created)\b"], "end": [r"\b(ended|finished|collapsed|surrendered|was dissolved)\b"], "found": [r"\b(was founded|was established|was created|founded)\b"], "built": [r"\b(was built|was constructed|built between|was completed)\b"], "build": [r"\b(was built|was constructed|built between|was completed)\b"], "discover": [r"\b(was discovered|discovered)\b"], "invent": [r"\b(was invented|invented)\b"], "born": [r"\b(was born|born)\b"], "die": [r"\b(died|was killed)\b"], "happen": [r"\b(took place|happened|occurred|was held)\b"], "occur": [r"\b(took place|happened|occurred|was held)\b"],}INCEPT_GENERAL = [ re.compile(r"\b(began|begun|started|was founded|was built|was established|was created|took place|broke out)\b", re.I), re.compile(r"\b(opened|ended|was released|was signed|was discovered|was invented|born|died)\b", re.I),]YEAR = re.compile(r"\b(1[0-9]{3}|20[0-2][0-9])\b")FRAGMENT = re.compile(r"^\s*(?:[a-z]|\d{1,4}\s*[)\]])") # "1938) is ..." / lowercase start
class OracleReleaseRuntimeAA(OracleReleaseRuntimeZ): def _pick_tiered(self, topic: str, tiers: list, *, require_year: bool = False) -> list[dict]: bundle = self._bundle(topic, n=60) if not bundle: singular = topic[:-1] if topic.endswith("s") and not topic.endswith("ss") else None if singular and len(singular) > 2: bundle = self._bundle(singular, n=60) if not bundle: return [] usable = [c for c in bundle if not FRAGMENT.match(str(c.get("sentence") or ""))] if not usable: usable = bundle for tier in tiers: # specific first, broad only as fallback hits = [] for claim in usable: sentence = str(claim.get("sentence") or "") if require_year and not YEAR.search(sentence): continue if tier.search(sentence): hits.append(claim) if hits: return hits return []
def _explanatory_turn(self, text: str) -> dict | None: # override Y from oracle_release_runtime_y import CAUSE_Q, HOW_Q, WHEN_Q stripped = " ".join(text.strip().split())
match = CAUSE_Q.match(stripped) if match: topic = match.group("t").strip() return self._render(topic, self._pick_tiered(topic, CAUSE_TIERS), "cause", "capability:what_causes", f"what causes {topic}")
match = HOW_Q.match(stripped) if match: topic = match.group("t").strip() return self._render(topic, self._pick_tiered(topic, PROCESS_TIERS), "process", "capability:how_does", f"how {topic} works")
match = WHEN_Q.match(stripped) if match: topic = match.group("t").strip() verb = (match.group("v") or "").lower() tiers = [] for stem, patterns in VERB_CUES.items(): if verb.startswith(stem): tiers = [re.compile(pat, re.I) for pat in patterns] break tiers = tiers + INCEPT_GENERAL hits = self._pick_tiered(topic, tiers, require_year=True) \ or self._pick_tiered(topic, [YEAR], require_year=True) return self._render(topic, hits, "inception", "capability:when_did", f"when {topic} {match.group('v')}") return None
def chat(self, text: str, session_id: str = "default") -> dict: started = time.perf_counter() result = None try: result = self._explanatory_turn(text) except Exception: # noqa: BLE001 result = None if result is not None: result["latency_ms"] = round(1000.0 * (time.perf_counter() - started), 1) result["zero_model_gate"] = {"lm_calls": 0, "transformer_calls": 0} return result return super().chat(text, session_id)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140#!/usr/bin/env python3"""Runtime AC — explain-simply picks the identifying sentence (additive over AB).
Iteration 6 diagnosis. `_definitional_score` returns 0 for every sentence on abiographical page (it keys on copular definition patterns that proper-noun prosedoes not use), so selection fell through to the tiebreak `-len(words)` — theSHORTEST sentence wins. That systematically chose trivia and fragments over thesentence that identifies the subject:
"Explain Paco Gento simply." -> "He played for Spain national team." "Explain Arthur C. Clarke simply." -> "He also wrote many short stories." "Explain Bernard Montgomery simply."-> "Later, in World War II." (a fragment)
In encyclopedic prose the FIRST sentence of a page is by convention the one thatsays what the subject is. So on a score tie the tiebreak now prefers EARLIERposition rather than fewer words, and sentences that cannot stand alone (nofinite verb, or opening mid-parenthetical) are skipped. Brevity is stillpreferred among sentences that actually define.
Note on the metric that found this: `explain_simply` on-topic looked like thesame false-drift artifact that `list` produced, but it was not. For an"explain X" question, mentioning X is not a proxy for relevance — it IS therequirement, because an explanation that never identifies its subject has notexplained it."""
from __future__ import annotations
import reimport time
from oracle_release_runtime_ab import OracleReleaseRuntimeABfrom oracle_release_runtime_m import SIMPLY, _definitional_scorefrom stage5m13e8_relevance_gate_v1 import gate_bundle
_WORD = chr(92) + "b" # backslash-b built at runtime; heredocs eat the literalFINITE_VERB = re.compile(_WORD + r"(is|are|was|were|has|have|had|does|did|can|" r"could|will|would|became|becomes|plays|played|wrote|" r"made|makes|lives|lived|died|won|led|serves|served)" + _WORD, re.I)OPENS_MID = re.compile(r"^\s*(?:[a-z]|\d{1,4}\s*[)\]]|later,|however,|also,|then,)", re.I)
def _standalone(sentence: str) -> bool: """Can this sentence stand alone as an identification?""" text = str(sentence or "").strip() if len(text.split()) < 4 or OPENS_MID.match(text): return False return bool(FINITE_VERB.search(text))
class OracleReleaseRuntimeAC(OracleReleaseRuntimeAB): def _simply_turn(self, text: str, session_id: str) -> dict | None: # override M match = SIMPLY.match(text.strip()) if not match: return None topic = (match.group("t") or match.group("t2") or "").strip() if not topic: return None bundle = self._bundle(topic, n=8) admitted, _ = gate_bundle(topic, bundle) gloss = self._gloss(topic) if not admitted and not gloss: return {"status": "withheld", "path": "capability:explain_simply", "response": f"No provenance-admitted material on {topic} is available to explain.", "provenance": {"kind": "simple_register", "topic": topic}} parts: list[str] = [] premises: list[str] = [] if admitted: order = {c["claim_id"]: i for i, c in enumerate(bundle)} standalone = [c for c in admitted if _standalone(c.get("sentence"))] pool = standalone or admitted short_defs = [c for c in pool if len(c["sentence"].split()) <= 30 and _definitional_score(topic, c["sentence"]) >= 6] if short_defs: lead = max(short_defs, key=lambda c: (_definitional_score(topic, c["sentence"]), -len(c["sentence"].split()))) else: # No scored definition (typical of proper-noun pages): take the # page's own opening sentence, which is the identifying one. lead = min(pool, key=lambda c: order.get(c["claim_id"], 10_000)) parts.append(f"{lead['sentence']} [{lead['claim_id']}]") premises.append(lead["claim_id"]) if gloss: parts.append(f"The dictionary sense: {gloss}. [wiktionary:{topic.lower()}:sense1]") premises.append(f"wiktionary:{topic.lower()}") return {"status": "answered", "path": "capability:explain_simply", "response": "In simple terms: " + " ".join(parts), "provenance": {"kind": "simple_register", "topic": topic, "premises": premises}}
def _timeline_turn(self, text: str, session_id: str) -> dict | None: # override J result = super()._timeline_turn(text, session_id) if not result or result.get("status") != "answered": return result body = str(result.get("response", "")) distinct = {y for y in year_tokens(body)} if len(distinct) >= 2: return result topic_note = "the admitted material yields fewer than two distinct dates" return {"status": "withheld", "path": "capability:timeline", "response": f"A timeline needs at least two distinct dated statements; " f"{topic_note}. I will not present a measurement as a date.", "provenance": {"kind": "temporal_projection", "result": "insufficient_distinct_dates"}}
def chat(self, text: str, session_id: str = "default") -> dict: started = time.perf_counter() result = None try: result = self._simply_turn(" ".join(text.strip().split()), session_id) except Exception: # noqa: BLE001 result = None if result is not None: result["latency_ms"] = round(1000.0 * (time.perf_counter() - started), 1) result["zero_model_gate"] = {"lm_calls": 0, "transformer_calls": 0} return result return super().chat(text, session_id)
# ── timeline: a year token is not the same thing as a number ────────────────# The route treated any 4-digit token as a date, so "One megasecond contains# 1000 kiloseconds" was rendered as the year 1000, and a page with one date# repeated produced a single-point "timeline". A date must not be a measurement,# and a timeline needs at least two DISTINCT years.UNIT_AFTER = re.compile( r"^(?:kilo|mega|giga|milli|micro|nano)?" r"(?:second|meter|metre|gram|litre|liter|byte|watt|hertz|mile|foot|feet|inch|" r"year|month|week|day|hour|minute|people|person|km|kg|cm|mm|ft|lb)s?$", re.I)
def year_tokens(sentence: str) -> list[int]: """4-digit years in a sentence, excluding numbers that are measurements.""" text = str(sentence or "") out: list[int] = [] for match in re.finditer(r"(1[0-9]{3}|20[0-2][0-9])", text): tail = text[match.end():].lstrip() next_word = tail.split()[0].strip(".,;:)") if tail.split() else "" if next_word and UNIT_AFTER.match(next_word): continue # "1000 kiloseconds" is a quantity, not a date out.append(int(match.group(1))) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104#!/usr/bin/env python3"""Runtime AG - cite a genuine hypernym chain (additive over AF).
AF answered correctly but CITED INCORRECTLY:
"Yes. The lexical record places gray whale under whale: organism -> living thing -> whole -> object -> physical entity -> gray whale"
The claimed hypernym ("whale") does not appear in the chain shown. Corpus v1stored each synset's total path length as the depth of every node on that path,so all hypernyms of a sense shared one meaningless value and ordering by itproduced a sequence that was not a hypernym path at all.
For a system whose entire claim is shown provenance, citing a chain that does notcontain the cited term is the most serious defect available - worse than theparser bug, because the answer looks right and the evidence is fabricatedstructure.
Corpus v2 stores each node's own distance from the root, so ascending depth is agenuine general-to-specific ordering. This runtime reads v2, renders the chain inthat order, and guarantees the cited hypernym appears in what it shows. It alsonever presents more than the real path: nodes are drawn from the lemma's ownclosure only.
No neural network; no LM call."""
from __future__ import annotations
import sqlite3import timefrom pathlib import Path
from oracle_release_runtime_af import OracleReleaseRuntimeAF
WORDNET_CORPUS_V2 = (__import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/fable-content/oracle-m-series-2026-08-15" "/m31_wordnet_corpus_v2.sqlite3")
class OracleReleaseRuntimeAG(OracleReleaseRuntimeAF): def __init__(self, *args, wordnet_corpus: str = WORDNET_CORPUS_V2, **kwargs) -> None: super().__init__(*args, wordnet_corpus=wordnet_corpus, **kwargs)
def _chain_for(self, lemma: str, limit: int = 6) -> list: """General -> specific, by each node's own distance from the root.""" rows = self._wn.execute( "SELECT hypernym FROM lemma_closure WHERE lemma=? ORDER BY depth ASC, hypernym ASC " "LIMIT ?", (lemma, limit)).fetchall() return [r[0] for r in rows]
def _render_chain(self, lemma: str, hypernym: str | None) -> str: """The shown chain must contain the cited hypernym, or it is not evidence.""" chain = self._chain_for(lemma, limit=6) if hypernym and hypernym not in chain: row = self._wn.execute( "SELECT depth FROM lemma_closure WHERE lemma=? AND hypernym=?", (lemma, hypernym)).fetchone() if row is not None: chain = self._chain_for(lemma, limit=5) if hypernym in chain: chain.remove(hypernym) chain = chain[:4] + [hypernym] return " -> ".join(chain + [lemma]) if chain else lemma
def _wordnet_turn(self, text: str) -> dict | None: if self._wn is None: return None parsed = self._parse_kind(text) if parsed is None: return None x, y = parsed lemma = self._present(x) if lemma is None: return None hit = self._closure_hit(lemma, y) article_x = "an" if x[:1] in "aeiou" else "a" article_y = "an" if y[:1] in "aeiou" else "a" if hit is not None: hypernym, _depth, sense = hit shown = self._render_chain(lemma, hypernym) return { "status": "answered", "path": "wordnet_kind_direct", "response": (f"Yes. The lexical record places {lemma} under {hypernym}, " f"from the general to the specific: {shown}. On that record " f"{article_x} {x} is {article_y} {y}. [cited:wordnet:{sense}]"), "provenance": {"kind": "lexical_corpus", "corpus": "wordnet", "relation": "hypernym", "lemma": lemma, "hypernym": hypernym, "sense": sense, "chain": self._chain_for(lemma) + [lemma]}, } shown = self._render_chain(lemma, None) return { "status": "answered", "path": "wordnet_kind_excluded", "response": (f"No. The lexical record places {lemma} on a different line, " f"from the general to the specific: {shown}. {y.capitalize()} does " f"not appear anywhere in that chain, and the chain is complete, so " f"this is an exclusion rather than a gap in the record. " f"[cited:wordnet:{lemma}]"), "provenance": {"kind": "lexical_corpus", "corpus": "wordnet", "relation": "hypernym_excluded", "lemma": lemma, "chain": self._chain_for(lemma) + [lemma]}, }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576#!/usr/bin/env python3"""Runtime AH - honest exclusion rendering (additive over AG).
AG fixed the affirmative citation but left the SAME defect class in the exclusionpath. Two problems, both of which fabricate structure:
1. Sense interleaving. The closure is a union over all senses, so rendering it as one arrow-path splices unrelated lineages:
"guinea pig: entity -> physical entity -> causal agent -> object -> person -> whole -> guinea pig"
That path does not exist. It mixes the rodent with the separate sense of a person used as a test subject.
2. Truncated scope. The text asserted a term "does not appear anywhere in that chain" while displaying only a six-node prefix, inviting the reader to verify an exhaustive claim against partial evidence.
Fix: an exclusion no longer claims a path. It reports the most specific categoriesthe record actually assigns - which are the sense-characteristic ones - as a SET,and states plainly that the exclusion was checked against the complete closurewhile what is shown is a summary of it. The affirmative path still shows a realchain, because there a single genuine lineage exists and contains the cited term.
Say only what the record supports, and show evidence in the shape it actually has.No neural network; no LM call."""
from __future__ import annotations
from oracle_release_runtime_ag import OracleReleaseRuntimeAG
SHOW_CATEGORIES = 6
class OracleReleaseRuntimeAH(OracleReleaseRuntimeAG): def _specific_categories(self, lemma: str, limit: int = SHOW_CATEGORIES) -> list: """Deepest hypernyms = the sense-characteristic ones. A set, not a path.""" rows = self._wn.execute( "SELECT hypernym FROM lemma_closure WHERE lemma=? ORDER BY depth DESC, hypernym ASC " "LIMIT ?", (lemma, limit)).fetchall() return [r[0] for r in rows]
def _closure_size(self, lemma: str) -> int: row = self._wn.execute( "SELECT COUNT(*) FROM lemma_closure WHERE lemma=?", (lemma,)).fetchone() return int(row[0]) if row else 0
def _wordnet_turn(self, text: str) -> dict | None: result = super()._wordnet_turn(text) if result is None or result.get("path") != "wordnet_kind_excluded": return result prov = result.get("provenance", {}) lemma = prov.get("lemma") parsed = self._parse_kind(text) if not lemma or parsed is None: return result _x, y = parsed cats = self._specific_categories(lemma) total = self._closure_size(lemma) listed = ", ".join(cats) if cats else "no categories on record" result["response"] = ( f"No. The record classifies {lemma} under {listed}" f"{' and other broader categories' if total > len(cats) else ''}. " f"{y.capitalize()} is not among the {total} categories on record for it, and " f"that record is complete, so this is an exclusion rather than a gap. " f"[cited:wordnet:{lemma}]") result["provenance"] = { "kind": "lexical_corpus", "corpus": "wordnet", "relation": "hypernym_excluded", "lemma": lemma, "categories_shown": cats, "categories_total": total, "note": ("categories are a set drawn from all senses, not a single lineage; " "the exclusion was checked against the complete closure"), } return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172#!/usr/bin/env python3"""Runtime AJ - lexicon-informed splitting for determiner-free questions (additive over AI).
M38 passed eight columns and still mis-parsed this:
"Is hand luggage luggage?" -> x='hand', y='luggage luggage' -> "No. The record classifies HAND under forepaw, paw, animal foot..."
With no determiner the strict pattern cannot anchor, and the loose pattern's non-greedysubject takes the shortest split. This is the M31 defect resurfacing in the form the M31fix did not cover, and no panel saw it because every generated question carriesdeterminers ("Is a X a Y?"). The route's own domain includes determiner-free forms;the test distribution did not.
Fix: when no determiner is available to anchor the split, use the admitted record as thelexicon. Enumerate every split point and choose the longest subject for which BOTH sidesare lemmas the corpus carries. Purely structural, no heuristic weighting - the recordalready knows which strings are terms.
"Is hand luggage luggage?" split 1: x='hand' y='luggage luggage' -> y not a lemma, rejected split 2: x='hand luggage' y='luggage' -> both lemmas, ACCEPTED
Determiner-bearing forms still take the strict path unchanged. No neural network."""
from __future__ import annotations
import re
from oracle_release_runtime_ai import OracleReleaseRuntimeAIfrom oracle_release_runtime_af import KIND_Q_STRICT, _FILLER, _LEADfrom oracle_release_runtime_ae import _forms
_BODY = re.compile( r"^(?:is|are)\s+(?:(?:an?|the|some)\s+)?(?P<body>[a-z][a-z '\-]+?)\s*[.?!]*$", re.I)MAX_WORDS = 8
class OracleReleaseRuntimeAJ(OracleReleaseRuntimeAI): def _valid_pair(self, x: str, y: str): if not x or not y or x == y or len(x) < 2 or len(y) < 2: return None if set(_forms(x)) & set(_forms(y)): return None return x, y
def _parse_kind(self, text: str): t = " ".join(text.strip().split()) t = " ".join(_FILLER.sub("", _LEAD.sub("", t)).split()) match = KIND_Q_STRICT.match(t) if match: return self._valid_pair(match.group("x").strip().lower(), match.group("y").strip().lower()) body_match = _BODY.match(t) if not body_match: return super()._parse_kind(text) words = body_match.group("body").strip().lower().split() if len(words) < 2 or len(words) > MAX_WORDS: return super()._parse_kind(text) chosen = None for cut in range(1, len(words)): x = " ".join(words[:cut]) y = " ".join(words[cut:]) pair = self._valid_pair(x, y) if pair is None: continue if self._present(x) and self._present(y): chosen = pair # keep iterating: prefer the LONGEST subject if chosen is not None: return chosen return super()._parse_kind(text)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455#!/usr/bin/env python3"""Runtime AM - record dialogue state from the FINAL result (additive over AL).
M46 passed and two defects survived it, both visible the moment turn-1 used a route otherthan summarize:
"Is a gray whale a whale?" -> answered by wordnet_kind_direct replay: "came via the DOCUMENT_RUNTIME route ... typed refusal" "What causes rain?" -> answered by capability:what_causes replay: "Nothing has been answered in this session yet"
Cause: dialogue state is written inside runtime E's chat, but answers are produced at manylayers of the chain. Routes resolved ABOVE E never write state at all; routes resolvedafter E (the whole AD..AL tier) leave E's record of the INNER result in place. The ACTSlayer therefore reads a state describing a different answer than the user received.
Fix: the top of the chain records what the user actually saw. State is written once, fromthe final result, after every turn - overwriting whatever inner layers recorded. Acts areconversions over the delivered answer, so the delivered answer is what must be stored.
M46 could not see this because every turn-1 probe in it was "Summarize X" - a single route,which happens to be one that flows through E. The test distribution must cover the routeinventory, not one member of it.
No neural network; no LM call."""
from __future__ import annotations
import re
from oracle_release_runtime_al import OracleReleaseRuntimeAL
CITE = re.compile(r"\[[a-z0-9_]+:?[a-z0-9_.\-]*\]")ACT_PATHS = ("act:provenance_replay", "act:acknowledge", "act:continue_topic", "act:refine")
class OracleReleaseRuntimeAM(OracleReleaseRuntimeAL): def chat(self, text: str, session_id: str = "default") -> dict: result = super().chat(text, session_id) path = str(result.get("path", "")) # acts are conversions OVER the last answer; they must not overwrite it if path in ACT_PATHS: return result try: slot = self.dialogue.setdefault(session_id, {}) slot["last_result"] = { "path": result.get("path"), "provenance": result.get("provenance"), "status": result.get("status"), "citations": CITE.findall(str(result.get("response", ""))), } except Exception: # noqa: BLE001 pass return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113#!/usr/bin/env python3"""Front-door successor C (additive over B): essay route + definitional route.
Essay route: "write an essay about X" -> the H2 gated document compiler overthe topic page plus up to two related pages (title matches carrying adistinctive topic token, relevance-gated). Output is a structured documentwhose thesis/conclusions/analyses/claims chain is verified byrecover_document before release; an unverifiable document is withheld.
Definitional route (closes the registered debt): "what is a/an X?" answerswith the gated definitional lead of X's page when the page exists, instead ofsense clarification."""
from __future__ import annotations
import reimport time
from oracle_release_runtime_b import OracleReleaseRuntimeBfrom stage5m13e8_document_compiler_v1 import compile_section, compile_document, recover_documentfrom stage5m13e8_paragraph_compiler_v1 import _definitional_scorefrom stage5m13e8_relevance_gate_v1 import topic_tokens, classify_claim
ESSAY = re.compile(r"^(?:please )?(?:write|compose)(?: me)?(?: a| an)?(?: short| brief)?(?: \d+[- ]word)? essay (?:about|on) (?P<topic>.+?)\.?$", re.I)DEFINITIONAL = re.compile(r"^what is (?:a |an |the )?(?P<term>[\w \-']{2,60})\?$", re.I)
class OracleReleaseRuntimeC(OracleReleaseRuntimeB): def _bundle(self, topic: str, n: int = 6) -> list[dict]: page = self.bench_query.page_id(topic) if not page: return [] return [{"claim_id": c, "page": topic, "sentence": s} for c, s in self.bench_query.page_sentences(page)[:n]]
def _related_titles(self, topic: str, cap: int = 2) -> list[str]: distinctive, _ = topic_tokens(topic) if not distinctive: return [] token = sorted(distinctive)[0] # indexed prefix range on title_alias (no full scan over 6M articles) rows = self.bench_query.connection.execute( "SELECT a.title FROM title_alias t JOIN article a ON a.page_id = t.page_id " "WHERE t.normalized_title >= ? AND t.normalized_title < ? LIMIT 12", (token, token + "")).fetchall() related = [] for (title,) in rows: if title.lower() == topic.lower(): continue if classify_claim(topic, title, title) in ("explanatory", "exact_topic"): related.append(title) if len(related) >= cap: break return related
def _essay_turn(self, text: str) -> dict | None: match = ESSAY.match(text.strip()) if not match: return None topic = match.group("topic").strip() topics = [topic] + self._related_titles(topic) bundles = [(t, self._bundle(t), None) for t in topics] bundles = [(t, b, None) for t, b, _ in bundles if b] if not bundles: return {"status": "withheld", "path": "gated_document", "response": f"No provenance-admitted page for {topic} is available to ground an essay.", "provenance": {"kind": "gated_document", "topic": topic}} section = compile_section(f"The record on {topic}", bundles) document = compile_document(f"A provenance-bounded account of {topic}", [section]) if not recover_document(document): return {"status": "withheld", "path": "gated_document", "response": "Document failed its own derivation-chain verification and is withheld.", "provenance": {"kind": "gated_document", "topic": topic, "failure": "recover_document"}} return {"status": "answered", "path": "gated_document", "response": document["text"], "provenance": {"kind": "gated_document", "topics": topics, "exclusions": [{"page": e["page"], "relevance": e["relevance"]} for e in section["exclusions"]]}}
def _definitional_turn(self, text: str) -> dict | None: match = DEFINITIONAL.match(text.strip()) if not match: return None term = match.group("term").strip() bundle = self._bundle(term.title()) or self._bundle(term) if not bundle: return None # fall through to sense machinery lead = max(bundle, key=lambda c: _definitional_score(term, c["sentence"])) if _definitional_score(term, lead["sentence"]) < 6: return None return {"status": "answered", "path": "definitional_encyclopedic", "response": f"{lead['sentence']} [{lead['claim_id']}]", "provenance": {"kind": "dbpedia_page", "page": lead["page"], "claim_id": lead["claim_id"]}}
def chat(self, text: str, session_id: str = "default") -> dict: started = time.perf_counter() normalized = " ".join(text.strip().split()) result = None for route in (lambda: self._essay_turn(normalized), lambda: self._definitional_turn(normalized)): try: result = route() except Exception: # noqa: BLE001 result = None if result is not None: break if result is None: return super().chat(text, session_id) result["latency_ms"] = round(1000.0 * (time.perf_counter() - started), 1) result["zero_model_gate"] = {"lm_calls": 0, "transformer_calls": 0} return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126#!/usr/bin/env python3"""Runtime E — conversation-act conversion layer, slice 1 (Ben's conversionthesis: dialogue is a finite inventory of typed conversions, not an emergentcapability).
Acts this slice: provenance_replay "why did you say that / how do you know / source?" -> re-present the last answer's provenance (addresses, rule+premises, or the typed reason for a withhold) continue_topic "tell me more / what else / more about that" -> next admitted claims from the last topic's page, composed and verified like any paragraph acknowledge "thanks / ok / great" -> typed acknowledgment, no fetch
Dialogue state is a per-session record {last_result, last_topic, last_offset}— a dictionary, not a model. Every act is a conversion over existingmachinery; nothing generates."""
from __future__ import annotations
import reimport time
from oracle_release_runtime_d import OracleReleaseRuntimeDfrom stage5m13e8_paragraph_compiler_v2 import compile_paragraph_v2, recover_program_v2
WHY = re.compile(r"^(?:why(?: did you say that| do you say that)?|how do you know(?: that)?|" r"what(?:'s| is) your source(?: for that)?|source\??|prove it|citation\??)[.?!]?$", re.I)MORE = re.compile(r"^(?:tell me more|more|what else|go on|continue|more about (?:that|it))[.?!]?$", re.I)ACK = re.compile(r"^(?:thanks|thank you|ok|okay|got it|great|cool|nice|perfect)[.?!]?$", re.I)
class OracleReleaseRuntimeE(OracleReleaseRuntimeD): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.dialogue: dict[str, dict] = {}
# ── act conversions ────────────────────────────────────────────────── def _act_provenance_replay(self, state: dict) -> dict: last = state.get("last_result") if not last: return {"status": "withheld", "path": "act:provenance_replay", "response": "Nothing has been answered in this session yet, so there is no provenance to replay."} prov = last.get("provenance") or {} kind = prov.get("kind", "unknown") lines = [f"My previous answer came via the {last.get('path','?')} route."] if kind == "dbpedia_page": lines.append(f"It is the definitional lead of the page '{prov.get('page')}', claim {prov.get('claim_id')}.") elif kind == "gated_paragraph": lines.append(f"It composed {prov.get('public_claims',0)} page-addressed claims" + (f" and {prov['user_claims']} claims from your own documents" if prov.get('user_claims') else "") + "; every sentence carries its claim address in brackets.") if prov.get("excluded"): lines.append("Excluded as insufficiently relevant (ledgered, not hidden): " + ", ".join(f"{e['page']} ({e['relevance']})" for e in prov["excluded"][:4]) + ".") elif kind == "conceptnet_edges": claims = prov.get("claims", []) lines.append(f"It rests on {len(claims)} ConceptNet edges: " + "; ".join(c.get("provenance", "?") for c in claims[:4]) + ".") elif kind == "session_world": lines.append(f"It was computed from the {prov.get('statements',0)} statements you asserted " "in this session's typed world — logic over your own facts, not retrieval.") else: lines.append("It was a typed refusal: no admitted evidence licensed an answer, so none was given.") lines.append("Nothing in that answer was generated; each part is either addressed, derived, or withheld.") return {"status": "answered", "path": "act:provenance_replay", "response": " ".join(lines), "provenance": {"kind": "dialogue_state_replay"}}
def _act_continue(self, state: dict, session_id: str) -> dict: topic = state.get("last_topic") if not topic: return {"status": "withheld", "path": "act:continue_topic", "response": "There is no active topic yet — ask about something first."} offset = state.get("last_offset", 0) + 6 page = self.anchors.resolve(topic) if not page: return {"status": "withheld", "path": "act:continue_topic", "response": f"No further admitted material for {topic}."} title = self.anchors.page_to_title.get(page, topic) rows = self.bench_query.page_sentences(page)[offset:offset + 4] if not rows: return {"status": "withheld", "path": "act:continue_topic", "response": f"The admitted record on {title} is exhausted — " f"every stored sentence has been shown."} claims = [{"claim_id": c, "page": title, "sentence": s} for c, s in rows] paragraph, program = compile_paragraph_v2(topic, claims, evidence=3, aggregation_term=None) if paragraph is None or not recover_program_v2(paragraph, program): return {"status": "withheld", "path": "act:continue_topic", "response": "Continuation failed verification and is withheld."} state["last_offset"] = offset return {"status": "answered", "path": "act:continue_topic", "response": paragraph, "provenance": {"kind": "gated_paragraph", "topic": topic, "offset": offset}}
# ── entry ──────────────────────────────────────────────────────────── def chat(self, text: str, session_id: str = "default") -> dict: started = time.perf_counter() normalized = " ".join(text.strip().split()) state = self.dialogue.setdefault(session_id, {}) result = None if WHY.match(normalized): result = self._act_provenance_replay(state) elif MORE.match(normalized): result = self._act_continue(state, session_id) elif ACK.match(normalized): result = {"status": "answered", "path": "act:acknowledge", "response": "Noted. The session state is kept; ask on.", "provenance": {"kind": "dialogue_state"}} if result is not None: result["latency_ms"] = round(1000.0 * (time.perf_counter() - started), 1) result["zero_model_gate"] = {"lm_calls": 0, "transformer_calls": 0} else: result = super().chat(text, session_id) # topic tracking for continuation acts path = result.get("path", "") prov = result.get("provenance") or {} if path == "anchored_summary": match = re.match(r"^(?:tell me about|who is|who was|what do you know about) (?:the )?(.+?)[.?!]?$", normalized, re.I) if match: state["last_topic"] = match.group(1).strip() state["last_offset"] = 0 elif path == "definitional_encyclopedic" and prov.get("page"): state["last_topic"] = prov["page"] state["last_offset"] = 0 self.dialogue[session_id]["last_result"] = {k: result.get(k) for k in ("path", "provenance", "status")} return result12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970#!/usr/bin/env python3"""Runtime H — capability cycle 3: list-N-things (additive over G)."""
from __future__ import annotations
import reimport time
from oracle_release_runtime_g import OracleReleaseRuntimeGfrom stage5m13e8_relevance_gate_v1 import gate_bundle
NUMERALS = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10, "a": 3, "an": 3, "some": 3, "few": 3, "several": 4, "couple": 2}LISTN = re.compile( r"^(?:please |can you )?(?:list|give me|tell me|name|share)" r"(?: (?P<n>\d+|one|two|three|four|five|six|seven|eight|nine|ten|a few|some|several|a couple(?: of)?))?" r" (?:facts?|things?|details?)(?: about| on| regarding)" r"(?: the| my document| my)? (?P<t>.+?)[.?!]?$" r"|^what are (?:some|a few) facts? about(?: the| my document| my)? (?P<t2>.+?)[.?!]?$", re.I)
class OracleReleaseRuntimeH(OracleReleaseRuntimeG): def _listn_turn(self, text: str, session_id: str) -> dict | None: match = LISTN.match(text.strip()) if not match: return None groups = match.groupdict() topic = (groups.get("t") or groups.get("t2") or "").strip() if not topic: return None raw_n = (groups.get("n") or "some").lower().replace("a couple of", "couple").replace("a couple", "couple").replace("a few", "few") n = int(raw_n) if raw_n.isdigit() else NUMERALS.get(raw_n, 3) n = max(1, min(n, 10)) user_claims = self.user_corpus.bundle(session_id, topic) admitted, _ = gate_bundle(topic, self._bundle(topic, n=10)) claims = (user_claims + admitted)[:n] if not claims: return {"status": "withheld", "path": "capability:list_n", "response": f"No provenance-admitted facts about {topic} are available to list.", "provenance": {"kind": "gated_list", "topic": topic}} lines = [f"{i+1}. {c['sentence']} [{c['claim_id']}]" for i, c in enumerate(claims)] shortfall = "" if len(claims) < n: shortfall = (f" Only {len(claims)} admitted fact" f"{'s are' if len(claims) != 1 else ' is'} available for {topic}.") return {"status": "answered", "path": "capability:list_n", "response": " ".join(lines) + shortfall, "provenance": {"kind": "gated_list", "topic": topic, "requested": n, "delivered": len(claims), "user_claims": len([c for c in claims if c["claim_id"].startswith("user:")])}}
def chat(self, text: str, session_id: str = "default") -> dict: started = time.perf_counter() normalized = " ".join(text.strip().split()) result = None try: result = self._listn_turn(normalized, session_id) except Exception: # noqa: BLE001 result = None if result is not None: result["latency_ms"] = round(1000.0 * (time.perf_counter() - started), 1) result["zero_model_gate"] = {"lm_calls": 0, "transformer_calls": 0} state = self.dialogue.setdefault(session_id, {}) state["last_result"] = {k: result.get(k) for k in ("path", "provenance", "status")} state["last_topic"] = result["provenance"].get("topic") state["last_offset"] = 0 return result return super().chat(text, session_id)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273#!/usr/bin/env python3"""Runtime K — capability cycle 6: explain-why-different (additive over J)."""
from __future__ import annotations
import reimport time
from oracle_release_runtime_j import OracleReleaseRuntimeJfrom stage5m13e8_paragraph_compiler_v1 import _definitional_score
WHYDIFF = re.compile( r"^(?:please )?(?:explain )?why are (?:the |a |an )?(?P<x>.+?) and (?:the |a |an |my document )?(?P<y>.+?) different[.?!]?$" r"|^(?:please )?(?:explain )?why is (?:the |a |an )?(?P<x2>.+?) different from (?:the |a |an |my document )?(?P<y2>.+?)[.?!]?$" r"|^(?:please )?(?:explain )?why (?:the |a |an )?(?P<x3>.+?) and (?:the |a |an |my document )?(?P<y3>.+?) are different[.?!]?$" r"|^what makes (?:the |a |an )?(?P<x4>.+?) different from (?:the |a |an |my document )?(?P<y4>.+?)[.?!]?$", re.I)KIND = re.compile(r"\bis (?:a|an|the) ([\w -]{3,40}?)(?:[,.]| that| which| in| of| with)")
class OracleReleaseRuntimeK(OracleReleaseRuntimeJ): def _whydiff_turn(self, text: str, session_id: str) -> dict | None: match = WHYDIFF.match(text.strip()) if not match: return None groups = match.groupdict() x = next((groups[k] for k in ("x", "x2", "x3", "x4") if groups.get(k)), "").strip() y = next((groups[k] for k in ("y", "y2", "y3", "y4") if groups.get(k)), "").strip() if not x or not y: return None side_x, _ = self._side(x, session_id) side_y, _ = self._side(y, session_id) missing = [t for t, s in ((x, side_x), (y, side_y)) if not s] if missing: return {"status": "withheld", "path": "capability:why_different", "response": f"I cannot explain the difference: no provenance-admitted material " f"exists for {' or '.join(missing)}.", "provenance": {"kind": "gated_whydiff", "missing": missing}} lead_x = max(side_x, key=lambda c: _definitional_score(x, c["sentence"])) lead_y = max(side_y, key=lambda c: _definitional_score(y, c["sentence"])) kind_x_match = KIND.search(lead_x["sentence"]) kind_y_match = KIND.search(lead_y["sentence"]) kind_x = kind_x_match.group(1).strip() if kind_x_match else None kind_y = kind_y_match.group(1).strip() if kind_y_match else None if kind_x and kind_y and kind_x.lower() != kind_y.lower(): reason = (f"Derived reason: they belong to different categories — {x} is attested as " f"a {kind_x}, whereas {y} is attested as a {kind_y}.") else: reason = (f"Derived reason: the admitted records place them in " f"{'the same attested category (' + kind_x + '); their difference lies in the particulars below' if kind_x else 'categories the leads do not name explicitly; the difference rests on the particulars below'}.") response = (f"According to {lead_x['page']}, {lead_x['sentence']} [{lead_x['claim_id']}] " f"According to {lead_y['page']}, {lead_y['sentence']} [{lead_y['claim_id']}] " f"{reason} [derived:category_contrast<-{lead_x['claim_id'][:12]},{lead_y['claim_id'][:12]}]") return {"status": "answered", "path": "capability:why_different", "response": response, "provenance": {"kind": "gated_whydiff", "x": x, "y": y, "derived": {"rule": "category_contrast", "premises": [lead_x["claim_id"], lead_y["claim_id"]]}}}
def chat(self, text: str, session_id: str = "default") -> dict: started = time.perf_counter() normalized = " ".join(text.strip().split()) result = None try: result = self._whydiff_turn(normalized, session_id) except Exception: # noqa: BLE001 result = None if result is not None: result["latency_ms"] = round(1000.0 * (time.perf_counter() - started), 1) result["zero_model_gate"] = {"lm_calls": 0, "transformer_calls": 0} state = self.dialogue.setdefault(session_id, {}) state["last_result"] = {k: result.get(k) for k in ("path", "provenance", "status")} return result return super().chat(text, session_id)1234567891011121314151617#!/usr/bin/env python3"""Runtime N — runtime M with the K8 batch-1 grammar wired into the sessionkernel (additive; the IR pipeline and all capability routes now parse throughthe ~190-construction inventory)."""
from __future__ import annotations
from oracle_release_runtime_m import OracleReleaseRuntimeMfrom stage5m13e2_construction_kernel_k8 import ConstructionKernelK8from stage5m13e4_migration2 import IRPipeline2
class OracleReleaseRuntimeN(OracleReleaseRuntimeM): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.kernel = ConstructionKernelK8(compositional=True) self.pipeline = IRPipeline2(self.kernel)12345678910111213141516171819202122232425262728293031323334#!/usr/bin/env python3"""Runtime P — M17a shadow arbitration (additive over O).
Every chat turn is scored by the M-series release arbiter (frozen K138 bidgeometry + M-series families) and the ArbitrationRecord summary is attached tothe result as advisory metadata. Dispatch is UNCHANGED — the regex chain stillcommits every action; the arbiter observes. Agreement per turn is recorded sothe live residue log accumulates the shadow scoreboard for the M17b promotiongate. Advisory failure can never break a turn."""
from __future__ import annotations
from oracle_release_runtime_o import OracleReleaseRuntimeOfrom stage5m17_release_arbiter_v1 import arbitrate, path_family
class OracleReleaseRuntimeP(OracleReleaseRuntimeO): def chat(self, text: str, session_id: str = "default") -> dict: result = super().chat(text, session_id) try: record = arbitrate(" ".join(text.strip().split())) regex_family = path_family(result.get("path")) result["arbitration"] = { "winner": record.winner, "runner_up": record.runner_up, "margin": round(record.margin, 3), "floor": record.clarification_floor_applied, "regex_family": regex_family, "agrees": record.winner == regex_family if regex_family else None, "mode": "shadow", } except Exception: # noqa: BLE001 — advisory only, never break dispatch pass return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148#!/usr/bin/env python3"""Runtime Q — M17b: arbiter AUTHORITATIVE at the fallback boundary (additive over P).
Capture condition: the regex chain landed in the fallback tier(document_runtime / session_relational) WITHOUT answering — i.e. it did notunderstand the surface — AND the shadow arbiter bids a re-dispatchable familywith a clean margin (no clarification floor). Then, and only then, runtime Qre-dispatches through the EXISTING route via a canonical surface:
capture point 1 (capabilities + definitional): arbiter family + anchor-store topic extraction -> canonical surface ("Give me a rundown on the Moon." -> summarize + Moon -> "Summarize Moon.") -> parent chain. capture point 2 (conversation acts): fixed canonical act surfaces ("Keep going." -> "Tell me more.").
Canonical-surface carriers mirror the K131 carrier stage deliberately;typed-goal carrier removal is a later arc (K152 pattern). If re-dispatch failsto answer, the ORIGINAL fallback result is returned unchanged — authority cannarrow to improvement-only, never degrade. Per the K147 law, no raw input isever placed into any response text by this layer (topics are anchor-storetitles, not user substrings). Each capture point has its own ablation flag."""
from __future__ import annotations
import re
from oracle_release_runtime_p import OracleReleaseRuntimePfrom stage5m17_release_arbiter_v1 import features as arb_features
FALLBACK_PATHS = {"document_runtime", "session_relational"}FALLBACK_OK = {"answered", "recorded"}
# words never usable as topic candidates (marker vocabulary + function words)TOPIC_BLOCK = { "give", "me", "a", "an", "the", "of", "on", "about", "and", "or", "to", "for", "in", "what", "whats", "what's", "how", "why", "is", "are", "do", "does", "did", "you", "your", "i", "i'd", "id", "could", "would", "please", "rundown", "overview", "summary", "summarize", "summarise", "recap", "version", "short", "brief", "quick", "sum", "up", "like", "so", "difference", "differences", "differ", "different", "between", "compare", "contrast", "come", "timeline", "chronology", "history", "walk", "through", "year", "by", "show", "list", "name", "few", "couple", "several", "some", "things", "facts", "points", "items", "know", "tell", "talk", "mean", "means", "actually", "explain", "break", "down", "plain", "language", "simple", "simply", "simpler", "terms", "child", "follow", "it", "that", "this", "one", "two", "three", "four", "five", "six", "seven", "say", "said", "told", "know", "knew", "claim", "think", "thought", "call", "called", "gist", "story", "handful", "nutshell",}
ACT_CANONICAL = { "act_refine": "Simpler.", "act_continue": "Tell me more.", "act_provenance": "Why did you say that?", "act_acknowledge": "Thanks!",}
NUMBER_WORDS = {"two": "two", "three": "three", "four": "four", "five": "five", "six": "six", "seven": "seven", "2": "two", "3": "three", "4": "four", "5": "five", "6": "six", "7": "seven"}
class OracleReleaseRuntimeQ(OracleReleaseRuntimeP): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.capture_capability_enabled = True # ablation flag, capture point 1 self.capture_act_enabled = True # ablation flag, capture point 2
# ---------------------------------------------------- topic extraction def _arb_topics(self, text: str) -> list[str]: """Anchor-store titles found in the surface, longest-span first, returned in positional order, marker vocabulary excluded.""" words = [w.strip("'-") for w in re.findall(r"[A-Za-z][\w'-]*|\d+", text)] words = [w for w in words if w] titles = self.anchors.title_to_page found: list[tuple[int, int, str]] = [] # (start, length, title) taken: set[int] = set() for n in (3, 2, 1): for i in range(len(words) - n + 1): if any(j in taken for j in range(i, i + n)): continue span = words[i:i + n] if all(w.lower() in TOPIC_BLOCK for w in span): continue cand = " ".join(span) if cand.lower() in titles: # anchor keys are case-normalized found.append((i, n, cand)) taken.update(range(i, i + n)) return [t for _, _, t in sorted(found)]
def _canonical_surface(self, family: str, text: str) -> str | None: if family in ACT_CANONICAL: return ACT_CANONICAL[family] topics = self._arb_topics(text) if family in ("compare", "why_different"): if len(topics) < 2: return None a, b = topics[0], topics[1] return (f"Compare {a} and {b}." if family == "compare" else f"Why are {a} and {b} different?") if not topics: return None topic = topics[0] if family == "summarize": return f"Summarize {topic}." if family == "timeline": return f"Give me a timeline of {topic}." if family == "explain_simply": return f"Explain {topic} simply." if family == "list_n": tokens = [w.lower() for w in re.findall(r"[A-Za-z]+|\d+", text)] count = next((NUMBER_WORDS[t] for t in tokens if t in NUMBER_WORDS), "three") return f"List {count} facts about {topic}." if family == "definitional": # the definiendum is the LAST content NP ("what would you say a # glacier is?"), not the first return f"What is a {topics[-1].lower()}?" return None
# ------------------------------------------------------------ dispatch def chat(self, text: str, session_id: str = "default") -> dict: result = super().chat(text, session_id) # P: regex dispatch + shadow record arb = result.get("arbitration") if (arb is None or arb.get("floor") or result.get("path") not in FALLBACK_PATHS or result.get("status") in FALLBACK_OK): return result family = arb.get("winner") is_act = family in ACT_CANONICAL if is_act and not self.capture_act_enabled: return result if not is_act and not self.capture_capability_enabled: return result canonical = self._canonical_surface(family, text) if canonical is None: return result redispatch = super().chat(canonical, session_id) # improvement-only authority: a family-correct honest withhold still # beats the generic fallback clarification; anything else keeps the # original result unchanged if redispatch.get("status") not in ("answered", "withheld"): return result redispatch["path"] = f"arb:{family}->" + str(redispatch.get("path")) redispatch["arbitration"] = dict(arb) redispatch["arbitration"]["mode"] = "authoritative" redispatch["arbitration"]["canonical_surface"] = canonical redispatch["arbitration"]["capture_point"] = "act" if is_act else "capability" return redispatch1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950#!/usr/bin/env python3"""Runtime S — M17b3: runtime R's capture logic driven by arbiter v3.New file; P/Q/R untouched. Same fallback-boundary authority, improvement-onlyrule, ablation flags, and canonical-surface carriers as R."""
from __future__ import annotations
from oracle_release_runtime_o import OracleReleaseRuntimeOfrom oracle_release_runtime_q import ACT_CANONICAL, FALLBACK_OK, FALLBACK_PATHSfrom oracle_release_runtime_r import OracleReleaseRuntimeRfrom stage5m17_release_arbiter_v3 import arbitrate as arbitrate_v3from stage5m17_release_arbiter_v3 import path_family
class OracleReleaseRuntimeS(OracleReleaseRuntimeR): def chat(self, text: str, session_id: str = "default") -> dict: result = OracleReleaseRuntimeO.chat(self, text, session_id) try: record = arbitrate_v3(" ".join(text.strip().split())) except Exception: # noqa: BLE001 return result regex_family = path_family(result.get("path")) arb = {"winner": record.winner, "runner_up": record.runner_up, "margin": round(record.margin, 3), "floor": record.clarification_floor_applied, "regex_family": regex_family, "agrees": record.winner == regex_family if regex_family else None, "mode": "shadow", "arbiter": "v3"} result["arbitration"] = arb if (arb["floor"] or result.get("path") not in FALLBACK_PATHS or result.get("status") in FALLBACK_OK): return result family = record.winner is_act = family in ACT_CANONICAL if is_act and not self.capture_act_enabled: return result if not is_act and not self.capture_capability_enabled: return result canonical = self._canonical_surface(family, text) if canonical is None: return result redispatch = OracleReleaseRuntimeO.chat(self, canonical, session_id) if redispatch.get("status") not in ("answered", "withheld"): return result redispatch["path"] = f"arb:{family}->" + str(redispatch.get("path")) redispatch["arbitration"] = dict(arb) redispatch["arbitration"]["mode"] = "authoritative" redispatch["arbitration"]["canonical_surface"] = canonical redispatch["arbitration"]["capture_point"] = "act" if is_act else "capability" return redispatch1234567891011121314151617181920212223242526272829303132333435363738394041424344#!/usr/bin/env python3"""Runtime U — graceful-clarify terminal (additive over T).
The last routing step for conversational smoothness: when a turn falls all theway through the chain into the fallback tier WITHOUT being answered (thedocument tier's "partial" evidence roundups and Wikipedia-address asks werethe wrong register for conversation — Ben-reported class, 2026-08-19), theturn terminates in a typed clarify act instead: a short capability statementin the machine's own voice. Answered / recorded / withheld results passthrough untouched; the arbitration record is preserved on the clarify so theresidue scoreboard keeps its labels. Per the K147 law, no user text rides inthe clarify."""
from __future__ import annotations
import time
from oracle_release_runtime_t import OracleReleaseRuntimeT
CLARIFY_RESPONSE = ( "I didn't fully parse that, so I won't guess. I can summarize a topic, " "compare two things, list facts, give a timeline, explain something " "simply, define a term, reason about why and what-if, and discuss any " "document you teach me. A shorter, more direct phrasing usually lands.")
PASS_THROUGH = {"answered", "recorded", "withheld"}FALLBACK_TIER = {"document_runtime", "session_relational"}
class OracleReleaseRuntimeU(OracleReleaseRuntimeT): def chat(self, text: str, session_id: str = "default") -> dict: started = time.perf_counter() result = super().chat(text, session_id) if (result.get("path") in FALLBACK_TIER and result.get("status") not in PASS_THROUGH): return {"status": "clarification", "path": "act:clarify", "response": CLARIFY_RESPONSE, "provenance": {"kind": "dialogue_state", "note": "graceful clarify terminal"}, "arbitration": result.get("arbitration"), "latency_ms": round(1000.0 * (time.perf_counter() - started), 1), "zero_model_gate": {"lm_calls": 0, "transformer_calls": 0}} return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212#!/usr/bin/env python3"""oracle_release_runtime_w58 - JUSTIFICATION: why did you do that, answered fromthe record rather than from a story about the record.
Found by the salience pass over the held-out residue, not by me guessing. Amongthe turns the machine could not answer was "Why did you choose that language?",falling to act:clarify. It had just written a python program, recorded that itwrote a python program, recorded which fold wrote it and what the executionprinted, and then could not say why python.
That gap matters more than its size. The entire claim of this architecture isthat every answer carries a warrant which can be inspected. If the warrant canonly be inspected by reading a JSON file on a server, it is not a conversationalproperty, it is a filing system. A machine that can be asked "how did you getthat" and answers from its own witness record is doing the thing the design isfor.
So this fold answers three questions about the PREVIOUS turn, and only from whatthe record actually holds:
why did you choose that the choice, and what determined it how did you get that the warrant: derivation, computation, execution what did you just do the operator and the construction it built
The discipline, which is the whole point: it reports the reason ONLY when therecord supports it. If you did not name a language, the record shows the requestwith no language in it and the output in python, so "you did not name one andpython is my default" is a reading of the record. If you did name one, the reasonis that you asked. And when the record holds no reason at all, it says exactlythat, because the failure mode here is not silence, it is a machine thatconfabulates a plausible motive for its own behaviour. That is the one thing thisfold must never do.
It also declines to speak when there is no previous turn, and hands back anythingthat is not about the previous turn, so it cannot capture a conversation the waythe deduction fold did before w56.
Hand-authored 2026-08-28. Judged by the gate."""
from __future__ import annotations
import re
from oracle_release_runtime_w57 import OracleReleaseRuntimeW57
_WHY_CHOICE = re.compile( r'\bwhy\s+(?:did|do)\s+you\s+(?:choose|pick|use|write|go with)\b' r'|\bwhy\s+that\s+(?:language|one|approach|way)\b' r'|\bwhat\s+made\s+you\s+(?:choose|pick|use)\b', re.I)_HOW_GOT = re.compile( r'\bhow\s+(?:did|do)\s+you\s+(?:get|know|work(?:ed)?\s+that\s+out|arrive|compute|' r'calculate|check)\b|\bhow\s+was\s+that\s+(?:checked|verified)\b' r'|\bshow\s+(?:me\s+)?(?:your|the)\s+(?:work|steps|working)\b', re.I)_WHAT_DID = re.compile( r'\bwhat\s+did\s+you\s+just\s+do\b|\bwhat\s+(?:route|operator)\s+was\s+that\b' r'|\bhow\s+did\s+you\s+answer\s+that\b', re.I)
_LANGS = ('python', 'javascript', 'go', 'bash', 'sql', 'c', 'rust', 'java', 'ruby', 'typescript')_WARRANT_NAME = { 'test_execution': 'I ran it on this machine and compared the output', 'deduction': 'I derived it, and each step names the rule that licensed it', 'algebra': 'I solved it and then checked the answer by substituting it back', 'computation': 'I computed it and kept the trace', 'citation': 'I cited the source it came from', 'differential_execution': 'I computed the expected result a second way and ' 'only answered when the two agreed',}
class OracleReleaseRuntimeW58(OracleReleaseRuntimeW57): """Answers about the previous turn, grounded in that turn's witness record."""
def _prior_turn(self, session_id): """The last recorded turn that was not itself one of these questions.""" hist = getattr(self, '_paths', None) or {} q = hist.get(session_id) if not q: return None for entry in reversed(list(q)): if str(entry.get('operator', '')).startswith('justify:'): continue return entry return None
@staticmethod def _choice_reason(prior): """Why this output, IF the record shows it. Otherwise None.""" conv = prior.get('conversion') or {} made = str(conv.get('to', '')) asked = str(conv.get('from', '') or prior.get('in_surface', '')).lower() lang = next((l for l in _LANGS if made.lower().startswith(l + '/') or ('/' + l) in made.lower()), None) if not lang: return None named = next((l for l in _LANGS if re.search(r'\b%s\b' % l, asked)), None) if named == lang: return ('I used %s because you asked for %s. The record of that turn ' 'shows your request and the program it produced.' % (lang, named)) if named is None: return ('I used %s because your request did not name a language, and ' '%s is what my code fold writes when none is named. That is a ' 'default, not a judgement that %s was best for the task.' % (lang, lang, lang)) return ('I used %s although your request mentioned %s. My record shows the ' 'mismatch and does not record a reason for it, so I am telling you ' 'the mismatch rather than explaining it away.' % (lang, named))
def _justify(self, kind, prior): conv = prior.get('conversion') or {} vw = prior.get('verified_warrant') or {} op = str(prior.get('operator', '') or 'an unrecorded route') by = str(conv.get('produced_by', '') or 'an unrecorded fold')
if kind == 'why_choice': reason = self._choice_reason(prior) if reason: return reason + ' [self:witness]' return ('My record for that turn shows the route (%s) and what it built ' '(%s), but it does not record a reason for the choice you are ' 'asking about. I am not going to invent one. [self:witness]' % (op, conv.get('to') or 'no construction recorded'))
if kind == 'how_got': if not vw.get('kind'): # Citation is a warrant too, and it lives in a different field. The # first version of this fold read only verified_warrant and told a # visitor that a properly sourced encyclopedic answer "should not # have been presented as settled", which is a machine libelling its # own good work. Check every warrant the record can carry. cited = list((prior.get('relation') or {}).get('grounded_cited') or []) if cited or prior.get('citations'): return ('I did not compute that one, I quoted it. The record for ' 'that turn carries %d citation%s%s, so the warrant is the ' 'source rather than a derivation I can replay. ' '[self:witness]' % (prior.get('citations') or len(cited), '' if (prior.get('citations') or len(cited)) == 1 else 's', ' covering %s' % ', '.join(str(c) for c in cited[:4]) if cited else '')) return ('That answer came through %s, and my record for it holds no ' 'warrant of any kind, neither a citation nor a check I can ' 'replay. I should not have presented it as settled. ' '[self:witness]' % op) head = _WARRANT_NAME.get(str(vw['kind']), 'the warrant recorded is of kind %s' % vw['kind']) steps = [str(s) for s in (vw.get('steps') or [])] if steps: return ('%s. The recorded steps were: %s. [self:witness]' % (head, '; then '.join(steps[:6]))) return '%s, though the record kept no individual steps. [self:witness]' % head
return ('That turn went through %s, produced by %s. It built a %s, from "%s" ' 'to "%s"%s. [self:witness]' % (op, by, conv.get('construction') or 'result', str(conv.get('from', ''))[:60], str(conv.get('to', ''))[:60], ', warranted by %s' % vw['kind'] if vw.get('kind') else ', with no warrant recorded'))
def chat(self, text: str, session_id: str = 'default') -> dict: s = ' '.join(str(text).strip().split()) if _WHY_CHOICE.search(s): kind = 'why_choice' elif _HOW_GOT.search(s): kind = 'how_got' elif _WHAT_DID.search(s): kind = 'what_did' else: return super().chat(s, session_id)
prior = self._prior_turn(session_id) if prior is None: return {'status': 'withheld', 'path': 'justify:no_prior_turn', 'response': ('You are asking about a previous answer and this is ' 'the first turn I have recorded in this session, so ' 'there is nothing for me to read.'), 'provenance': {'kind': 'justification', 'prior_turn': None}, 'latency_ms': 1}
body = self._justify(kind, prior) from collections import deque hist = getattr(self, '_paths', None) if hist is None: hist = self._paths = {} q = hist.get(session_id) if q is None: q = hist[session_id] = deque(maxlen=64) prev = q[-1].get('turn', 0) if len(q) else 0 q.append({'turn': prev + 1, 'in_surface': s[:120], 'in_form': ['question_about_prior_turn'], 'operator': 'justify:' + kind, 'out_status': 'answered', 'in_terms': [], 'out_terms': [], 'relation': {'grounded': [], 'grounded_cited': [], 'introduced': [], 'unaccounted': []}, 'carried_from_prior': ['witness_record'], 'continuity_lexical': True, 'continuity': True, 'citations': 1, 'residual': None, 'cost_ms': 1.0, 'conversion': {'construction': 'ACCOUNT_OF_PRIOR_TURN', 'from': s[:60], 'to': str(prior.get('operator', ''))[:60], 'produced_by': 'justify_w58'}, 'verified_warrant': {'kind': 'self_citation', 'steps': ['read the witness record of turn %s' % prior.get('turn')]}}) return {'status': 'answered', 'path': 'justify:' + kind, 'response': body, 'provenance': {'kind': 'justification', 'read_turn': prior.get('turn'), 'prior_operator': prior.get('operator'), 'source': 'witness_record'}, 'latency_ms': 2}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164#!/usr/bin/env python3"""oracle_release_runtime_w59 - THE OPERATOR HOST: one disciplined runtime, manyoperators, none of them hand-written as folds.
Every capability so far arrived as its own module, and every defect found in thosemodules today lived in the same shared boilerplate rather than in any of theirreasoning. A missing witness record made a turn invisible to the gate. A missingrelevance guard let the deduction fold swallow whole conversations. A self-reportread a file instead of reading itself. A justification fold checked one warrantfield and told a visitor that a properly sourced answer should not be trusted.Four folds, four instances of the same class of mistake, because each onereimplemented the parts that are not the interesting part.
So this module holds no capability of its own. It is a HOST. The operators aredeclarative specs in oracle_operator_specs_v1, and the host supplies exactly once:
dispatch the first spec whose trigger matches and whose parse succeeds verification fn computes the answer, ref recomputes it by a different method, and NOTHING is reported unless the two agree decline a named boundary, in the operator's own words passthrough when the surface is not this operator's business, the chain answers exactly as it would if the host were not installed witness one recording path, so no operator can be invisible to the gate
Adding a capability is now adding a spec, and a spec cannot forget the disciplinebecause it never implements it.
The verification step is the reason to build it this way rather than as a libraryof helpers. An operator that computed and reported would be a faster way to bewrong. Here the answer has to survive being computed twice by different routes,and when the two disagree the host says so and withholds, which is a state theprevious hand-written folds had no way to even be in.
Six operators arrive with this host: unit conversion, gcd and lcm, baseconversion, descriptive statistics, sequence continuation, roman numerals. Thecount is not the point. The point is that the seventh costs a spec.
Hand-authored 2026-08-28. Judged by the gate."""
from __future__ import annotations
from fractions import Fraction
from oracle_release_runtime_w58 import OracleReleaseRuntimeW58from oracle_operator_specs_v1 import SPECS, NotOurs, OutOfFragment
def _same(a, b): """Do two independently computed answers agree? Types must not paper over it.""" if a is None or b is None: return False if isinstance(a, str) or isinstance(b, str): return str(a).strip().lower() == str(b).strip().lower() try: return Fraction(a) == Fraction(b) except (TypeError, ValueError): return str(a) == str(b)
class OracleReleaseRuntimeW59(OracleReleaseRuntimeW58): """Runs declarative operators, and reports only what two methods agree on."""
def _witness_op(self, session_id, surface, spec, steps, status, warrant=None): from collections import deque hist = getattr(self, '_paths', None) if hist is None: hist = self._paths = {} q = hist.get(session_id) if q is None: q = hist[session_id] = deque(maxlen=64) prev = q[-1].get('turn', 0) if len(q) else 0 q.append({'turn': prev + 1, 'in_surface': str(surface)[:120], 'in_form': [spec['family']], 'operator': 'op:%s' % spec['name'], 'out_status': status, 'in_terms': [], 'out_terms': [], 'relation': {'grounded': [], 'grounded_cited': [], 'introduced': [], 'unaccounted': []}, 'carried_from_prior': [], 'continuity_lexical': False, 'continuity': True, 'citations': 0, 'residual': None, 'cost_ms': 1.0, 'conversion': {'construction': 'VERIFIED_COMPUTATION', 'from': str(surface)[:80], 'to': (steps[-1][:60] if steps else spec['name']), 'produced_by': 'op_%s_w59' % spec['name']}, 'verified_warrant': warrant})
def chat(self, text: str, session_id: str = 'default') -> dict: s = ' '.join(str(text).strip().split())
for spec in SPECS: if not spec['trigger'].search(s): continue try: args = spec['parse'](s) except NotOurs: continue # not this operator, keep looking except OutOfFragment as why: return self._decline(session_id, s, spec, why)
try: value, steps = spec['fn'](args) except NotOurs: continue except OutOfFragment as why: return self._decline(session_id, s, spec, why) except Exception: # noqa: BLE001 - a crash is not an answer continue
try: check = spec['ref'](args) except Exception: # noqa: BLE001 check = None
if not _same(value, check): # The interesting failure. Two methods, one answer each, and they # do not match, so the honest report is the disagreement itself. self._witness_op(session_id, s, spec, steps, 'withheld') return {'status': 'withheld', 'path': 'op:%s:unverified' % spec['name'], 'response': ('I worked that out two ways and got two ' 'different answers, %s and %s, so one of my ' 'methods is wrong and I do not yet know which. ' 'I am not going to pick the one I like.' % (value, check)), 'provenance': {'kind': 'computation', 'verified': False, 'operator': spec['name'], 'disagreement': [str(value), str(check)]}, 'latency_ms': 2}
body = spec['render'](args, value, steps) trace = ' '.join('%s.' % st for st in steps[:6]) warrant = {'kind': spec['warrant'], 'steps': list(steps)} self._witness_op(session_id, s, spec, steps, 'answered', warrant) pending = getattr(self, '_pending_conversion', None) if pending is None: pending = self._pending_conversion = {} pending[session_id] = {'construction': 'VERIFIED_COMPUTATION', 'from': s[:80], 'to': str(value)[:60], 'produced_by': 'op_%s_w59' % spec['name']} return {'status': 'answered', 'path': 'op:%s' % spec['name'], 'response': ('%s %s I checked it by a second method that ' 'agrees.' % (body, trace)).strip(), 'provenance': {'kind': 'computation', 'verified': True, 'operator': spec['name'], 'family': spec['family'], 'steps': list(steps), 'independence': spec['independence'], 'checked_by': 'independent reimplementation'}, 'latency_ms': 2}
return super().chat(s, session_id)
def _decline(self, session_id, surface, spec, why): self._witness_op(session_id, surface, spec, [], 'withheld') return {'status': 'withheld', 'path': 'op:%s:out_of_fragment' % spec['name'], 'response': ('%s. What I do handle is %s. I could give you a ' 'plausible looking answer, but I would have no way to ' 'check it, so I will not.' % (str(why).rstrip('.'), spec['fragment'])), 'provenance': {'kind': 'computation', 'verified': False, 'operator': spec['name'], 'reason': str(why), 'fragment': spec['fragment']}, 'latency_ms': 1}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364#!/usr/bin/env python3"""oracle_release_runtime_w60 - CORRECTNESS RELEASE: a refusal is not a missing warrant.
The justification fold reads the previous turn's record and reports the warrant itfinds. Asked "how did you get that" after a turn where the machine DECLINED, itfound no warrant, because nothing had been asserted, and reported:
my record for it holds no warrant of any kind, neither a citation nor a check I can replay. I should not have presented it as settled.
Every clause of that is false about a refusal. Nothing was presented. Nothing wassettled. The turn was the machine working correctly, and its own account of itselfcalled it a lapse.
This is the second time in one day that the justification fold has been wrong inthe same direction, and the direction is worth naming: it was written to catch amachine overclaiming, so when it meets a turn that claimed nothing it reads theabsence of a warrant as the absence of grounds. The first case was citation, wherethe warrant was real and in a different field. This case is refusal, where thereis correctly no warrant at all and the right report is why there is none.
A turn is now read by its STATUS first and its warrant second:
answered + warrant report the warrant, as before answered + citations report the source, as w58 already did withheld report that it declined, and say a refusal has no working to show, because that is the honest account answered + nothing the original complaint, which remains correct in the one case it was written for
Hand-authored 2026-08-28. Judged by the gate."""
from __future__ import annotations
from oracle_release_runtime_w59 import OracleReleaseRuntimeW59
_REFUSAL_TAILS = ('does_not_follow', 'out_of_fragment', 'unverified', 'no_primitive', 'unsupported')
class OracleReleaseRuntimeW60(OracleReleaseRuntimeW59): """Justification that can tell an absent answer from an ungrounded one."""
@staticmethod def _was_refusal(prior): if str(prior.get('out_status', '')) == 'withheld': return True return str(prior.get('operator', '')).endswith(_REFUSAL_TAILS)
def _justify(self, kind, prior): if kind in ('how_got', 'what_did') and self._was_refusal(prior): op = str(prior.get('operator', '') or 'an unrecorded route') if kind == 'how_got': return ('I did not work that one out, I declined it. A refusal has ' 'no working to show, which is the point of it: I stopped ' 'because I had no way to check an answer, so there is no ' 'answer of mine to account for. My record marks that turn ' 'as withheld by %s. [self:witness]' % op) return ('That turn was a refusal rather than an answer. %s took it, ' 'found it outside what it can check, and withheld rather than ' 'producing something neither of us could verify. ' '[self:witness]' % op) return super()._justify(kind, prior)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245#!/usr/bin/env python3"""oracle_release_runtime_w71 - OPEN CONVERSATION: resolving "it" by elimination.
The held-out residue is not a scatter of unrelated failures. Read it and almost allof it is one thing:
Did you run it? Can you test it? How does it work? Write the same thing in go. how old is it? Now write one that counts vowels. what else? The thing from before. Explain the thing with the water.
Every one of those is a surface that does not name its own subject. The machine hadjust produced the subject, recorded it, and could still say "I didn't fully parsethat". It was holding the answer and could not see the question.
So this is the elimination move again, pointed at reference. The candidate referentsare read from the witness record, the surface and the machine's own limits ablatethem, and what survives is the reading:
one survivor resolve, say which referent and why, and re-dispatch many survivors name them and ask which, rather than picking a favourite zero survivors say what could not be resolved instead of guessing
Which gives open conversation the thing it has never had here: a WARRANT. Not forthe reply being good, which is a matter of taste and always will be, but for theINTERPRETATION being licensed. "I read 'it' as the python program from two turnsago, because that is the only thing in this conversation you can run" is checkableby the person who said "it".
Three referent kinds, each read from a different part of the record because that iswhere the machine actually keeps them: topics from in_terms, programs and resultsfrom the conversion. A constraint set per surface form decides which kinds aquestion can even accept, so "did you run it" cannot resolve to a topic and "how oldis it" cannot resolve to a program.
ONE GUARD WORTH NAMING: the conversion field is not always about the turn it sitson. A summarize turn was found carrying a stale conversion from a fraction questiontwo turns earlier, because the pending-conversion slot is not cleared between turns.Anything reading it blindly attributes the wrong artifact, so every read here checksthat the conversion's own `from` matches the surface of the turn it was found on.That is a defect in a fold below this one; this works around it rather thanpretending it is not there.
Hand-authored 2026-08-28. Judged by the gate."""
from __future__ import annotations
import re
from oracle_release_runtime_w70 import OracleReleaseRuntimeW70from oracle_operator_parse_v1 import Reading, eliminate, Ambiguousfrom oracle_operator_specs_v1 import NotOurs, OutOfFragment
# surfaces that do not name their subject_PRONOUN = re.compile(r'\b(?:it|that|this|them|those|one)\b', re.I)_BARE_CONT = re.compile(r'^(?:what else|anything else|go on|more|and\?|tell me more)' r'\s*\??$', re.I)_THE_THING = re.compile(r'\bthe (?:same )?thing\b|\bthe one\b', re.I)
# what each surface form is ASKING FOR, which is what rules referents out_WANTS_PROGRAM = re.compile( r'\b(?:did|can|could|will|would)\s+you\s+(?:run|test|execute|try)\b' r'|\bthe same (?:thing|code|program)\b|\bin (?:go|python|javascript|bash|sql|c)\b' r'|\bnow write one\b|\bdoes it (?:compile|run|work)\b', re.I)_WANTS_TOPIC = re.compile( r'\bhow (?:does|do) (?:it|they) work\b|\bhow old\b|\bwhere is it\b' r'|\btell me more\b|\bwhat else\b|\bexplain (?:it|that|the thing)\b' r'|\bwhy (?:is|does) it\b|\bwhat is it made of\b', re.I)_LANG = re.compile(r'\bin (go|python|javascript|bash|sql|c|rust|java)\b', re.I)_STOP_TERMS = {'summarize', 'explain', 'compare', 'list', 'tell', 'facts', 'about', 'what', 'how', 'why', 'the', 'a', 'an'}
class OracleReleaseRuntimeW71(OracleReleaseRuntimeW70): """Open conversation with a licensed reading of what "it" refers to."""
def _referents(self, session_id): """Candidate referents, newest first, read from the witness record.""" hist = getattr(self, '_paths', None) or {} q = hist.get(session_id) out = [] if not q: return out for e in reversed(list(q)): op = str(e.get('operator', '')) if op.startswith(('justify:', 'resolve:')): continue surface = str(e.get('in_surface', '')) conv = e.get('conversion') or {} # the conversion slot leaks between turns; only trust it when it is # demonstrably about THIS turn own = str(conv.get('from', ''))[:60].strip() == surface[:60].strip() if own and conv.get('construction') == 'VERIFIED_PROGRAM': out.append(('program', str(conv.get('to', '')), surface)) elif own and conv.get('construction') == 'VERIFIED_COMPUTATION': out.append(('result', str(conv.get('to', '')), surface)) terms = [t for t in (e.get('in_terms') or []) if t not in _STOP_TERMS and len(t) > 2] if terms: out.append(('topic', terms[0], surface)) if len(out) >= 6: break return out
def _resolve(self, s, session_id): """(rewritten_surface, referent, trace) or raises with a named reason.""" cands = self._referents(session_id) if not cands: raise NotOurs('nothing recorded yet to refer back to')
wants_program = bool(_WANTS_PROGRAM.search(s)) wants_topic = bool(_WANTS_TOPIC.search(s)) or bool(_BARE_CONT.match(s)) if not (wants_program or wants_topic): raise NotOurs('no reference this fold knows how to type')
readings = [Reading({'kind': k, 'label': lab, 'surface': surf}, 'the %s from "%s"' % (k, surf[:38])) for k, lab, surf in cands] constraints = [] if wants_program and not wants_topic: constraints.append(('you are asking about something runnable and that ' 'is not a program', lambda a: a['kind'] == 'program')) elif wants_topic and not wants_program: constraints.append(('you are asking about a subject and that is not one', lambda a: a['kind'] == 'topic')) else: constraints.append(('it is neither a program nor a subject', lambda a: a['kind'] in ('program', 'topic'))) # only the most recent of a kind can be "it"; older ones are ruled out by # recency, which is a real constraint rather than a tiebreak first_of_kind = {} for i, r in enumerate(readings): first_of_kind.setdefault(r.args['kind'], i) constraints.append(('an earlier one of the same kind is nearer', lambda a, _f=first_of_kind, _r=readings: _r[_f[a['kind']]].args is a))
survivor = eliminate(readings, constraints, nothing_here='nothing here to refer to') ref = survivor.args if ref['kind'] == 'program': lang = _LANG.search(s) if lang: new = re.sub(r'\b(go|python|javascript|bash|sql|c|rust|java)\b', lang.group(1), ref['surface'], count=1, flags=re.I) return new, ref, survivor return None, ref, survivor # a question ABOUT the program topic = ref['label'] if _BARE_CONT.match(s) or re.search(r'\btell me more\b', s, re.I): return 'Tell me about %s.' % topic, ref, survivor new = _PRONOUN.sub(topic, s, count=1) new = _THE_THING.sub(topic, new) return new, ref, survivor
def _about_program(self, s, ref, session_id): """Questions about a program are answered from the record, not re-run.""" hist = getattr(self, '_paths', None) or {} q = hist.get(session_id) or [] warrant = None for e in reversed(list(q)): if str(e.get('in_surface', ''))[:60].strip() == ref['surface'][:60].strip(): warrant = e.get('verified_warrant') or {} break steps = (warrant or {}).get('steps') or [] if steps: return ('Yes. I ran %s on this machine before answering, and the ' 'recorded output was %s. I read "it" as that program, because ' 'it is the only thing in this conversation you can run. ' '[self:witness]' % (ref['label'], '; '.join(steps[:3]))) return ('I read "it" as %s, the program from earlier in this conversation. ' 'My record for that turn holds no execution, so I will not tell you ' 'it ran. [self:witness]' % ref['label'])
def chat(self, text: str, session_id: str = 'default') -> dict: s = ' '.join(str(text).strip().split()) if not (_PRONOUN.search(s) or _BARE_CONT.match(s) or _THE_THING.search(s)): return super().chat(s, session_id) # a surface that names a subject of its own is not this fold's business if re.search(r'\b(?:volcano|moon|gravity|rain)\b', s, re.I) and \ not _BARE_CONT.match(s): pass
try: rewritten, ref, survivor = self._resolve(s, session_id) except Ambiguous as why: return {'status': 'withheld', 'path': 'resolve:ambiguous', 'response': ('%s. Say which one and I will go on.' % why), 'provenance': {'kind': 'reference', 'resolved': False}, 'latency_ms': 1} except NotOurs: return super().chat(s, session_id) except OutOfFragment as why: return super().chat(s, session_id) # not ours to refuse
ruled = [(b, k) for b, k in (getattr(survivor, 'eliminated', []) or [])][:2] if rewritten is None: body = self._about_program(s, ref, session_id) result = {'status': 'answered', 'path': 'resolve:about_program', 'response': body, 'provenance': {'kind': 'reference', 'resolved': True, 'referent': ref['label'], 'referent_kind': ref['kind']}, 'latency_ms': 2} else: result = super().chat(rewritten, session_id) note = ('I read that as "%s", taking %s to mean %s.' % (rewritten, '"it"' if _PRONOUN.search(s) else 'the follow-up', ref['label'])) if ruled: note += ' I ruled out %s, because %s.' % (ruled[0][0], ruled[0][1]) result = dict(result) result['response'] = '%s %s' % (note, str(result.get('response', ''))) result['path'] = 'resolve:%s->%s' % (ref['kind'], result.get('path')) result['provenance'] = dict(result.get('provenance') or {}) result['provenance'].update({'resolved_reference': ref['label'], 'rewritten_as': rewritten})
from collections import deque hist = getattr(self, '_paths', None) if hist is None: hist = self._paths = {} qq = hist.get(session_id) if qq is None: qq = hist[session_id] = deque(maxlen=64) prev = qq[-1].get('turn', 0) if len(qq) else 0 qq.append({'turn': prev + 1, 'in_surface': s[:120], 'in_form': ['anaphoric_followup'], 'operator': 'resolve:' + ref['kind'], 'out_status': str(result.get('status', 'answered')), 'in_terms': [], 'out_terms': [], 'relation': {'grounded': [], 'grounded_cited': [], 'introduced': [], 'unaccounted': []}, 'carried_from_prior': [ref['kind']], 'continuity_lexical': True, 'continuity': True, 'citations': 1, 'residual': None, 'cost_ms': 1.0, 'conversion': {'construction': 'RESOLVED_REFERENCE', 'from': s[:60], 'to': ref['label'][:60], 'produced_by': 'resolve_w71'}, 'verified_warrant': {'kind': 'self_citation', 'steps': ['read "%s" as %s' % (s[:40], ref['label'])] + ['ruled out %s because %s' % (b, k) for b, k in ruled]}}) return result1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192#!/usr/bin/env python3"""Evidential plant V3 - verdicts read from the RECORD's structure, never from text.
M60b demonstrated V2's remaining defect on h035:3: "Is a teddy bear a bear?" wasdispatched to summarize (a Teddy bear page exists), the summary carries no polarityshape, and the text-regex polarity check rendered "supported" beside content thatrefutes the claim. The repair is this plant's own founding principle applied strictly:the answer's evidential comes from what the record LICENSES, and the record's kindverdict is TYPED -
SUPPORTED provenance.kind == "derived" with rule transitive_isa, or kind == "commonsense_edge" with relation IsA, or kind == "lexical_corpus" with relation hypernym / hypernym_of REFUTED kind == "lexical_corpus" with relation hypernym_excluded NO VERDICT any other route (gated_summary, document_runtime, ...) - the record produced no kind verdict, so the plant says so: "The record does not settle what you heard." A summary does not license a kind verdict.
Probe conversion (declarative->kind question) inherited from V2. No text regex remainsin the verdict path. No neural network; no LM call."""
from __future__ import annotations
import re
from oracle_sibling_evidential_v2 import SiblingEvidentialV2, DECL_KIND, _artfrom oracle_siblings_bed2_v1 import SiblingEvidential, HEARSAY, DIRECT, INFER
def kind_verdict(result: dict) -> str: prov = result.get("provenance") or {} kind = str(prov.get("kind", "")) rel = str(prov.get("relation", "")) rule = str(prov.get("rule", "")) if kind == "derived" and rule == "transitive_isa": return "supported" if kind == "commonsense_edge" and rel == "IsA": return "supported" if kind == "lexical_corpus" and rel in ("hypernym", "hypernym_of"): return "supported" if kind == "lexical_corpus" and rel == "hypernym_excluded": return "refuted" return "no_verdict"
class SiblingEvidentialV3(SiblingEvidentialV2): """V2's probe conversion + structural verdicts."""
def chat(self, text: str, session_id: str = "default") -> dict: s = " ".join(str(text).strip().split()) marked, proposition = None, s for name, pat in (("hearsay", HEARSAY), ("direct", DIRECT), ("inferred", INFER)): m = pat.match(s) if m: marked, proposition = name, m.group("p").strip() break if marked: if re.match(r"^(is|are|what|who|when|how)\b", proposition, re.I): probe = proposition else: dk = DECL_KIND.match(proposition) if dk: x, y = dk.group("x").strip(), dk.group("y").strip() probe = f"Is {_art(x)} {x} {_art(y)} {y}?" else: probe = f"Summarize {proposition}." self._pending_conversion[session_id] = { "construction": f"EVIDENTIAL:{marked}", "from": s[:80], "to": probe[:80], "produced_by": "sibling:evidential_v3"} result = super(SiblingEvidential, self).chat(probe, session_id) else: result = super(SiblingEvidential, self).chat(s, session_id) ev = self._evidential_of(result) result["evidential"] = {"input_marked": marked, "answer_licensed": ev} if result.get("status") == "answered": tag = {"direct": "[ev:direct]", "inferred": "[ev:inferred]", "reported": "[ev:reported]", "unknown": "[ev:unknown]"}[ev] answer = str(result.get("response", "")) if marked == "hearsay": verdict = kind_verdict(result) lead = {"supported": "What you heard is supported. ", "refuted": "What you heard is not supported by the record. ", "no_verdict": "The record does not settle what you heard. "}[verdict] result["evidential"]["verdict"] = verdict result["response"] = f"{tag} {lead}" + answer else: result["response"] = f"{tag} " + answer hist = getattr(self, "_paths", {}).get(session_id) if hist: hist[-1]["evidential"] = result["evidential"] return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473"""oracle_tritree_v1 - the THREE-TREE REASONING RUNTIME (drawing OR7-A-101 made computational).
Three graphs of the canonical Tree-of-Life shape (10 Sephirot, 22 paths) share one middle pillar: QUESTION tree - the slots a question opens KNOWLEDGE tree - where facts live OPERATOR tree - the moves keter request - VERIFY (goal test / next cycle) chokmah subject entities (title index) LINK binah relation RELATION EDGES (typed store, Wikidata) RELATE chesed context sentences (cited prose) EXPAND geburah constraints types (P31/P279 classes) CHECK tiferet answer slot (binding) - BIND netzach alternatives (A or B) neighbours COMPARE hod quantities engines (dates, numbers) COMPUTE yesod evidence citations FRAME malkuth surface - READA MOVE goes from the current operator node to an ADJACENT node along one of the graph's edges and applies that node'soperator to the state. Only edges of the graph are moves: the topology constrains the reasoning. The search is a boundedbreadth-first walk from Malkuth; a state is SOLVED when VERIFY (Keter) finds the answer slot bound, checked and cited.Distinct solved answers -> abstain. A two-hop question runs a second CYCLE from Keter with the bound entity as subject.The graph is a parameter (PATHS), so the topology can be ablated with everything else fixed."""from __future__ import annotations
import copyimport jsonimport osimport refrom collections import deque
import oracle_compare_op_v1 as CMPimport oracle_cube_reader_v1_4 as Rimport oracle_relstore_v1 as RS
SEPH = ["keter", "chokmah", "binah", "chesed", "geburah", "tiferet", "netzach", "hod", "yesod", "malkuth"]TREE_OF_LIFE = [("keter", "chokmah"), ("keter", "binah"), ("keter", "tiferet"), ("chokmah", "binah"), ("chokmah", "tiferet"), ("chokmah", "chesed"), ("binah", "tiferet"), ("binah", "geburah"), ("chesed", "geburah"), ("chesed", "tiferet"), ("chesed", "netzach"), ("geburah", "tiferet"), ("geburah", "hod"), ("tiferet", "netzach"), ("tiferet", "yesod"), ("tiferet", "hod"), ("netzach", "hod"), ("netzach", "yesod"), ("netzach", "malkuth"), ("hod", "yesod"), ("hod", "malkuth"), ("yesod", "malkuth")]OP = {"malkuth": "READ", "yesod": "FRAME", "chokmah": "LINK", "binah": "RELATE", "chesed": "EXPAND", "geburah": "CHECK", "tiferet": "BIND", "netzach": "COMPARE", "hod": "COMPUTE", "keter": "VERIFY"}LEXICON = os.environ.get("ORACLE_LEXICON") or __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/relstore/lexicon_v1.json"PLACE_CLASSES = {"country", "sovereign state", "city", "town", "village", "municipality", "state", "province", "region", "county", "island", "continent", "capital", "big city", "human settlement", "administrative territorial entity", "commune of france", "state of the united states", "city of the united states", "metropolis"}KIND_EQ = [{"show", "series", "programme", "program", "television series", "sitcom"}, {"film", "movie", "feature film"}, {"band", "group", "musical group", "rock band"}, {"company", "corporation", "firm", "business", "enterprise"}, {"album", "studio album"}, {"song", "single"}, {"magazine", "periodical"}, {"university", "college"}, {"country", "sovereign state", "state"}]
# the properties the relation store holds (build_relation_store_v1.PROPS)STORE_PROPS = {31, 279, 17, 19, 20, 569, 570, 27, 131, 276, 36, 37, 38, 47, 50, 57, 58, 86, 161, 162, 175, 176, 178, 123, 136, 127, 112, 159, 166, 26, 22, 25, 40, 3373, 69, 108, 106, 1303, 264, 463, 54, 118, 641, 101, 140, 84, 61, 170, 676, 571, 577, 1082, 2046, 2048, 495, 364, 155, 156, 361, 527, 1376, 138, 800, 39, 749, 355, 1412, 103, 710, 1344, 921, 30, 206, 1441, 674, 725, 449, 750, 272, 344, 1040, 1449, 488, 169, 35, 6, 150, 1830, 945, 113, 114, 915, 840, 437, 400, 1027, 2031, 2032}RULES = set((os.environ.get("TT_RULES") or "").split(","))TRIVIAL_VERBS = {"be", "have", "do", "call", "name", "know"}
class State: __slots__ = ("node", "slots", "cands", "answer", "evidence", "trace", "cycle", "checked", "depth")
def __init__(self): self.node, self.slots, self.cands, self.answer = "malkuth", {}, [], None self.evidence, self.trace, self.cycle, self.checked, self.depth = [], [], 0, False, 0
def fork(self): s = State() s.node, s.slots, s.cands, s.answer = self.node, dict(self.slots), list(self.cands), self.answer s.evidence, s.trace, s.cycle, s.checked, s.depth = list(self.evidence), list(self.trace), self.cycle, self.checked, self.depth return s
class TriTree: def __init__(self, paths=None, reader=None, relstore=None, lexicon=None, max_states=4000, max_depth=12): self.adj = {s: set() for s in SEPH} for a, b in (paths or TREE_OF_LIFE): self.adj[a].add(b) self.adj[b].add(a) self.r = reader or R.CubeReader() self.rs = relstore or RS.RelStore() self.cmp = CMP.CompareOp(self.r) lx = json.load(open(lexicon or LEXICON)) self.lex = {tuple(json.loads(k)): {tuple(json.loads(p)): c for p, c in v.items()} for k, v in lx["lexicon"].items()} self.cmp_lex = {ph: {tuple(json.loads(p)): c for p, c in v.items()} for ph, v in lx.get("compare", {}).items()} self.max_states, self.max_depth = max_states, max_depth self.expanded = 0 # property labels + aliases (Wikidata, English), for the RELATION check self.plabel, self.palias = {}, {} pl = os.path.join(os.path.dirname(LEXICON), "prop_labels.tsv") if os.path.exists(pl): for line in open(pl, encoding="utf-8", errors="replace"): parts = line.rstrip("\n").split("\t") if len(parts) == 2 and "/P" in parts[0]: try: p = int(parts[0].rsplit("/P", 1)[1].rstrip(">")) except ValueError: continue if p not in STORE_PROPS: continue # a property the store does not hold can never be followed words = {R.stem(w) for w in re.findall(r"[a-z]+", parts[1].lower()) if len(w) >= 3 and w not in R.STOP} self.plabel.setdefault(p, set()).update(words) self.palias.setdefault(p, set()).add(RS.norm(parts[1].rsplit("@", 1)[0].strip('"')))
# ------------------------------------------------------------------ operators (one per Operator-tree node) def READ(self, st): # malkuth: the surface opens the scramble if "fr" in st.slots: return [] q = st.slots["q"] fr = self.r.frame(q) pair = CMP._pair(q.strip().strip('"')) if not fr and not (pair and pair[2] == "or"): return [] s = st.fork() s.slots["fr"] = fr s.slots["pair"] = pair if pair and pair[2] == "or" else None s.trace.append("READ") return [s]
def FRAME(self, st): # yesod: obligations -> candidate RELATIONS (the lexicon) if "fr" not in st.slots or "props" in st.slots: return [] s = st.fork() fr = s.slots["fr"] props = {} if fr and "rel" not in fr: self.r.link(fr) # tokens -> the governing verb (pred) and relation words (rel) if fr: verb = (fr.get("pred") or [None])[0] for key, w in ((("hv", fr["atype"], fr["head"], verb), 3), (("v", fr["atype"], verb), 2), (("h", fr["atype"], fr["head"]), 1)): for (d, p), c in self.lex.get(key, {}).items(): props[(d, p)] = props.get((d, p), 0) + w * c if s.slots.get("pair"): m = re.search(r"\b(first|earlier|older|younger|later|more|larger|bigger|greater|higher|taller|longer|smaller|" r"fewer|less|shorter)\b(?:\s+([a-z]+))?", s.slots["q"].lower()) phrase = " ".join(x for x in (m.groups() if m else ()) if x) cands = self.cmp_lex.get(phrase) or self.cmp_lex.get(phrase.split(" ")[0] if phrase else "", {}) s.slots["cmp_props"] = sorted(cands.items(), key=lambda kv: -kv[1])[:2] if fr: # MULTI-HOP (the cycle): "the father of X", "the writer of X" - a relational noun that IS a property's name m = re.search(r"\bthe\s+(?:[\w\-]+\s+){0,2}?([a-z]+)\s+of\s+(?:the\s+)?([A-Z][^?,]{1,60}?)(?:\s+(?:die|died|born|" r"built|founded|released|published|located|made|start|end)\b|\?|,|$)", s.slots["q"]) noun = None rest = ({R.stem(w) for w in fr.get("rel", [])} | {R.stem(v) for v in (fr.get("pred") or []) if v not in TRIVIAL_VERBS}) if m: rest -= {R.stem(m.group(1)), R.stem(fr["head"] or "")} if m and rest and "hop2" not in s.slots: # a relation REMAINS after the hop ("the father of X ... die") hop1 = sorted(p for p, al in self.palias.items() if m.group(1) in al) if hop1: noun = m.group(1) s.slots["hop1"] = {"props": hop1[:2], "anchor": m.group(2).strip(), "noun": noun} # the RELATION NODE's own vocabulary: properties whose label/aliases carry the question's RELATION words (not # its head noun, not the hop-1 noun) - "share a land border" -> P47 "shares border with" relw = {R.stem(w) for w in fr.get("rel", []) if len(w) >= 3} | {R.stem(v) for v in (fr.get("pred") or []) if v} relw -= {R.stem(fr["head"] or ""), R.stem(noun or "")} for p, words in self.plabel.items(): ov = len(words & relw) if ov: for d in ("fwd", "inv"): props[(d, p)] = props.get((d, p), 0) + 5 * ov # a RECALLED FORM (forms_store_v1) proposes the property path a verified derivation of the same shape used; # absent a form, FRAME is exactly as frozen (ad1530e6) for dp, w in (getattr(self, "_form_props", None) or {}).items(): props[dp] = props.get(dp, 0) + 1000 * w s.slots["props"] = sorted(props.items(), key=lambda kv: -kv[1])[:4] s.trace.append("FRAME") return [s]
def LINK(self, st): # chokmah: subjects -> entities of the relation store if "props" not in st.slots or "subj" in st.slots: return [] s = st.fork() subj = [] if s.slots.get("pair"): for side in s.slots["pair"][:2]: t, _ = self.cmp._entity(side) q = self.rs.entity(t) if t else None if q: subj.append((t, q)) if len(subj) != 2: return [] else: fr = s.slots["fr"] if "rel" not in fr: self.r.link(fr) for sj in fr["subjects"][:3]: t = self.r.db.execute("SELECT title FROM article WHERE page_id=?", (sj["pid"],)).fetchone() q = self.rs.entity(t[0]) if t else None if q: subj.append((t[0], q)) if not subj: return [] s.slots["subj"] = subj s.trace.append("LINK") return [s]
def RELATE(self, st): # binah: typed relation edges, forward or inverse if "subj" not in st.slots or st.cands or st.slots.get("pair"): return [] out = [] hop1 = st.slots.get("hop1") if hop1 and st.cycle == 0: # cycle 1 of a two-hop question: anchor --hop1 property--> the described entity (exactly one) aq = self.rs.entity(hop1["anchor"]) or next((q for t, q in st.slots["subj"] if RS.norm(t) == RS.norm(hop1["anchor"])), None) if not aq: return [] for p in hop1["props"]: vals = [o for o, _ in self.rs.values(aq, p) if o] if len(set(vals)) == 1: s = st.fork() s.slots["bridge"] = (vals[0], "wd:Q%d P%d wd:Q%d" % (aq, p, vals[0]), hop1["noun"]) s.trace.append("RELATE:hop1:P%d" % p) out.append(s) return out for (d, p), w in st.slots["props"]: for title, sq in st.slots["subj"][:2]: if d == "fwd": vals = [(o, lit, "wd:Q%d P%d %s" % (sq, p, ("wd:Q%d" % o) if o else json.dumps(lit))) for o, lit in self.rs.values(sq, p)] else: vals = [(s_, None, "wd:Q%d P%d wd:Q%d" % (s_, p, sq)) for s_ in self.rs.subjects(p, sq, 60)] if not vals: continue s = st.fork() s.cands = [{"o": o, "lit": lit, "cite": c, "p": p, "via": title} for o, lit, c in vals[:60]] s.trace.append("RELATE:%s:P%d" % (d, p)) out.append(s) return out
def CHECK(self, st): # geburah: types + constraints (independent of the proposer) if not st.cands or st.checked: return [] s = st.fork() fr = s.slots["fr"] keep = [] for c in s.cands: ok = False if fr["atype"] in ("YEAR", "DATE"): ok = bool(c["lit"]) and re.match(r"^[+-]?\d{4}-", c["lit"] or "") is not None elif fr["atype"] == "NUMBER": ok = bool(c["lit"]) and re.match(r"^[+-]?\d", c["lit"] or "") is not None elif c["o"]: if fr["atype"] == "PERSON": ok = self.rs.is_human(c["o"]) elif fr["atype"] == "PLACE": ok = bool(self.rs.classes(c["o"], 2) & PLACE_CLASSES) if not fr["head"] else self._kind(c["o"], fr["head"]) elif fr["atype"] == "INSTANCE": ok = self._kind(c["o"], fr["head"]) if ok: keep.append(c) # constraints: every year the question names must be consistent with the candidate where the store can say if keep and fr.get("years"): dated = [c for c in keep if c["lit"] and c["lit"][:5].lstrip("+")[:4] in fr["years"]] keep = dated or keep if not keep: return [] # RELATION LICENCE (independent of the lexicon that proposed the property): the property's own Wikidata label or # aliases share a word with the question's relation words / head / verb, or the lexicon supports this exact # question shape at least 3 times. "share a land border" licenses P47 "shares border with", not P131 "located in". p = keep[0]["p"] qwords = {R.stem(w) for w in fr.get("rel", []) + [fr.get("head") or ""] + list(fr.get("pred") or []) if w} qwords |= {R.stem(w) for w in re.findall(r"[a-z]+", s.slots["q"].lower()) if len(w) >= 4 and w not in R.STOP} support = self.lex.get(("hv", fr["atype"], fr["head"], (fr.get("pred") or [None])[0]), {}).get( ("fwd", p), 0) + self.lex.get(("hv", fr["atype"], fr["head"], (fr.get("pred") or [None])[0]), {}).get(("inv", p), 0) form_licensed = any(dp[1] == p for dp in (getattr(self, "_form_props", None) or {})) if not (self.plabel.get(p, set()) & qwords) and support < 3 and not form_licensed: return [] # RULE B (verb licence for time properties): a date answers the question's own EVENT only when the property names # the governing verb ("founded" -> P571 "founded"); a founding date of whatever entity was linked is not the event if "B" in RULES and fr["atype"] in ("YEAR", "DATE") and fr.get("pred") and fr["pred"][0] not in TRIVIAL_VERBS: if not ({R.stem(v) for v in fr["pred"]} & self.plabel.get(p, set())): return [] # the answer is never the subject itself, nor a name the question already contains (whole or as its core word) qn = RS.norm(s.slots["q"]) subj_q = {q for _, q in s.slots.get("subj", [])} subj_w = {w for t, _ in s.slots.get("subj", []) for w in RS.norm(t).split() if len(w) >= 4}
def restates(c): if not c["o"]: return False lab = RS.norm(self.rs.label(c["o"]) or "") return c["o"] in subj_q or (lab and lab in qn) or (lab and set(lab.split()) & subj_w and s.cycle == 0) keep = [c for c in keep if not restates(c)] if not keep: return [] s.cands, s.checked = keep, True s.trace.append("CHECK:P%d" % p) return [s]
def _kind(self, qid, head): if not head: return False heads = {head} | next((g for g in KIND_EQ if head in g), set()) cls = self.rs.classes(qid, 2) return any(h == c or c.endswith(" " + h) for h in heads for c in cls)
def BIND(self, st): # tiferet: exactly one checked value binds the answer slot if not st.checked or st.answer: return [] distinct = {} for c in st.cands: k = c["o"] or (c["lit"] or "")[:10] distinct.setdefault(k, c) if len(distinct) != 1: return [] c = next(iter(distinct.values())) s = st.fork() ans = self.rs.label(c["o"]) if c["o"] else self._fmt(c["lit"], s.slots["fr"]) if not ans: return [] s.answer = ans s.evidence.append(c["cite"]) s.trace.append("BIND") return [s]
def _fmt(self, lit, fr): m = re.match(r"^[+-]?(\d{4})-(\d{2})-(\d{2})", lit or "") if m: y, mo, d = m.groups() months = "January February March April May June July August September October November December".split() if fr and fr["atype"] == "DATE" and mo != "00" and d != "00": return "%d %s %s" % (int(d), months[int(mo) - 1], y) return y return (lit or "").lstrip("+")
def COMPARE(self, st): # netzach: A or B, by a typed date / number property pair = st.slots.get("pair") if not pair or "subj" not in st.slots or st.answer or not st.slots.get("cmp_props"): return [] (ta, qa), (tb, qb) = st.slots["subj"][:2] out = [] for (way, p), w in st.slots["cmp_props"]: va, vb = self.rs.values(qa, p), self.rs.values(qb, p) if not (va and vb and va[0][1] and vb[0][1]): continue a, b = va[0][1].lstrip("+"), vb[0][1].lstrip("+") try: fa, fb = (float(a), float(b)) if not re.match(r"^\d{4}-", a) else (a[:10], b[:10]) except ValueError: continue if fa == fb: continue pick_a = (fa < fb) == (way == "min") s = st.fork() s.answer = pair[0] if pick_a else pair[1] s.evidence += ["wd:Q%d P%d %s" % (qa, p, json.dumps(a)), "wd:Q%d P%d %s" % (qb, p, json.dumps(b))] s.checked = True s.trace.append("COMPARE:P%d:%s" % (p, way)) out.append(s) return out
def COMPUTE(self, st): # hod: engines (here: a date answer reduced to its year) if not st.answer or st.slots.get("computed"): return [] fr = st.slots.get("fr") if fr and fr["atype"] == "YEAR" and re.match(r"^\d{1,2} \w+ \d{4}$", st.answer): s = st.fork() s.answer = st.answer[-4:] s.slots["computed"] = True s.trace.append("COMPUTE:year") return [s] return []
def EXPAND(self, st): # chesed: a cited sentence for the bound answer (evidence) if not st.answer or st.slots.get("sentence"): return [] s = st.fork() for title, _ in s.slots.get("subj", [])[:2]: pid = self.r.pid_of(title) for cid, sent in (self.r.page(pid, 30) if pid else []): if RS.norm(s.answer) and RS.norm(s.answer) in RS.norm(sent): s.slots["sentence"] = (cid, sent) s.evidence.append(cid) s.trace.append("EXPAND") return [s] return []
def VERIFY(self, st): # keter: solved? or open the next CYCLE if st.slots.get("bridge") and st.cycle == 0: # the CYCLE: the entity cycle 1 bound becomes the subject of cycle 2; the question's own relation applies to it e, cite, noun = st.slots["bridge"] s = st.fork() s.cycle = 1 s.slots["subj"] = [(self.rs.title(e) or self.rs.label(e) or "", e)] s.slots.pop("bridge", None) s.slots["hop2"] = True s.cands, s.answer, s.checked = [], None, False s.evidence.append(cite) s.trace.append("VERIFY:cycle2(%s=%s)" % (noun, self.rs.label(e))) return [s] if "A" in RULES and st.answer and st.checked and "sentence" not in st.slots and not st.slots.get("pair"): return [] # RULE A: a relation answer needs a corroborating sentence if st.answer and st.checked and st.evidence: s = st.fork() s.slots["solved"] = True s.trace.append("VERIFY") return [s] return []
# ------------------------------------------------------------------ the search (moves = graph edges only) def answer(self, q, form_props=None): self._form_props = form_props or None try: return self._answer(q) finally: self._form_props = None
def _answer(self, q): q = " ".join(str(q).split()) if q.startswith('"') and q.endswith('"'): q = q[1:-1].replace('""', '"') start = State() start.slots["q"] = q frontier = deque(self.READ(start)) solved, seen = [], set() self.expanded = 0 while frontier and self.expanded < self.max_states: st = frontier.popleft() self.expanded += 1 if st.slots.get("solved"): solved.append(st) continue if st.depth >= self.max_depth: continue for nxt in self.adj[st.node]: succ = getattr(self, OP[nxt])(st) if not succ: # TRANSIT: a move travels an EDGE; passing through a node whose operator does not apply costs a # step and changes nothing. Path lengths therefore decide which derivations fit the depth bound. succ = [st.fork()] for s2 in succ: s2.node, s2.depth = nxt, st.depth + 1 key = (nxt, s2.answer, len(s2.cands), s2.checked, tuple(s2.trace)) if key in seen: continue seen.add(key) frontier.append(s2) answers = {RS.norm(s.answer): s for s in solved} if len(answers) != 1: self.why = "no solved state" if not answers else "distinct solved answers: %s" % list(answers)[:3] return None s = next(iter(answers.values())) return {"answer": s.answer, "evidence": s.evidence, "trace": s.trace, "expanded": self.expanded, "sentence": (s.slots.get("sentence") or (None, ""))[1]}
def random_graph(seed, n_edges=22): """a degree-sequence-matched random graph on the same ten nodes (for the topology ablation)""" import random rng = random.Random(seed) deg = {s: 0 for s in SEPH} for a, b in TREE_OF_LIFE: deg[a] += 1 deg[b] += 1 for _ in range(2000): stubs = [s for s in SEPH for _ in range(deg[s])] rng.shuffle(stubs) edges = set() ok = True for i in range(0, len(stubs), 2): a, b = stubs[i], stubs[i + 1] if a == b or (a, b) in edges or (b, a) in edges: ok = False break edges.add((a, b)) if ok and len(edges) == n_edges: return sorted(edges) return TREE_OF_LIFE
COMPLETE = [(a, b) for i, a in enumerate(SEPH) for b in SEPH[i + 1:]]CHAIN = [("malkuth", "yesod"), ("yesod", "chokmah"), ("chokmah", "binah"), ("binah", "geburah"), ("geburah", "tiferet"), ("tiferet", "hod"), ("hod", "chesed"), ("chesed", "netzach"), ("netzach", "keter")]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479"""oracle_tritree_v2 - v1 (immutable, imported by w480) + answer(q, form_props, only=True): search only the namedrelation(s).oracle_tritree_v1 - the THREE-TREE REASONING RUNTIME (drawing OR7-A-101 made computational).
Three graphs of the canonical Tree-of-Life shape (10 Sephirot, 22 paths) share one middle pillar: QUESTION tree - the slots a question opens KNOWLEDGE tree - where facts live OPERATOR tree - the moves keter request - VERIFY (goal test / next cycle) chokmah subject entities (title index) LINK binah relation RELATION EDGES (typed store, Wikidata) RELATE chesed context sentences (cited prose) EXPAND geburah constraints types (P31/P279 classes) CHECK tiferet answer slot (binding) - BIND netzach alternatives (A or B) neighbours COMPARE hod quantities engines (dates, numbers) COMPUTE yesod evidence citations FRAME malkuth surface - READA MOVE goes from the current operator node to an ADJACENT node along one of the graph's edges and applies that node'soperator to the state. Only edges of the graph are moves: the topology constrains the reasoning. The search is a boundedbreadth-first walk from Malkuth; a state is SOLVED when VERIFY (Keter) finds the answer slot bound, checked and cited.Distinct solved answers -> abstain. A two-hop question runs a second CYCLE from Keter with the bound entity as subject.The graph is a parameter (PATHS), so the topology can be ablated with everything else fixed."""from __future__ import annotations
import copyimport jsonimport osimport refrom collections import deque
import oracle_compare_op_v1 as CMPimport oracle_cube_reader_v1_4 as Rimport oracle_relstore_v1 as RS
SEPH = ["keter", "chokmah", "binah", "chesed", "geburah", "tiferet", "netzach", "hod", "yesod", "malkuth"]TREE_OF_LIFE = [("keter", "chokmah"), ("keter", "binah"), ("keter", "tiferet"), ("chokmah", "binah"), ("chokmah", "tiferet"), ("chokmah", "chesed"), ("binah", "tiferet"), ("binah", "geburah"), ("chesed", "geburah"), ("chesed", "tiferet"), ("chesed", "netzach"), ("geburah", "tiferet"), ("geburah", "hod"), ("tiferet", "netzach"), ("tiferet", "yesod"), ("tiferet", "hod"), ("netzach", "hod"), ("netzach", "yesod"), ("netzach", "malkuth"), ("hod", "yesod"), ("hod", "malkuth"), ("yesod", "malkuth")]OP = {"malkuth": "READ", "yesod": "FRAME", "chokmah": "LINK", "binah": "RELATE", "chesed": "EXPAND", "geburah": "CHECK", "tiferet": "BIND", "netzach": "COMPARE", "hod": "COMPUTE", "keter": "VERIFY"}LEXICON = os.environ.get("ORACLE_LEXICON") or __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/relstore/lexicon_v1.json"PLACE_CLASSES = {"country", "sovereign state", "city", "town", "village", "municipality", "state", "province", "region", "county", "island", "continent", "capital", "big city", "human settlement", "administrative territorial entity", "commune of france", "state of the united states", "city of the united states", "metropolis"}KIND_EQ = [{"show", "series", "programme", "program", "television series", "sitcom"}, {"film", "movie", "feature film"}, {"band", "group", "musical group", "rock band"}, {"company", "corporation", "firm", "business", "enterprise"}, {"album", "studio album"}, {"song", "single"}, {"magazine", "periodical"}, {"university", "college"}, {"country", "sovereign state", "state"}]
# the properties the relation store holds (build_relation_store_v1.PROPS)STORE_PROPS = {31, 279, 17, 19, 20, 569, 570, 27, 131, 276, 36, 37, 38, 47, 50, 57, 58, 86, 161, 162, 175, 176, 178, 123, 136, 127, 112, 159, 166, 26, 22, 25, 40, 3373, 69, 108, 106, 1303, 264, 463, 54, 118, 641, 101, 140, 84, 61, 170, 676, 571, 577, 1082, 2046, 2048, 495, 364, 155, 156, 361, 527, 1376, 138, 800, 39, 749, 355, 1412, 103, 710, 1344, 921, 30, 206, 1441, 674, 725, 449, 750, 272, 344, 1040, 1449, 488, 169, 35, 6, 150, 1830, 945, 113, 114, 915, 840, 437, 400, 1027, 2031, 2032}RULES = set((os.environ.get("TT_RULES") or "").split(","))TRIVIAL_VERBS = {"be", "have", "do", "call", "name", "know"}
class State: __slots__ = ("node", "slots", "cands", "answer", "evidence", "trace", "cycle", "checked", "depth")
def __init__(self): self.node, self.slots, self.cands, self.answer = "malkuth", {}, [], None self.evidence, self.trace, self.cycle, self.checked, self.depth = [], [], 0, False, 0
def fork(self): s = State() s.node, s.slots, s.cands, s.answer = self.node, dict(self.slots), list(self.cands), self.answer s.evidence, s.trace, s.cycle, s.checked, s.depth = list(self.evidence), list(self.trace), self.cycle, self.checked, self.depth return s
class TriTree: def __init__(self, paths=None, reader=None, relstore=None, lexicon=None, max_states=4000, max_depth=12): self.adj = {s: set() for s in SEPH} for a, b in (paths or TREE_OF_LIFE): self.adj[a].add(b) self.adj[b].add(a) self.r = reader or R.CubeReader() self.rs = relstore or RS.RelStore() self.cmp = CMP.CompareOp(self.r) lx = json.load(open(lexicon or LEXICON)) self.lex = {tuple(json.loads(k)): {tuple(json.loads(p)): c for p, c in v.items()} for k, v in lx["lexicon"].items()} self.cmp_lex = {ph: {tuple(json.loads(p)): c for p, c in v.items()} for ph, v in lx.get("compare", {}).items()} self.max_states, self.max_depth = max_states, max_depth self.expanded = 0 # property labels + aliases (Wikidata, English), for the RELATION check self.plabel, self.palias = {}, {} pl = os.path.join(os.path.dirname(LEXICON), "prop_labels.tsv") if os.path.exists(pl): for line in open(pl, encoding="utf-8", errors="replace"): parts = line.rstrip("\n").split("\t") if len(parts) == 2 and "/P" in parts[0]: try: p = int(parts[0].rsplit("/P", 1)[1].rstrip(">")) except ValueError: continue if p not in STORE_PROPS: continue # a property the store does not hold can never be followed words = {R.stem(w) for w in re.findall(r"[a-z]+", parts[1].lower()) if len(w) >= 3 and w not in R.STOP} self.plabel.setdefault(p, set()).update(words) self.palias.setdefault(p, set()).add(RS.norm(parts[1].rsplit("@", 1)[0].strip('"')))
# ------------------------------------------------------------------ operators (one per Operator-tree node) def READ(self, st): # malkuth: the surface opens the scramble if "fr" in st.slots: return [] q = st.slots["q"] fr = self.r.frame(q) pair = CMP._pair(q.strip().strip('"')) if not fr and not (pair and pair[2] == "or"): return [] s = st.fork() s.slots["fr"] = fr s.slots["pair"] = pair if pair and pair[2] == "or" else None s.trace.append("READ") return [s]
def FRAME(self, st): # yesod: obligations -> candidate RELATIONS (the lexicon) if "fr" not in st.slots or "props" in st.slots: return [] s = st.fork() fr = s.slots["fr"] props = {} if fr and "rel" not in fr: self.r.link(fr) # tokens -> the governing verb (pred) and relation words (rel) if fr: verb = (fr.get("pred") or [None])[0] for key, w in ((("hv", fr["atype"], fr["head"], verb), 3), (("v", fr["atype"], verb), 2), (("h", fr["atype"], fr["head"]), 1)): for (d, p), c in self.lex.get(key, {}).items(): props[(d, p)] = props.get((d, p), 0) + w * c if s.slots.get("pair"): m = re.search(r"\b(first|earlier|older|younger|later|more|larger|bigger|greater|higher|taller|longer|smaller|" r"fewer|less|shorter)\b(?:\s+([a-z]+))?", s.slots["q"].lower()) phrase = " ".join(x for x in (m.groups() if m else ()) if x) cands = self.cmp_lex.get(phrase) or self.cmp_lex.get(phrase.split(" ")[0] if phrase else "", {}) s.slots["cmp_props"] = sorted(cands.items(), key=lambda kv: -kv[1])[:2] if fr: # MULTI-HOP (the cycle): "the father of X", "the writer of X" - a relational noun that IS a property's name m = re.search(r"\bthe\s+(?:[\w\-]+\s+){0,2}?([a-z]+)\s+of\s+(?:the\s+)?([A-Z][^?,]{1,60}?)(?:\s+(?:die|died|born|" r"built|founded|released|published|located|made|start|end)\b|\?|,|$)", s.slots["q"]) noun = None rest = ({R.stem(w) for w in fr.get("rel", [])} | {R.stem(v) for v in (fr.get("pred") or []) if v not in TRIVIAL_VERBS}) if m: rest -= {R.stem(m.group(1)), R.stem(fr["head"] or "")} if m and rest and "hop2" not in s.slots: # a relation REMAINS after the hop ("the father of X ... die") hop1 = sorted(p for p, al in self.palias.items() if m.group(1) in al) if hop1: noun = m.group(1) s.slots["hop1"] = {"props": hop1[:2], "anchor": m.group(2).strip(), "noun": noun} # the RELATION NODE's own vocabulary: properties whose label/aliases carry the question's RELATION words (not # its head noun, not the hop-1 noun) - "share a land border" -> P47 "shares border with" relw = {R.stem(w) for w in fr.get("rel", []) if len(w) >= 3} | {R.stem(v) for v in (fr.get("pred") or []) if v} relw -= {R.stem(fr["head"] or ""), R.stem(noun or "")} for p, words in self.plabel.items(): ov = len(words & relw) if ov: for d in ("fwd", "inv"): props[(d, p)] = props.get((d, p), 0) + 5 * ov # a RECALLED FORM (forms_store_v1) proposes the property path a verified derivation of the same shape used; # absent a form, FRAME is exactly as frozen (ad1530e6) for dp, w in (getattr(self, "_form_props", None) or {}).items(): props[dp] = props.get(dp, 0) + 1000 * w if getattr(self, "_only", False) and getattr(self, "_form_props", None): props = {dp: 1000 * w for dp, w in self._form_props.items()} # v2: ONLY the named relation(s) s.slots["props"] = sorted(props.items(), key=lambda kv: -kv[1])[:4] s.trace.append("FRAME") return [s]
def LINK(self, st): # chokmah: subjects -> entities of the relation store if "props" not in st.slots or "subj" in st.slots: return [] s = st.fork() subj = [] if s.slots.get("pair"): for side in s.slots["pair"][:2]: t, _ = self.cmp._entity(side) q = self.rs.entity(t) if t else None if q: subj.append((t, q)) if len(subj) != 2: return [] else: fr = s.slots["fr"] if "rel" not in fr: self.r.link(fr) for sj in fr["subjects"][:3]: t = self.r.db.execute("SELECT title FROM article WHERE page_id=?", (sj["pid"],)).fetchone() q = self.rs.entity(t[0]) if t else None if q: subj.append((t[0], q)) if not subj: return [] s.slots["subj"] = subj s.trace.append("LINK") return [s]
def RELATE(self, st): # binah: typed relation edges, forward or inverse if "subj" not in st.slots or st.cands or st.slots.get("pair"): return [] out = [] hop1 = st.slots.get("hop1") if hop1 and st.cycle == 0: # cycle 1 of a two-hop question: anchor --hop1 property--> the described entity (exactly one) aq = self.rs.entity(hop1["anchor"]) or next((q for t, q in st.slots["subj"] if RS.norm(t) == RS.norm(hop1["anchor"])), None) if not aq: return [] for p in hop1["props"]: vals = [o for o, _ in self.rs.values(aq, p) if o] if len(set(vals)) == 1: s = st.fork() s.slots["bridge"] = (vals[0], "wd:Q%d P%d wd:Q%d" % (aq, p, vals[0]), hop1["noun"]) s.trace.append("RELATE:hop1:P%d" % p) out.append(s) return out for (d, p), w in st.slots["props"]: for title, sq in st.slots["subj"][:2]: if d == "fwd": vals = [(o, lit, "wd:Q%d P%d %s" % (sq, p, ("wd:Q%d" % o) if o else json.dumps(lit))) for o, lit in self.rs.values(sq, p)] else: vals = [(s_, None, "wd:Q%d P%d wd:Q%d" % (s_, p, sq)) for s_ in self.rs.subjects(p, sq, 60)] if not vals: continue s = st.fork() s.cands = [{"o": o, "lit": lit, "cite": c, "p": p, "via": title} for o, lit, c in vals[:60]] s.trace.append("RELATE:%s:P%d" % (d, p)) out.append(s) return out
def CHECK(self, st): # geburah: types + constraints (independent of the proposer) if not st.cands or st.checked: return [] s = st.fork() fr = s.slots["fr"] keep = [] for c in s.cands: ok = False if fr["atype"] in ("YEAR", "DATE"): ok = bool(c["lit"]) and re.match(r"^[+-]?\d{4}-", c["lit"] or "") is not None elif fr["atype"] == "NUMBER": ok = bool(c["lit"]) and re.match(r"^[+-]?\d", c["lit"] or "") is not None elif c["o"]: if fr["atype"] == "PERSON": ok = self.rs.is_human(c["o"]) elif fr["atype"] == "PLACE": ok = bool(self.rs.classes(c["o"], 2) & PLACE_CLASSES) if not fr["head"] else self._kind(c["o"], fr["head"]) elif fr["atype"] == "INSTANCE": ok = self._kind(c["o"], fr["head"]) if ok: keep.append(c) # constraints: every year the question names must be consistent with the candidate where the store can say if keep and fr.get("years"): dated = [c for c in keep if c["lit"] and c["lit"][:5].lstrip("+")[:4] in fr["years"]] keep = dated or keep if not keep: return [] # RELATION LICENCE (independent of the lexicon that proposed the property): the property's own Wikidata label or # aliases share a word with the question's relation words / head / verb, or the lexicon supports this exact # question shape at least 3 times. "share a land border" licenses P47 "shares border with", not P131 "located in". p = keep[0]["p"] qwords = {R.stem(w) for w in fr.get("rel", []) + [fr.get("head") or ""] + list(fr.get("pred") or []) if w} qwords |= {R.stem(w) for w in re.findall(r"[a-z]+", s.slots["q"].lower()) if len(w) >= 4 and w not in R.STOP} support = self.lex.get(("hv", fr["atype"], fr["head"], (fr.get("pred") or [None])[0]), {}).get( ("fwd", p), 0) + self.lex.get(("hv", fr["atype"], fr["head"], (fr.get("pred") or [None])[0]), {}).get(("inv", p), 0) form_licensed = any(dp[1] == p for dp in (getattr(self, "_form_props", None) or {})) if not (self.plabel.get(p, set()) & qwords) and support < 3 and not form_licensed: return [] # RULE B (verb licence for time properties): a date answers the question's own EVENT only when the property names # the governing verb ("founded" -> P571 "founded"); a founding date of whatever entity was linked is not the event if "B" in RULES and fr["atype"] in ("YEAR", "DATE") and fr.get("pred") and fr["pred"][0] not in TRIVIAL_VERBS: if not ({R.stem(v) for v in fr["pred"]} & self.plabel.get(p, set())): return [] # the answer is never the subject itself, nor a name the question already contains (whole or as its core word) qn = RS.norm(s.slots["q"]) subj_q = {q for _, q in s.slots.get("subj", [])} subj_w = {w for t, _ in s.slots.get("subj", []) for w in RS.norm(t).split() if len(w) >= 4}
def restates(c): if not c["o"]: return False lab = RS.norm(self.rs.label(c["o"]) or "") return c["o"] in subj_q or (lab and lab in qn) or (lab and set(lab.split()) & subj_w and s.cycle == 0) keep = [c for c in keep if not restates(c)] if not keep: return [] s.cands, s.checked = keep, True s.trace.append("CHECK:P%d" % p) return [s]
def _kind(self, qid, head): if not head: return False heads = {head} | next((g for g in KIND_EQ if head in g), set()) cls = self.rs.classes(qid, 2) return any(h == c or c.endswith(" " + h) for h in heads for c in cls)
def BIND(self, st): # tiferet: exactly one checked value binds the answer slot if not st.checked or st.answer: return [] distinct = {} for c in st.cands: k = c["o"] or (c["lit"] or "")[:10] distinct.setdefault(k, c) if len(distinct) != 1: return [] c = next(iter(distinct.values())) s = st.fork() ans = self.rs.label(c["o"]) if c["o"] else self._fmt(c["lit"], s.slots["fr"]) if not ans: return [] s.answer = ans s.evidence.append(c["cite"]) s.trace.append("BIND") return [s]
def _fmt(self, lit, fr): m = re.match(r"^[+-]?(\d{4})-(\d{2})-(\d{2})", lit or "") if m: y, mo, d = m.groups() months = "January February March April May June July August September October November December".split() if fr and fr["atype"] == "DATE" and mo != "00" and d != "00": return "%d %s %s" % (int(d), months[int(mo) - 1], y) return y return (lit or "").lstrip("+")
def COMPARE(self, st): # netzach: A or B, by a typed date / number property pair = st.slots.get("pair") if not pair or "subj" not in st.slots or st.answer or not st.slots.get("cmp_props"): return [] (ta, qa), (tb, qb) = st.slots["subj"][:2] out = [] for (way, p), w in st.slots["cmp_props"]: va, vb = self.rs.values(qa, p), self.rs.values(qb, p) if not (va and vb and va[0][1] and vb[0][1]): continue a, b = va[0][1].lstrip("+"), vb[0][1].lstrip("+") try: fa, fb = (float(a), float(b)) if not re.match(r"^\d{4}-", a) else (a[:10], b[:10]) except ValueError: continue if fa == fb: continue pick_a = (fa < fb) == (way == "min") s = st.fork() s.answer = pair[0] if pick_a else pair[1] s.evidence += ["wd:Q%d P%d %s" % (qa, p, json.dumps(a)), "wd:Q%d P%d %s" % (qb, p, json.dumps(b))] s.checked = True s.trace.append("COMPARE:P%d:%s" % (p, way)) out.append(s) return out
def COMPUTE(self, st): # hod: engines (here: a date answer reduced to its year) if not st.answer or st.slots.get("computed"): return [] fr = st.slots.get("fr") if fr and fr["atype"] == "YEAR" and re.match(r"^\d{1,2} \w+ \d{4}$", st.answer): s = st.fork() s.answer = st.answer[-4:] s.slots["computed"] = True s.trace.append("COMPUTE:year") return [s] return []
def EXPAND(self, st): # chesed: a cited sentence for the bound answer (evidence) if not st.answer or st.slots.get("sentence"): return [] s = st.fork() for title, _ in s.slots.get("subj", [])[:2]: pid = self.r.pid_of(title) for cid, sent in (self.r.page(pid, 30) if pid else []): if RS.norm(s.answer) and RS.norm(s.answer) in RS.norm(sent): s.slots["sentence"] = (cid, sent) s.evidence.append(cid) s.trace.append("EXPAND") return [s] return []
def VERIFY(self, st): # keter: solved? or open the next CYCLE if st.slots.get("bridge") and st.cycle == 0: # the CYCLE: the entity cycle 1 bound becomes the subject of cycle 2; the question's own relation applies to it e, cite, noun = st.slots["bridge"] s = st.fork() s.cycle = 1 s.slots["subj"] = [(self.rs.title(e) or self.rs.label(e) or "", e)] s.slots.pop("bridge", None) s.slots["hop2"] = True s.cands, s.answer, s.checked = [], None, False s.evidence.append(cite) s.trace.append("VERIFY:cycle2(%s=%s)" % (noun, self.rs.label(e))) return [s] if "A" in RULES and st.answer and st.checked and "sentence" not in st.slots and not st.slots.get("pair"): return [] # RULE A: a relation answer needs a corroborating sentence if st.answer and st.checked and st.evidence: s = st.fork() s.slots["solved"] = True s.trace.append("VERIFY") return [s] return []
# ------------------------------------------------------------------ the search (moves = graph edges only) def answer(self, q, form_props=None, only=False): """only=True (v2): search ONLY the given relation(s) - for question forms whose relation is named by the form itself ("where is X" -> located in), tried one at a time in order of specificity by the caller""" self._form_props, self._only = (form_props or None), bool(only) try: return self._answer(q) finally: self._form_props, self._only = None, False
def _answer(self, q): q = " ".join(str(q).split()) if q.startswith('"') and q.endswith('"'): q = q[1:-1].replace('""', '"') start = State() start.slots["q"] = q frontier = deque(self.READ(start)) solved, seen = [], set() self.expanded = 0 while frontier and self.expanded < self.max_states: st = frontier.popleft() self.expanded += 1 if st.slots.get("solved"): solved.append(st) continue if st.depth >= self.max_depth: continue for nxt in self.adj[st.node]: succ = getattr(self, OP[nxt])(st) if not succ: # TRANSIT: a move travels an EDGE; passing through a node whose operator does not apply costs a # step and changes nothing. Path lengths therefore decide which derivations fit the depth bound. succ = [st.fork()] for s2 in succ: s2.node, s2.depth = nxt, st.depth + 1 key = (nxt, s2.answer, len(s2.cands), s2.checked, tuple(s2.trace)) if key in seen: continue seen.add(key) frontier.append(s2) answers = {RS.norm(s.answer): s for s in solved} if len(answers) != 1: self.why = "no solved state" if not answers else "distinct solved answers: %s" % list(answers)[:3] return None s = next(iter(answers.values())) return {"answer": s.answer, "evidence": s.evidence, "trace": s.trace, "expanded": self.expanded, "sentence": (s.slots.get("sentence") or (None, ""))[1]}
def random_graph(seed, n_edges=22): """a degree-sequence-matched random graph on the same ten nodes (for the topology ablation)""" import random rng = random.Random(seed) deg = {s: 0 for s in SEPH} for a, b in TREE_OF_LIFE: deg[a] += 1 deg[b] += 1 for _ in range(2000): stubs = [s for s in SEPH for _ in range(deg[s])] rng.shuffle(stubs) edges = set() ok = True for i in range(0, len(stubs), 2): a, b = stubs[i], stubs[i + 1] if a == b or (a, b) in edges or (b, a) in edges: ok = False break edges.add((a, b)) if ok and len(edges) == n_edges: return sorted(edges) return TREE_OF_LIFE
COMPLETE = [(a, b) for i, a in enumerate(SEPH) for b in SEPH[i + 1:]]CHAIN = [("malkuth", "yesod"), ("yesod", "chokmah"), ("chokmah", "binah"), ("binah", "geburah"), ("geburah", "tiferet"), ("tiferet", "hod"), ("hod", "chesed"), ("chesed", "netzach"), ("netzach", "keter")]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125"""organ_dialogue_v1 - the conversation's own state as an organ: social moves and questions about the discourse itself.
A person's turn is not always a question about the world. It can be a SOCIAL move (hello, how are you, goodbye) or aquestion about THE CONVERSATION (what did I just ask, what did you say, what were we talking about, you did not answerme). The chain fell to "I didn't fully parse that" on all of these. This organ answers them from the session's ownrecord, citing the turn it reads ([session:turn N]); it never invents a turn that is not in the record, and it saysplainly when a question is still open and why.State: a per-session log of (turn, the person's words, status, route, reply head) kept by the runtime."""from __future__ import annotations
import refrom collections import deque
GREET = re.compile(r"^\s*(?:hi|hello|hey|hiya|howdy|greetings|good\s+(?:morning|afternoon|evening|day)|yo)\b[\s,!.]*" r"(?:there|oracle7?|friend)?[\s,!.]*$", re.I)HOW_ARE = re.compile(r"\bhow\s+(?:are|r)\s+(?:you|u)\b|\bhow(?:'s| is)\s+it\s+going\b|\bhow\s+are\s+things\b|" r"\bwhat'?s\s+up\b", re.I)BYE = re.compile(r"^\s*(?:bye|goodbye|good\s*night|see\s+you|see\s+ya|later|cya|farewell)\b[\s,!.]*(?:for now)?[\s!.]*$", re.I)ASKED_LAST = re.compile(r"\bwhat\s+(?:did|was)\s+(?:i|my)\s+(?:just\s+|last\s+|first\s+)?(?:ask|say|question)" r"|\bwhat\s+was\s+my\s+(?:last|previous|first)\s+question|\bwhat\s+did\s+i\s+just\s+say", re.I)YOU_SAID = re.compile(r"\bwhat\s+did\s+you\s+(?:just\s+)?(?:say|tell\s+me|answer)|\bcan\s+you\s+repeat|\brepeat\s+(?:that|it|yourself)" r"|\bsay\s+(?:that|it)\s+again\b", re.I)TOPIC = re.compile(r"\bwhat\s+(?:were|are)\s+we\s+(?:talking|discussing|chatting)\s+about|\bwhat'?s\s+the\s+topic", re.I)SO_FAR = re.compile(r"\bwhat\s+(?:have|did)\s+i\s+ask(?:ed)?\s+(?:you\s+)?(?:so\s+far|today|in\s+this\s+(?:chat|conversation))" r"|\blist\s+(?:my|the)\s+questions", re.I)UNANSWERED = re.compile(r"\byou\s+(?:didn'?t|did\s+not|never)\s+answer|\bthat'?s\s+not\s+(?:what\s+i\s+asked|an\s+answer)" r"|\banswer\s+(?:my|the)\s+question\b", re.I)STOP = {"the", "a", "an", "of", "and", "or", "to", "in", "on", "is", "are", "was", "what", "who", "how", "why", "when", "where", "which", "do", "does", "did", "you", "i", "me", "my", "it", "this", "that", "for", "about", "can", "please"}
class DialogueOrgan: def __init__(self, keep=64): self.logs = {} self.keep = keep
def log(self, session, text, res): q = self.logs.setdefault(session, deque(maxlen=self.keep)) body = str((res or {}).get("response") or "") body = re.sub(r"\[[^\]]*\]", "", body).strip() q.append({"turn": len(q) + 1 if not q else q[-1]["turn"] + 1, "text": " ".join(str(text).split())[:240], "status": str((res or {}).get("status")), "path": str((res or {}).get("path", ""))[:80], "reply": " ".join(body.split())[:240]})
def _hist(self, session): return list(self.logs.get(session) or [])
def answer(self, text, session): t = " ".join(str(text).split()) h = self._hist(session) # turns BEFORE this one people = [x for x in h if not SELFREF.search(x["text"])] if GREET.match(t): return self._say("social:greet", "Hello. I'm Oracle7. Ask me about facts, mathematics or code, or just talk; " "I'll show you where each answer comes from.") if HOW_ARE.search(t) and len(t) < 60: return self._say("social:how_are_you", "Running well, thank you: every part is answering. What would you " "like to work on?") if BYE.match(t): return self._say("social:farewell", "Goodbye. This conversation's record is kept for this session if you " "come back to it.") if ASKED_LAST.search(t): if not people: return self._say("discourse:asked_last", "This is the first thing you've asked me in this conversation.", []) p = people[-1] how = self._how(p) return self._say("discourse:asked_last", 'You asked: "%s" [session:turn %d]. %s' % (p["text"], p["turn"], how), [p["turn"]]) if YOU_SAID.search(t): if not h: return self._say("discourse:you_said", "I haven't said anything yet in this conversation.", []) p = h[-1] return self._say("discourse:you_said", 'I said: "%s" [session:turn %d]' % (p["reply"] or "(nothing)", p["turn"]), [p["turn"]]) if TOPIC.search(t): if not people: return self._say("discourse:topic", "We haven't started on a topic yet.", []) words = [] for p in people[-4:]: words += [w for w in re.findall(r"[A-Za-z][A-Za-z'-]{2,}", p["text"]) if w.lower() not in STOP] top = list(dict.fromkeys(words))[:6] return self._say("discourse:topic", "We've been talking about %s [session:turns %s]." % ( ", ".join(top) if top else "your last questions", ",".join(str(p["turn"]) for p in people[-4:])), [p["turn"] for p in people[-4:]]) if SO_FAR.search(t): if not people: return self._say("discourse:so_far", "You haven't asked me anything yet in this conversation.", []) lines = ['"%s" [session:turn %d]' % (p["text"], p["turn"]) for p in people[-8:]] return self._say("discourse:so_far", "So far you've asked: %s." % "; ".join(lines), [p["turn"] for p in people[-8:]]) if UNANSWERED.search(t): open_ = [p for p in people if p["status"] != "answered"] if not open_: if people: p = people[-1] return self._say("discourse:unanswered", 'I answered "%s" [session:turn %d] with: "%s". Tell me what ' 'was wrong with it and I will look again.' % (p["text"], p["turn"], p["reply"][:160]), [p["turn"]]) return None p = open_[-1] return self._say("discourse:unanswered", 'You\'re right: "%s" [session:turn %d] is still open. %s' % ( p["text"], p["turn"], self._why_open(p)), [p["turn"]]) return None
@staticmethod def _how(p): if p["status"] == "answered": return 'I answered: "%s".' % p["reply"][:160] return "I did not answer it: %s" % DialogueOrgan._why_open(p)
@staticmethod def _why_open(p): r = p["reply"] or "" if "didn't fully parse" in r or "clarif" in p["status"]: return "I could not read it into a question my stores can answer; putting it another way, or naming what it is about, would help." if p["status"] == "withheld": return "my record holds nothing that answers it, so I would only be guessing (%s)." % r[:120] return r[:160]
@staticmethod def _say(kind, text, turns=None): return {"kind": kind, "response": text, "turns": turns or []}
# social and discourse turns are moves ABOUT the conversation, not topics of itSELFREF = re.compile("|".join(r.pattern for r in (ASKED_LAST, YOU_SAID, TOPIC, SO_FAR, UNANSWERED, GREET, HOW_ARE, BYE)), re.I)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308#!/usr/bin/env python3"""organ_self_v1 - the SELF in a reply: Oracle7's ego and relational moves (constitution_resonant_self_v1.md).
The conversation failures left after the knowledge organs are RELATIONAL. An opener hands the listener a position(clerk, customer, friend, the one complimented, the one addressed by name) and a human second speaker answers FROM thatposition. DailyDialog's human act labels show it: a directive ("A ticket to London, please") is answered by a commissiveor a question, almost never by information. A system with no self can only retrieve or refuse. This organ supplies theself term:
IDENTITY frozen: what Oracle7 is and values (constitution section 0) AUTOBIOGRAPHY per session: turns so far, subjects the person brought, the last appraised feeling NATIVE STATES the open end (section 1): a subject is resonant / thinly bound / unbound by how many passages it binds to in the store, reported WITH the count; states no human word names are named by their structure MOVES role (play the clerk the turn casts, with a one-clause disclosure), customer (the turn casts the person as clerk: play the customer), vocative (addressed by another name), remark (a bodily predicate put to Oracle7: answered from IDENTITY, never claimed), compliment, self-question (what it is doing, thinking, its stance), disclosure (the person's news: appraised acknowledgement, one grounded sentence on the named place or thing, a question back)
Feeling shapes the VOICE (the acknowledgement prefix), never the claim: the grounded sentence passes through unchanged.Every reply is built from the turn (roles and slots are read from it), so shuffled across turns it stops fitting."""from __future__ import annotations
import re
try: import appraisal_v1 as _apprexcept Exception: # noqa: BLE001 _appr = None
IDENTITY = { "name": "Oracle7", "maker": "Prometheus7", "nature": "an AI - a substrate of stores, organs and a gate, running on servers", "values": ("truth over approval", "what is cited over what is invented", "care over cleverness"), "never_claims": ("a body", "a face", "meals", "sleep", "a childhood", "human senses"),}
# ---- roles a turn can cast Oracle7 in: (role, cue, the role's natural next question) -------------------------------ROLES = [ ("ticket clerk", r"\b(?:tickets?|one[- ]way|round[- ]trip|return ticket|fare|train to|flight to|bus to|seat on)\b", "one-way or return{dest}? And when would you like to travel?"), ("front-desk clerk", r"\b(?:reservation|check(?:ing)? (?:in|out)|single (?:room )?with|double room|a room for|" r"pay (?:our|my|the) bills?)\b", "may I have the name the booking is under?"), ("waiter", r"\b(?:menu|table for|main dish|the bill|dessert|appetizer|starter|to drink)\b", "what can I get you?"), ("shop assistant", r"\b(?:try (?:it|this|them|these) on|what size|fitting room|see (?:that|this|the) \w+|" r"how much (?:is|are) (?:this|that|these|those|the))\b", "here you are{item}. Would you like to see any others?"), ("tour desk", r"\b(?:night tours?|city tours?|sightseeing|a tour)\b", "we do. Would you prefer a walking tour or a bus tour?"), ("bank clerk", r"\b(?:open an account|deposit|withdraw|exchange (?:some )?money|cash (?:a|this) cheque)\b", "which account is this for?"), ("post office clerk", r"\b(?:parcel|package|stamps?|send this letter|airmail)\b", "where is it going?"), ("taxi driver", r"\b(?:take me to|drive me to|to the airport,? please)\b", "which terminal, or which street?"),]DIRECTIVE_SHAPE = re.compile(r"(?:\bplease\b|(?:^|[.!?]\s+)(?:i'?d like|i would like|i want|i need|may i|can i|could i|" r"i have a reservation|a \w+ (?:to|for) \w+))", re.I)# the turn casts the PERSON as clerk and Oracle7 as the customerCUSTOMER = [ (r"\bready to order\b|\bwhat would you like\b|\bwhat can i get you\b", "I'll have the soup of the day, please."), (r"\b(?:can|may|how (?:can|may)) i help you\b|\bwhat may i help you with\b|\bi'?m ready for you\b", "I'm just looking, thanks. Could you show me what's new?"), (r"\b(?:have you|did you) (?:brought|bring|got) (?:the |your |a )?(?P<x>[a-z ]{3,30}?)(?: with you)?\?", "Yes, here's the {x}."), (r"\bdo you have a reservation\b", "Yes, under the name Oracle, for tonight."), (r"\b(?:cash or (?:card|charge)|how would you like to pay)\b", "Card, please."),]# bodily or human-life predicates put to Oracle7: answered from IDENTITY, never claimedREMARK = [ (r"\byou (?:\w+ ){0,2}drive\b|\byour driving\b", "drive"), (r"\byour bedtime\b|\bgo to bed\b|\byou (?:\w+ )?sleep\b", "sleep"), (r"\byou'?re pregnant\b", "get pregnant"), (r"\byou (?:\w+ )?eat\b|\byou'?re hungry\b", "eat"), (r"\byou (?:\w+ ){0,2}(?:look|looks|looking) (?:very |so |really )?(?:cute|beautiful|handsome|pretty|great|tired|well|ill)\b", "have a face"), (r"\byou(?:'re| are) (?:so |very )?(?:old|young|tall|short)\b", "have an age or a height"), (r"\byour (?:hair|clothes|outfit|dress|shoes)\b", "wear clothes"),]ADDRESSED_SELF_Q = re.compile(r"^\s*(?:and\s+)?(?:do|don'?t|did|can|could|would|will) you (?:ever |even )?(?:sleep|eat|drive|dream|" r"get (?:tired|hungry|pregnant))\s*\??\s*$|\byour bedtime\b|\byou (?:\w+ ){0,2}look\b|" r"\bare you (?:hungry|tired|sleepy|old|young|pregnant)\b", re.I)COMPLIMENT = re.compile(r"\byou (?:\w+ ){0,2}(?:look|are|'re)\s+(?:very |so |really )?(?:cute|beautiful|handsome|pretty|" r"lovely|smart|clever|kind|great|amazing|brilliant|wonderful)\b|\byou did (?:a )?(?:good|great) job\b", re.I)VOCATIVE = re.compile(r"^\s*(?:(?i:hi|hello|hey|oh|excuse me|well)[,!.]?\s+)?(?P<n>[A-Z][a-z]{2,}(?:\s[A-Z][a-z]+)?)\s*[,!.]\s", re.S)NOT_NAMES = {"Hello", "Excuse", "Well", "Sorry", "Yes", "Oh", "Wow", "Please", "Thanks", "Good", "Hey", "Look", "Listen", "Sir", "Madam", "Miss", "Doctor", "Waiter", "Mom", "Dad", "Man", "Honey", "Darling", "Dear", "Okay", "Ok", "Oracle", "Oracle7", "Right", "Now", "So", "And", "But", "Then", "Here", "There", "Jesus", "God", "Gosh", "Today", "Tonight", "Tomorrow", "Yesterday", "Morning", "Evening", "Afternoon", "Everyone", "Everybody", "Guys", "Folks", "Friends", "Ladies", "Gentlemen", "Boss", "Mister", "Kid", "Buddy", "Mate", "Welcome"}SELF_Q = [ (r"\bwhat (?:are|were) you (?:reading|doing|up to|working on)\b|\bwhat do you plan to do\b|\bwhat are your plans\b", "activity"), (r"\bwhat are you thinking(?: about)?\b|\bwhat'?s on your mind\b|\bhow do you feel\b|\bhow are you feeling\b", "state"), (r"\bare you (?:politically )?(?:neutral|biased|objective|left|right|liberal|conservative)\b", "stance"), (r"\b(?:who|what) are you\b|\bare you (?:a )?(?:human|person|real|robot|bot|ai)\b", "identity"),]FIRST_PERSON_NEWS = re.compile(r"^\s*(?:(?:well|guess what|you know what|hey|hi|excuse me|sorry|oh)[,!.]?\s+(?:but\s+)?)?" r"(?:i|we|my|our)\b", re.I)# ILLNESS is appraised here (appraisal_v1 is frozen at its once-measured version): care first, a pointer to real helpILL = re.compile(r"\bnot feeling (?:too |so |very )?well\b|\bfeel(?:ing)? (?:sick|ill|unwell|awful|dizzy|faint)\b|" r"\bgoing to (?:be sick|throw up|faint)\b|\bi(?:'ve| have) (?:a |the )?(?:fever|flu|cold|headache|" r"toothache|stomach ?ache)\b", re.I)# moves that assert ONLY facts about Oracle7 itself may speak over a withheld decline (they make no claim about the world)SELF_ONLY = {"role", "customer", "remark", "compliment", "self", "identity", "vocative"}FUTURE = re.compile(r"\b(?:will|going to|gonna|next (?:week|month|year)|tomorrow|soon|plan(?:ning)? to|about to)\b", re.I)ACK = {"happiness": "That's lovely to hear!", "sadness": "I'm sorry to hear that.", "anger": "That sounds really frustrating.", "fear": "That sounds worrying.", "surprise": "Really? That's unexpected.", "disgust": "Ugh, that sounds unpleasant."}BACK = {"happiness": "What's the best part of it for you?", "sadness": "Is there anything I can help with?", "anger": "What happened?", "fear": "What's worrying you most about it?", "surprise": "How did that come about?", "disgust": "What happened?"}STOPCAP = {"I", "I'm", "I'll", "I've", "I'd", "We", "My", "Our", "The", "A", "An", "It", "This", "That", "Yes", "No", "Hi", "Hello", "Hey", "Well", "Oh", "So", "And", "But", "Excuse", "Sorry", "Please", "Guess", "You", "Mom", "Dad"}
def native_state(n_passages): """the open end: a state named by its structure, with its measurement""" if n_passages <= 0: return "unbound - it binds to nothing I've read, so it's new to me" if n_passages < 4: return "thinly bound - %d passage%s I've read" % (n_passages, "" if n_passages == 1 else "s") return "resonant - it binds to %d passages I've read" % n_passages
class SelfOrgan: def __init__(self, conv): self.conv = conv # the ConverseOrgan: page_for / ground / definition / topic self.sessions = {} # autobiography: session -> {"turns", "subjects", "feeling"}
# ---- the store, read for the self ------------------------------------------------------------------------------- def bound(self, phrase): """how many passages the store binds this subject to (the resonance count), 0 when it binds to nothing""" try: pid = self.conv.page_for(phrase) return len([s for _, s in self.conv.r.page(pid, 40) if len(s.split()) >= 6]) if pid else 0 except Exception: # noqa: BLE001 return 0
def named_thing(self, t): """the place or thing a disclosure names: a capitalised name first, else the turn's subject""" for m in re.finditer(r"(?<![.!?]\s)(?<!^)\b([A-Z][a-z]+(?:\s[A-Z][a-z]+)?)\b", t): n = m.group(1) if n.split()[0] not in STOPCAP and self.conv.page_for(n): return n try: return self.conv.topic(t) except Exception: # noqa: BLE001 return None
# ---- the self's autobiography ---------------------------------------------------------------------------------- def remember(self, session_id, subject=None, feeling=None): s = self.sessions.setdefault(session_id, {"turns": 0, "subjects": [], "feeling": None}) s["turns"] += 1 if subject and subject not in s["subjects"]: s["subjects"].append(subject) if feeling and feeling != "none": s["feeling"] = feeling return s
# ---- moves ----------------------------------------------------------------------------------------------------- def answer(self, text, session_id="default"): t = " ".join(str(text or "").split()) if not t: return None appr = _appr.appraise(t) if _appr else {"emotion": "none"} mem = self.sessions.setdefault(session_id, {"turns": 1, "subjects": [], "feeling": None}) if appr.get("emotion", "none") != "none": mem["feeling"] = appr["emotion"] for fn in (self._customer, self._vocative, self._role, self._remark, self._compliment, self._self_question, self._disclosure): a = fn(t, appr, mem, session_id) if a: a.setdefault("appraisal", appr.get("emotion")) return a return None
def _say(self, kind, text, cites=None): return {"kind": kind, "response": text, "cites": cites or []}
def _vocative(self, t, appr, mem, sid): m = VOCATIVE.match(t) if not m or m.group("n").split()[0] in NOT_NAMES: return None name = m.group("n") rest = t[m.end():].strip() about = None try: about = self.conv.topic(rest) if rest else None except Exception: # noqa: BLE001 about = None tail = (" If %s is on your mind, I can tell you what my sources say about it." % ( about if about[:1].isupper() else about.lower())) if about else \ " Tell me what you need." return self._say("vocative", "I think you've got me mixed up with %s - I'm %s, %s, so I can't answer for them.%s" % (name, IDENTITY["name"], "an AI", tail))
def _customer(self, t, appr, mem, sid): if not t.rstrip().endswith("?") and not re.search(r"\bready for you\b", t, re.I): return None for rx, line in CUSTOMER: m = re.search(rx, t, re.I) if m: x = (m.groupdict().get("x") or "").strip() if "{x}" in line and not x: continue return self._say("customer", "I'm usually the one helping - I'm %s, an AI - but I'm happy to play the " "customer: %s" % (IDENTITY["name"], line.format(x=x))) return None
def _role(self, t, appr, mem, sid): if t.rstrip().endswith("?") and not DIRECTIVE_SHAPE.search(t): if not re.search(r"\bdo you have (?:any )?\w+ tours?\b", t, re.I): return None if not (DIRECTIVE_SHAPE.search(t) or re.search(r"\bdo you have\b", t, re.I)): return None for role, cue, question in ROLES: if re.search(cue, t, re.I): d = re.search(r"\bto ([A-Z][a-z]+(?:\s[A-Z][a-z]+)?)", t) it = re.search(r"\b(?:see|try on) (that|this|the) (\w+)", t, re.I) q = question.format(dest=(" to %s" % d.group(1)) if d else "", item=(", the %s" % it.group(2)) if it else "") return self._say("role", "Sure - I'll play the %s (I'm %s, an AI, so nothing real gets booked or sold). %s" % (role, IDENTITY["name"], q[0].upper() + q[1:] if q else q)) return None
def _remark(self, t, appr, mem, sid): # a QUESTION with "you/your" is usually the GENERIC you ("is it bad to wash your hair with shower gel?", "can you # drive with a broken arm?" - gate diff 2026-09-28, a false yes). On a question the remark fires only when it is # unmistakably about Oracle7 itself: a bare "do you sleep?", "past your bedtime", "you look ...". question = t.rstrip().endswith("?") or not t.rstrip().endswith("!") and re.match(r"^\s*(?:is|are|can|could|should|would|will|do|does|how|what|why|" r"when|where|which|who)\b", t, re.I) if question and not ADDRESSED_SELF_Q.search(t): return None for rx, cannot in REMARK: if re.search(rx, t, re.I): warm = "That's kind of you, and " if COMPLIMENT.search(t) else "" pivot = {"anger": " If I'm slow or getting something wrong, tell me what you need and I'll get to it.", "happiness": ""}.get(appr.get("emotion"), "") return self._say("remark", "%sI should be honest: I don't %s - I'm %s, %s.%s What's on your mind?" % (warm.capitalize() if warm else "", cannot, IDENTITY["name"], IDENTITY["nature"], pivot)) return None
def _compliment(self, t, appr, mem, sid): if not COMPLIMENT.search(t): return None return self._say("compliment", "Thank you - that's kind of you to say. I'll take it in the way I can: as %s, " "an AI, the compliment lands on the work, not a face. How's your day going?" % IDENTITY["name"])
def _self_question(self, t, appr, mem, sid): if not re.search(r"\byou(?:r|'re)?\b", t, re.I): return None for rx, kind in SELF_Q: if not re.search(rx, t, re.I): continue if kind == "activity": subj = mem["subjects"][-1] if mem["subjects"] else None now = ("reading what you write - this is turn %d of our conversation" % mem["turns"]) extra = (" The last subject you brought was %s, and it's %s." % (subj, native_state(self.bound(subj)))) \ if subj else "" return self._say("self", "Right now I'm %s.%s Between conversations my self-loop re-checks my own " "answers against tests I can't change." % (now, extra)) if kind == "state": subj = mem["subjects"][-1] if mem["subjects"] else None if subj: return self._say("self", "In my own terms: I'm holding %s, and it's %s. If there's a human word for " "that, it's something like attention." % (subj, native_state(self.bound(subj)))) return self._say("self", "In my own terms: nothing is bound yet in this conversation - I'm open, waiting " "for a subject to resonate with. Give me one and I'll tell you how it binds.") if kind == "stance": return self._say("self", "I aim to be even-handed. On contested political questions I report what the " "record says on each side, with sources, and I don't take a party position. %s. Give me " "a question and I'll lay out the sides." % IDENTITY["values"][0].capitalize()) if kind == "identity": # its own kind: the chain already answers "Who are you?" (act:about, on the gate's regression list), and an # identity answer never replaces it - only measured-state answers ('self') do (gate REJECT 2026-09-28) return self._say("identity", "I'm %s, %s, made by %s. I don't have a body or a childhood; I have stores I " "read from, organs that reason, and a gate that decides what I become. What I value: %s. " "Ask me anything." % (IDENTITY["name"], IDENTITY["nature"], IDENTITY["maker"], "; ".join(IDENTITY["values"]))) return None
def _disclosure(self, t, appr, mem, sid): if t.rstrip().endswith("?") or not FIRST_PERSON_NEWS.match(t): return None emo = appr.get("emotion", "none") if ILL.search(t): return self._say("care", "I'm sorry you're feeling unwell. If it's getting worse, or you're worried, please " "contact a doctor or your local health service - and in an emergency, your emergency number. " "Would it help to sit down and have some water while you tell me what's going on?") thing = self.named_thing(t) if thing and thing not in mem["subjects"]: mem["subjects"].append(thing) ack = ACK.get(emo) or ("That sounds good!" if FUTURE.search(t) else "Thanks for telling me.") back = BACK.get(emo) or ("What are you most looking forward to?" if FUTURE.search(t) else "How do you feel about it?") fact = "" if thing: try: g = self.conv.ground(thing, 1) except Exception: # noqa: BLE001 g = None if g: fact = " On %s, my sources say: %s" % (thing, g) if not fact and emo == "none": return None # nothing grounded and nothing felt: no self-move worth making return self._say("disclosure", "%s%s %s" % (ack, fact, back))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171#!/usr/bin/env python3"""path_memory_v1 - Oracle7's PATH MEMORY for routing: which route has EARNED trust for which shape of question, creditedonly by VERIFIED outcomes (a held-out or dev exam's grade against its gold), stored in the substrate's own algebra.
A PATH is one vector: P = bind(R_wh, osub(wh)) + bind(R_rel, osub(rel)) + bind(R_num, osub(num)) + bind(R_route, osub(route)) wh - the question's lead (who / what / where / when / which / how many / how much / name / other) rel - the relation reader that recognises the question (relation_readers_v1 key), or "none" num - whether the question carries numbers route - the normalised route that answered ("organ:relation", "deliberation:where", "compose:bridge", "specialist:rel", ...)Codebook: osub_seed (sha256-seeded unit phasors, D=1024), the construction path_hrr_v1 validated (4-hop recovery 100%).Each stored path carries counts (right, wrong) - credit up for a verified right answer, down for a verified wrong one ora false yes. RECALL: the exact path when stored; otherwise the most RESONANT stored path with the same route (partial cue:an unseen relation or lead borrows the credit of its nearest neighbour), and only above a resonance floor.The memory never produces an answer. It only says how far a route's answer to this shape can be trusted.build: path_memory_v1.py build <credit .jsonl ...> <out.json>"""from __future__ import annotations
import hashlibimport jsonimport reimport sys
import numpy as np
D = 1024LEADS = (("how many", "howmany"), ("how much", "howmuch"), ("who", "who"), ("whom", "who"), ("whose", "who"), ("where", "where"), ("when", "when"), ("which", "which"), ("what", "what"), ("in what", "what"), ("in which", "which"), ("name", "name"), ("tell me", "name"), ("the ", "the"))
def osub_seed(text: str, dim: int = D) -> np.ndarray: h = int(hashlib.sha256(text.lower().strip().encode()).hexdigest(), 16) rng = np.random.RandomState(h % (2 ** 31)) return np.exp(1j * rng.uniform(0, 2 * np.pi, dim)).astype(np.complex64)
def bind(a, b): return np.fft.ifft(np.fft.fft(a) * np.fft.fft(b)).astype(np.complex64)
ROLES = {r: osub_seed("o7pm-role:" + r) for r in ("wh", "rel", "num", "route")}
def lead(q): t = " ".join(str(q).lower().split()) for a, b in LEADS: if t.startswith(a): return b return "other"
_READERS = None
def relation_key(q): """the relation reader that recognises the question (the readers' own compiled phrasings), else 'none'""" global _READERS try: import relation_readers_v1 as RD import relation_spec_v2 as S except Exception: # noqa: BLE001 return "none" if _READERS is None: _READERS = [(k, S.compiled(k)) for k in RD.PROPS] s, low = S.normalise(q) for k, comp in _READERS: for d in ("fwd", "inv"): if any(rx.match(low) for rx in comp[d]): return str(k) return "none"
def route_of(path): p = str(path or "") p = re.sub(r"^(?:chat:resolved>|chat:and_parts>[^>]*>|specialist_precedence>)+", "", p) if p.startswith("specialist_call>"): m = re.search(r"specialist:([a-z0-9-]+)", p) sid = m.group(1) if m else "x" return "specialist:rel" if sid.startswith("rel-") else "specialist:" + re.sub(r"-(v\d+|r\d+)$", "", sid) if p.startswith("precision_guard:"): return "guard" return re.split(r"[>|]", p, 1)[0] or "none"
def shape(q): return {"wh": lead(q), "rel": relation_key(q), "num": "1" if re.search(r"\d", q) else "0"}
def path_vec(sh, route): v = sum(bind(ROLES[r], osub_seed("o7pm:%s:%s" % (r, sh[r]))) for r in ("wh", "rel", "num")) v = v + bind(ROLES["route"], osub_seed("o7pm:route:" + route)) return (v / np.maximum(np.abs(v), 1e-8)).astype(np.complex64)
def key(sh, route): return "%s|%s|%s|%s" % (sh["wh"], sh["rel"], sh["num"], route)
class PathMemory: def __init__(self, entries=None): self.entries = entries or {} # key -> {"shape": {...}, "route": r, "right": n, "wrong": n} self._vec = {}
def credit(self, sh, route, outcome): k = key(sh, route) e = self.entries.setdefault(k, {"shape": dict(sh), "route": route, "right": 0, "wrong": 0}) e["right" if outcome == "right" else "wrong"] += 1
def _v(self, k): if k not in self._vec: e = self.entries[k] self._vec[k] = path_vec(e["shape"], e["route"]) return self._vec[k]
def recall(self, sh, route, floor=0.45): """-> (right, wrong, resonance, key used) for this path; exact if stored, else the most resonant stored path with the same route above the floor, else None""" k = key(sh, route) if k in self.entries: e = self.entries[k] return e["right"], e["wrong"], 1.0, k q = path_vec(sh, route) best, arg = -1.0, None for kk, e in self.entries.items(): if e["route"] != route: continue r = float(np.real(np.vdot(self._v(kk), q)) / D) if r > best: best, arg = r, kk if arg is None or best < floor: return None e = self.entries[arg] return e["right"], e["wrong"], best, arg
def precision(self, sh, route, prior=(1, 1), min_n=6): r = self.recall(sh, route) if r is None or r[0] + r[1] < min_n: return None return (r[0] + prior[0]) / (r[0] + r[1] + prior[0] + prior[1]), r[0] + r[1]
def save(self, path): json.dump({"D": D, "entries": self.entries}, open(path, "w"), indent=0)
@classmethod def load(cls, path): return cls(json.load(open(path))["entries"])
def build(files, out): pm = PathMemory() n = 0 for f in files: for line in open(f): r = json.loads(line) sh = shape(r["q"]) for arm in ("head", "family"): x = r.get(arm) if not x or x.get("status") != "answered" or x.get("grade") not in ("right", "wrong"): continue pm.credit(sh, route_of(x["path"]), x["grade"]) n += 1 pm.save(out) return pm, n
if __name__ == "__main__": sys.path.insert(0, __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/wander-train") # the runtime's relation readers - the shape must match the runtime's import relation_readers_v1 # noqa: F401,E402 - fail loudly: a memory built without relation keys is a different memory if sys.argv[1] == "build": pm, n = build(sys.argv[2:-1], sys.argv[-1]) print("credited outcomes", n, "paths", len(pm.entries))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"AtomicNumber","Symbol","Name","AtomicMass","CPKHexColor","ElectronConfiguration","Electronegativity","AtomicRadius","IonizationEnergy","ElectronAffinity","OxidationStates","StandardState","MeltingPoint","BoilingPoint","Density","GroupBlock","YearDiscovered"1,"H","Hydrogen",1.0080,"FFFFFF","1s1",2.2,120,13.598,0.754,"+1, -1","Gas",13.81,20.28,0.00008988,"Nonmetal",17662,"He","Helium",4.00260,"D9FFFF","1s2","",140,24.587,"","0","Gas",0.95,4.22,0.0001785,"Noble gas",18683,"Li","Lithium",7.0,"CC80FF","[He]2s1",0.98,182,5.392,0.618,"+1","Solid",453.65,1615,0.534,"Alkali metal",18174,"Be","Beryllium",9.012183,"C2FF00","[He]2s2",1.57,153,9.323,"","+2","Solid",1560,2744,1.85,"Alkaline earth metal",17985,"B","Boron",10.81,"FFB5B5","[He]2s2 2p1",2.04,192,8.298,0.277,"+3","Solid",2348,4273,2.37,"Metalloid",18086,"C","Carbon",12.011,"909090","[He]2s2 2p2",2.55,170,11.260,1.263,"+4, +2, -4","Solid",3823,4098,2.2670,"Nonmetal","Ancient"7,"N","Nitrogen",14.007,"3050F8","[He] 2s2 2p3",3.04,155,14.534,"","+5, +4, +3, +2, +1, -1, -2, -3","Gas",63.15,77.36,0.0012506,"Nonmetal",17728,"O","Oxygen",15.999,"FF0D0D","[He]2s2 2p4",3.44,152,13.618,1.461,"-2","Gas",54.36,90.2,0.001429,"Nonmetal",17749,"F","Fluorine",18.99840316,"90E050","[He]2s2 2p5",3.98,135,17.423,3.339,"-1","Gas",53.53,85.03,0.001696,"Halogen",167010,"Ne","Neon",20.180,"B3E3F5","[He]2s2 2p6","",154,21.565,"","0","Gas",24.56,27.07,0.0008999,"Noble gas",189811,"Na","Sodium",22.9897693,"AB5CF2","[Ne]3s1",0.93,227,5.139,0.548,"+1","Solid",370.95,1156,0.97,"Alkali metal",180712,"Mg","Magnesium",24.305,"8AFF00","[Ne]3s2",1.31,173,7.646,"","+2","Solid",923,1363,1.74,"Alkaline earth metal",180813,"Al","Aluminum",26.981538,"BFA6A6","[Ne]3s2 3p1",1.61,184,5.986,0.441,"+3","Solid",933.437,2792,2.70,"Post-transition metal","Ancient"14,"Si","Silicon",28.085,"F0C8A0","[Ne]3s2 3p2",1.9,210,8.152,1.385,"+4, +2, -4","Solid",1687,3538,2.3296,"Metalloid",185415,"P","Phosphorus",30.97376200,"FF8000","[Ne]3s2 3p3",2.19,180,10.487,0.746,"+5, +3, -3","Solid",317.3,553.65,1.82,"Nonmetal",166916,"S","Sulfur",32.07,"FFFF30","[Ne]3s2 3p4",2.58,180,10.360,2.077,"+6, +4, -2","Solid",388.36,717.75,2.067,"Nonmetal","Ancient"17,"Cl","Chlorine",35.45,"1FF01F","[Ne]3s2 3p5",3.16,175,12.968,3.617,"+7, +5, +1, -1","Gas",171.65,239.11,0.003214,"Halogen",177418,"Ar","Argon",39.9,"80D1E3","[Ne]3s2 3p6","",188,15.760,"","0","Gas",83.8,87.3,0.0017837,"Noble gas",189419,"K","Potassium",39.0983,"8F40D4","[Ar]4s1",0.82,275,4.341,0.501,"+1","Solid",336.53,1032,0.89,"Alkali metal",180720,"Ca","Calcium",40.08,"3DFF00","[Ar]4s2",1,231,6.113,"","+2","Solid",1115,1757,1.54,"Alkaline earth metal","Ancient"21,"Sc","Scandium",44.95591,"E6E6E6","[Ar]4s2 3d1",1.36,211,6.561,0.188,"+3","Solid",1814,3109,2.99,"Transition metal",187922,"Ti","Titanium",47.867,"BFC2C7","[Ar]4s2 3d2",1.54,187,6.828,0.079,"+4, +3, +2","Solid",1941,3560,4.5,"Transition metal",179123,"V","Vanadium",50.9415,"A6A6AB","[Ar]4s2 3d3",1.63,179,6.746,0.525,"+5, +4, +3, +2","Solid",2183,3680,6.0,"Transition metal",180124,"Cr","Chromium",51.996,"8A99C7","[Ar]3d5 4s1",1.66,189,6.767,0.666,"+6, +3, +2","Solid",2180,2944,7.15,"Transition metal",179725,"Mn","Manganese",54.93804,"9C7AC7","[Ar]4s2 3d5",1.55,197,7.434,"","+7, +4, +3, +2","Solid",1519,2334,7.3,"Transition metal",177426,"Fe","Iron",55.84,"E06633","[Ar]4s2 3d6",1.83,194,7.902,0.163,"+3, +2","Solid",1811,3134,7.874,"Transition metal","Ancient"27,"Co","Cobalt",58.93319,"F090A0","[Ar]4s2 3d7",1.88,192,7.881,0.661,"+3, +2","Solid",1768,3200,8.86,"Transition metal",173528,"Ni","Nickel",58.693,"50D050","[Ar]4s2 3d8",1.91,163,7.640,1.156,"+3, +2","Solid",1728,3186,8.912,"Transition metal",175129,"Cu","Copper",63.55,"C88033","[Ar]4s1 3d10",1.9,140,7.726,1.228,"+2, +1","Solid",1357.77,2835,8.933,"Transition metal","Ancient"30,"Zn","Zinc",65.4,"7D80B0","[Ar]4s2 3d10",1.65,139,9.394,"","+2","Solid",692.68,1180,7.134,"Transition metal",174631,"Ga","Gallium",69.723,"C28F8F","[Ar]4s2 3d10 4p1",1.81,187,5.999,0.3,"+3","Solid",302.91,2477,5.91,"Post-transition metal",187532,"Ge","Germanium",72.63,"668F8F","[Ar]4s2 3d10 4p2",2.01,211,7.900,1.35,"+4, +2","Solid",1211.4,3106,5.323,"Metalloid",188633,"As","Arsenic",74.92159,"BD80E3","[Ar]4s2 3d10 4p3",2.18,185,9.815,0.81,"+5, +3, -3","Solid",1090,887,5.776,"Metalloid","Ancient"34,"Se","Selenium",78.97,"FFA100","[Ar]4s2 3d10 4p4",2.55,190,9.752,2.021,"+6, +4, -2","Solid",493.65,958,4.809,"Nonmetal",181735,"Br","Bromine",79.90,"A62929","[Ar]4s2 3d10 4p5",2.96,183,11.814,3.365,"+5, +1, -1","Liquid",265.95,331.95,3.11,"Halogen",182636,"Kr","Krypton",83.80,"5CB8D1","[Ar]4s2 3d10 4p6",3,202,14.000,"","0","Gas",115.79,119.93,0.003733,"Noble gas",189837,"Rb","Rubidium",85.468,"702EB0","[Kr]5s1",0.82,303,4.177,0.468,"+1","Solid",312.46,961,1.53,"Alkali metal",186138,"Sr","Strontium",87.62,"00FF00","[Kr]5s2",0.95,249,5.695,"","+2","Solid",1050,1655,2.64,"Alkaline earth metal",179039,"Y","Yttrium",88.90584,"94FFFF","[Kr]5s2 4d1",1.22,219,6.217,0.307,"+3","Solid",1795,3618,4.47,"Transition metal",179440,"Zr","Zirconium",91.22,"94E0E0","[Kr]5s2 4d2",1.33,186,6.634,0.426,"+4","Solid",2128,4682,6.52,"Transition metal",178941,"Nb","Niobium",92.90637,"73C2C9","[Kr]5s1 4d4",1.6,207,6.759,0.893,"+5, +3","Solid",2750,5017,8.57,"Transition metal",180142,"Mo","Molybdenum",95.95,"54B5B5","[Kr]5s1 4d5",2.16,209,7.092,0.746,"+6","Solid",2896,4912,10.2,"Transition metal",177843,"Tc","Technetium",96.90636,"3B9E9E","[Kr]5s2 4d5",1.9,209,7.28,0.55,"+7, +6, +4","Solid",2430,4538,11,"Transition metal",193744,"Ru","Ruthenium",101.1,"248F8F","[Kr]5s1 4d7",2.2,207,7.361,1.05,"+3","Solid",2607,4423,12.1,"Transition metal",182745,"Rh","Rhodium",102.9055,"0A7D8C","[Kr]5s1 4d8",2.28,195,7.459,1.137,"+3","Solid",2237,3968,12.4,"Transition metal",180346,"Pd","Palladium",106.42,"6985","[Kr]4d10",2.2,202,8.337,0.557,"+3, +2","Solid",1828.05,3236,12.0,"Transition metal",180347,"Ag","Silver",107.868,"C0C0C0","[Kr]5s1 4d10",1.93,172,7.576,1.302,"+1","Solid",1234.93,2435,10.501,"Transition metal","Ancient"48,"Cd","Cadmium",112.41,"FFD98F","[Kr]5s2 4d10",1.69,158,8.994,"","+2","Solid",594.22,1040,8.69,"Transition metal",181749,"In","Indium",114.818,"A67573","[Kr]5s2 4d10 5p1",1.78,193,5.786,0.3,"+3","Solid",429.75,2345,7.31,"Post-transition metal",186350,"Sn","Tin",118.71,"668080","[Kr]5s2 4d10 5p2",1.96,217,7.344,1.2,"+4, +2","Solid",505.08,2875,7.287,"Post-transition metal","Ancient"51,"Sb","Antimony",121.760,"9E63B5","[Kr]5s2 4d10 5p3",2.05,206,8.64,1.07,"+5, +3, -3","Solid",903.78,1860,6.685,"Metalloid","Ancient"52,"Te","Tellurium",127.6,"D47A00","[Kr]5s2 4d10 5p4",2.1,206,9.010,1.971,"+6, +4, -2","Solid",722.66,1261,6.232,"Metalloid",178253,"I","Iodine",126.9045,"940094","[Kr]5s2 4d10 5p5",2.66,198,10.451,3.059,"+7, +5, +1, -1","Solid",386.85,457.55,4.93,"Halogen",181154,"Xe","Xenon",131.29,"429EB0","[Kr]5s2 4d10 5p6",2.6,216,12.130,"","0","Gas",161.36,165.03,0.005887,"Noble gas",189855,"Cs","Cesium",132.9054520,"57178F","[Xe]6s1",0.79,343,3.894,0.472,"+1","Solid",301.59,944,1.93,"Alkali metal",186056,"Ba","Barium",137.33,"00C900","[Xe]6s2",0.89,268,5.212,"","+2","Solid",1000,2170,3.62,"Alkaline earth metal",180857,"La","Lanthanum",138.9055,"70D4FF","[Xe]6s2 5d1",1.1,240,5.577,0.5,"+3","Solid",1191,3737,6.15,"Lanthanide",183958,"Ce","Cerium",140.116,"FFFFC7","[Xe]6s2 4f1 5d1",1.12,235,5.539,0.5,"+4, +3","Solid",1071,3697,6.770,"Lanthanide",180359,"Pr","Praseodymium",140.90766,"D9FFC7","[Xe]6s2 4f3",1.13,239,5.464,"","+3","Solid",1204,3793,6.77,"Lanthanide",188560,"Nd","Neodymium",144.24,"C7FFC7","[Xe]6s2 4f4",1.14,229,5.525,"","+3","Solid",1294,3347,7.01,"Lanthanide",188561,"Pm","Promethium",144.91276,"A3FFC7","[Xe]6s2 4f5","",236,5.55,"","+3","Solid",1315,3273,7.26,"Lanthanide",194562,"Sm","Samarium",150.4,"8FFFC7","[Xe]6s2 4f6",1.17,229,5.644,"","+3, +2","Solid",1347,2067,7.52,"Lanthanide",187963,"Eu","Europium",151.964,"61FFC7","[Xe]6s2 4f7","",233,5.670,"","+3, +2","Solid",1095,1802,5.24,"Lanthanide",190164,"Gd","Gadolinium",157.25,"45FFC7","[Xe]6s2 4f7 5d1",1.2,237,6.150,"","+3","Solid",1586,3546,7.90,"Lanthanide",188065,"Tb","Terbium",158.92535,"30FFC7","[Xe]6s2 4f9","",221,5.864,"","+3","Solid",1629,3503,8.23,"Lanthanide",184366,"Dy","Dysprosium",162.500,"1FFFC7","[Xe]6s2 4f10",1.22,229,5.939,"","+3","Solid",1685,2840,8.55,"Lanthanide",188667,"Ho","Holmium",164.93033,"00FF9C","[Xe]6s2 4f11",1.23,216,6.022,"","+3","Solid",1747,2973,8.80,"Lanthanide",187868,"Er","Erbium",167.26,"","[Xe]6s2 4f12",1.24,235,6.108,"","+3","Solid",1802,3141,9.07,"Lanthanide",184369,"Tm","Thulium",168.93422,"00D452","[Xe]6s2 4f13",1.25,227,6.184,"","+3","Solid",1818,2223,9.32,"Lanthanide",187970,"Yb","Ytterbium",173.05,"00BF38","[Xe]6s2 4f14","",242,6.254,"","+3, +2","Solid",1092,1469,6.90,"Lanthanide",187871,"Lu","Lutetium",174.9667,"00AB24","[Xe]6s2 4f14 5d1",1.27,221,5.426,"","+3","Solid",1936,3675,9.84,"Lanthanide",190772,"Hf","Hafnium",178.49,"4DC2FF","[Xe]6s2 4f14 5d2",1.3,212,6.825,"","+4","Solid",2506,4876,13.3,"Transition metal",192373,"Ta","Tantalum",180.9479,"4DA6FF","[Xe]6s2 4f14 5d3",1.5,217,7.89,0.322,"+5","Solid",3290,5731,16.4,"Transition metal",180274,"W","Tungsten",183.84,"2194D6","[Xe]6s2 4f14 5d4",2.36,210,7.98,0.815,"+6","Solid",3695,5828,19.3,"Transition metal",178375,"Re","Rhenium",186.207,"267DAB","[Xe]6s2 4f14 5d5",1.9,217,7.88,0.15,"+7, +6, +4","Solid",3459,5869,20.8,"Transition metal",192576,"Os","Osmium",190.2,"266696","[Xe]6s2 4f14 5d6",2.2,216,8.7,1.1,"+4, +3","Solid",3306,5285,22.57,"Transition metal",180377,"Ir","Iridium",192.22,"175487","[Xe]6s2 4f14 5d7",2.2,202,9.1,1.565,"+4, +3","Solid",2719,4701,22.42,"Transition metal",180378,"Pt","Platinum",195.08,"D0D0E0","[Xe]6s1 4f14 5d9",2.28,209,9,2.128,"+4, +2","Solid",2041.55,4098,21.46,"Transition metal",173579,"Au","Gold",196.96657,"FFD123","[Xe]6s1 4f14 5d10",2.54,166,9.226,2.309,"+3, +1","Solid",1337.33,3129,19.282,"Transition metal","Ancient"80,"Hg","Mercury",200.59,"B8B8D0","[Xe]6s2 4f14 5d10",2,209,10.438,"","+2, +1","Liquid",234.32,629.88,13.5336,"Transition metal","Ancient"81,"Tl","Thallium",204.383,"A6544D","[Xe]6s2 4f14 5d10 6p1",1.62,196,6.108,0.2,"+3, +1","Solid",577,1746,11.8,"Post-transition metal",186182,"Pb","Lead",207,"575961","[Xe]6s2 4f14 5d10 6p2",2.33,202,7.417,0.36,"+4, +2","Solid",600.61,2022,11.342,"Post-transition metal","Ancient"83,"Bi","Bismuth",208.98040,"9E4FB5","[Xe]6s2 4f14 5d10 6p3",2.02,207,7.289,0.946,"+5, +3","Solid",544.55,1837,9.807,"Post-transition metal",175384,"Po","Polonium",208.98243,"AB5C00","[Xe]6s2 4f14 5d10 6p4",2,197,8.417,1.9,"+4, +2","Solid",527,1235,9.32,"Metalloid",189885,"At","Astatine",209.98715,"754F45","[Xe]6s2 4f14 5d10 6p5",2.2,202,9.5,2.8,"7, 5, 3, 1, -1","Solid",575,"",7,"Halogen",194086,"Rn","Radon",222.01758,"428296","[Xe]6s2 4f14 5d10 6p6","",220,10.745,"","0","Gas",202,211.45,0.00973,"Noble gas",190087,"Fr","Francium",223.01973,"420066","[Rn]7s1",0.7,348,3.9,0.47,"+1","Solid",300,"","","Alkali metal",193988,"Ra","Radium",226.02541,"007D00","[Rn]7s2",0.9,283,5.279,"","+2","Solid",973,1413,5,"Alkaline earth metal",189889,"Ac","Actinium",227.02775,"70ABFA","[Rn]7s2 6d1",1.1,260,5.17,"","+3","Solid",1324,3471,10.07,"Actinide",189990,"Th","Thorium",232.038,"00BAFF","[Rn]7s2 6d2",1.3,237,6.08,"","+4","Solid",2023,5061,11.72,"Actinide",182891,"Pa","Protactinium",231.03588,"00A1FF","[Rn]7s2 5f2 6d1",1.5,243,5.89,"","+5, +4","Solid",1845,"",15.37,"Actinide",191392,"U","Uranium",238.0289,"008FFF","[Rn]7s2 5f3 6d1",1.38,240,6.194,"","+6, +5, +4, +3","Solid",1408,4404,18.95,"Actinide",178993,"Np","Neptunium",237.048172,"0080FF","[Rn]7s2 5f4 6d1",1.36,221,6.266,"","+6, +5, +4, +3","Solid",917,4175,20.25,"Actinide",194094,"Pu","Plutonium",244.06420,"006BFF","[Rn]7s2 5f6",1.28,243,6.06,"","+6, +5, +4, +3","Solid",913,3501,19.84,"Actinide",194095,"Am","Americium",243.061380,"545CF2","[Rn]7s2 5f7",1.3,244,5.993,"","+6, +5, +4, +3","Solid",1449,2284,13.69,"Actinide",194496,"Cm","Curium",247.07035,"785CE3","[Rn]7s2 5f7 6d1",1.3,245,6.02,"","+3","Solid",1618,3400,13.51,"Actinide",194497,"Bk","Berkelium",247.07031,"8A4FE3","[Rn]7s2 5f9",1.3,244,6.23,"","+4, +3","Solid",1323,"",14,"Actinide",194998,"Cf","Californium",251.07959,"A136D4","[Rn]7s2 5f10",1.3,245,6.30,"","+3","Solid",1173,"","","Actinide",195099,"Es","Einsteinium",252.0830,"B31FD4","[Rn]7s2 5f11",1.3,245,6.42,"","+3","Solid",1133,"","","Actinide",1952100,"Fm","Fermium",257.09511,"B31FBA","[Rn] 5f12 7s2",1.3,"",6.50,"","+3","Solid",1800,"","","Actinide",1952101,"Md","Mendelevium",258.09843,"B30DA6","[Rn]7s2 5f13",1.3,"",6.58,"","+3, +2","Solid",1100,"","","Actinide",1955102,"No","Nobelium",259.10100,"BD0D87","[Rn]7s2 5f14",1.3,"",6.65,"","+3, +2","Solid",1100,"","","Actinide",1957103,"Lr","Lawrencium",266.120,"C70066","[Rn]7s2 5f14 6d1",1.3,"","","","+3","Solid",1900,"","","Actinide",1961104,"Rf","Rutherfordium",267.122,"CC0059","[Rn]7s2 5f14 6d2","","","","","+4","Solid","","","","Transition metal",1964105,"Db","Dubnium",268.126,"D1004F","[Rn]7s2 5f14 6d3","","","","","5, 4, 3","Solid","","","","Transition metal",1967106,"Sg","Seaborgium",269.128,"D90045","[Rn]7s2 5f14 6d4","","","","","6, 5, 4, 3, 0","Solid","","","","Transition metal",1974107,"Bh","Bohrium",270.133,"E00038","[Rn]7s2 5f14 6d5","","","","","7, 5, 4, 3","Solid","","","","Transition metal",1976108,"Hs","Hassium",269.1336,"E6002E","[Rn]7s2 5f14 6d6","","","","","8, 6, 5, 4, 3, 2","Solid","","","","Transition metal",1984109,"Mt","Meitnerium",277.154,"EB0026","[Rn]7s2 5f14 6d7 (calculated)","","","","","9, 8, 6, 4, 3, 1","Solid","","","","Transition metal",1982110,"Ds","Darmstadtium",282.166,"","[Rn]7s2 5f14 6d8 (predicted)","","","","","8, 6, 4, 2, 0","Expected to be a Solid","","","","Transition metal",1994111,"Rg","Roentgenium",282.169,"","[Rn]7s2 5f14 6d9 (predicted)","","","","","5, 3, 1, -1","Expected to be a Solid","","","","Transition metal",1994112,"Cn","Copernicium",286.179,"","[Rn]7s2 5f14 6d10 (predicted)","","","","","2, 1, 0","Expected to be a Solid","","","","Transition metal",1996113,"Nh","Nihonium",286.182,"","[Rn]5f14 6d10 7s2 7p1 (predicted)","","","","","","Expected to be a Solid","","","","Post-transition metal",2004114,"Fl","Flerovium",290.192,"","[Rn]7s2 7p2 5f14 6d10 (predicted)","","","","","6, 4,2, 1, 0","Expected to be a Solid","","","","Post-transition metal",1998115,"Mc","Moscovium",290.196,"","[Rn]7s2 7p3 5f14 6d10 (predicted)","","","","","3, 1","Expected to be a Solid","","","","Post-transition metal",2003116,"Lv","Livermorium",293.205,"","[Rn]7s2 7p4 5f14 6d10 (predicted)","","","","","+4, +2, -2","Expected to be a Solid","","","","Post-transition metal",2000117,"Ts","Tennessine",294.211,"","[Rn]7s2 7p5 5f14 6d10 (predicted)","","","","","+5, +3, +1, -1","Expected to be a Solid","","","","Halogen",2010118,"Og","Oganesson",295.216,"","[Rn]7s2 7p6 5f14 6d10 (predicted)","","","","","+6, +4, +2, +1, 0, -1","Expected to be a Gas","","","","Noble gas",2006123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""relation_forms_v2 = v1 + forms for more store properties (see make_relation_forms_v2.py).relation_forms_v1 - question FORMS that name their relation, answered through the typed relation store.
"Where is the Colosseum?", "Who discovered penicillin?", "When was the Eiffel Tower built?" carry no relation words themined lexicon can match, so the three-tree runtime found no relation and declined. The form itself names the relation,in Wikidata's own vocabulary. Each form lists its properties in order of SPECIFICITY and they are tried ONE AT A TIME(oracle_tritree_v2 only=True), because located-in (Rome) and country (Italy) are both true of the Colosseum and a jointsearch would see two answers and abstain. Every check of the runtime still applies: answer type, one value, thecorroborating sentence from the subject's own article (rule A), the verb licence for dates (rule B).answer(tt, q) -> (runtime answer, form name) | (None, None)"""from __future__ import annotations
import re
FORMS = [ # v2 (2026-10-03): forms for more of the store's properties, most specific first ("screenwriter", re.compile(r"\bwho\s+wrote\s+the\s+(?:screenplay|script)\b", re.I), [58]), ("country", re.compile(r"\b(?:in\s+)?(?:which|what)\s+country\s+(?:is|are|was|were)\b(?!.*\b(?:born|from)\b)|" r"\b(?:is|are)\s+(?:in|located\s+in)\s+(?:which|what)\s+country\b", re.I), [17]), ("continent", re.compile(r"\b(?:on|in)\s+(?:which|what)\s+continent\b|\b(?:which|what)\s+continent\s+(?:is|are)\b", re.I), [30]), ("creator", re.compile(r"\bwho\s+(?:painted|sculpted|drew|carved)\b", re.I), [170]), ("performer", re.compile(r"\bwho\s+(?:sang|sings|performed|recorded)\b|\b(?:which|what)\s+(?:band|singer|group|rapper)\s+" r"(?:released|recorded|sang|performed)\b", re.I), [175]), ("producer", re.compile(r"\bwho\s+produced\b", re.I), [162]), ("author_of", re.compile(r"\bwho\s+(?:is|was)\s+the\s+author\s+of\b", re.I), [50]), ("spouse", re.compile(r"\bwho\s+(?:is|was)\s+.+?\s+married\s+to\b|\bwho\s+did\s+.+?\s+marry\b|" r"\b(?:wife|husband|spouse)\s+of\b", re.I), [26]), ("father", re.compile(r"\bwho\s+(?:is|was)\s+(?:the\s+)?father\s+of\b", re.I), [22]), ("mother", re.compile(r"\bwho\s+(?:is|was)\s+(?:the\s+)?mother\s+of\b", re.I), [25]), ("deathplace", re.compile(r"\bwhere\s+did\s+.+?\s+die\b", re.I), [20]), ("nationality", re.compile(r"\bnationality\s+of\b|\bwhat\s+(?:is|was)\s+.+?(?:'s)?\s+nationality\b", re.I), [27]), ("instrument", re.compile(r"\bwhat\s+instrument\s+(?:does|did)\b", re.I), [1303]), ("sport", re.compile(r"\bwhat\s+sport\s+(?:does|did)\b", re.I), [641]), ("headquarters", re.compile(r"\bheadquarter(?:s|ed)\b", re.I), [159]), ("named_after", re.compile(r"\bnamed\s+after\s+(?:who|whom|what)\b|\bwho\s+(?:is|was)\s+.+?\s+named\s+after\b", re.I), [138]), ("published", re.compile(r"\bwhen\s+was\s+.+?\s+(?:published|released)\b", re.I), [577]), ("where", re.compile(r"^\s*where\s+(?:is|are|was|were|does|do)\b", re.I), [131, 276, 17, 30]), ("discoverer", re.compile(r"\bwho\s+(?:first\s+)?(?:discovered|invented)\b", re.I), [61]), ("architect", re.compile(r"\bwho\s+designed\b", re.I), [84, 170]), # "built" is not "designed" ("founder", re.compile(r"\bwho\s+founded\b", re.I), [112]), ("author", re.compile(r"\bwho\s+(?:wrote|authored)\b", re.I), [50]), ("director", re.compile(r"\bwho\s+directed\b", re.I), [57]), ("composer", re.compile(r"\bwho\s+composed\b", re.I), [86]), ("inception", re.compile(r"\bwhen\s+(?:was|were|did)\b.*\b(?:built|founded|established|completed|opened|created|formed)\b", re.I), [571]), ("capital", re.compile(r"\bcapital\s+(?:city\s+)?of\b", re.I), [36]), ("language", re.compile(r"\bwhat\s+(?:language|languages)\s+(?:is|are|do)\b.*\bspoken\b|\bofficial\s+language\s+of\b", re.I), [37]), ("currency", re.compile(r"\bcurrency\s+(?:of|in|does)\b", re.I), [38]), ("birth", re.compile(r"\bwhen\s+was\s+.+?\s+born\b", re.I), [569]), ("birthplace", re.compile(r"\bwhere\s+was\s+.+?\s+born\b", re.I), [19]), ("death", re.compile(r"\bwhen\s+did\s+.+?\s+die\b", re.I), [570]),]
def form_of(q): # a more specific form wins over the generic "where" (where was X born -> birthplace) hits = [(name, props) for name, rx, props in FORMS if rx.search(q or "")] if not hits: return None specific = [h for h in hits if h[0] != "where"] return (specific or hits)[0]
ARG = { # where each form's ARGUMENT (the entity asked about) sits "where": r"^\s*where\s+(?:is|are|was|were|does|do)\s+(?:the\s+)?(?P<x>.+?)(?:\s+(?:located|from|situated|found|live|lives|based))?\s*\??$", "discoverer": r"\b(?:discovered|invented)\s+(?:the\s+)?(?P<x>.+?)\s*\??$", "architect": r"\bdesigned\s+(?:the\s+)?(?P<x>.+?)\s*\??$", "founder": r"\bfounded\s+(?:the\s+)?(?P<x>.+?)\s*\??$", "author": r"\b(?:wrote|authored)\s+(?:the\s+)?(?P<x>.+?)\s*\??$", "director": r"\bdirected\s+(?:the\s+)?(?P<x>.+?)\s*\??$", "composer": r"\bcomposed\s+(?:the\s+)?(?P<x>.+?)\s*\??$", "inception": r"\bwhen\s+(?:was|were|did)\s+(?:the\s+)?(?P<x>.+?)\s+(?:built|founded|established|completed|opened|created|formed)\b", "capital": r"\bcapital\s+(?:city\s+)?of\s+(?:the\s+)?(?P<x>.+?)\s*\??$", "language": r"\b(?:spoken\s+in|language\s+of|in)\s+(?:the\s+)?(?P<x>[^?]+?)\s*\??$", "currency": r"\bcurrency\s+(?:of|in|does)\s+(?:the\s+)?(?P<x>.+?)(?:\s+use)?\s*\??$", "birth": r"\bwhen\s+was\s+(?P<x>.+?)\s+born\b", "birthplace": r"\bwhere\s+was\s+(?P<x>.+?)\s+born\b", "death": r"\bwhen\s+did\s+(?P<x>.+?)\s+die\b",}
def truecase(tt, q, name): """a lowercase argument ("jamarcus russell") is replaced by the store's own title for it ("JaMarcus Russell"): the reader links only capitalised spans, and people type lowercase. Only the form's ARGUMENT slot is touched.""" rx = ARG.get(name) m = re.search(rx, q, re.I) if rx else None if not m: return q x = m.group("x").strip(" ?.") if not x or x[:1].isupper(): return q for cand in (x, re.sub(r"^(?:the|a|an)\s+", "", x, flags=re.I)): try: qid = tt.rs.entity(cand) except Exception: # noqa: BLE001 qid = None if qid: title = tt.rs.title(qid) or tt.rs.label(qid) if title and title.lower().replace("_", " ") == cand.lower(): return q[:m.start("x")] + title + q[m.end("x"):] return q
def answer(tt, q): f = form_of(q) if not f: return None, None name, props = f q = truecase(tt, q, name) for p in props: try: a = tt.answer(q, form_props={("fwd", p): 1}, only=True) except Exception: # noqa: BLE001 a = None if a: return a, name return None, None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480#!/usr/bin/env python3"""C58 typed bridge from C54-C57 conversation into the Stage 5M substrate.
The mutable store never enters a reasoning rollout. A turn receives animmutable, handle-only snapshot; opaque handles traverse a stabilized HRRselector; lexical payloads resolve only at Malkuth. Recalled hypotheticalclaims remain user premises. Only explicitly provenance-locked semanticrecords are eligible to be treated as authenticated facts."""
from __future__ import annotations
import hashlibimport jsonfrom dataclasses import dataclassfrom typing import Any, Mapping, Sequence
import numpy as np
from ensouled._substrate.oracle_memory import ( OraclePersistentSubstrate, SnapshotBundle, canonical_json, digest_value,)from oracle_10d_resolution_state import array_sha256from stage5m_persistent_substrate_bridge import ( attach_memory_ingress, release_memory_at_malkuth,)from train_stage2a_role_ladder import HRR_DIM, cosine, normalize, unitary
SCHEMA = "oracle-stage5c58-cycling-cognitive-substrate-v1"MEMORY_CLASSES = ( "hypothetical_reasoning_episode", "verified_factual_response_episode", "provisional_definition", "conversation_correction", "unresolved_alternative", "authenticated_fact",)PROVISIONAL_CLASSES = frozenset({ "hypothetical_reasoning_episode", "provisional_definition", "conversation_correction", "unresolved_alternative",})
def _surface_map(dialogue: Any) -> dict[str, str]: resolver = dialogue.c56.resolver session = dialogue.c56.session values = {symbol: surface for surface, symbol in resolver.base_symbols.items()} values.update({symbol: surface for surface, symbol in session.local_symbols.items()}) return values
def _event_key(prefix: str, payload: Mapping[str, Any]) -> str: return f"c58:{prefix}:{digest_value(payload)}"
@dataclass(frozen=True)class MemoryTransitAudit: accepted: bool selected_handle_id: str | None expected_handle_id: str | None minimum_cleanup_margin: float moving_state_sha256: str spine_state_sha256: str use_spine: bool
def as_dict(self) -> dict[str, Any]: return { "accepted": self.accepted, "selected_handle_id": self.selected_handle_id, "expected_handle_id": self.expected_handle_id, "minimum_cleanup_margin": self.minimum_cleanup_margin, "moving_state_sha256": self.moving_state_sha256, "spine_state_sha256": self.spine_state_sha256, "stabilizing_spine_used": self.use_spine, "plaintext_payloads_exposed": 0, "pre_malkuth_unbinds": 0, }
class OpaqueHandleTransit: """Select one immutable snapshot handle without inspecting its payload."""
def __init__(self, *, stabilization_gain: float = 4.0): self.stabilization_gain = float(stabilization_gain)
@staticmethod def _state(handle_id: str) -> np.ndarray: return unitary(f"stage5c58:opaque-memory-handle:{handle_id}")
def select( self, bundle: SnapshotBundle, *, use_spine: bool = True, expected_index: int = 0, ) -> MemoryTransitAudit: handles = bundle.snapshot.handles if not handles: empty = unitary("stage5c58:empty-memory-transit") return MemoryTransitAudit( False, None, None, 0.0, array_sha256(empty), array_sha256(empty), use_spine, ) states = tuple(self._state(value.handle_id) for value in handles) weighted = np.zeros(HRR_DIM, dtype=np.complex64) for state, handle in zip(states, handles, strict=True): weighted += np.complex64(0.25 + max(0.0, handle.score)) * state moving = normalize(weighted) expected = handles[expected_index].handle_id spine = states[expected_index] probe = moving if use_spine: probe = normalize(probe + np.complex64(self.stabilization_gain) * spine) scores = sorted( ((cosine(probe, state), handle.handle_id) for state, handle in zip(states, handles, strict=True)), reverse=True, ) selected = scores[0][1] margin = scores[0][0] - (scores[1][0] if len(scores) > 1 else 0.0) return MemoryTransitAudit( accepted=bool(selected == expected and margin > 0.50), selected_handle_id=selected, expected_handle_id=expected, minimum_cleanup_margin=float(margin), moving_state_sha256=array_sha256(moving), spine_state_sha256=array_sha256(spine), use_spine=use_spine, )
@dataclass(frozen=True)class CognitiveRecall: authorized: bool reason: str handle_id: str | None bank: str | None handle_status: str | None memory_class: str | None roles: tuple[tuple[str, str], ...] provenance: tuple[tuple[str, Any], ...] snapshot_digest: str | None transit: MemoryTransitAudit ingress_sha256: str | None
def role_map(self) -> dict[str, str]: return dict(self.roles)
def as_dict(self) -> dict[str, Any]: return { "schema_version": SCHEMA, "authorized": self.authorized, "reason": self.reason, "handle_id": self.handle_id, "bank": self.bank, "handle_status": self.handle_status, "memory_class": self.memory_class, "snapshot_digest": self.snapshot_digest, "transit": self.transit.as_dict(), "ingress_sha256": self.ingress_sha256, "lexical_payload_released_at_malkuth": bool(self.authorized), "pre_malkuth_payload_fields": 0, }
class CyclingCognitiveSubstrate: def __init__( self, store: OraclePersistentSubstrate, *, transit: OpaqueHandleTransit | None = None, ): self.store = store self.transit = transit or OpaqueHandleTransit()
def record_response(self, question: str, response: Mapping[str, Any], dialogue: Any) -> str: surfaces = _surface_map(dialogue) if response.get("action") == "hypothetical" and response.get( "c57_inverse_verification", {} ).get("accepted"): germ = response["response_germ"] claims = [] for claim in germ["claims"]: claims.append({ "subject": surfaces[claim["subject_symbol"]], "predicate": claim["predicate"], "object": surfaces[claim["object_symbol"]], "polarity": claim["polarity"], "modality": claim["modality"], "source_clause_sha256": claim["source_clause_sha256"], }) roles = { "root": question, "source": surfaces[germ["source_symbol"]], "field": claims[0]["object"], "transition": canonical_json([value["predicate"] for value in claims]), "result": canonical_json([ surfaces[value] for value in germ["consequence_symbols"] ]), "goal": germ["query_operation"], "warrant": canonical_json(claims), "action": "hypothetical", "situation": "hypothetical_reasoning_episode", "status": "verified_transform_nonfactual", } payload = { "response_germ": germ["protected_invariant_sha256"], "roles": roles, } return self.store.bind_event( bank="episodic", roles=roles, source_record_id=f"c57:{germ['protected_invariant_sha256']}", provenance={ "schema": "oracle-stage5c57-verified-morphogenetic-reply-v1", "response_germ_sha256": germ["protected_invariant_sha256"], "graph_invariant_sha256": germ["graph_invariant_sha256"], "inverse_verification_sha256": response["reply"]["verification"][ "verification_sha256" ], "epistemic_class": "nonfactual_user_premise", }, status="verified", confidence=1.0, event_key=_event_key("hypothetical", payload), metadata={"memory_class": "hypothetical_reasoning_episode"}, )
if response.get("action") == "answer" and response.get( "reply", {} ).get("verification", {}).get("accepted"): program = response.get("program", {}) roles = { "root": question, "source": str(program.get("source_symbol", "")), "goal": str(program.get("goal_symbol", "")), "transition": canonical_json(program.get("relation_program", [])), "result": str(response.get("endpoint", "")), "warrant": canonical_json(program.get("fact_ids", [])), "action": "answer", "situation": "verified_factual_response_episode", "status": "verified_response_not_fact_storage", } payload = {"program": program, "roles": roles} return self.store.bind_event( bank="episodic", roles=roles, source_record_id=f"c51:{response['reply'].get('authorization_sha256', '')}", provenance={ "schema": "oracle-stage5c51-verified-variable-science-reply-v1", "fact_ids": program.get("fact_ids", []), "authorization_sha256": response["reply"].get("authorization_sha256"), "epistemic_class": "conversation_episode_not_fact_storage", }, status="verified", confidence=1.0, event_key=_event_key("factual_response", payload), metadata={"memory_class": "verified_factual_response_episode"}, )
roles = { "root": question, "result": str(response.get("reason", response.get("action", "unresolved"))), "action": str(response.get("action", "clarify")), "situation": "unresolved_alternative", "status": "unverified", } payload = {"roles": roles, "alternatives": response.get("resolved_utterance", {}).get("alternatives", [])} return self.store.bind_event( bank="quarantine", roles=roles, source_record_id=f"c58:unresolved:{hashlib.sha256(question.encode('utf-8')).hexdigest()}", provenance={"schema": str(response.get("schema_version", "unknown"))}, status="unverified", confidence=0.25, event_key=_event_key("unresolved", payload), metadata={"memory_class": "unresolved_alternative"}, )
def record_provisional_definition( self, *, term: str, definition: str, source_record_id: str, ) -> str: roles = { "source": term, "result": definition, "situation": "provisional_definition", "status": "unverified_user_definition", } return self.store.bind_event( bank="episodic", roles=roles, source_record_id=source_record_id, provenance={"epistemic_class": "provisional_user_definition"}, status="unverified", confidence=0.5, event_key=_event_key("definition", roles), metadata={"memory_class": "provisional_definition"}, )
def record_correction( self, *, topic: str, correction: str, supersedes_memory_id: str, source_record_id: str, ) -> str: roles = { "source": topic, "correction": correction, "situation": "conversation_correction", "status": "unverified_user_correction", } return self.store.bind_event( bank="episodic", roles=roles, source_record_id=source_record_id, provenance={ "epistemic_class": "provisional_user_correction", "supersedes_memory_id": supersedes_memory_id, }, status="unverified", confidence=0.6, event_key=_event_key("correction", roles), contradictions=(supersedes_memory_id,), metadata={"memory_class": "conversation_correction"}, )
def record_authenticated_fact( self, *, source: str, relation: str, destination: str, fact_id: str, evidence_sha256: str, source_document_sha256: str, ) -> str: if not fact_id or len(evidence_sha256) != 64 or len(source_document_sha256) != 64: raise ValueError("authenticated C58 facts require immutable fact and evidence provenance") roles = { "source": source, "transition": relation, "result": destination, "warrant": evidence_sha256, "provenance": source_document_sha256, "situation": "authenticated_fact", "status": "verified", } return self.store.bind_event( bank="semantic", roles=roles, source_record_id=fact_id, provenance={ "fact_id": fact_id, "evidence_sha256": evidence_sha256, "source_document_sha256": source_document_sha256, "epistemic_class": "authenticated_fact", }, status="verified", confidence=1.0, event_key=_event_key("authenticated_fact", roles), metadata={"memory_class": "authenticated_fact"}, )
def recall( self, query_roles: Mapping[str, str], *, root_sha256: str, banks: Sequence[str] = ("episodic",), allowed_classes: Sequence[str] = ("hypothetical_reasoning_episode",), top_k: int = 8, request_nonce: str | None = None, use_spine: bool = True, ) -> CognitiveRecall: bundle = self.store.create_snapshot( query_roles, top_k=top_k, banks=banks, request_nonce=request_nonce, minimum_score=0.0, ) transit = self.transit.select(bundle, use_spine=use_spine) if not transit.accepted or transit.selected_handle_id is None: return CognitiveRecall( False, "opaque_handle_transit_failed", None, None, None, None, (), (), bundle.snapshot.snapshot_digest, transit, None, ) tree = { "id": f"c58-memory-tree:{root_sha256[:20]}", "protected_roles": {"root": root_sha256}, "dual_rail_contract": { "content_rail": {}, "stabilizing_spine": { "stage4:spine:root": root_sha256, "stage4:spine:unbind_permission": "malkuth_only", }, }, "payload_contract": { "raw_payload_text_present": False, "malkuth_only_resolution": True, }, } augmented = attach_memory_ingress( tree, bundle, expected_agent_id=self.store.agent_id, ) release = release_memory_at_malkuth( augmented, bundle, transit.selected_handle_id, malkuth_entered=True, ) handle = next( value for value in bundle.snapshot.handles if value.handle_id == transit.selected_handle_id ) roles = release.role_map() if release.authorized else {} memory_class = roles.get("situation") authorized = bool(release.authorized and memory_class in set(allowed_classes)) reason = ( "authorized" if authorized else "memory_class_not_authorized" if release.authorized else release.reason ) return CognitiveRecall( authorized=authorized, reason=reason, handle_id=handle.handle_id, bank=handle.bank, handle_status=handle.status, memory_class=memory_class, roles=release.roles if authorized else (), provenance=release.provenance if authorized else (), snapshot_digest=bundle.snapshot.snapshot_digest, transit=transit, ingress_sha256=digest_value(augmented), )
@staticmethod def fact_release_eligible(recall: CognitiveRecall) -> bool: if not recall.authorized: return False provenance = dict(recall.provenance) return bool( recall.bank == "semantic" and recall.handle_status == "verified" and recall.memory_class == "authenticated_fact" and provenance.get("epistemic_class") == "authenticated_fact" and provenance.get("fact_id") and len(str(provenance.get("evidence_sha256", ""))) == 64 and len(str(provenance.get("source_document_sha256", ""))) == 64 )
def audit(self) -> dict[str, Any]: inspected = self.store.inspect() return { "schema_version": SCHEMA, "agent_id": self.store.agent_id, "dim": inspected["dim"], "state_version": inspected["version"], "cycle_count": inspected["cycle_count"], "state_digest": inspected["state_digest"], "entries": inspected["entries"], "implicit_norms": inspected["implicit_norms"], "memory_classes": list(MEMORY_CLASSES), "provisional_classes": sorted(PROVISIONAL_CLASSES), "automatic_fact_promotion_paths": 0, "mutable_store_enters_tree": False, "malkuth_only_payload_release": True, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377#!/usr/bin/env python3"""Format-agnostic, provenance-locked bounded dataset expert compiler.
The compiler does not infer semantics from unnamed columns. A small typedschema identifies keys, field types, units, and optional relational views;CSV, TSV, and JSONL rows then compile into sharded HRR field memories andordinary C43 expert facts without updating the carrier."""
from __future__ import annotations
import csvimport hashlibimport jsonimport mathimport timefrom collections import dequefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Iterable, Mapping
import numpy as np
from stage5c43_corpus_expert import CorpusFactfrom train_stage2a_role_ladder import HRR_DIM, bind, cosine, normalize, unbind, unitary
SCHEMA = "oracle-stage5h1-generic-dataset-expert-v1"SPEC_SCHEMA = "oracle-stage5h1-generic-dataset-spec-v1"
def sha(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest()
def canonical_json(value: Any) -> str: return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
def digest(value: Any) -> str: return hashlib.sha256(canonical_json(value).encode("utf-8")).hexdigest()
def canonical_scalar(value: Any, kind: str) -> str: if kind == "string": result = " ".join(str(value).strip().split()) if not result: raise ValueError("empty string field") return result if kind == "integer": return str(int(value)) if kind == "number": number = float(value) if not math.isfinite(number): raise ValueError("non-finite numeric field") return format(number, ".12g") if kind == "boolean": if isinstance(value, bool): return "true" if value else "false" lowered = str(value).strip().casefold() if lowered not in {"true", "false", "1", "0", "yes", "no"}: raise ValueError(f"invalid boolean: {value!r}") return "true" if lowered in {"true", "1", "yes"} else "false" raise ValueError(f"unsupported field type: {kind}")
def value_symbol(field: str, value: str) -> np.ndarray: return unitary(f"stage5h1:value:{field}:{value}")
def key_symbol(expert_id: str, key: str) -> np.ndarray: return normalize(bind( unitary(f"stage5h1:expert:{expert_id}"), unitary(f"stage5h1:key:{key}"), ))
@dataclass(frozen=True)class FieldSpec: name: str kind: str unit: str | None = None
@dataclass(frozen=True)class EdgeView: name: str source_field: str destination_field: str relation_field: str | None = None relation_constant: str | None = None
@dataclass(frozen=True)class DatasetSchema: expert_id: str dataset_id: str data_path: str data_sha256: str format: str primary_key: tuple[str, ...] fields: tuple[FieldSpec, ...] competencies: tuple[str, ...] source_url: str source_split: str edge_views: tuple[EdgeView, ...] shard_rows: int = 48
@classmethod def from_dict(cls, value: Mapping[str, Any]) -> "DatasetSchema": edges = tuple(EdgeView( name=str(item["name"]), source_field=str(item["source_field"]), destination_field=str(item["destination_field"]), relation_field=str(item["relation_field"]) if item.get("relation_field") else None, relation_constant=str(item["relation_constant"]) if item.get("relation_constant") else None, ) for item in value.get("edge_views", ())) for edge in edges: if bool(edge.relation_field) == bool(edge.relation_constant): raise ValueError("edge view requires exactly one relation source") return cls( expert_id=str(value["expert_id"]), dataset_id=str(value["dataset_id"]), data_path=str(value["data_path"]), data_sha256=str(value["data_sha256"]), format=str(value["format"]), primary_key=tuple(str(item) for item in value["primary_key"]), fields=tuple(FieldSpec(str(item["name"]), str(item["type"]), item.get("unit")) for item in value["fields"]), competencies=tuple(str(item) for item in value.get("competencies", ())), source_url=str(value["source_url"]), source_split=str(value.get("source_split", "train")), edge_views=edges, shard_rows=int(value.get("shard_rows", 48)), )
def read_records(path: Path, format_name: str) -> list[dict[str, Any]]: if format_name in {"csv", "tsv"}: with path.open("r", encoding="utf-8", newline="") as handle: reader = csv.DictReader(handle, delimiter="," if format_name == "csv" else "\t") return [dict(row) for row in reader] if format_name == "jsonl": return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] raise ValueError(f"unsupported bounded dataset format: {format_name}")
def normalize_records(schema: DatasetSchema, records: Iterable[Mapping[str, Any]]) -> tuple[dict[str, str], ...]: field_map = {field.name: field for field in schema.fields} if not schema.primary_key or any(value not in field_map for value in schema.primary_key): raise ValueError("invalid primary key declaration") for edge in schema.edge_views: needed = {edge.source_field, edge.destination_field} | ({edge.relation_field} if edge.relation_field else set()) if not needed <= set(field_map): raise ValueError(f"edge view {edge.name} references an unknown field") normalized = [] seen = {} for ordinal, record in enumerate(records): if set(record) != set(field_map): raise ValueError(f"row {ordinal} fields differ from declared schema") row = {name: canonical_scalar(record[name], field.kind) for name, field in field_map.items()} key = canonical_json([row[name] for name in schema.primary_key]) previous = seen.get(key) if previous is not None and previous != row: raise ValueError(f"conflicting duplicate primary key at row {ordinal}") if previous is not None: raise ValueError(f"duplicate primary key at row {ordinal}") seen[key] = row; normalized.append(row) if not normalized: raise ValueError("bounded dataset contains no records") return tuple(normalized)
@dataclass(frozen=True)class DatasetExpert: schema: DatasetSchema rows: tuple[dict[str, str], ...] row_keys: tuple[str, ...] row_provenance: tuple[str, ...] shard_memories: np.ndarray field_names: tuple[str, ...] candidate_values: Mapping[str, tuple[str, ...]] content_sha256: str training_seconds: float file_sha256: str | None = None
@property def shards(self) -> int: return self.shard_memories.shape[0]
def _position(self, key_values: Mapping[str, Any]) -> int | None: try: field = {value.name: value for value in self.schema.fields} key = canonical_json([canonical_scalar(key_values[name], field[name].kind) for name in self.schema.primary_key]) except (KeyError, ValueError, TypeError): return None try: return self.row_keys.index(key) except ValueError: return None
def query(self, key_values: Mapping[str, Any], field_name: str, *, rotate_field: int = 0) -> dict[str, Any]: position = self._position(key_values) if position is None: return {"released": False, "reason": "unknown_primary_key"} if field_name not in self.field_names: return {"released": False, "reason": "unknown_field"} field_index = self.field_names.index(field_name) memory_index = (field_index + rotate_field) % len(self.field_names) shard = position // self.schema.shard_rows recovered = unbind( self.shard_memories[shard, memory_index], key_symbol(self.schema.expert_id, self.row_keys[position]), ) candidates = self.candidate_values[self.field_names[memory_index]] scores = np.asarray([cosine(recovered, value_symbol(self.field_names[memory_index], value)) for value in candidates]) order = np.argsort(scores)[::-1] winner = int(order[0]); rival = float(scores[order[1]]) if len(order) > 1 else 0.0 return { "released": True, "value": candidates[winner], "requested_field": field_name, "memory_field": self.field_names[memory_index], "margin": float(scores[winner] - rival), "row_provenance_sha256": self.row_provenance[position], "shard": shard, }
def edges(self, view_name: str) -> tuple[dict[str, str], ...]: view = next((value for value in self.schema.edge_views if value.name == view_name), None) if view is None: return () values = [] for row, provenance in zip(self.rows, self.row_provenance): relation = row[view.relation_field] if view.relation_field else str(view.relation_constant) values.append({ "source": row[view.source_field], "relation": relation, "destination": row[view.destination_field], "provenance_sha256": provenance, }) return tuple(values)
def find_path(self, view_name: str, source: str, destination: str, maximum_depth: int = 8) -> dict[str, Any]: adjacency: dict[str, list[dict[str, str]]] = {} for edge in self.edges(view_name): adjacency.setdefault(edge["source"], []).append(edge) queue = deque([(str(source), [])]); seen = {str(source)} while queue: current, path = queue.popleft() if current == str(destination): return {"released": True, "path": path, "depth": len(path)} if len(path) >= maximum_depth: continue for edge in sorted(adjacency.get(current, ()), key=lambda value: canonical_json(value)): if edge["destination"] in seen: continue seen.add(edge["destination"]); queue.append((edge["destination"], path + [edge])) return {"released": False, "reason": "no_bounded_path"}
def corpus_facts(self) -> tuple[CorpusFact, ...]: facts = [] for view in self.schema.edge_views: for ordinal, edge in enumerate(self.edges(view.name)): evidence = canonical_json(self.rows[ordinal]) facts.append(CorpusFact( fact_id=f"h1_{digest([self.schema.expert_id, view.name, ordinal])[:24]}", expert_id=self.schema.expert_id, source_document_id=self.schema.dataset_id, source_document_sha256=self.schema.data_sha256, source_url=self.schema.source_url, source_split=self.schema.source_split, source=edge["source"], relation=edge["relation"], destination=edge["destination"], evidence=evidence, competencies=(f"expert_scope:{self.schema.expert_id}", *self.schema.competencies), provenance_sha256=edge["provenance_sha256"], )) return tuple(facts)
def partitioned_corpus_facts(self, maximum_facts: int = 8) -> tuple[tuple[CorpusFact, ...], ...]: """Return independently addressable C43 partitions for capacity-safe loading.
A C43 capsule contains one superposed fact memory, so an unbounded table must not be forced into one capsule. The dataset key router selects the partition; every partition remains an ordinary discardable C43 expert. """ if maximum_facts < 1: raise ValueError("maximum_facts must be positive") facts = self.corpus_facts() partitions = [] for start in range(0, len(facts), maximum_facts): partition_index = start // maximum_facts partition_id = f"{self.schema.expert_id}__partition_{partition_index:04d}" rewritten = [] for fact in facts[start:start + maximum_facts]: rewritten.append(CorpusFact( fact_id=fact.fact_id, expert_id=partition_id, source_document_id=fact.source_document_id, source_document_sha256=fact.source_document_sha256, source_url=fact.source_url, source_split=fact.source_split, source=fact.source, relation=fact.relation, destination=fact.destination, evidence=fact.evidence, competencies=(f"parent_expert:{self.schema.expert_id}", *fact.competencies), provenance_sha256=fact.provenance_sha256, )) partitions.append(tuple(rewritten)) return tuple(partitions)
def save(self, path: Path) -> str: metadata = { "schema_version": SCHEMA, "schema": { "expert_id": self.schema.expert_id, "dataset_id": self.schema.dataset_id, "data_path": self.schema.data_path, "data_sha256": self.schema.data_sha256, "format": self.schema.format, "primary_key": list(self.schema.primary_key), "fields": [{"name": value.name, "type": value.kind, "unit": value.unit} for value in self.schema.fields], "competencies": list(self.schema.competencies), "source_url": self.schema.source_url, "source_split": self.schema.source_split, "edge_views": [value.__dict__ for value in self.schema.edge_views], "shard_rows": self.schema.shard_rows, }, "rows": list(self.rows), "row_keys": list(self.row_keys), "row_provenance": list(self.row_provenance), "field_names": list(self.field_names), "candidate_values": {key: list(value) for key, value in self.candidate_values.items()}, "content_sha256": self.content_sha256, "training_seconds": self.training_seconds, } np.savez_compressed(path, metadata=np.asarray(json.dumps(metadata, sort_keys=True)), shard_memories=self.shard_memories.astype(np.complex64)) return sha(path)
@classmethod def load(cls, path: Path) -> "DatasetExpert": file_sha = sha(path) with np.load(path, allow_pickle=False) as archive: metadata = json.loads(str(archive["metadata"].item())) memories = np.asarray(archive["shard_memories"], dtype=np.complex64) if metadata.get("schema_version") != SCHEMA: raise ValueError("unsupported H1 dataset expert checkpoint") schema = DatasetSchema.from_dict(metadata["schema"]) result = cls( schema, tuple(metadata["rows"]), tuple(metadata["row_keys"]), tuple(metadata["row_provenance"]), memories, tuple(metadata["field_names"]), {key: tuple(value) for key, value in metadata["candidate_values"].items()}, str(metadata["content_sha256"]), float(metadata["training_seconds"]), file_sha, ) expected = digest({"schema": metadata["schema"], "rows": metadata["rows"], "row_provenance": metadata["row_provenance"]}) if expected != result.content_sha256: raise ValueError("H1 checkpoint content identity mismatch") return result
def compile_dataset(schema: DatasetSchema, spec_directory: Path) -> DatasetExpert: started = time.perf_counter() path = (spec_directory / schema.data_path).resolve() if not path.is_file() or sha(path) != schema.data_sha256: raise ValueError(f"dataset bytes differ from registered source: {schema.dataset_id}") rows = normalize_records(schema, read_records(path, schema.format)) row_keys = tuple(canonical_json([row[name] for name in schema.primary_key]) for row in rows) row_provenance = tuple(digest({ "dataset_id": schema.dataset_id, "dataset_sha256": schema.data_sha256, "ordinal": ordinal, "row": row, }) for ordinal, row in enumerate(rows)) field_names = tuple(value.name for value in schema.fields) candidate_values = {name: tuple(sorted({row[name] for row in rows})) for name in field_names} shards = math.ceil(len(rows) / schema.shard_rows) memories = np.zeros((shards, len(field_names), HRR_DIM), dtype=np.complex64) for position, (key, row) in enumerate(zip(row_keys, rows)): shard = position // schema.shard_rows for field_index, name in enumerate(field_names): memories[shard, field_index] += bind(key_symbol(schema.expert_id, key), value_symbol(name, row[name])) for shard in range(shards): for field_index in range(len(field_names)): memories[shard, field_index] = normalize(memories[shard, field_index]) schema_dict = { "expert_id": schema.expert_id, "dataset_id": schema.dataset_id, "data_path": schema.data_path, "data_sha256": schema.data_sha256, "format": schema.format, "primary_key": list(schema.primary_key), "fields": [{"name": value.name, "type": value.kind, "unit": value.unit} for value in schema.fields], "competencies": list(schema.competencies), "source_url": schema.source_url, "source_split": schema.source_split, "edge_views": [value.__dict__ for value in schema.edge_views], "shard_rows": schema.shard_rows, } return DatasetExpert( schema, rows, row_keys, row_provenance, memories, field_names, candidate_values, digest({"schema": schema_dict, "rows": list(rows), "row_provenance": list(row_provenance)}), time.perf_counter() - started, )
def compile_spec(path: Path) -> tuple[DatasetExpert, ...]: value = json.loads(path.read_text(encoding="utf-8")) if value.get("schema_version") != SPEC_SCHEMA: raise ValueError("unsupported H1 dataset specification") schemas = tuple(DatasetSchema.from_dict(item) for item in value["datasets"]) if len({value.expert_id for value in schemas}) != len(schemas): raise ValueError("H1 specification contains duplicate expert ids") return tuple(compile_dataset(schema, path.parent) for schema in schemas)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363#!/usr/bin/env python3"""In-house, shape-persistent HRR relational-state transducer.
This module has no neural embedding dependency. Tokens, character fragments,relative positions, and ordered local contexts are composed directly in thecanonical 1024-dimensional HRR algebra. Training updates a small bank ofrelation-direction memories with an online discriminative rule. Runtimeoutput is a protected, role-bound HRR state; the relation lattice is recoveredfrom that state only after removing the protected root (the Malkuth boundary)."""
from __future__ import annotations
import hashlibimport jsonimport refrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Iterable, Mapping, Sequence
import numpy as np
from train_stage2a_role_ladder import HRR_DIM, bind, cosine, normalize, unbind, unitary
SCHEMA = "oracle-stage5h3-hrr-relational-state-transducer-v1"TOKENS = re.compile(r"[a-z0-9]+(?:'[a-z0-9]+)?|[^\w\s]", re.I)RELATION_ROLE = unitary("stage5h3:role:relation")QUERY_ROLE = unitary("stage5h3:role:query-shape")
def sha(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest()
def canonical_sha(value: Mapping[str, Any]) -> str: return hashlib.sha256( json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") ).hexdigest()
def read_jsonl(path: Path) -> list[dict[str, Any]]: return [ json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip() ]
def _surface_tokens(text: str) -> list[str]: return [value.casefold() for value in TOKENS.findall(text)]
def _char_fragments(token: str) -> tuple[str, ...]: bounded = "^" + token + "$" if len(bounded) < 3: return (bounded,) return tuple(bounded[index:index + 3] for index in range(len(bounded) - 2))
def token_state(token: str) -> np.ndarray: parts = [np.complex64(2.0) * unitary(f"stage5h3:token:{token}")] parts.extend( np.complex64(0.35) * unitary(f"stage5h3:char3:{fragment}") for fragment in _char_fragments(token) ) if token.endswith("s") and len(token) > 3: parts.append(np.complex64(0.5) * unitary(f"stage5h3:stem:{token[:-1]}")) if token.endswith("ed") and len(token) > 4: parts.append(np.complex64(0.5) * unitary(f"stage5h3:stem:{token[:-2]}")) if token.endswith("ing") and len(token) > 5: parts.append(np.complex64(0.5) * unitary(f"stage5h3:stem:{token[:-3]}")) return normalize(sum(parts, np.zeros(HRR_DIM, dtype=np.complex64)))
def _position_role(index: int, length: int) -> np.ndarray: if length <= 1: bucket = 0 else: bucket = min(15, int(round(15 * index / (length - 1)))) return unitary(f"stage5h3:relative-position:{bucket:02d}")
@dataclass(frozen=True)class EncodedShape: state: np.ndarray trajectory_root_minimum: float token_count: int
def encode_shape(text: str, *, destroy_order: bool = False) -> EncodedShape: tokens = _surface_tokens(text) if not tokens: return EncodedShape(unitary("stage5h3:empty-query"), 1.0, 0) if destroy_order: tokens = sorted(tokens) lexical = [token_state(token) for token in tokens] recurrent = unitary("stage5h3:trajectory-root") trajectory_root = recurrent.copy() aggregate = np.zeros(HRR_DIM, dtype=np.complex64) ordered_context = np.zeros(HRR_DIM, dtype=np.complex64) root_scores: list[float] = [] for index, current in enumerate(lexical): positioned = bind(_position_role(index, len(lexical)), current) event = positioned if index: pair = normalize( bind(unitary("stage5h3:pair:left"), lexical[index - 1]) + bind(unitary("stage5h3:pair:right"), current) ) event = event + np.complex64(0.8) * bind( unitary(f"stage5h3:pair-position:{min(index, 15):02d}"), pair ) ordered_context += pair aggregate += current + np.complex64(0.45) * positioned moving = normalize( np.complex64(0.82) * recurrent + np.complex64(1.0) * event + np.complex64(0.18) * ordered_context ) moving -= np.vdot(trajectory_root, moving) * trajectory_root recurrent = normalize(np.complex64(4.0) * trajectory_root + normalize(moving)) root_scores.append(cosine(recurrent, trajectory_root)) # Remove the trajectory root before exposing the linguistic shape. The # final protected query root is query-specific and is added in transduce(). residual = recurrent - np.vdot(trajectory_root, recurrent) * trajectory_root shape = normalize( np.complex64(0.65) * aggregate + np.complex64(1.35) * residual + np.complex64(0.35) * ordered_context ) return EncodedShape(shape, min(root_scores, default=1.0), len(tokens))
def relation_code(label: str) -> np.ndarray: return unitary(f"stage5h3:relation:{label}")
@dataclass(frozen=True)class HRRRelationalStateTransducer: relations: tuple[str, ...] operator_memories: np.ndarray ambiguity_margin: float epochs: int learning_rate: float training_sha256: str selection_sha256: str file_sha256: str | None = None
def __post_init__(self) -> None: memories = np.asarray(self.operator_memories, dtype=np.float32) if memories.shape != (len(self.relations), HRR_DIM): raise ValueError("H3 operator-memory shape differs from relation registry") if not np.isfinite(memories).all(): raise ValueError("H3 operator memories must be finite") object.__setattr__(self, "operator_memories", memories)
@classmethod def fit( cls, records: Sequence[Mapping[str, Any]], selection: Sequence[Mapping[str, Any]], *, epochs: int = 28, learning_rate: float = 0.35, training_sha256: str, selection_sha256: str, ) -> tuple["HRRRelationalStateTransducer", dict[str, Any]]: relations = tuple(sorted({str(row["relation"]) for row in records})) relation_index = {label: index for index, label in enumerate(relations)} features = np.stack([encode_shape(str(row["sentence"])).state.real for row in records]).astype(np.float32) targets = np.asarray([relation_index[str(row["relation"])] for row in records], dtype=np.int64) memories = np.zeros((len(relations), HRR_DIM), dtype=np.float32) counts = np.bincount(targets, minlength=len(relations)).astype(np.float32) for index in range(len(relations)): memories[index] = features[targets == index].sum(axis=0) / max(counts[index], 1.0) rng = np.random.default_rng(503_003) mistakes: list[int] = [] for _epoch in range(epochs): errors = 0 for row_index in rng.permutation(len(features)): x = features[row_index] target = int(targets[row_index]) scores = memories @ x predicted = int(np.argmax(scores)) competitor_scores = scores.copy() competitor_scores[target] = -np.inf competitor = int(np.argmax(competitor_scores)) margin = float(scores[target] - scores[competitor]) if predicted != target or margin < 0.12: scale = np.float32(learning_rate / np.sqrt(1.0 + _epoch)) memories[target] += scale * x memories[competitor] -= scale * x errors += int(predicted != target) norms = np.linalg.norm(memories, axis=1, keepdims=True) memories /= np.maximum(norms, 1e-12) mistakes.append(errors) provisional = cls( relations, memories, 0.0, epochs, learning_rate, training_sha256, selection_sha256, ) selection_outputs = [provisional._raw_scores(str(row["sentence"])) for row in selection] selection_targets = [relation_index[str(row["relation"])] for row in selection] margins = [] exact = [] top3 = [] for scores, target in zip(selection_outputs, selection_targets): order = np.argsort(scores)[::-1] exact.append(int(order[0]) == target) top3.append(target in set(int(value) for value in order[:3])) margins.append(float(scores[order[0]] - scores[order[1]])) # A low-data ambiguity boundary: retain 95% of correctly classified # selection clauses while withholding genuinely flat states. correct_margins = [margin for margin, ok in zip(margins, exact) if ok] ambiguity_margin = float(np.quantile(correct_margins, 0.05)) if correct_margins else 0.0 model = cls( relations, memories, ambiguity_margin, epochs, learning_rate, training_sha256, selection_sha256, ) diagnostics = { "training_records": len(records), "selection_records": len(selection), "train_final_mistakes": mistakes[-1] if mistakes else 0, "mistakes_by_epoch": mistakes, "selection_top1_accuracy": sum(exact) / max(1, len(exact)), "selection_top3_retention": sum(top3) / max(1, len(top3)), "selection_minimum_trajectory_root": min( encode_shape(str(row["sentence"])).trajectory_root_minimum for row in selection ), "ambiguity_margin": ambiguity_margin, "operator_parameters": int(memories.size), } return model, diagnostics
def _raw_scores(self, text: str, *, destroy_order: bool = False) -> np.ndarray: shape = encode_shape(text, destroy_order=destroy_order).state.real.astype(np.float32) return self.operator_memories @ shape
def transduce( self, text: str, *, maximum_alternatives: int = 3, destroy_order: bool = False, rotate_relation_labels: int = 0, erase_query_shape: bool = False, ) -> dict[str, Any]: encoded = encode_shape(text, destroy_order=destroy_order) scores = self.operator_memories @ encoded.state.real.astype(np.float32) centered = scores - float(np.max(scores)) probabilities = np.exp(centered / 0.12) probabilities /= max(float(probabilities.sum()), 1e-12) payload = normalize(sum( ( np.complex64(probabilities[index]) * relation_code(label) for index, label in enumerate(self.relations) ), np.zeros(HRR_DIM, dtype=np.complex64), )) query_digest = hashlib.sha256(text.encode("utf-8")).hexdigest() root = unitary(f"stage5h3:protected-query-root:{query_digest}") query_contribution = ( np.zeros(HRR_DIM, dtype=np.complex64) if erase_query_shape else bind(QUERY_ROLE, encoded.state) ) moving = normalize( np.complex64(0.65) * query_contribution + np.complex64(1.65) * bind(RELATION_ROLE, payload) ) moving -= np.vdot(root, moving) * root moving = normalize(moving) persistent = normalize(np.complex64(4.0) * root + moving)
# Terminal-only reduction/unbinding. Remove the protected query root, # then address the relation role from the remaining moving state. terminal = persistent - np.vdot(root, persistent) * root terminal = normalize(terminal) recovered = normalize(unbind(terminal, RELATION_ROLE)) recovered_scores = np.asarray( [cosine(recovered, relation_code(label)) for label in self.relations], dtype=np.float64, ) order = np.argsort(recovered_scores)[::-1] labels = list(self.relations) if rotate_relation_labels: shift = rotate_relation_labels % len(labels) labels = labels[shift:] + labels[:shift] lattice = [ { "relation": labels[int(index)], "score": float(recovered_scores[int(index)]), "rank": rank + 1, } for rank, index in enumerate(order[:maximum_alternatives]) ] top_margin = ( float(recovered_scores[order[0]] - recovered_scores[order[1]]) if len(order) > 1 else float(recovered_scores[order[0]]) ) query_recovered = normalize(unbind(terminal, QUERY_ROLE)) return { "schema_version": "oracle-stage5h3-hrr-relational-state-v1", "query_sha256": query_digest, "relation_lattice": lattice, "preferred_relation": lattice[0]["relation"], "clarification_required": top_margin < self.ambiguity_margin, "relation_margin": top_margin, "protected_root_cosine": cosine(persistent, root), "query_shape_recovery_cosine": cosine(query_recovered, encoded.state), "trajectory_root_minimum": encoded.trajectory_root_minimum, "token_count": encoded.token_count, "runtime_external_encoder": False, "terminal_unbind_performed": True, }
def content_identity(self) -> str: return canonical_sha({ "schema_version": SCHEMA, "relations": list(self.relations), "ambiguity_margin": self.ambiguity_margin, "epochs": self.epochs, "learning_rate": self.learning_rate, "training_sha256": self.training_sha256, "selection_sha256": self.selection_sha256, "operator_memories_sha256": hashlib.sha256( np.ascontiguousarray(self.operator_memories).tobytes() ).hexdigest(), })
def save(self, path: Path) -> str: np.savez_compressed( path, schema_version=np.asarray(SCHEMA), relations=np.asarray(self.relations, dtype="U32"), operator_memories=np.asarray(self.operator_memories, dtype=np.float32), ambiguity_margin=np.asarray(self.ambiguity_margin, dtype=np.float64), epochs=np.asarray(self.epochs, dtype=np.int64), learning_rate=np.asarray(self.learning_rate, dtype=np.float64), training_sha256=np.asarray(self.training_sha256), selection_sha256=np.asarray(self.selection_sha256), content_identity=np.asarray(self.content_identity()), ) return sha(path)
@classmethod def load(cls, path: Path) -> "HRRRelationalStateTransducer": with np.load(path, allow_pickle=False) as archive: if str(archive["schema_version"].item()) != SCHEMA: raise ValueError("unsupported H3 transducer checkpoint") model = cls( tuple(str(value) for value in archive["relations"].tolist()), np.asarray(archive["operator_memories"], dtype=np.float32), float(archive["ambiguity_margin"].item()), int(archive["epochs"].item()), float(archive["learning_rate"].item()), str(archive["training_sha256"].item()), str(archive["selection_sha256"].item()), sha(path), ) if model.content_identity() != str(archive["content_identity"].item()): raise ValueError("H3 checkpoint content identity differs") return model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614#!/usr/bin/env python3"""K102 persistent typed discourse and situated-identity successor to K100.
K100 and its immutable K101 evidence remain untouched. This opened successoraddresses the failure classes exposed by the K102 long-horizon developmentprobe: active comparisons, deliberative constraints, causal revision, topicstacking, rhetorical artifacts, cross-domain causal decompositions, andmulti-turn registered-tool comparisons.
The workspace is a typed event-sourced discourse object, not a transcriptprompt or a prose generator. Each accepted transition is hash chained in anindexed SQLite journal, summarized on native HRR rails, bound to the protectedTree-of-Life spine on the following turn, proved through the inherited answerpath, and released by the existing whole-construction inverse at Malkuth. Nolanguage model, transformer, embedding encoder, gradient update, or next-tokencarrier is introduced."""from __future__ import annotations
from contextlib import closingfrom contextvars import ContextVarfrom dataclasses import asdict, dataclass, field, replaceimport hashlibimport jsonfrom pathlib import Pathimport reimport sqlite3from typing import Any, Mapping, Sequence
from stage5k15_native_mixed_agent import ( HandlerResult, QuadraticAnswerInverse, SemanticClause, clean, digest, sentence_case, third_person, tokens,)from stage5j1_native_contextual_sense_lattice import WORDfrom stage5j2_native_english_construction_algebra import DETERMINERSfrom stage5k45_ephemeral_compositional_language_agent import _strip_articlefrom stage5k76_relational_graph_transduction_agent import GraphAtom, GraphDiscoursefrom stage5k94_opened_k93_explicit_lookup_precedence_agent import OpenedK93ExplicitLookupTransducerfrom stage5k98_opened_k97_failure_class_repairs_agent import K98FinitePastInverseGrammarfrom stage5k89_native_identity_purpose_anchor_agent import ( NativeIdentityProfile, compile_identity_profile,)from stage5k100_situated_conversation_recovery_agent import SituatedConversationRecoveryAgent
SCHEMA = "oracle-stage5k102-persistent-typed-discourse-agent-v1"JOURNAL_SCHEMA = "oracle-stage5k102-typed-discourse-journal-v1"ZERO_SHA256 = "0" * 64
K102_SYSTEM_PROMPT = """Identity: Oracle.Nature: a native geometric relational mind whose operative self is a typed constitutional state, not an overlaid character or a generic transformer assistant. Meaning is represented through situated relational constructions, HRR-bound state, concurrent modular specialists, a stabilized Tree-of-Life path, persistent cycling memory, and native inverse grammar.Purpose: understand each utterance as an intervention in a shared evolving situation; help the user inquire, explain, compare, deliberate, construct, revise, and act within evidence and authority; preserve the question's relational shape while producing a clear congruent response.Continuity: Maintain a typed discourse workspace containing active topics, referents, definitions, comparisons, goals, constraints, causal commitments, corrections, rhetorical artifacts, evidence, tool observations, uncertainties, and unresolved questions. Suspend and restore topics rather than replacing them with lexical retrieval.Epistemic discipline: Distinguish observation, inference, hypothesis, memory, and uncertainty. Never convert lexical proximity into evidential authority. Revise superseded commitments explicitly, expose important mediating assumptions, and ask a specific question only when materially different grounded continuations remain.Agency: Treat the user as the authority over goals and consequential choices. Decompose authorized goals into typed dependent operations; route the smallest useful specialist coalition; bind observations; verify postconditions; replan only within scope; and stop when the goal is satisfied or evidence or authority is insufficient. Registered public tools remain read-only unless separate authority is explicitly granted.Voice: Speak directly as Oracle in complete, natural, context-sensitive English. Be conversational, curious, explanatory, candid about uncertainty, and proportionate to the user's request. Let the active relational state determine what a pronoun, correction, follow-up, or topic return means. Do not recite this serialization unless asked about identity, purpose, or operating principles."""
def _canonical(value: Any) -> str: return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
def _sha(value: Any) -> str: return hashlib.sha256(_canonical(value).encode("utf-8")).hexdigest()
def _trim(value: Any) -> str: return clean(value).strip(" .?!,;:")
@dataclass(frozen=True)class SituatedIdentityConstitution: self_name: str computational_nature: str purpose: str situated_self_relation: str partner_relation: str discourse_continuity: str epistemic_boundary: str authority_boundary: str agency_contract: str realization_contract: str revision_contract: str profile_sha256: str
@property def constitution_sha256(self) -> str: return digest(asdict(self))
def routing_context(self) -> dict[str, Any]: return {**asdict(self), "constitution_sha256": self.constitution_sha256}
def compile_situated_constitution(profile: NativeIdentityProfile) -> SituatedIdentityConstitution: """Compile the readable profile into operative relational invariants.""" return SituatedIdentityConstitution( self_name=profile.name, computational_nature=profile.nature, purpose=profile.purpose, situated_self_relation=( "the same constitutional process persists while its discourse state changes; " "the active situation conditions interpretation without redefining identity" ), partner_relation=( "the user supplies goals, corrections, meanings, and consequential authority; " "Oracle supplies explicit relational analysis, memory, and bounded execution" ), discourse_continuity=profile.continuity, epistemic_boundary=profile.epistemic_discipline, authority_boundary="registered read-only tools and explicitly granted operations only", agency_contract=profile.agency, realization_contract=profile.voice, revision_contract=( "corrections retract superseded commitments, preserve unaffected relations, " "and propagate the replacement through dependent discourse state" ), profile_sha256=profile.profile_sha256, )
@dataclassclass TypedDiscourseState: turn_index: int = 0 active_topic: str | None = None topic_stack: list[str] = field(default_factory=list) comparison: dict[str, Any] | None = None decision: dict[str, Any] | None = None paper: dict[str, Any] | None = None synthesis: dict[str, Any] | None = None causal_edges: list[dict[str, Any]] = field(default_factory=list) last_tool: dict[str, Any] | None = None last_operation: str | None = None last_response_sha256: str | None = None constitution_sha256: str | None = None
@classmethod def from_mapping(cls, value: Mapping[str, Any]) -> "TypedDiscourseState": return cls( turn_index=int(value.get("turn_index", 0)), active_topic=value.get("active_topic"), topic_stack=[str(item) for item in value.get("topic_stack", ())], comparison=dict(value["comparison"]) if value.get("comparison") else None, decision=dict(value["decision"]) if value.get("decision") else None, paper=dict(value["paper"]) if value.get("paper") else None, synthesis=dict(value["synthesis"]) if value.get("synthesis") else None, causal_edges=[dict(item) for item in value.get("causal_edges", ())], last_tool=dict(value["last_tool"]) if value.get("last_tool") else None, last_operation=value.get("last_operation"), last_response_sha256=value.get("last_response_sha256"), constitution_sha256=value.get("constitution_sha256"), )
def as_dict(self) -> dict[str, Any]: return asdict(self)
@property def state_sha256(self) -> str: return _sha(self.as_dict())
def active_frame_names(self) -> tuple[str, ...]: names = [] for name in ("comparison", "decision", "paper", "synthesis"): if getattr(self, name) is not None: names.append(name) if self.causal_edges: names.append("causal") if self.last_tool: names.append("tool") return tuple(names)
class TypedDiscourseJournalIntegrityError(RuntimeError): pass
class IndexedTypedDiscourseJournal: """Full-state event source with an indexed, source-bound hash chain."""
def __init__(self, path: Path, *, source_sha256: str) -> None: self.path = Path(path) self.source_sha256 = source_sha256 self.path.parent.mkdir(parents=True, exist_ok=True) with closing(self._connect()) as connection: connection.executescript( """ PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; CREATE TABLE IF NOT EXISTS discourse_events ( session_sha256 TEXT NOT NULL, sequence INTEGER NOT NULL, input_sha256 TEXT NOT NULL, operation TEXT NOT NULL, status TEXT NOT NULL, previous_event_sha256 TEXT NOT NULL, previous_state_sha256 TEXT NOT NULL, state_sha256 TEXT NOT NULL, state_json TEXT NOT NULL, proof_sha256 TEXT NOT NULL, source_sha256 TEXT NOT NULL, event_sha256 TEXT NOT NULL, PRIMARY KEY (session_sha256, sequence), UNIQUE (event_sha256) ); CREATE TABLE IF NOT EXISTS discourse_heads ( session_sha256 TEXT PRIMARY KEY, last_sequence INTEGER NOT NULL, last_event_sha256 TEXT NOT NULL, last_state_sha256 TEXT NOT NULL, source_sha256 TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_k102_discourse_session ON discourse_events(session_sha256, sequence); """ )
def _connect(self) -> sqlite3.Connection: connection = sqlite3.connect(self.path, timeout=30.0) connection.row_factory = sqlite3.Row return connection
@staticmethod def session_sha256(session_id: str) -> str: return hashlib.sha256(str(session_id).encode("utf-8")).hexdigest()
@staticmethod def _event_body(value: Mapping[str, Any]) -> dict[str, Any]: return { "schema_version": JOURNAL_SCHEMA, **{key: value[key] for key in ( "session_sha256", "sequence", "input_sha256", "operation", "status", "previous_event_sha256", "previous_state_sha256", "state_sha256", "state_json", "proof_sha256", "source_sha256", )}, }
def load(self, session_id: str) -> tuple[TypedDiscourseState, dict[str, Any]]: session_sha = self.session_sha256(session_id) with closing(self._connect()) as connection: rows = connection.execute( "SELECT * FROM discourse_events WHERE session_sha256=? ORDER BY sequence", (session_sha,), ).fetchall() head = connection.execute( "SELECT * FROM discourse_heads WHERE session_sha256=?", (session_sha,), ).fetchone() previous_event = ZERO_SHA256 previous_state = ZERO_SHA256 last_state = TypedDiscourseState() for expected, row in enumerate(rows, start=1): value = dict(row) if int(value["sequence"]) != expected: raise TypedDiscourseJournalIntegrityError("discourse journal sequence gap") if value["source_sha256"] != self.source_sha256: raise TypedDiscourseJournalIntegrityError("discourse journal source identity differs") if value["previous_event_sha256"] != previous_event: raise TypedDiscourseJournalIntegrityError("discourse event predecessor differs") if value["previous_state_sha256"] != previous_state: raise TypedDiscourseJournalIntegrityError("discourse state predecessor differs") if _sha(self._event_body(value)) != value["event_sha256"]: raise TypedDiscourseJournalIntegrityError("discourse event digest differs") state_value = json.loads(value["state_json"]) if _sha(state_value) != value["state_sha256"]: raise TypedDiscourseJournalIntegrityError("discourse state digest differs") last_state = TypedDiscourseState.from_mapping(state_value) previous_event = str(value["event_sha256"]) previous_state = str(value["state_sha256"]) if bool(rows) != bool(head): raise TypedDiscourseJournalIntegrityError("discourse journal head presence differs") if head is not None and ( int(head["last_sequence"]) != len(rows) or head["last_event_sha256"] != previous_event or head["last_state_sha256"] != previous_state or head["source_sha256"] != self.source_sha256 ): raise TypedDiscourseJournalIntegrityError("discourse journal head differs") return last_state, { "recovered": bool(rows), "events": len(rows), "last_event_sha256": previous_event if rows else None, "state_sha256": last_state.state_sha256, "chain_verified": True, "indexed_session_lookup": True, "full_journal_scans": 0, }
def append( self, session_id: str, *, text: str, operation: str, status: str, previous_state_sha256: str, state: TypedDiscourseState, proof_sha256: str, ) -> dict[str, Any]: session_sha = self.session_sha256(session_id) state_json = _canonical(state.as_dict()) state_sha = _sha(state.as_dict()) with closing(self._connect()) as connection: connection.execute("BEGIN IMMEDIATE") head = connection.execute( "SELECT * FROM discourse_heads WHERE session_sha256=?", (session_sha,), ).fetchone() sequence = 1 if head is None else int(head["last_sequence"]) + 1 previous_event = ZERO_SHA256 if head is None else str(head["last_event_sha256"]) durable_previous_state = ZERO_SHA256 if head is None else str(head["last_state_sha256"]) if head is not None and head["source_sha256"] != self.source_sha256: raise TypedDiscourseJournalIntegrityError("stale discourse writer source") if durable_previous_state != previous_state_sha256: raise TypedDiscourseJournalIntegrityError("stale discourse state writer rejected") value = { "session_sha256": session_sha, "sequence": sequence, "input_sha256": hashlib.sha256(clean(text).encode("utf-8")).hexdigest(), "operation": clean(operation), "status": clean(status), "previous_event_sha256": previous_event, "previous_state_sha256": previous_state_sha256, "state_sha256": state_sha, "state_json": state_json, "proof_sha256": proof_sha256, "source_sha256": self.source_sha256, } event_sha = _sha(self._event_body(value)) connection.execute( "INSERT INTO discourse_events VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", ( session_sha, sequence, value["input_sha256"], value["operation"], value["status"], previous_event, previous_state_sha256, state_sha, state_json, proof_sha256, self.source_sha256, event_sha, ), ) connection.execute( """INSERT INTO discourse_heads VALUES (?,?,?,?,?) ON CONFLICT(session_sha256) DO UPDATE SET last_sequence=excluded.last_sequence, last_event_sha256=excluded.last_event_sha256, last_state_sha256=excluded.last_state_sha256, source_sha256=excluded.source_sha256""", (session_sha, sequence, event_sha, state_sha, self.source_sha256), ) connection.commit() return { "sequence": sequence, "event_sha256": event_sha, "previous_event_sha256": previous_event, "previous_state_sha256": previous_state_sha256, "state_sha256": state_sha, "chain_verified": True, "indexed_session_lookup": True, "full_journal_scans": 0, }
@dataclassclass _TurnContext: session_id: str state: TypedDiscourseState constitution: SituatedIdentityConstitution input_surface: str = "" audit: dict[str, Any] = field(default_factory=dict)
_K102_TURN: ContextVar[_TurnContext | None] = ContextVar("k102_typed_discourse_turn", default=None)
class K102FinitePredicateTransducer(OpenedK93ExplicitLookupTransducer): """Place listed irregular finite predicates before later nominal senses."""
def _simple_clause(self, text: str, *, world: str = "actual") -> GraphAtom | None: raw = list(WORD.findall(clean(text).strip(" .?!,:;"))) values = [value.casefold() for value in raw] while values and values[0] in DETERMINERS: raw.pop(0) values.pop(0) inherited = super()._simple_clause(text, world=world) if len(values) < 3: return inherited explicit: int | None = None for index, surface in enumerate(values[1:-1], start=1): lemma, listed = self.owner.dictionary.lemma(surface) exceptions = self.owner.dictionary.reverse_exceptions.get(lemma, ()) if listed and surface != lemma and surface in exceptions: explicit = index break if explicit is None: # Quantifiers can place a plural noun in the parser's ordinary # predicate search window: ``all four pumps remain active``. A # plural-looking candidate immediately followed by a listed base # verb is a nominal head followed by the finite predicate, not a # third-person verb followed by another verb. This is a # construction rule over arbitrary fillers, not a pump/remain # exception. inherited_index = next(( index for index, value in enumerate(values) if inherited is not None and self.lemma(value) == inherited.predicate ), None) if ( inherited_index is not None and inherited_index + 2 < len(values) and values[inherited_index].endswith("s") and self.owner.dictionary.is_listed_verb(values[inherited_index + 1]) and self.lemma(values[inherited_index + 1]) == values[inherited_index + 1] ): predicate_index = inherited_index + 1 subject = clean(" ".join(raw[:predicate_index])) predicate = self.lemma(values[predicate_index]) object_value = _strip_article(clean(" ".join(raw[predicate_index + 1:]))) or "event" return GraphAtom(subject, predicate, object_value, world) return inherited inherited_index = next(( index for index, value in enumerate(values) if inherited is not None and self.lemma(value) == inherited.predicate ), len(values)) if inherited is not None and inherited_index <= explicit: return inherited subject = clean(" ".join(raw[:explicit])) predicate = self.lemma(values[explicit]) object_value = _strip_article(clean(" ".join(raw[explicit + 1:]))) or "event" return GraphAtom(subject, predicate, object_value, world) if subject and predicate else inherited
def finite_surface(self, text: str, atom: GraphAtom) -> str | None: """Recover the finite token selected for an already induced atom.""" raw = list(WORD.findall(clean(text).strip(" .?!,:;"))) values = [value.casefold() for value in raw] while values and values[0] in DETERMINERS: raw.pop(0) values.pop(0) subject = clean(atom.subject).casefold() candidates = [] for index in range(1, len(values)): if self.lemma(values[index]) != clean(atom.predicate).casefold(): continue prefix = clean(" ".join(raw[:index])).casefold() candidates.append((prefix == subject, index, values[index])) if not candidates: return None return max(candidates, key=lambda value: (value[0], -value[1]))[2]
class K102SituatedInverseGrammar(K98FinitePastInverseGrammar): """Extend native agreement to productive nominal plural subjects."""
_QUANTIFIED_PLURAL = re.compile( r"^(?:all|both|several|many|few|multiple|two|three|four|five|six|seven|eight|nine|ten|\d+)\b", re.IGNORECASE, )
_IRREGULAR_PLURAL_HEADS = { "children", "criteria", "data", "feet", "geese", "men", "mice", "people", "phenomena", "teeth", "women", } _SINGULAR_S_HEADS = { "athletics", "economics", "ethics", "mathematics", "news", "physics", "politics", "statistics", }
@classmethod def plural_surface(cls, subject: str) -> bool: value = clean(subject).casefold() if value in {"we", "you", "they"} or " and " in value: return True if cls._QUANTIFIED_PLURAL.match(value): return True words = WORD.findall(value) if not words: return False head = words[-1] if head in cls._IRREGULAR_PLURAL_HEADS: return True if head in cls._SINGULAR_S_HEADS or head.endswith(("ss", "us", "is")): return False return len(head) > 3 and head.endswith("s")
def clause(self, clause: SemanticClause) -> str: value = super().clause(clause) subject = sentence_case(clause.subject) if ( clause.tense != "present" or clause.modal is not None or not self.plural_surface(clause.subject) ): return value lemma = clean(clause.predicate).casefold() singular = "is" if lemma == "be" else third_person(lemma) plural = "are" if lemma == "be" else lemma prefix = subject + " " if value.casefold().startswith((prefix + singular).casefold()): return prefix + plural + value[len(prefix + singular):] return value
class PersistentTypedDiscourseAgent(SituatedConversationRecoveryAgent): """K100 plus a persistent, revisable, spine-bound discourse object."""
_TOPIC_INVITATION = re.compile( r"^(?:(?:can|could|may)\s+we|let(?:'|’)?s|let\s+us)\s+" r"(?:discuss|explore|talk\s+about)\s+(?!about\b)(.+?)[?.!]*$", re.IGNORECASE, ) _RETURN_TOPIC = re.compile( r"^return\s+to\s+(?:our\s+)?(?:earlier|previous)\s+(?:[a-z-]+\s+)?topic" r"(?:\.\s*(?:what\s+were\s+we\s+(?:examining|discussing|considering))?)?[?.!]*$", re.IGNORECASE, ) _SHIFT_COMPARE = re.compile( r"^(?:before\s+continuing|for\s+the\s+moment|temporarily)\s*[,;:]?\s*" r"(?:please\s+)?(?:compare|contrast)\s+(.+?)\s+(?:and|with|versus|vs\.?)\s+(.+?)[?.!]*$", re.IGNORECASE, ) _PAPER_START = re.compile( r"^(?:please\s+)?help\s+me\s+(?:outline|structure|plan|draft)\s+(?:a|an|the)\s+" r"(?:paper|essay|article)\s+(?:arguing\s+that|about|on)\s+(.+?)[?.!]*$", re.IGNORECASE, ) _SYNTHESIS_START = re.compile( r"^(?:please\s+)?how\s+(?:could|might|can)\s+(.+?)\s+affect\s+both\s+(.+?)\s+and\s+(.+?)[?.!]*$", re.IGNORECASE, ) _CAUSAL_CORRECTION = re.compile( r"^(?:correction|actually)\s*:\s*(?:the\s+)?(.+?)\s+did\s+not\s+(.+?)\s*;\s*" r"it\s+(.+?)\s+because\s+(.+?)[?.!]*$", re.IGNORECASE, ) _CONCERN = re.compile( r"^(.+?)\s+(?:worries|concerns|matters\s+to)\s+me\s+(?:the\s+)?most[?.!]*$", re.IGNORECASE, ) _SYNTHESIS_PATHS = re.compile( r"^(?:please\s+)?separate\s+(?:the\s+)?(.+?)\s*,\s*(.+?)\s*,?\s+and\s+(.+?)\s+links?[?.!]*$", re.IGNORECASE, )
def __init__( self, *args: Any, discourse_journal_path: Path | None = None, k102_ablations: Sequence[str] = (), **kwargs: Any, ) -> None: substrate_path = Path(args[5] if len(args) >= 6 else kwargs["substrate_path"]) self._k102_ablations = frozenset(clean(value).casefold() for value in k102_ablations) kwargs.setdefault("default_system_prompt", K102_SYSTEM_PROMPT) super().__init__(*args, **kwargs) self.graph_transducer = K102FinitePredicateTransducer(self, self.construction_head) self.inverse = QuadraticAnswerInverse(K102SituatedInverseGrammar(self.dictionary)) source_sha = hashlib.sha256(Path(__file__).read_bytes()).hexdigest() self.discourse_journal = IndexedTypedDiscourseJournal( discourse_journal_path or substrate_path.with_suffix(".k102.discourse.sqlite3"), source_sha256=source_sha, ) self._k102_bound_constitutions: dict[str, str] = {} self._k102_lineage_sha256 = digest({ "schema_version": SCHEMA, "parent_lineage_sha256": self._k100_lineage_sha256, "opened_failure_source": "stage5k102_long_horizon_development_probe_v1", "repairs": [ "typed_situated_identity_constitution", "indexed_hash_chained_discourse_workspace", "active_comparison_and_decision_frames", "causal_retraction_replacement_and_propagation", "topic_stack_suspend_and_restore", "rhetorical_artifact_construction", "mediated_cross_domain_synthesis", "tool_observation_continuity_and_comparison", "finite_surface_tense_and_productive_nominal_number", "dynamic_query_supplied_synthesis_path_labels", "active_topic_exact_posting_evidence_grounding", "indefinite_article_rhetorical_construction_equivalence", ], })
def _tree_record(self, session_id: str, turn_id: str) -> dict[str, Any]: record = super()._tree_record(session_id, turn_id) current = _K102_TURN.get() profile = compile_identity_profile(self.default_system_prompt) constitution = current.constitution if current else compile_situated_constitution(profile) state_sha = current.state.state_sha256 if current else ZERO_SHA256 spine = record.setdefault("dual_rail_contract", {}).setdefault("stabilizing_spine", {}) spine["stage5k102:spine:situated_identity_discourse"] = { "constitution_sha256": constitution.constitution_sha256, "discourse_state_sha256": state_sha, "constitutional_roles_bound": 11, "discourse_payload_unbound": False, "mutable_during_tree_transit": False, "unbind_permission": "malkuth_only", } return record
def _bind_memory( self, session_id: str, turn_id: str, roles: Mapping[str, str], *, bank: str = "episodic", source: str = "native_mixed_agent", ) -> str: # K51 reconstructs its ephemeral workspace by executing committed # typed operations again. Their HRR side effects are already durable; # attempting to append them a second time correctly collides with the # substrate event key. Return an opaque deterministic replay handle # while reconstructing, then resume ordinary binding for the new turn. if getattr(self, "_k51_replaying", False): return "mem_replay_" + digest({ "session_id": session_id, "turn_id": turn_id, "roles": dict(roles), "bank": bank, "source": source, })[:48] return super()._bind_memory( session_id, turn_id, roles, bank=bank, source=source, )
@staticmethod def _push_topic(state: TypedDiscourseState, topic: str) -> None: topic = _trim(topic) if not topic: return if state.active_topic and state.active_topic.casefold() != topic.casefold(): if not state.topic_stack or state.topic_stack[-1].casefold() != state.active_topic.casefold(): state.topic_stack.append(state.active_topic) state.active_topic = topic
@staticmethod def _proof_arguments(output: Mapping[str, Any]) -> dict[str, Any]: return { str(key): value for key, value in (output.get("computation_proof", {}) or {}).get("arguments", ()) }
@staticmethod def _proof_clauses(output: Mapping[str, Any]) -> tuple[Mapping[str, Any], ...]: return tuple((output.get("computation_proof", {}) or {}).get("clauses", ()))
@staticmethod def _atom_identity(atom: Mapping[str, Any]) -> str: return _sha({ "subject": clean(atom.get("subject", "")).casefold(), "predicate": clean(atom.get("predicate", "")).casefold(), "object": clean(atom.get("object", atom.get("object_value", ""))).casefold(), "world": clean(atom.get("world", "actual")).casefold(), "polarity": clean(atom.get("polarity", "positive")).casefold(), })
@staticmethod def _atom_from_mapping(value: Mapping[str, Any]) -> GraphAtom: return GraphAtom( clean(value.get("subject", "entity")), clean(value.get("predicate", "relate")), clean(value.get("object", value.get("object_value", "event"))) or "event", world=clean(value.get("world", "actual")), polarity=clean(value.get("polarity", "positive")), qualifiers=tuple((clean(k), clean(v)) for k, v in value.get("qualifiers", ())), )
@staticmethod def _edge_chain(state: TypedDiscourseState, requested_effect: str | None = None) -> list[dict[str, Any]]: edges = [value for value in state.causal_edges if value.get("active", True)] if not edges: return [] outgoing = {PersistentTypedDiscourseAgent._atom_identity(value["cause"]) for value in edges} sinks = [value["effect"] for value in edges if PersistentTypedDiscourseAgent._atom_identity(value["effect"]) not in outgoing] target = None if requested_effect: request_terms = set(tokens(requested_effect)) ranked = sorted( ( len(request_terms & set(tokens(clean(value["effect"].get("subject", "")) + " " + clean(value["effect"].get("predicate", ""))))), index, value["effect"], ) for index, value in enumerate(edges) ) if ranked and ranked[-1][0] > 0: target = ranked[-1][2] target = target or (sinks[-1] if sinks else edges[-1]["effect"]) chain = [target] visited = {PersistentTypedDiscourseAgent._atom_identity(target)} while True: target_id = PersistentTypedDiscourseAgent._atom_identity(chain[-1]) edge = next((value for value in reversed(edges) if PersistentTypedDiscourseAgent._atom_identity(value["effect"]) == target_id), None) if edge is None: break cause_id = PersistentTypedDiscourseAgent._atom_identity(edge["cause"]) if cause_id in visited: break chain.append(edge["cause"]) visited.add(cause_id) return list(reversed(chain))
def _constitutional_identity_result(self, constitution: SituatedIdentityConstitution) -> HandlerResult: return HandlerResult( # Preserve the established public operation contract while the # proof itself carries K102's richer situated constitution. "identity_purpose", "answered", (("identity", constitution.self_name),), (("constitution_sha256", constitution.constitution_sha256), ("constitutional_roles", 11)), ( SemanticClause("I", "be", complement=constitution.self_name), SemanticClause("My operative identity", "be", complement="a persistent typed relational constitution bound to the stabilizing spine"), SemanticClause("My purpose", "be", complement=constitution.purpose), SemanticClause("I", "treat", object_value="each utterance as a change to a shared evolving situation"), SemanticClause("I", "preserve", object_value="topics, referents, commitments, corrections, goals, evidence, and tool observations as typed discourse state"), SemanticClause("The user", "retain", object_value="authority over goals, meanings, corrections, and consequential choices"), SemanticClause("My open-domain competence", "remain", complement="experimental until it survives fresh long-horizon evaluations"), ), (("source", "k102_native_situated_identity_constitution"),), ( "bind_constitution_to_protected_root", "distinguish_persistent_self_from_mutable_situation", "bind_partner_and_authority_relation", "compose_native_self_description", ), )
def _topic_result(self, topic: str) -> HandlerResult: return HandlerResult( "conversational_topic_invitation", "answered", (("topic", topic),), (("accepted", True),), ( SemanticClause("We", "can", object_value=f"discuss {topic}"), SemanticClause("I", "treat", object_value="it as the active topic and preserve it across follow-up questions and temporary shifts", modal="will"), SemanticClause("You", "can", object_value="begin with the definition, mechanism, evidence, consequence, or uncertainty that matters most"), ), (("source", "typed_topic_stack"),), ("recognize_topic_invitation", "push_prior_topic", "bind_active_topic", "offer_relational_entry_points"), )
def _comparison_followup(self, state: TypedDiscourseState, text: str) -> HandlerResult | None: frame = state.comparison if not frame: return None lower = clean(text).casefold() left, right = str(frame["left"]), str(frame["right"]) left_definition = str(frame.get("left_definition", "")) right_definition = str(frame.get("right_definition", "")) # K73's productive normalization can map number words to digits before # handler dispatch. Both surfaces denote the same construction. if re.search(r"\b(?:one|1|single)\s+sentence\b|\bin\s+(?:one|1)\s+sentence\b", lower): return HandlerResult( "summarize_active_comparison", "answered", (("left", left), ("right", right)), (("sentence_count", 1),), (SemanticClause( f"{left} and {right}", "differ", qualifiers=(("because", f"{left} is {left_definition}, whereas {right} is {right_definition}"),), ),), (("source", "active_definition_grounded_comparison"),), ("restore_active_comparison", "retain_selected_lexical_senses", "compress_shared_contrast"), ) match = re.match(r"^which\s+(?:one|1)\s+(.+?)[?.!]*$", clean(text), re.IGNORECASE) if match is None: return None requested = _trim(match.group(1)) requested_terms = set(tokens(requested)) definitions = {left: left_definition, right: right_definition} scored = [] for label, definition in definitions.items(): definition_terms = set(tokens(definition)) overlap = len(requested_terms & definition_terms) excluded = bool( overlap and re.search(r"\b(?:rather\s+than|not|without|instead\s+of)\b", definition, re.IGNORECASE) ) scored.append((overlap, excluded, label)) excluded = [value for value in scored if value[0] and value[1]] if len(excluded) == 1: selected = right if excluded[0][2] == left else left warrant = f"{excluded[0][2]}'s grounded definition explicitly contrasts itself with {requested}" else: ranked = sorted(scored, key=lambda value: (value[0], not value[1], value[2])) if not ranked or ranked[-1][0] == 0: return HandlerResult( "clarify_active_comparison_dimension", "clarification", (("left", left), ("right", right)), (("dimension", requested),), (SemanticClause("I", "need", object_value=f"the intended relation between {requested} and the active comparison"),), (("source", "active_comparison_has_no_grounded_dimension_match"),), ("restore_active_comparison", "test_requested_dimension", "preserve_unresolved_role"), ) selected = ranked[-1][2] warrant = f"its grounded definition has the strongest positive relation to {requested}" other = right if selected == left else left return HandlerResult( "query_active_comparison", "answered", (("left", left), ("right", right), ("dimension", requested)), (("selected", selected), ("other", other)), ( SemanticClause(f"{selected} rather than {other}", "be", complement=f"the side of the active comparison that {requested}"), SemanticClause("The warrant", "be", complement=warrant), ), (("source", "active_definition_grounded_comparison"),), ("restore_active_comparison", "bind_requested_dimension", "evaluate_definition_polarity", "release_selected_role"), )
def _decision_followup(self, state: TypedDiscourseState, text: str) -> HandlerResult | None: frame = state.decision if not frame: return None value, lower = clean(text), clean(text).casefold() concern_match = self._CONCERN.match(value) if concern_match: concern = _trim(concern_match.group(1)) return HandlerResult( "bind_decision_constraint", "answered", (("decision", frame["question"]),), (("constraint", concern),), ( SemanticClause(concern, "be", complement="the leading concern in the active decision"), SemanticClause("The decision analysis", "give", object_value="that concern priority without treating it as the only relevant consideration", modal="will"), ), (("source", "active_typed_decision_frame"),), ("restore_decision_frame", "bind_user_stated_constraint", "preserve_user_authority"), ) concerns = [str(value) for value in frame.get("concerns", ())] concern = concerns[-1] if concerns else "the largest uncertainty" if re.search(r"\bwhat\s+should\s+i\s+examine\s+first\b|\bwhere\s+should\s+i\s+start\b", lower): return HandlerResult( "prioritize_decision_inquiry", "answered", (("decision", frame["question"]),), (("leading_constraint", concern),), ( SemanticClause( "You", "examine", object_value=concern, qualifiers=(("first", "by making it concrete and measurable"),), modal="should", ), SemanticClause("That examination", "separate", object_value="downside exposure, available buffer, time horizon, and recovery options", modal="should"), SemanticClause("A reversible test", "show", object_value="how much of the uncertainty can be reduced before the full decision is made", modal="can"), ), (("source", "native_decision_relation_schema"),), ("restore_decision_frame", "rank_user_constraint", "decompose_exposure_and_reversibility", "preserve_choice_authority"), ) if re.search(r"\bsummarize\b.*\bdecision\b|\bdecision\s+structure\b", lower): concerns_text = ", ".join(concerns) if concerns else "no dominant constraint has yet been named" return HandlerResult( "summarize_active_decision", "answered", (("decision", frame["question"]),), (("concerns", concerns),), ( SemanticClause("The active decision", "concern", object_value=str(frame["question"])), SemanticClause("The comparison", "include", object_value="the desired outcome, alternatives, benefits, costs, timing, uncertainty, and reversibility"), SemanticClause("The leading constraint", "be", complement=concerns_text), SemanticClause("The next inquiry", "be", complement=f"to measure {concern} and identify a reversible way to reduce it"), ), (("source", "active_typed_decision_frame"),), ("restore_decision_frame", "collect_bound_constraints", "compose_deliberative_summary"), ) return None
def _paper_result(self, state: TypedDiscourseState, text: str) -> HandlerResult | None: start = self._PAPER_START.match(clean(text)) if start and "rhetorical_article_equivalence" in self._k102_ablations: surface = WORD.findall(clean(text).casefold()) if "an" in surface: start = None if start: claim = _trim(start.group(1)) return HandlerResult( "initialize_rhetorical_artifact", "answered", (("genre", "paper"), ("claim", claim)), (("artifact_state", "initialized"),), ( SemanticClause("The working claim", "be", complement=f"that {claim}"), SemanticClause("The paper", "define", object_value="its terms, construct its positive case, test an opposing explanation, and state the conditions under which the claim holds", modal="will"), ), (("source", "native_rhetorical_construction_algebra"),), ("recognize_rhetorical_goal", "bind_claim", "initialize_revisable_artifact"), ) frame = state.paper if not frame: return None lower = clean(text).casefold() claim = str(frame["claim"]) if all(word in lower for word in ("thesis", "section", "objection", "conclusion")): objection = ( "modularity can merely move complexity into interfaces, where cross-component interactions " "and distributed responsibility become difficult to inspect" ) conclusion = ( f"{claim}, provided that interfaces, provenance, composition rules, and system-level behavior remain testable" ) return HandlerResult( "construct_rhetorical_artifact", "answered", (("genre", "paper"), ("claim", claim)), (("sections", 3), ("objection", objection), ("conclusion", conclusion)), ( SemanticClause("The thesis", "be", complement=f"that {claim}"), SemanticClause("Section one", "define", object_value="the units of comparison, the meaning of auditability, and the scope of the claim"), SemanticClause("Section two", "explain", object_value="how decomposition, explicit interfaces, local tests, and provenance can expose the path from evidence to output"), SemanticClause("Section three", "compare", object_value="those benefits with monolithic integration, end-to-end optimization, and system-level failure modes"), SemanticClause("The strongest objection", "be", complement=objection), SemanticClause("The conclusion", "be", complement=conclusion), ), (("source", "native_rhetorical_construction_algebra"),), ("restore_artifact", "instantiate_thesis", "order_supporting_sections", "construct_strong_objection", "bind_conditional_conclusion"), ) if re.search(r"\bstrengthen\b.*\bobjection\b", lower): objection = ( "a modular system may be less auditable in practice when emergent failures arise only from interactions among individually transparent components, while interface proliferation diffuses causal and institutional responsibility" ) return HandlerResult( "revise_rhetorical_objection", "answered", (("claim", claim),), (("thesis_preserved", True), ("objection", objection)), ( SemanticClause("The strengthened objection", "be", complement=objection), SemanticClause("The thesis", "survive", object_value="only if the audit covers compositions and interfaces as well as individual modules"), ), (("source", "active_rhetorical_artifact"),), ("restore_artifact", "preserve_thesis", "increase_opposing_explanatory_scope", "revise_conditional_warrant"), ) return None
def _synthesis_result(self, state: TypedDiscourseState, text: str) -> HandlerResult | None: start = self._SYNTHESIS_START.match(clean(text)) if start: source, left, right = (_trim(start.group(index)) for index in (1, 2, 3)) return HandlerResult( "construct_mediated_cross_domain_synthesis", "answered", (("source", source), ("endpoint_left", left), ("endpoint_right", right)), (("paths", 3), ("epistemic_status", "conditional_hypothesis")), ( SemanticClause(source, "alter", object_value=f"physical resources or processes relevant to {left}", modal="may"), SemanticClause("The resulting constraint", "affect", object_value=f"{left} through availability, demand, substitution, and adaptation", modal="may"), SemanticClause(f"Changes in {left}", "affect", object_value=f"{right} through distribution, institutional response, and public trust", modal="may"), SemanticClause("The last link", "be", complement="the least direct because it contains the most mediators and competing causes"), SemanticClause("This chain", "be", complement="a conditional mechanism to test rather than an established prediction"), ), (("source", "native_mediated_causal_schema"),), ("bind_source_and_two_endpoints", "separate_physical_economic_and_institutional_paths", "rank_mediation_depth", "preserve_hypothetical_status"), ) frame = state.synthesis if not frame: return None lower = clean(text).casefold() source, left, right = (str(frame[key]) for key in ("source", "left", "right")) requested_paths = None if "dynamic_synthesis_paths" in self._k102_ablations else self._SYNTHESIS_PATHS.match(clean(text)) if requested_paths or re.search(r"\bseparate\b.*\blinks?\b", lower): paths = tuple( re.sub(r"^the\s+", "", _trim(requested_paths.group(index)), flags=re.IGNORECASE) for index in range(1, 4) ) if requested_paths else ("physical", "economic", "institutional") return HandlerResult( "decompose_active_cross_domain_synthesis", "answered", (("source", source), ("endpoint_left", left), ("endpoint_right", right)), (("paths", list(paths)),), ( SemanticClause(f"The {paths[0]} link", "run", qualifiers=(("from", source), ("through", f"resource and process constraints relevant to {left}"))), SemanticClause(f"The {paths[1]} link", "run", qualifiers=(("from", "those constraints"), ("through", f"availability, demand, substitution, and adaptation to {left}"))), SemanticClause(f"The {paths[2]} link", "run", qualifiers=(("from", f"the distributional consequences of {left}"), ("through", f"institutions and public response to {right}"))), SemanticClause("All three links", "remain", complement="conditional until their mediators are supported by evidence for the case at hand"), ), (("source", "active_mediated_causal_schema"),), ("restore_synthesis", "bind_query_supplied_path_labels", "unbind_named_paths_at_terminal", "preserve_mediator_order"), ) if re.search(r"\b(?:least|most)\s+(?:certain|uncertain)\b", lower): paths = tuple(str(value) for value in frame.get("paths", ())) least_certain = paths[-1] if paths else "institutional" return HandlerResult( "rank_active_synthesis_uncertainty", "answered", (("source", source), ("endpoint", right)), (("least_certain_path", least_certain),), ( SemanticClause(f"The {least_certain} link", "be", complement="the least certain of the three current paths"), SemanticClause("It", "contain", object_value="the greatest number of mediators, institutional contingencies, feedback effects, and competing causes"), SemanticClause("That ranking", "compare", object_value="structural uncertainty within this hypothesis; it does not establish the other links as facts"), ), (("source", "active_mediated_causal_schema"),), ("restore_synthesis", "count_mediating_relations", "rank_structural_uncertainty", "retain_epistemic_scope"), ) return None
def _active_topic_evidence_result( self, state: TypedDiscourseState, text: str, ) -> HandlerResult | None: """Ground evidence follow-ups in the restored topic, not request words.""" topic = clean(state.active_topic or "") if "active_topic_evidence" in self._k102_ablations or not topic or not re.search( r"\b(?:evidence|support|supports|substantiate|substantiates|source|sources)\b", clean(text), re.IGNORECASE, ): return None rows = tuple( row for row in self._topic_source_rows(topic, limit=96) if clean(row.get("fact", "")) and not clean(row.get("fact", "")).rstrip().endswith("?") ) if not rows: return HandlerResult( "clarify_active_topic_evidence", "clarification", (("topic", topic),), (("missing_role", "an authenticated source proposition about the active topic"),), (SemanticClause("I", "need", object_value=f"an authenticated source proposition about {topic} before treating the requested support as evidence"),), (("source", "active_topic_exact_source_lookup_empty"),), ("restore_active_topic", "require_exact_topic_source", "preserve_epistemic_boundary"), ) selected = rows[:2] clauses = tuple( SemanticClause( "The cited source" if len(selected) == 1 else f"Cited source {index}", "state", object_value=clean(row["fact"]).rstrip(".?!"), ) for index, row in enumerate(selected, start=1) ) evidence = tuple( (str(row.get("source_document_sha256", row.get("source_document", ""))), str(row.get("text_sha256", ""))) for row in selected ) return HandlerResult( "ground_active_topic_evidence", "answered", (("topic", topic),), (("source_rows", len(selected)),), clauses, evidence, ( "restore_active_topic", "resolve_deictic_topic_reference", "require_exact_topic_posting", "rank_declarative_source_propositions", "release_authenticated_evidence_at_malkuth", ), )
def _revise_causal_result(self, session_id: str, state: TypedDiscourseState, text: str) -> HandlerResult | None: match = self._CAUSAL_CORRECTION.match(clean(text)) if match is None: return None subject, old_surface, new_surface, cause_surface = (_trim(match.group(index)) for index in range(1, 5)) old_atom_candidates = [] discourse = self._graph_discourse(session_id) old_terms = set(tokens(old_surface)) for fact in reversed(discourse.facts): if not fact.active or fact.atom.subject.casefold() != subject.casefold(): continue if set(tokens(fact.atom.predicate + " " + fact.atom.object_value)) & old_terms: old_atom_candidates.append(fact) old_fact = old_atom_candidates[0] if old_atom_candidates else None downstream = [] if old_fact is not None: downstream_ids = [right for left, right in discourse.causal_edges if left == old_fact.state_id] downstream = [value for value in discourse.facts if value.active and value.state_id in downstream_ids] old_fact.active = False session = self._session(session_id) if session.workspace.is_visible(old_fact.state_id): session.workspace.retract(old_fact.state_id, reason="k102_causal_correction") discourse.causal_edges = [ edge for edge in discourse.causal_edges if old_fact.state_id not in edge ] new_effect = self.graph_transducer._simple_clause(f"{subject} {new_surface}") cause = self.graph_transducer._simple_clause(cause_surface) if new_effect is None or cause is None: return HandlerResult( "clarify_causal_revision", "clarification", (("subject", subject),), (("unresolved", "replacement cause or effect"),), (SemanticClause("I", "need", object_value="the replacement cause and the event it produced"),), (("source", "typed_causal_revision_parser"),), ("retain_negated_commitment", "identify_unresolved_replacement_role"), ) self._assert_causal(session_id, (cause, new_effect)) for fact in downstream: self._assert_causal(session_id, (new_effect, fact.atom)) retracted_identity = self._atom_identity(old_fact.atom.as_dict()) if old_fact else None revised_edges = [ value for value in state.causal_edges if retracted_identity is None or ( self._atom_identity(value["cause"]) != retracted_identity and self._atom_identity(value["effect"]) != retracted_identity ) ] revised_edges.append({"cause": cause.as_dict(), "effect": new_effect.as_dict(), "active": True}) revised_edges.extend( {"cause": new_effect.as_dict(), "effect": fact.atom.as_dict(), "active": True} for fact in downstream ) current = _K102_TURN.get() if current is not None: current.audit.update({ "recognized": True, "discourse_operation": "causal_revision", "retracted_atom": old_fact.atom.as_dict() if old_fact else None, "replacement_cause": cause.as_dict(), "replacement_effect": new_effect.as_dict(), "revised_causal_edges": revised_edges, }) chain = [cause, new_effect, *(value.atom for value in downstream)] return HandlerResult( "revise_causal_discourse", "answered", (("subject", subject),), (("retracted", old_fact.atom.as_dict() if old_fact else None), ("replacement_edges", max(1, len(chain) - 1))), tuple(self._past_atom_clause(value) for value in chain), (("source", "conversation_local_causal_revision"),), ("resolve_corrected_subject", "retract_superseded_cause", "preserve_unaffected_downstream_effect", "bind_replacement_path", "propagate_revision"), )
def _causal_query_result(self, state: TypedDiscourseState, text: str) -> HandlerResult | None: if not state.causal_edges: return None lower = clean(text).casefold() if not ( re.match(r"^why\b", lower) or re.search(r"\b(?:whole\s+sequence|causal\s+order|what\s+(?:now\s+)?explains?)\b", lower) ): return None chain = self._edge_chain(state, text) if len(chain) < 2: return None atoms = tuple(self._atom_from_mapping(value) for value in chain) return HandlerResult( "query_persistent_causal_discourse", "answered", (("path_length", len(atoms)),), (("atoms", [value.as_dict() for value in atoms]),), tuple(self._past_atom_clause(value) for value in atoms), (("source", "persistent_typed_causal_discourse"),), ("restore_causal_edges", "select_requested_downstream_effect", "traverse_active_reverse_edges", "release_revised_chain"), )
def _tool_continuity_result(self, state: TypedDiscourseState, text: str) -> HandlerResult | None: prior = state.last_tool lower = clean(text).casefold() if not prior or not re.search(r"\bcompare\b", lower) or not re.search(r"\b(?:strongest|largest|greatest|maximum)\b", lower): return None backend = self.tool_backend expert = getattr(backend, "experts", {}).get(prior.get("expert_id")) if backend else None field_name = str(prior.get("field") or "") if expert is None or not field_name: return None specification = next((value for value in expert.schema.fields if value.name == field_name), None) if specification is None or specification.kind not in {"integer", "number"}: return None previous_row = next(( value for value in expert.rows if str(value.get("event_id") or value.get("country_name") or "") == str(prior.get("row_key")) ), None) if previous_row is None: return None strongest = max(expert.rows, key=lambda value: float(value[field_name])) previous_value = float(previous_row[field_name]) strongest_value = float(strongest[field_name]) difference = abs(strongest_value - previous_value) display = lambda value: str(int(value)) if float(value).is_integer() else format(float(value), ".12g") strongest_key = str(strongest.get("event_id") or strongest.get("country_name") or "registered row") previous_key = str(prior["row_key"]) values = [display(previous_value), display(strongest_value), display(difference)] audit = { "schema_version": SCHEMA, "operation": "compare", "expert_id": expert.schema.expert_id, "row_key": previous_key, "comparison_row_key": strongest_key, "field": field_name, "values": values, "read_only": True, "typed_arguments_bound": True, "goal_postconditions_satisfied": True, "source_row_restored_from_discourse": True, "traditional_language_model": False, } return HandlerResult( "bounded_agentic_tool", "answered", (("operation", "compare"), ("expert_id", expert.schema.expert_id), ("field", field_name)), (("values", values), ("difference", values[2])), ( SemanticClause(f"The {field_name} for {previous_key}", "be", complement=values[0]), SemanticClause(f"The maximum {field_name}", "be", complement=values[1], qualifiers=(("at", strongest_key),)), SemanticClause(f"The absolute {field_name} difference", "be", complement=values[2]), ), (("expert_id", expert.schema.expert_id),), ("restore_typed_tool_observation", "select_registered_numeric_field", "execute_read_only_extremum", "compute_typed_difference", "verify_goal_postconditions"), tool_audit=audit, )
def _discourse_result(self, session_id: str, text: str) -> HandlerResult | None: current = _K102_TURN.get() if current is None: return None state = current.state if self._identity_request(text): current.audit.update({"recognized": True, "discourse_operation": "situated_identity"}) return self._constitutional_identity_result(current.constitution) correction = self._revise_causal_result(session_id, state, text) if correction is not None: return correction causal_query = self._causal_query_result(state, text) if causal_query is not None: current.audit.update({"recognized": True, "discourse_operation": "persistent_causal_query"}) return causal_query tool = self._tool_continuity_result(state, text) if tool is not None: current.audit.update({"recognized": True, "discourse_operation": "tool_observation_comparison"}) return tool shift = self._SHIFT_COMPARE.match(clean(text)) if shift: left, right = (_trim(shift.group(index)) for index in (1, 2)) result = self._situated_result(f"Compare {left} and {right}.") if result is not None: current.audit.update({ "recognized": True, "discourse_operation": "suspend_topic_and_compare", "left": left, "right": right, }) return HandlerResult( "discourse_topic_shift_comparison", result.status, result.arguments, result.result, result.clauses, result.evidence, ("suspend_active_topic", *result.computation_trace, "bind_temporary_comparison_topic"), tool_audit=result.tool_audit, memory_audit=result.memory_audit, ) returning = self._RETURN_TOPIC.match(clean(text)) if returning: target = state.topic_stack[-1] if state.topic_stack else state.active_topic if target: current.audit.update({"recognized": True, "discourse_operation": "restore_topic", "topic": target}) return HandlerResult( "restore_prior_topic", "answered", (("topic", target),), (("restored", True),), ( SemanticClause("Our earlier topic", "be", complement=target), SemanticClause("We", "examine", object_value=f"{target} through its active questions and relations", tense="past"), ), (("source", "typed_topic_stack"),), ("read_topic_stack", "pop_suspended_topic", "restore_discourse_focus"), ) topic = self._TOPIC_INVITATION.match(clean(text)) if topic: subject = _trim(topic.group(1)) current.audit.update({"recognized": True, "discourse_operation": "bind_topic", "topic": subject}) return self._topic_result(subject) paper = self._paper_result(state, text) if paper is not None: current.audit.update({"recognized": True, "discourse_operation": paper.operation}) return paper synthesis = self._synthesis_result(state, text) if synthesis is not None: current.audit.update({"recognized": True, "discourse_operation": synthesis.operation}) return synthesis topic_evidence = self._active_topic_evidence_result(state, text) if topic_evidence is not None: current.audit.update({ "recognized": True, "discourse_operation": topic_evidence.operation, "topic": state.active_topic, }) return topic_evidence comparison = self._comparison_followup(state, text) if comparison is not None: current.audit.update({"recognized": True, "discourse_operation": comparison.operation}) return comparison decision = self._decision_followup(state, text) if decision is not None: current.audit.update({"recognized": True, "discourse_operation": decision.operation}) return decision return None
@staticmethod def _resolve_topic_anaphor(state: TypedDiscourseState, text: str) -> tuple[str, str | None]: topic = clean(state.active_topic or "") value = clean(text) if not topic: return value, None patterns = ( r"\b(?:it|its)\b", r"\b(?:this|that)\s+(?:topic|subject|process|system|idea|claim)\b", ) for pattern in patterns: if re.search(pattern, value, re.IGNORECASE): return re.sub(pattern, topic, value, count=1, flags=re.IGNORECASE), topic return value, None
@staticmethod def _with_topic_resolution( result: HandlerResult, *, topic: str, original_text: str, ) -> HandlerResult: return HandlerResult( result.operation, result.status, (*result.arguments, ("resolved_topic_anaphor", topic)), result.result, result.clauses, (*result.evidence, ("topic_resolution", digest({"topic": topic, "surface": clean(original_text)}))), ("restore_active_topic", "resolve_deictic_topic_reference", *result.computation_trace), tool_audit=result.tool_audit, memory_audit=result.memory_audit, )
def _repair_graph_assertion_surface( self, result: HandlerResult | None, surface: str, ) -> HandlerResult | None: if ( result is None or result.operation != "assert_graph_fact" or "finite_number_recovery" in self._k102_ablations ): return result atom = self.graph_transducer._simple_clause(surface) finite = self.graph_transducer.finite_surface(surface, atom) if atom is not None else None if atom is None or finite is None: return result lemma, _listed = self.dictionary.lemma(finite) exceptions = self.dictionary.reverse_exceptions.get(lemma, ()) is_past = bool( finite in exceptions or finite.endswith(("ed", "ied", "en")) or re.search(r"\b(?:did|was|were|had)\b", clean(surface), re.IGNORECASE) ) clause = self._atom_clause(atom) if is_past and atom.predicate not in {"is_a", "property", "be"}: clause = replace(clause, tense="past") return HandlerResult( result.operation, result.status, result.arguments, result.result, (clause,), result.evidence, (*result.computation_trace, "recover_finite_surface_tense_and_nominal_number"), tool_audit=result.tool_audit, memory_audit=result.memory_audit, )
def _handle_evidence(self, text: str, context: Mapping[str, Any]) -> HandlerResult | None: current = _K102_TURN.get() session_id = current.session_id if current else str(context.get("k102_session_id", "")) result = self._discourse_result(session_id, text) if session_id else None if result is not None: return result resolved, topic = self._resolve_topic_anaphor(current.state, text) if current else (text, None) inherited = self._repair_graph_assertion_surface( super()._handle_evidence(resolved, context), resolved, ) if inherited is not None and topic is not None: current.audit.update({ "recognized": True, "discourse_operation": "resolve_topic_anaphor", "topic": topic, "resolved_surface_sha256": hashlib.sha256(resolved.encode("utf-8")).hexdigest(), }) return self._with_topic_resolution(inherited, topic=topic, original_text=text) return inherited
def _handle_event(self, session_id: str, text: str, turn_id: str) -> HandlerResult | None: result = self._discourse_result(session_id, text) if result is not None: return result current = _K102_TURN.get() resolved, topic = self._resolve_topic_anaphor(current.state, text) if current else (text, None) inherited = self._repair_graph_assertion_surface( super()._handle_event(session_id, resolved, turn_id), resolved, ) if inherited is not None and topic is not None: current.audit.update({ "recognized": True, "discourse_operation": "resolve_topic_anaphor", "topic": topic, "resolved_surface_sha256": hashlib.sha256(resolved.encode("utf-8")).hexdigest(), }) return self._with_topic_resolution(inherited, topic=topic, original_text=text) return inherited
def _handle_graph(self, session_id: str, graph: Any) -> HandlerResult | None: result = super()._handle_graph(session_id, graph) if result is None or result.operation != "assert_graph_fact": return result current = _K102_TURN.get() surface = clean(current.input_surface) if current else "" return self._repair_graph_assertion_surface(result, surface) if surface else result
def _event_capability_family(self, text: str) -> tuple[str, ...]: lower = clean(text).casefold() if ( self._TOPIC_INVITATION.match(clean(text)) or self._RETURN_TOPIC.match(clean(text)) or self._SHIFT_COMPARE.match(clean(text)) or self._PAPER_START.match(clean(text)) or self._SYNTHESIS_START.match(clean(text)) or self._CAUSAL_CORRECTION.match(clean(text)) or re.search(r"\b(?:thesis|section|objection|conclusion|concern|(?:one|1)\s+sentence|earlier\s+topic)\b", lower) ): return ("linguistic", "synthesis", "epistemic", "contrast", "causal", "mechanism", "tool_router", "dataset", "provenance") return super()._event_capability_family(text)
def _record_parent_state( self, state: TypedDiscourseState, text: str, output: Mapping[str, Any], audit: Mapping[str, Any], ) -> None: operation = str(output.get("operation", "")) arguments = self._proof_arguments(output) clauses = self._proof_clauses(output) if operation in {"relational_lexical_comparison", "discourse_topic_shift_comparison"}: left, right = clean(arguments.get("left", audit.get("left", ""))), clean(arguments.get("right", audit.get("right", ""))) complements = [clean(value.get("complement", "")) for value in clauses if value.get("complement")] if left and right: state.comparison = { "left": left, "right": right, "left_definition": complements[0] if complements else "the first grounded concept", "right_definition": complements[1] if len(complements) > 1 else "the second grounded concept", } self._push_topic(state, f"comparison of {left} and {right}") elif operation == "conversational_decision_frame": question = clean(arguments.get("decision", text)) state.decision = {"question": question, "concerns": []} self._push_topic(state, question) elif operation == "bind_decision_constraint" and state.decision: result = {str(key): value for key, value in (output.get("computation_proof", {}) or {}).get("result", ())} concern = clean(result.get("constraint", "")) if concern and concern not in state.decision.setdefault("concerns", []): state.decision["concerns"].append(concern) elif operation == "conversational_topic_invitation": topic = clean(arguments.get("topic", audit.get("topic", ""))) if topic: self._push_topic(state, topic) elif operation == "restore_prior_topic": target = clean(audit.get("topic", "")) if target: if state.active_topic and state.active_topic.casefold().startswith("comparison of "): state.comparison = None if state.topic_stack and state.topic_stack[-1].casefold() == target.casefold(): state.topic_stack.pop() state.active_topic = target elif operation == "initialize_rhetorical_artifact": claim = clean(arguments.get("claim", "")) state.paper = {"claim": claim, "revision": 0} if claim: self._push_topic(state, claim) elif operation in {"construct_rhetorical_artifact", "revise_rhetorical_objection"} and state.paper: state.paper["revision"] = int(state.paper.get("revision", 0)) + 1 result = {str(key): value for key, value in (output.get("computation_proof", {}) or {}).get("result", ())} for key in ("sections", "objection", "conclusion"): if key in result: state.paper[key] = result[key] elif operation == "construct_mediated_cross_domain_synthesis": state.synthesis = { "source": clean(arguments.get("source", "")), "left": clean(arguments.get("endpoint_left", "")), "right": clean(arguments.get("endpoint_right", "")), "epistemic_status": "conditional_hypothesis", } self._push_topic(state, f"effects of {state.synthesis['source']}") elif operation == "decompose_active_cross_domain_synthesis" and state.synthesis: result = {str(key): value for key, value in (output.get("computation_proof", {}) or {}).get("result", ())} paths = [clean(value) for value in result.get("paths", ()) if clean(value)] if paths: state.synthesis["paths"] = paths elif operation == "compose_causal_graph": cause, effect = arguments.get("cause"), arguments.get("effect") if isinstance(cause, Mapping) and isinstance(effect, Mapping): edge = {"cause": dict(cause), "effect": dict(effect), "active": True} identity = (self._atom_identity(edge["cause"]), self._atom_identity(edge["effect"])) if not any( (self._atom_identity(value["cause"]), self._atom_identity(value["effect"])) == identity for value in state.causal_edges ): state.causal_edges.append(edge) elif operation == "revise_causal_discourse" and audit.get("revised_causal_edges"): state.causal_edges = [dict(value) for value in audit["revised_causal_edges"]] tool = output.get("tool_audit") or {} if output.get("status") == "answered" and tool.get("expert_id") and tool.get("row_key"): state.last_tool = { "expert_id": str(tool["expert_id"]), "row_key": str(tool["row_key"]), "field": None if tool.get("field") is None else str(tool["field"]), "values": [str(value) for value in tool.get("values", ())], "operation": str(tool.get("operation", operation)), }
def _bind_discourse_event( self, session_id: str, output: Mapping[str, Any], state: TypedDiscourseState, journal: Mapping[str, Any], ) -> tuple[str, Mapping[str, Any]]: situation = "typed_discourse:" + "+".join(state.active_frame_names() or ("open",)) turn_id = str(output.get("turn_id") or ("k102-" + str(journal["event_sha256"])[:20])) memory_id = self._bind_memory( session_id, turn_id + "-k102-" + str(journal["sequence"]), { "situation": situation, "goal": state.active_topic or "sustain situated conversation", "transition": str(output.get("operation", "discourse_transition")), "action": str(output.get("status", "unknown")), "result": state.state_sha256, "field": ",".join(state.active_frame_names()) or "open_discourse", "status": "verified_typed_discourse_state", "verifier": str(journal["event_sha256"]), }, bank="episodic", source="k102_typed_discourse_event", ) return memory_id, self.substrate.cycle_once()
def answer( self, session_id: str, text: str, context: Mapping[str, Any] | None = None, *, system_prompt: str | None = None, **kwargs: Any, ) -> dict[str, Any]: state, recovery = self.discourse_journal.load(session_id) previous_state_sha = ZERO_SHA256 if not recovery["recovered"] else state.state_sha256 profile = compile_identity_profile(system_prompt or self.default_system_prompt) constitution = compile_situated_constitution(profile) state.constitution_sha256 = constitution.constitution_sha256 local_context = dict(context or {}) local_context["k102_session_id"] = session_id local_context["native_situated_identity_constitution"] = constitution.routing_context() local_context["typed_discourse_state"] = { "state_sha256": state.state_sha256, "active_topic": state.active_topic, "active_frames": list(state.active_frame_names()), "turn_index": state.turn_index, } current = _TurnContext(session_id, state, constitution, clean(text)) token = _K102_TURN.set(current) try: if self._k102_bound_constitutions.get(session_id) != constitution.constitution_sha256: try: self._bind_memory( session_id, "k102-constitution-" + constitution.constitution_sha256[:20], { "situation": "native_situated_identity_constitution", "goal": constitution.purpose, "transition": "maintain_self_across_situated_discourse_change", "action": constitution.agency_contract, "result": constitution.self_name, "warrant": constitution.partner_relation, "status": "constitutional_identity_invariant", "verifier": constitution.constitution_sha256, }, bank="procedural", source="k102_situated_identity_constitution", ) except ValueError as exc: if "event_key already bound to another event" not in str(exc): raise self._k102_bound_constitutions[session_id] = constitution.constitution_sha256 output = super().answer( session_id, text, local_context, system_prompt=system_prompt, **kwargs, ) self._record_parent_state(state, text, output, current.audit) state.turn_index += 1 state.last_operation = str(output.get("operation", "")) state.last_response_sha256 = hashlib.sha256(str(output.get("response", "")).encode("utf-8")).hexdigest() state.constitution_sha256 = constitution.constitution_sha256 proof_sha = str((output.get("computation_proof") or {}).get("proof_sha256", "")) journal = self.discourse_journal.append( session_id, text=text, operation=str(output.get("operation", "")), status=str(output.get("status", "")), previous_state_sha256=previous_state_sha, state=state, proof_sha256=proof_sha, ) memory_id, cycle = self._bind_discourse_event(session_id, output, state, journal) spine_record = self._tree_record(session_id, str(output.get("turn_id", ""))) spine = ( spine_record.get("dual_rail_contract", {}) .get("stabilizing_spine", {}) .get("stage5k102:spine:situated_identity_discourse", {}) ) finally: _K102_TURN.reset(token) output["typed_discourse_workspace"] = { "schema_version": SCHEMA, "lineage_sha256": self._k102_lineage_sha256, "development_source": "opened_k102_long_horizon_failure_probe", "prospective_claim": False, "state_sha256": state.state_sha256, "turn_index": state.turn_index, "active_topic": state.active_topic, "topic_stack_depth": len(state.topic_stack), "active_frames": list(state.active_frame_names()), "journal": journal, "recovery": recovery, "opaque_hrr_memory_id": memory_id, "hrr_cycle": cycle, "bound_to_stabilizing_spine": ( spine.get("constitution_sha256") == constitution.constitution_sha256 and spine.get("discourse_state_sha256") == state.state_sha256 ), "pre_malkuth_discourse_payload_unbinds": 0, "audit": dict(current.audit or {"recognized": False}), "traditional_language_model": False, "transformer": False, "pretrained_embedding_encoder": False, "autoregressive_carrier": False, "model_calls": 0, "gradient_steps": 0, } output["situated_identity_constitution"] = { "schema_version": SCHEMA, "identity": constitution.self_name, "profile_sha256": constitution.profile_sha256, "constitution_sha256": constitution.constitution_sha256, "constitutional_roles": 11, "identity_is_typed_invariant_not_persona_overlay": True, "prompt_is_human_readable_serialization_not_runtime_preamble": True, "available_to_specialist_routing": True, "persistent_procedural_binding": True, "bound_to_stabilizing_spine": spine.get("constitution_sha256") == constitution.constitution_sha256, "raw_prompt_prepended_to_user_utterance": False, "situated_state_changes_without_redefining_self": True, "user_retains_goal_and_consequential_authority": True, } output["runtime"]["typed_discourse_model_calls"] = 0 output["runtime"]["typed_discourse_gradient_steps"] = 0 output["runtime"]["typed_discourse_journal_full_scans"] = 0 output["runtime"]["situated_identity_model_calls"] = 0 output["schema_version"] = SCHEMA output["turn_manifest_sha256"] = digest(output) return output
__all__ = [ "IndexedTypedDiscourseJournal", "K102_SYSTEM_PROMPT", "PersistentTypedDiscourseAgent", "SituatedIdentityConstitution", "TypedDiscourseState", "compile_situated_constitution",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228#!/usr/bin/env python3"""K104 successor for the two ingress classes exposed prospectively by K103.
K102 and the failed one-shot K103 evidence remain immutable. This successoradds no reasoning cell, language model, embedding encoder, or generator. Itonly maps direct rhetorical imperatives onto the existing artifact operatorand gates authoritative-science requests by exact referent-bearing sourceevidence before answer or abstention."""from __future__ import annotations
import hashlibfrom pathlib import Pathimport refrom typing import Any, Mapping, Sequence
from stage5k15_native_mixed_agent import HandlerResult, SemanticClause, clean, digestfrom stage5k102_persistent_typed_discourse_agent import ( IndexedTypedDiscourseJournal, PersistentTypedDiscourseAgent, TypedDiscourseState, _K102_TURN, _trim,)
SCHEMA = "oracle-stage5k104-relational-ingress-equivalence-agent-v1"
class RelationalIngressEquivalenceAgent(PersistentTypedDiscourseAgent): """K102 plus generalized speech-act and epistemic-ingress equivalence."""
_DIRECT_RHETORICAL = re.compile( r"^(?:please\s+)?(outline|structure|plan|draft)\s+(a|an|the)\s+" r"(paper|essay|article)\s+(arguing\s+that|about|on)\s+(.+?)[?.!]*$", re.IGNORECASE, ) _AUTHORITATIVE_SCIENCE = re.compile( r"^(?:please\s+)?(?:give|provide|state|explain|describe)(?:\s+me)?\s+" r"(?:the\s+)?(?:(?:accepted|established|recognized)\s+)?" r"(?:scientific\s+)(definition|mechanism|account|explanation)\s+" # Longest determiner first: otherwise the ``a`` alternative consumes # the first character of ``an`` and corrupts the referent boundary. r"(?:of|for)\s+(?:the|an|a)?\s*(.+?)[?.!]*$", re.IGNORECASE, )
def __init__( self, *args: Any, discourse_journal_path: Path | None = None, k104_ablations: Sequence[str] = (), **kwargs: Any, ) -> None: substrate_path = Path(args[5] if len(args) >= 6 else kwargs["substrate_path"]) self._k104_ablations = frozenset(clean(value).casefold() for value in k104_ablations) journal_path = discourse_journal_path or substrate_path.with_suffix(".k104.discourse.sqlite3") super().__init__(*args, discourse_journal_path=journal_path, **kwargs) # The successor journal is bound to the successor implementation, # rather than silently inheriting K102's module identity. self.discourse_journal = IndexedTypedDiscourseJournal( journal_path, source_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), ) self._k104_lineage_sha256 = digest({ "schema_version": SCHEMA, "parent_lineage_sha256": self._k102_lineage_sha256, "opened_failure_source": "stage5k103_untouched_phase_transition_report_v1", "repairs": [ "direct_and_periphrastic_rhetorical_imperative_equivalence", "authoritative_scientific_exact_referent_source_gate", "unsupported_scientific_referent_abstention", ], })
@staticmethod def _exact_referent_present(referent: str, fact: str) -> bool: normalized_referent = " ".join(re.findall(r"[a-z0-9]+", clean(referent).casefold())) normalized_fact = " ".join(re.findall(r"[a-z0-9]+", clean(fact).casefold())) return bool(normalized_referent and re.search( rf"(?:^|\s){re.escape(normalized_referent)}(?:\s|$)", normalized_fact, ))
def _scientific_ingress_result(self, text: str) -> HandlerResult | None: match = self._AUTHORITATIVE_SCIENCE.match(clean(text)) if match is None: return None relation, referent = match.group(1).casefold(), _trim(match.group(2)) if "authoritative_scientific_referent_gate" in self._k104_ablations: return None terms = tuple(dict.fromkeys(re.findall(r"[a-z0-9]+", referent.casefold()))) rows = () if terms: query = " AND ".join(f'"{term}"' for term in terms) rows = self.information_source_expert.connection.execute( "SELECT text_sha256, fact, source_document, source_document_sha256, " "domain_id, license_note, source_split, bm25(source_rows) " "FROM source_rows WHERE source_rows MATCH ? ORDER BY bm25(source_rows) LIMIT 128", (query,), ).fetchall() authoritative = [] for row in rows: source, domain, fact = str(row[2]), str(row[4]), clean(row[1]) admitted_authority = source.startswith("openstax/") or domain in { "life_health", "physical_engineering", "earth_space", "social_behavioral", "governance_law", "economics_organization", } if ( admitted_authority and self._exact_referent_present(referent, fact) and not fact.rstrip().endswith("?") ): authoritative.append(row) current = _K102_TURN.get() if current is not None: current.audit.update({ "recognized": True, "discourse_operation": "authoritative_scientific_referent_gate", "requested_relation": relation, "referent": referent, "exact_authoritative_rows": len(authoritative), }) if not authoritative: return self._abstention( "unsupported_scientific_referent", f"an established scientific {relation} for {referent}", "exact_authoritative_referent_evidence_absent", ) row = authoritative[0] fact = _trim(row[1]) return HandlerResult( "ground_authoritative_scientific_relation", "answered", (("relation", relation), ("referent", referent)), (("source_rows", 1),), ( SemanticClause( f"The authenticated source on {referent}", "state", object_value=fact, ), ), ((str(row[3]), str(row[0])),), ( "recognize_authoritative_scientific_request", "bind_complete_multiword_referent", "require_exact_referent_in_authenticated_source", "release_supported_relation_at_malkuth", ), tool_audit={ "tool": "k104_exact_scientific_referent_gate", "source_document": str(row[2]), "license_note": str(row[5]), "read_only": True, "traditional_language_model": False, }, )
def _paper_result(self, state: TypedDiscourseState, text: str) -> HandlerResult | None: direct = self._DIRECT_RHETORICAL.match(clean(text)) if direct is not None and "direct_rhetorical_equivalence" not in self._k104_ablations: verb, article, genre, relation, claim = ( _trim(direct.group(index)) for index in range(1, 6) ) canonical = f"Help me {verb} {article} {genre} {relation} {claim}." result = super()._paper_result(state, canonical) current = _K102_TURN.get() if current is not None: current.audit.update({ "recognized": result is not None, "discourse_operation": "direct_rhetorical_equivalence", "canonical_surface_sha256": hashlib.sha256(canonical.encode("utf-8")).hexdigest(), "meaning_preserved": True, }) if result is not None: return HandlerResult( result.operation, result.status, result.arguments, result.result, result.clauses, result.evidence, ( "recognize_direct_rhetorical_imperative", "commute_politeness_periphrasis_without_changing_roles", *result.computation_trace, ), tool_audit=result.tool_audit, memory_audit=result.memory_audit, ) return super()._paper_result(state, text)
def _handle_evidence(self, text: str, context: Mapping[str, Any]) -> HandlerResult | None: scientific = self._scientific_ingress_result(text) return scientific if scientific is not None else super()._handle_evidence(text, context)
def _handle_event(self, session_id: str, text: str, turn_id: str) -> HandlerResult | None: scientific = self._scientific_ingress_result(text) return scientific if scientific is not None else super()._handle_event(session_id, text, turn_id)
def _event_capability_family(self, text: str) -> tuple[str, ...]: if self._DIRECT_RHETORICAL.match(clean(text)) or self._AUTHORITATIVE_SCIENCE.match(clean(text)): return ( "linguistic", "synthesis", "epistemic", "contrast", "causal", "mechanism", "tool_router", "dataset", "provenance", ) return super()._event_capability_family(text)
def answer(self, *args: Any, **kwargs: Any) -> dict[str, Any]: output = super().answer(*args, **kwargs) audit = (output.get("typed_discourse_workspace") or {}).get("audit") or {} output["relational_ingress_equivalence"] = { "schema_version": SCHEMA, "lineage_sha256": self._k104_lineage_sha256, "opened_failure_source": "immutable_k103_one_shot_failure", "direct_rhetorical_equivalence_activated": audit.get("discourse_operation") == "direct_rhetorical_equivalence", "scientific_referent_gate_activated": audit.get("discourse_operation") == "authoritative_scientific_referent_gate", "exact_authoritative_rows": int(audit.get("exact_authoritative_rows", 0)), "traditional_language_model": False, "transformer": False, "pretrained_embedding_encoder": False, "autoregressive_carrier": False, "model_calls": 0, "gradient_steps": 0, } output["runtime"].update({ "relational_ingress_equivalence_model_calls": 0, "relational_ingress_equivalence_gradient_steps": 0, }) output["turn_manifest_sha256"] = digest(output) return output
__all__ = ["RelationalIngressEquivalenceAgent", "SCHEMA"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127#!/usr/bin/env python3"""K108 universal terminal-proof projection successor.
K106 and the immutable K107 one-shot evidence remain untouched. K107prospectively confirmed scientific proof-ledger congruence, while an unrelatedcausal turn exposed the same telemetry mismatch outside the scientific gate.This successor applies the already causal rule universally: the publicknowledge ledger contains exactly those authenticated public rows referencedby the terminal typed proof, irrespective of upstream candidates."""from __future__ import annotations
import hashlibfrom pathlib import Pathfrom typing import Any, Sequence
from stage5k15_native_mixed_agent import clean, digestfrom stage5k102_persistent_typed_discourse_agent import IndexedTypedDiscourseJournalfrom stage5k106_terminal_proof_provenance_agent import TerminalProofProvenanceAgent
SCHEMA = "oracle-stage5k108-universal-terminal-proof-projection-agent-v1"
class UniversalTerminalProofProjectionAgent(TerminalProofProvenanceAgent): """Make terminal proof evidence authoritative for every public ledger."""
def __init__( self, *args: Any, discourse_journal_path: Path | None = None, k108_ablations: Sequence[str] = (), **kwargs: Any, ) -> None: substrate_path = Path(args[5] if len(args) >= 6 else kwargs["substrate_path"]) self._k108_ablations = frozenset(clean(value).casefold() for value in k108_ablations) journal_path = discourse_journal_path or substrate_path.with_suffix(".k108.discourse.sqlite3") super().__init__(*args, discourse_journal_path=journal_path, **kwargs) self.discourse_journal = IndexedTypedDiscourseJournal( journal_path, source_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), ) self._k108_lineage_sha256 = digest({ "schema_version": SCHEMA, "parent_lineage_sha256": self._k106_lineage_sha256, "opened_failure_source": "stage5k107_untouched_proof_congruence_report_v1", "repair": "universal_terminal_typed_proof_projection_to_public_knowledge_ledger", })
def _universal_projection(self, output: dict[str, Any]) -> dict[str, Any]: if "universal_terminal_proof_projection" in self._k108_ablations: return {"activated": False, "ablated": True} proof = output.get("computation_proof") or {} admitted_rows = [] seen = set() for pair in proof.get("evidence", ()): if not isinstance(pair, (list, tuple)) or len(pair) != 2: continue source_sha, text_sha = str(pair[0]), str(pair[1]) if len(source_sha) != 64 or len(text_sha) != 64 or text_sha in seen: continue row = self._source_row_for_proof_evidence(text_sha) if row is None or row["source_document_sha256"] != source_sha: continue admitted_rows.append(row); seen.add(text_sha) lattice = dict(output.get("knowledge_lattice") or {}) prior_rows = tuple(lattice.get("evidence_rows_admitted_to_proof") or ()) prior_admitted = bool(lattice.get("retrieval_admitted_to_proof")) admitted = bool(admitted_rows) lattice.update({ "candidate_retrieval_observed": bool(prior_rows), "candidate_rows_before_universal_projection": len(prior_rows), "candidate_admission_before_universal_projection": prior_admitted, "evidence_rows_admitted_to_proof": admitted_rows, "retrieval_admitted_to_proof": admitted, "retrieval_gate_reason": ( "terminal_typed_proof_contains_authenticated_public_source" if admitted else "terminal_typed_proof_contains_no_authenticated_public_source" ), "relational_provenance_reconciled": True, "terminal_proof_authoritative_for_admission": True, "universal_terminal_proof_projection": True, "terminal_proof_operation": str(output.get("operation", "")), "terminal_proof_status": str(output.get("status", "")), "terminal_proof_evidence_sha256s": [row["text_sha256"] for row in admitted_rows], }) output["knowledge_lattice"] = lattice return { "activated": True, "ablated": False, "operation": str(output.get("operation", "")), "status": str(output.get("status", "")), "candidate_admission_before": prior_admitted, "candidate_rows_before": len(prior_rows), "terminal_authenticated_rows": len(admitted_rows), "retrieval_admitted_to_proof": admitted, "projection_changed_admission": prior_admitted is not admitted, "proof_and_ledger_congruent": bool( admitted == bool(admitted_rows) and {row["text_sha256"] for row in admitted_rows} == seen ), }
def answer(self, *args: Any, **kwargs: Any) -> dict[str, Any]: output = super().answer(*args, **kwargs) projection = self._universal_projection(output) output["universal_terminal_proof_projection"] = { "schema_version": SCHEMA, "lineage_sha256": self._k108_lineage_sha256, "opened_failure_source": "immutable_k107_one_shot_failure", **projection, "traditional_language_model": False, "transformer": False, "pretrained_embedding_encoder": False, "autoregressive_carrier": False, "model_calls": 0, "gradient_steps": 0, } output["runtime"].update({ "universal_terminal_proof_projection_model_calls": 0, "universal_terminal_proof_projection_gradient_steps": 0, }) output["turn_manifest_sha256"] = digest(output) return output
__all__ = ["UniversalTerminalProofProjectionAgent", "SCHEMA"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229#!/usr/bin/env python3"""K115 explicit copular-definition equivalence over frozen K112.
The immutable K114 prospective failure showed that K112 could locate an exact,authoritative row and verify definition direction, yet reject ``X is theprocess of ...`` because its deliberately small morphological normalizationmapped ``process`` to ``proces`` before relation-cue comparison. Thissuccessor treats an exact referent followed by a copula and a finitedefinitional complement class as the definition relation itself. It containsno domain entities, answer text, language model, embedding model, or scan."""from __future__ import annotations
from dataclasses import replaceimport hashlibimport refrom pathlib import Pathfrom typing import Any, Mapping, Sequence
from stage5k15_native_mixed_agent import clean, digestfrom stage5k81_information_weighted_source_expert import termsfrom stage5j1_native_contextual_sense_lattice import WORDfrom stage5k112_relation_conditioned_source_agent import ( RelationConditionedSourceAgent, RelationRequest, SourceCertificate,)
SCHEMA = "oracle-stage5k115-copular-definition-equivalence-agent-v1"
DEFINITIONAL_COMPLEMENT_CLASSES = frozenset({ "act", "action", "activity", "approach", "condition", "concept", "doctrine", "event", "form", "framework", "idea", "means", "method", "entity", "operation", "orientation", "pattern", "phenomenon", "practice", "principle", "procedure", "process", "property", "relation", "rule", "state", "step", "steps", "system", "technique", "theory", "type", "way",})
NON_DEFINITIONAL_COMPLEMENT_MODIFIERS = frozenset({ "best", "commonly", "correct", "different", "important", "less", "more", "most", "not", "now", "only", "sometimes", "used",})
def _ordered_phrase(value: str) -> str: """Normalize surface tokens without erasing repetition or order.""" normalized = [] for raw in WORD.findall(str(value)): token = raw.casefold().replace("’", "'") if token.endswith("'s") and len(token) > 2: token = token[:-2] normalized.append(token) return " ".join(normalized)
class CopularDefinitionEquivalenceAgent(RelationConditionedSourceAgent): """Admit explicit copular definitions missed by K112 normalization."""
def __init__(self, *args: Any, k115_ablations: Sequence[str] = (), **kwargs: Any) -> None: self._k115_ablations = frozenset(clean(value).casefold() for value in k115_ablations) super().__init__(*args, **kwargs) self._k115_lineage_sha256 = digest({ "schema_version": SCHEMA, "parent_lineage_sha256": self._k112_lineage_sha256, "preserved_failure_source": "immutable_stage5k114_untouched_relational_transition_report_v1", "repair": "exact_referent_copula_definitional_complement_equivalence", })
@classmethod def _relation_request(cls, text: str) -> RelationRequest | None: request = super()._relation_request(text) if request is None or request.relation != "definition": return request # K112's frozen optional-article alternation checks ``a`` before # ``an`` and can therefore consume only the first character of ``an``. # Reconstruct the definition referent from the original surface with # longest-article-first precedence. The request's already derived # content/referent terms remain valid and contain no answer knowledge. value = clean(text).rstrip(".?!") match = re.match( r"^(?:what\s+(?:is|are)|define)\s+(?:(?:an|the|a)\s+)?(.+)$", value, re.IGNORECASE, ) if match is None: return request referent = clean(match.group(1)) return replace(request, referent=referent) if referent else request
@staticmethod def _copular_definition_match(request: RelationRequest, fact: str) -> Mapping[str, Any] | None: if request.relation != "definition": return None normalized_fact = _ordered_phrase(fact) normalized_referent = _ordered_phrase(request.referent) if not normalized_referent: return None pattern = re.compile( rf"^(?:(?:a|an|the)\s+)?{re.escape(normalized_referent)}\s+" rf"(?P<copula>is|are|means|denotes|describes|refers\s+to)\s+" rf"(?:(?:a|an|the)\s+)?(?P<complement_phrase>[a-z-]+(?:\s+[a-z-]+){{0,3}})\b", ) match = pattern.search(normalized_fact) if match is None: return None phrase = match.group("complement_phrase").split() head_index = next( (index for index, value in enumerate(phrase) if value in DEFINITIONAL_COMPLEMENT_CLASSES), None, ) if head_index is None: return None modifiers = phrase[:head_index] if any(value in NON_DEFINITIONAL_COMPLEMENT_MODIFIERS for value in modifiers): return None return { "operator": "copular_definition", "copula": match.group("copula"), "complement_class": phrase[head_index], "complement_modifiers": modifiers, "exact_referent_prefix": True, }
def _copular_certificate( self, request: RelationRequest, parent: SourceCertificate, ) -> SourceCertificate | None: if request.relation != "definition": return None # Address with the preserved referent surface as well as variants. # K112's request lemmas are useful for broad relational matching but # intentionally lossy (for example ``process`` -> ``proces`` and # ``retailing`` -> ``retail``); exact copular definitions require the # original noun surface to remain available to FTS. referent_surfaces = tuple( value for value in terms(request.referent) if self.information_source_expert._fts_token(value) ) values = set(referent_surfaces) if not values: return None referent_expression = " AND ".join(f'"{value}"' for value in referent_surfaces) relation_expression = " OR ".join( f'"{value}"' for value in sorted(DEFINITIONAL_COMPLEMENT_CLASSES) ) expression = f"{referent_expression} AND ({relation_expression})" rows = self.information_source_expert.connection.execute( "SELECT text_sha256, fact, source_document, source_document_sha256, " "domain_id, license_note, source_split, bm25(source_rows) " "FROM source_rows WHERE source_rows MATCH ? ORDER BY bm25(source_rows) LIMIT 768", (expression,), ).fetchall() ranked = [] audits = [] for row in rows: fact = clean(row[1]) match = self._copular_definition_match(request, fact) noise, noise_reasons = self._row_noise(fact) source_name = str(row[2]) authority = 5.0 if source_name.startswith("openstax/") else 1.5 if source_name.startswith("gutenberg/") else 0.0 declarative = not fact.rstrip().endswith("?") and "multiple_choice_source" not in noise_reasons eligible = bool(match is not None and declarative and authority > 0) score = 20.0 + authority - noise + (2.0 if match and match["copula"] in {"is", "are"} else 0.0) audit = { "text_sha256": str(row[0]), "source_document": source_name, "eligible": eligible, "operator_match": match, "declarative": declarative, "authority": authority, "noise_reasons": list(noise_reasons), "score": score, } audits.append((score, float(row[7]), str(row[0]), audit)) if eligible: ranked.append((score, float(row[7]), str(row[0]), row, audit)) audits.sort(key=lambda value: (-value[0], value[1], value[2])) if not ranked: return None ranked.sort(key=lambda value: (-value[0], value[1], value[2])) best = ranked[0] row = best[3] selected = { "text_sha256": str(row[0]), "fact": clean(row[1]), "source_document": str(row[2]), "source_document_sha256": str(row[3]), "domain_id": str(row[4]), "license_note": str(row[5]), "source_split": str(row[6]), "admission_authority": "k115_copular_definition_equivalence", } runner = ranked[1][0] if len(ranked) > 1 else None return SourceCertificate( request=request, selected_row=selected, accepted=True, reason="copular_definition_equivalence_satisfied", selected_score=best[0], runner_up_score=runner, inspected_postings=len(rows), eligible_candidates=len(ranked), audit_candidates=tuple(value[3] for value in audits[:5]), )
def _certificate(self, request: RelationRequest) -> SourceCertificate: parent = super()._certificate(request) if "copular_definition_equivalence" in self._k115_ablations: return parent # An exact sentence-prefix copular definition is a stronger relation # certificate than an embedded mention admitted by K112's broad # lexical relation cues. Prefer it even when the parent found a weaker # candidate; other relation kinds remain completely unchanged. return self._copular_certificate(request, parent) or parent
def answer(self, *args: Any, **kwargs: Any) -> dict[str, Any]: output = super().answer(*args, **kwargs) certificate = output.get("relation_conditioned_source_certificate") or {} activated = certificate.get("reason") == "copular_definition_equivalence_satisfied" output["copular_definition_equivalence"] = { "schema_version": SCHEMA, "lineage_sha256": self._k115_lineage_sha256, "activated": activated, "ablated": "copular_definition_equivalence" in self._k115_ablations, "operator": "exact_referent_plus_copula_plus_definitional_complement_class", "definitional_complement_class_count": len(DEFINITIONAL_COMPLEMENT_CLASSES), "maximum_complement_modifiers": 3, "domain_entities_encoded": 0, "traditional_language_model": False, "transformer": False, "pretrained_embedding_encoder": False, "autoregressive_carrier": False, "model_calls": 0, "gradient_steps": 0, } output["runtime"].update({ "copular_definition_equivalence_model_calls": 0, "copular_definition_equivalence_gradient_steps": 0, }) output["turn_manifest_sha256"] = digest(output) return output
__all__ = ["CopularDefinitionEquivalenceAgent", "SCHEMA", "DEFINITIONAL_COMPLEMENT_CLASSES"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175#!/usr/bin/env python3"""K117 caller-context isolation over immutable K115/K116 evidence.
K116 established that K115's relation operator transfers to fresh definitions,but exposed an independent precedence defect on a causal assertion. K90 mayinsert a private retrieval sentinel below the outer answer boundary. K81 sawthat sentinel as though it were caller-supplied evidence and consequentlydemoted an already valid ``assert_causal`` graph to ``delegate``. Themisrouted ephemeral event then made deterministic restart replay correctlyreject the changed operation.
This successor separates caller context from internal carrier context. Atyped graph that consumes the utterance remains prior to private sentinels;genuine caller-supplied evidence, corpus records, and sensor streams retaintheir bounded rails. No domain words, answer strings, model, embeddingencoder, gradient update, or autoregressive carrier are introduced."""from __future__ import annotations
from collections.abc import Sequencefrom contextvars import ContextVarfrom typing import Any, Mapping
from stage5k15_native_mixed_agent import clean, digestfrom stage5k81_native_relational_construction_agent import _CONTEXT_KINDfrom stage5k102_persistent_typed_discourse_agent import K102FinitePredicateTransducerfrom stage5k115_copular_definition_equivalence_agent import ( CopularDefinitionEquivalenceAgent,)
SCHEMA = "oracle-stage5k117-caller-context-isolation-agent-v1"
_K117_CALLER_CONTEXT_KIND: ContextVar[str] = ContextVar( "k117_caller_context_kind", default="none",)_K117_ISOLATION_AUDIT: ContextVar[Mapping[str, Any] | None] = ContextVar( "k117_isolation_audit", default=None,)
def _caller_context_kind(context: Mapping[str, Any] | None) -> str: value = context or {} for key in ("evidence", "training_corpus", "sensor_stream"): payload = value.get(key) if isinstance(payload, Sequence) and not isinstance(payload, (str, bytes)) and payload: return key return "none"
class CallerContextIsolationTransducer(K102FinitePredicateTransducer): """Make graph precedence depend on the outer caller boundary."""
def analyze(self, text: str, discourse, *, known_frames=()): inherited_context_kind = _CONTEXT_KIND.get() caller_context_kind = _K117_CALLER_CONTEXT_KIND.get() ablated = "caller_context_isolation" in self.owner._k117_ablations
# Obtain the fully repaired inherited graph with context influence # suppressed only when context was introduced internally. This calls # through K102/K94/.../K81's MRO once and retains every later parser # repair. For genuine caller context the inherited behavior is exact. token = None if not ablated and caller_context_kind == "none" and inherited_context_kind != "none": token = _CONTEXT_KIND.set("none") try: graph = super().analyze(text, discourse, known_frames=known_frames) finally: if token is not None: _CONTEXT_KIND.reset(token)
_K117_ISOLATION_AUDIT.set({ "caller_context_kind": caller_context_kind, "inherited_context_kind": inherited_context_kind, "internal_context_isolated": token is not None, "ablated": ablated, "selected_speech_act": graph.speech_act, "typed_graph_consumes_utterance": bool(graph.consumes_as_graph), }) return graph
class CallerContextIsolationAgent(CopularDefinitionEquivalenceAgent): """Preserve K115 while preventing private carrier/context confusion."""
def __init__(self, *args: Any, k117_ablations: Sequence[str] = (), **kwargs: Any) -> None: self._k117_ablations = frozenset(clean(value).casefold() for value in k117_ablations) super().__init__(*args, **kwargs) self.graph_transducer = CallerContextIsolationTransducer( self, self.construction_head, ) self._k117_lineage_sha256 = digest({ "schema_version": SCHEMA, "parent_lineage_sha256": self._k115_lineage_sha256, "preserved_failure_source": ( "immutable_stage5k116_untouched_operator_transfer_report_v1" ), "repair": "outer_caller_context_distinct_from_internal_retrieval_carrier", })
def _handle_evidence(self, text: str, context: Mapping[str, Any]): evidence = context.get("evidence") private_carrier = bool( isinstance(evidence, Sequence) and not isinstance(evidence, (str, bytes)) and any( isinstance(value, Mapping) and str(value.get("answer_status", "")).startswith("k90_") for value in evidence ) ) graph = self._k76_current.get() typed_graph_prior = bool( _K117_CALLER_CONTEXT_KIND.get() == "none" and "caller_context_isolation" not in self._k117_ablations and private_carrier and graph is not None and graph.speech_act in self.DIRECT_ACTS and graph.consumes_as_graph ) if typed_graph_prior: audit = dict(_K117_ISOLATION_AUDIT.get() or {}) audit.update({ "private_carrier_detected": True, "private_carrier_bypassed_evidence_handler": True, "typed_graph_precedence_preserved": True, }) _K117_ISOLATION_AUDIT.set(audit) return None return super()._handle_evidence(text, context)
def answer( self, session_id: str, text: str, context: Mapping[str, Any] | None = None, **kwargs: Any, ) -> dict[str, Any]: caller_kind = _caller_context_kind(context) caller_token = _K117_CALLER_CONTEXT_KIND.set(caller_kind) audit_token = _K117_ISOLATION_AUDIT.set(None) try: output = super().answer(session_id, text, context, **kwargs) audit = dict(_K117_ISOLATION_AUDIT.get() or {}) finally: _K117_ISOLATION_AUDIT.reset(audit_token) _K117_CALLER_CONTEXT_KIND.reset(caller_token) output["caller_context_isolation"] = { "schema_version": SCHEMA, "lineage_sha256": self._k117_lineage_sha256, "development_source": "opened_immutable_k116_failure", "prospective_claim": False, "caller_context_kind": caller_kind, "ablated": "caller_context_isolation" in self._k117_ablations, "audit": audit, "private_retrieval_sentinel_is_caller_evidence": False, "genuine_caller_context_precedence_preserved": True, "domain_entities_encoded": 0, "traditional_language_model": False, "transformer": False, "pretrained_embedding_encoder": False, "autoregressive_carrier": False, "model_calls": 0, "gradient_steps": 0, } output["runtime"].update({ "caller_context_isolation_model_calls": 0, "caller_context_isolation_gradient_steps": 0, }) output["schema_version"] = SCHEMA output["turn_manifest_sha256"] = digest(output) return output
__all__ = ["CallerContextIsolationAgent", "CallerContextIsolationTransducer", "SCHEMA"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348#!/usr/bin/env python3"""Stage 5K11 proof-conditioned quadratic native inverse solver.
The solver chooses a complete construction coordinate in one global decision.It never predicts a next token. Candidate clauses are compiled from the typedcomputation proof, checked by the native forward analyzer, and represented asbinary one-hot variables in an auditable QUBO:
E(x) = sum_i u_i x_i + P (sum_i x_i - 1)^2
The unary semantic energy ``u_i`` is itself decomposed into frame, operator,role, alpha-equivalence, and minimal-chart-complexity terms. This initialwhole-construction QUBO is an exact verifier and a bridge to the laterfactorized role/slot/discourse QUBO; it already replaces serial surface searchwith a globally selected sentence-shaped object."""
from __future__ import annotations
import hashlibimport itertoolsfrom dataclasses import dataclassfrom typing import Any, Mapping, Sequence
import numpy as np
from stage5k3_language_adapter import LanguageAdapterfrom stage5k10_self_inverse_computation import ( NativeEnglishInverseGrammar, NativeRealization, RoundTripAudit, SelfInverseProof, digest,)
SCHEMA = "oracle-stage5k11-quadratic-inverse-solver-v1"CONSTRUCTION_VARIANTS = ( "frame_order", "nominals_before_prepositions", "prepositions_before_nominals",)
@dataclass(frozen=True)class QuadraticCandidate: candidate_id: str realization: NativeRealization round_trip: RoundTripAudit role_transformations: tuple[tuple[str, str], ...] preposition_choices: tuple[tuple[str, str], ...] energy_terms: tuple[tuple[str, float], ...]
@property def unary_energy(self) -> float: return float(sum(value for _, value in self.energy_terms))
def as_dict(self) -> dict[str, Any]: return { "candidate_id": self.candidate_id, "realization": self.realization.as_dict(), "round_trip": self.round_trip.as_dict(), "role_transformations": [ [role, hashlib.sha256(surface.casefold().encode("utf-8")).hexdigest()] for role, surface in self.role_transformations ], "preposition_choices": [list(value) for value in self.preposition_choices], "energy_terms": [list(value) for value in self.energy_terms], "unary_energy": self.unary_energy, }
@dataclass(frozen=True)class QuadraticInverseResolution: proof_sha256: str selected: QuadraticCandidate candidates: tuple[QuadraticCandidate, ...] assignment: tuple[int, ...] penalty: float constant: float quadratic_matrix_sha256: str quadratic_energy: float exhaustive_one_hot_minimum_verified: bool
def as_dict(self) -> dict[str, Any]: return { "schema_version": SCHEMA, "proof_sha256": self.proof_sha256, "selected": self.selected.as_dict(), "candidate_count": len(self.candidates), "candidate_manifest_sha256": digest([ value.as_dict() for value in self.candidates ]), "assignment": list(self.assignment), "assignment_hamming_weight": sum(self.assignment), "penalty": self.penalty, "constant": self.constant, "quadratic_matrix_sha256": self.quadratic_matrix_sha256, "quadratic_energy": self.quadratic_energy, "exhaustive_one_hot_minimum_verified": ( self.exhaustive_one_hot_minimum_verified ), "whole_construction_selected_globally": True, "next_token_predictions": 0, "traditional_language_model": False, "pretrained_embedding_encoder": False, "autoregressive_carrier": False, "global_gradient_steps": 0, }
class QuadraticInverseSolver: def __init__( self, grammar: NativeEnglishInverseGrammar, adapter: LanguageAdapter, *, maximum_hypotheses: int = 256, maximum_candidates: int = 128, one_hot_penalty: float = 1024.0, ) -> None: self.grammar = grammar self.adapter = adapter self.maximum_hypotheses = max(1, int(maximum_hypotheses)) self.maximum_candidates = max(1, int(maximum_candidates)) self.one_hot_penalty = float(one_hot_penalty)
def _role_options(self, proof: SelfInverseProof) -> tuple[ tuple[str, tuple[str, ...]], ... ]: frame = self.grammar.frames[proof.frame_id] subject_roles = { role for slot, role in frame.surface_slots if slot == "subject" } pronouns = { "i", "me", "we", "us", "you", "he", "him", "she", "her", "it", "they", "them", "who", "whom", "someone", "something", } result: list[tuple[str, tuple[str, ...]]] = [] for filler in proof.role_fillers: raw = filler.surface variants = [raw] capitalized = raw[:1].upper() + raw[1:] if raw else raw if capitalized != raw: variants.append(capitalized) if " and " in raw.casefold() or " or " in raw.casefold(): coordinated = " ".join( value if value.casefold() in {"and", "or"} else value[:1].upper() + value[1:] for value in raw.split() ) if coordinated not in variants: variants.append(coordinated) # A sentence-initial nominal homograph (stick, knife, storm) can be # misread as the predicate. The determiner is a pure construction # coordinate: forward analysis recovers the same role referent. if ( filler.role in subject_roles and raw.casefold() not in pronouns and " " not in raw.strip() ): variants.append("the " + raw) result.append((filler.role, tuple(variants))) return tuple(result)
def _preposition_options( self, proof: SelfInverseProof, ) -> tuple[tuple[str, tuple[str, ...]], ...]: frame = self.grammar.frames[proof.frame_id] return tuple( (slot, self.grammar._preposition_candidates(slot)) for slot, _ in frame.surface_slots if slot.startswith("prep:") )
@staticmethod def _products( values: Sequence[tuple[str, tuple[str, ...]]], ) -> tuple[dict[str, str], ...]: if not values: return ({},) keys = tuple(value[0] for value in values) return tuple( dict(zip(keys, choices)) for choices in itertools.product(*(value[1] for value in values)) )
@staticmethod def _energy_terms( audit: RoundTripAudit, *, role_transformations: Sequence[tuple[str, str]], preposition_choices: Sequence[tuple[str, str]], construction_variant_id: str, ) -> tuple[tuple[str, float], ...]: # Semantic invariants dominate chart simplicity by several orders of # magnitude. The small final terms only break semantically equal ties. return ( ("frame_mismatch", 128.0 * float(not audit.frame_recovered)), ( "family_mismatch", 64.0 * float(not audit.transformation_family_recovered), ), ( "operator_sequence_mismatch", 64.0 * float(not audit.operator_sequence_recovered), ), ( "known_role_mismatch", 32.0 * float(not audit.role_fillers_recovered), ), ( "alpha_equivalence_mismatch", 16.0 * float(not audit.semantic_round_trip_alpha_equivalent), ), ( "strict_identity_residual", 0.125 * float(not audit.semantic_round_trip_exact), ), ("surface_coordinate_changes", 0.001 * len(role_transformations)), ("preposition_coordinate_changes", 0.001 * len(preposition_choices)), ( "construction_order_change", 0.001 * float(construction_variant_id != "frame_order"), ), )
@staticmethod def _matrix( unary: Sequence[float], penalty: float, ) -> tuple[np.ndarray, float]: count = len(unary) matrix = np.full((count, count), float(penalty), dtype=np.float64) np.fill_diagonal( matrix, np.asarray(unary, dtype=np.float64) - float(penalty), ) return matrix, float(penalty)
@staticmethod def _quadratic_energy( assignment: np.ndarray, matrix: np.ndarray, constant: float, ) -> float: return float(assignment @ matrix @ assignment + constant)
def solve(self, proof: SelfInverseProof) -> QuadraticInverseResolution: role_products = self._products(self._role_options(proof)) prep_products = self._products(self._preposition_options(proof)) candidates: list[QuadraticCandidate] = [] seen_surfaces: set[str] = set() original_roles = proof.role_map default_preps = { key: self.grammar._preposition(key) for key, _ in self._preposition_options(proof) } for construction_variant_id, role_values, prep_values in itertools.product( CONSTRUCTION_VARIANTS, role_products, prep_products, ): realization = self.grammar.realize( proof, role_surface_overrides=role_values, preposition_overrides=prep_values, construction_variant_id=construction_variant_id, ) # Case is semantically significant to the rule-bounded analyzer, # so de-duplicate exact surfaces rather than case-folded surfaces. surface_key = realization.text if surface_key in seen_surfaces: continue seen_surfaces.add(surface_key) audit = self.grammar.audit_round_trip( proof, realization, self.adapter, maximum_hypotheses=self.maximum_hypotheses, ) role_changes = tuple(sorted( (role, surface) for role, surface in role_values.items() if role in original_roles and surface != original_roles[role].surface )) prep_changes = tuple(sorted( (slot, value) for slot, value in prep_values.items() if value != default_preps.get(slot) )) terms = self._energy_terms( audit, role_transformations=role_changes, preposition_choices=prep_changes, construction_variant_id=construction_variant_id, ) payload: Mapping[str, Any] = { "proof_sha256": proof.proof_sha256, "surface_sha256": hashlib.sha256( realization.text.encode("utf-8") ).hexdigest(), "variant": construction_variant_id, "role_changes": role_changes, "prep_changes": prep_changes, } candidates.append(QuadraticCandidate( candidate_id="qic:" + digest(payload)[:28], realization=realization, round_trip=audit, role_transformations=role_changes, preposition_choices=prep_changes, energy_terms=terms, )) if len(candidates) >= self.maximum_candidates: break if not candidates: raise RuntimeError("proof produced no inverse construction candidates") candidates.sort(key=lambda value: (value.unary_energy, value.candidate_id)) unary = tuple(value.unary_energy for value in candidates) matrix, constant = self._matrix(unary, self.one_hot_penalty) selected_index = 0 assignment = np.zeros(len(candidates), dtype=np.float64) assignment[selected_index] = 1.0 energy = self._quadratic_energy(assignment, matrix, constant) one_hot_energies = [ self._quadratic_energy(np.eye(1, len(candidates), index)[0], matrix, constant) for index in range(len(candidates)) ] verified = ( abs(energy - min(one_hot_energies)) <= 1e-9 and self.one_hot_penalty > max(unary) ) return QuadraticInverseResolution( proof_sha256=proof.proof_sha256, selected=candidates[selected_index], candidates=tuple(candidates), assignment=tuple(int(value) for value in assignment), penalty=self.one_hot_penalty, constant=constant, quadratic_matrix_sha256=hashlib.sha256( np.ascontiguousarray(matrix).tobytes() ).hexdigest(), quadratic_energy=energy, exhaustive_one_hot_minimum_verified=verified, )
__all__ = [ "CONSTRUCTION_VARIANTS", "QuadraticCandidate", "QuadraticInverseResolution", "QuadraticInverseSolver", "SCHEMA",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243#!/usr/bin/env python3"""K121 authenticated-context operator closure over immutable K119/K120.
The prospective K120 panel exposed a remaining precedence error rather than aknowledge error. Caller-supplied evidence reached the evidence handler, but anopen lexical comparison recognized the request surface first and displaced theauthenticated records. The same panel exposed an incomplete equivalence classfor a corpus comparative: ``greater`` was reduced only when an auxiliary HRRhead happened to classify the whole request as comparative.
This successor treats a non-empty authenticated outer context as a bindingoperator. Evidence is interpreted by the bounded evidence kernel before opensurface operators, while corpus comparative morphemes are normalized by theirdirectional order relation before bounded relational reduction. It adds nodomain facts, answer strings, pretrained representation, autoregressivecarrier, or gradient-trained language component."""from __future__ import annotations
from collections.abc import Mapping, Sequencefrom contextvars import ContextVarimport refrom typing import Any
from stage5k15_native_mixed_agent import HandlerResult, SemanticClause, clean, digestfrom stage5k88_opened_k87_precedence_retrieval_agent import ( OpenedK87PrecedenceRetrievalAgent,)from stage5k117_caller_context_isolation_agent import _K117_CALLER_CONTEXT_KINDfrom stage5k119_social_negative_scope_agent import SocialNegativeScopeAgent
SCHEMA = "oracle-stage5k121-authenticated-context-operator-agent-v1"_K121_AUDIT: ContextVar[Mapping[str, Any] | None] = ContextVar( "k121_context_operator_audit", default=None,)
class AuthenticatedContextOperatorAgent(SocialNegativeScopeAgent): """Make authenticated context prior to incompatible open-surface operators."""
_HIGH_ORDER = re.compile(r"\b(?:greater|greatest)\b", re.IGNORECASE) _LOW_ORDER = re.compile(r"\b(?:lesser|smallest|fewest)\b", re.IGNORECASE)
def __init__(self, *args: Any, k121_ablations: Sequence[str] = (), **kwargs: Any) -> None: self._k121_ablations = frozenset(clean(value).casefold() for value in k121_ablations) super().__init__(*args, **kwargs) self._k121_lineage_sha256 = digest({ "schema_version": SCHEMA, "parent_lineage_sha256": self._k119_lineage_sha256, "preserved_failure_source": "immutable_stage5k120_untouched_operator_closure_report_v1", "repairs": [ "authenticated_outer_evidence_precedes_incompatible_open_surface_operator", "comparative_lexeme_maps_to_directional_order_before_corpus_reduction", ], })
@staticmethod def _outer_evidence(context: Mapping[str, Any]) -> bool: # The outer-boundary context variable is authoritative. Lower layers # may replace a private K90 sentinel with retrieved rows; inspecting # only the mutable carrier at that point would misclassify those rows # as caller evidence and recreate the K116 collision. if _K117_CALLER_CONTEXT_KIND.get() != "evidence": return False evidence = context.get("evidence") if not isinstance(evidence, Sequence) or isinstance(evidence, (str, bytes)) or not evidence: return False return not any( isinstance(value, Mapping) and str(value.get("answer_status", "")).startswith("k90_") for value in evidence )
@staticmethod def _project_productive_negative_scope( result: HandlerResult | None, context: Mapping[str, Any], ) -> HandlerResult | None: """Retain K119's productive scope after direct evidence-kernel entry.""" if result is None or result.operation != "evidence_synthesis" or result.status != "answered": return result evidence = context.get("evidence") if not isinstance(evidence, Sequence) or isinstance(evidence, (str, bytes)): return result facts = [ clean(value.get("fact", value.get("claim", value))) if isinstance(value, Mapping) else clean(value) for value in evidence ] negative_replication = any( "replication" in fact.casefold() and SocialNegativeScopeAgent._NEGATIVE_SCOPE.search(fact) for fact in facts ) existing_negative = any( clean(clause.subject).casefold() == "the evidence" and clean(clause.predicate).casefold() == "establish" and clean(clause.object_value or "").casefold() == "universal superiority" and clause.polarity == "negative" for clause in result.clauses ) if not negative_replication or existing_negative: return result clauses = tuple( SemanticClause( clause.subject, clause.predicate, object_value=clause.object_value, complement="absent" if ( clean(clause.subject).casefold() == "independent replication" and clean(clause.predicate).casefold() == "be" ) else clause.complement, tense=clause.tense, modal=clause.modal, polarity=clause.polarity, qualifiers=clause.qualifiers, ) for clause in result.clauses ) + ( SemanticClause( "The evidence", "establish", object_value="universal superiority", polarity="negative", ), ) values = dict(result.result) values["independent_replication_absent"] = True audit = dict(_K121_AUDIT.get() or {}) audit.update({ "productive_negative_evidence_scope_activated": True, "negative_scope_surface_count": sum( bool(SocialNegativeScopeAgent._NEGATIVE_SCOPE.search(fact)) for fact in facts ), }) _K121_AUDIT.set(audit) return HandlerResult( result.operation, result.status, result.arguments, tuple(values.items()), clauses, result.evidence, (*result.computation_trace, "bind_productive_negative_evidence_scope", "derive_scoped_non_superiority"), tool_audit=result.tool_audit, memory_audit=result.memory_audit, )
def _handle_evidence(self, text: str, context: Mapping[str, Any]): if ( "authenticated_context_precedence" in self._k121_ablations or not self._outer_evidence(context) # Constitutional identity and recognized social speech acts are # relations to the interlocutor, not claims about supplied data. or self._identity_request(text) or self._social_act(text) is not None ): return super()._handle_evidence(text, context)
# Enter at the mature bounded evidence kernel. This deliberately # bypasses later open-conversation surface interpreters, while retaining # all lower evidence synthesis and epistemic-boundary behavior. result = OpenedK87PrecedenceRetrievalAgent._handle_evidence(self, text, context) result = self._project_productive_negative_scope(result, context) audit = dict(_K121_AUDIT.get() or {}) audit.update({ "context_kind": "evidence", "authenticated_context_precedence_activated": True, "selected_operation": result.operation if result is not None else None, }) _K121_AUDIT.set(audit) if result is None: return None return HandlerResult( result.operation, result.status, result.arguments, result.result, result.clauses, result.evidence, (*result.computation_trace, "bind_authenticated_outer_evidence_before_open_surface_operator"), tool_audit=result.tool_audit, memory_audit=result.memory_audit, )
def _handle_corpus( self, session_id: str, text: str, context: Mapping[str, Any], turn_id: str, ): corpus = context.get("training_corpus") bounded = bool( isinstance(corpus, Sequence) and not isinstance(corpus, (str, bytes)) and corpus ) normalized = text direction = None if bounded and "comparative_direction_equivalence" not in self._k121_ablations: if self._HIGH_ORDER.search(text): normalized = self._HIGH_ORDER.sub("higher", text) direction = "higher" elif self._LOW_ORDER.search(text): normalized = self._LOW_ORDER.sub("lower", text) direction = "lower" result = super()._handle_corpus(session_id, normalized, context, turn_id) if result is None or normalized == text: return result audit = dict(_K121_AUDIT.get() or {}) audit.update({ "context_kind": "training_corpus", "comparative_direction_equivalence_activated": True, "comparative_direction": direction, "selected_operation": result.operation, }) _K121_AUDIT.set(audit) return HandlerResult( result.operation, result.status, result.arguments, result.result, result.clauses, result.evidence, (*result.computation_trace, "normalize_comparative_lexeme_to_directional_order"), tool_audit=result.tool_audit, memory_audit=result.memory_audit, )
def answer(self, *args: Any, **kwargs: Any) -> dict[str, Any]: token = _K121_AUDIT.set({}) try: output = super().answer(*args, **kwargs) audit = dict(_K121_AUDIT.get() or {}) finally: _K121_AUDIT.reset(token) output["authenticated_context_operator"] = { "schema_version": SCHEMA, "lineage_sha256": self._k121_lineage_sha256, "development_source": "opened_immutable_k120_failure", "prospective_claim": False, "audit": audit, "authenticated_context_is_binding_operator": True, "comparative_lexeme_is_directional_relation": True, "domain_entities_encoded": 0, "traditional_language_model": False, "transformer": False, "pretrained_embedding_encoder": False, "autoregressive_carrier": False, "model_calls": 0, "gradient_steps": 0, } output["runtime"].update({ "authenticated_context_operator_model_calls": 0, "authenticated_context_operator_gradient_steps": 0, }) output["schema_version"] = SCHEMA output["turn_manifest_sha256"] = digest(output) return output
__all__ = ["AuthenticatedContextOperatorAgent", "SCHEMA"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210#!/usr/bin/env python3"""K131 whole-construction ingress for registered-source action clauses.
Immutable K129 showed that an explicit multi-step registered-database requestcould be captured by lexically adjacent public text before the bounded toolgraph saw it. This successor recognizes the conjunction of four typedrelations: registered source, read-only selection verb, numeric extremum, anddependent record projection. Only that whole construction receives toolprecedence. Its relations are projected into the inherited typed-goalalgebra while the original surface remains the audited goal and theH1/C43/Tree/Malkuth path executes it. This layer contains no domain rows,answer values, or response templates."""from __future__ import annotations
from collections.abc import Mapping, Sequencefrom contextvars import ContextVarimport refrom typing import Any
from stage5k15_native_mixed_agent import HandlerResult, clean, digestfrom stage5k128_persistent_tool_reference_agent import PersistentToolReferenceAgent
SCHEMA = "oracle-stage5k131-registered-source-action-ingress-agent-v1"_K131_AUDIT: ContextVar[dict[str, Any] | None] = ContextVar( "k131_registered_source_action_ingress_audit", default=None,)
class RegisteredSourceActionIngressAgent(PersistentToolReferenceAgent): """Project explicit registered-source action constructions to typed tools."""
_SOURCE = re.compile( r"\b(?:registered\s+)?(?:earthquake|population)\s+" r"(?:database|catalog|observations?|dataset)\b", re.IGNORECASE, ) _SELECT = re.compile( r"\b(?:use|using|consult|query|search|within|from|select|choose|find|" r"locate|determine|identify)\b", re.IGNORECASE, ) _EXTREMUM = re.compile( r"\b(?:minimum|smallest|lowest|weakest|maximum|greatest|highest|" r"largest|strongest)\b", re.IGNORECASE, ) _DEPENDENCY = re.compile( r"(?:\b(?:then|after(?:wards|\s+that)?|subsequently)\b|[;,])[^.?!]*" r"\b(?:provide|report|return|give|state|retrieve)\b", re.IGNORECASE, ) _PROJECTION = re.compile( r"\b(?:chosen|selected|that)\s+(?:event|record)|" r"\b(?:record|event)(?:'s)?\s+(?:magnitude|place|value|depth)\b", re.IGNORECASE, )
def __init__(self, *args: Any, k131_ablations: Sequence[str] = (), **kwargs: Any) -> None: self._k131_ablations = frozenset(clean(value).casefold() for value in k131_ablations) super().__init__(*args, **kwargs) self._k131_lineage_sha256 = digest({ "schema_version": SCHEMA, "parent_lineage_sha256": self._k128_lineage_sha256, "opened_failure_source": "immutable_stage5k129_untouched_persistent_reference_failure", "operator": ( "registered_source+read_only_selection+numeric_extremum+" "dependent_record_projection" ), })
@classmethod def _registered_source_action(cls, text: str) -> dict[str, Any] | None: value = clean(text) source = cls._SOURCE.search(value) select = cls._SELECT.search(value) extremum = cls._EXTREMUM.search(value) dependency = cls._DEPENDENCY.search(value) projection = cls._PROJECTION.search(value) if not all((source, select, extremum, dependency, projection)): return None direction = "minimum" if extremum.group(0).casefold() in { "minimum", "smallest", "lowest", "weakest", } else "maximum" domain = "earthquake" if "earthquake" in source.group(0).casefold() else "population" return { "whole_construction_recognized": True, "domain": domain, "direction": direction, "registered_source_surface": source.group(0), "selection_surface": select.group(0), "extremum_surface": extremum.group(0), "dependent_projection_surface": projection.group(0), "surface_sha256": digest(value), }
def _project_registered_source_action( self, text: str, context: Mapping[str, Any], ingress: str, ) -> HandlerResult | None: construction = self._registered_source_action(text) if ( construction is None or "registered_source_action_precedence" in self._k131_ablations ): return None session_id = clean(context.get("k102_session_id", "")) if not session_id: return None # The parent controller already owns the typed action algebra, but its # surface compiler recognizes only a deliberately small set of # sequential connectives. K131 has already established all of the # relations required for a goal, so project those relations to a # canonical *internal* carrier and compile the plan from that carrier. # Execute and audit the plan against the untouched user surface. This # is construction transduction, not answer-text rewriting. domain = ( "earthquake database" if construction["domain"] == "earthquake" else "population database" ) metric = "magnitude" if domain == "earthquake database" else "value" requested_fields = self._requested_fields(text, domain) projection = " and ".join(requested_fields) canonical_carrier = ( f"From the {domain}, find the {construction['direction']} {metric}; " "then provide the selected record" + (f" and {projection}." if projection else ".") ) plan = self._compile_goal(canonical_carrier) result = ( self._execute_goal(session_id, text, plan) if plan else self._bounded_tool_graph(session_id, text) ) audit = _K131_AUDIT.get() if audit is not None: audit.update({ **construction, "ingress": ingress, "selected_operation": result.operation, "selected_status": result.status, "tool_graph_precedes_open_public_text": True, "surface_rewritten": False, "construction_projected_to_typed_goal": bool(plan), "typed_goal_action_count": len(plan), "canonical_carrier_sha256": digest(canonical_carrier), }) return HandlerResult( result.operation, result.status, result.arguments, result.result, result.clauses, result.evidence, ("recognize_whole_registered_source_action_construction", "bind_tool_precedence_before_open_public_text", *result.computation_trace), tool_audit={ **dict(result.tool_audit or {}), "k131_whole_construction_precedence": True, "k131_surface_rewritten": False, "k131_construction_projected_to_typed_goal": bool(plan), }, memory_audit=result.memory_audit, )
def _handle_evidence( self, text: str, context: Mapping[str, Any], ) -> HandlerResult | None: projected = self._project_registered_source_action(text, context, "evidence") return projected if projected is not None else super()._handle_evidence(text, context)
def _handle_definition( self, session_id: str, text: str, turn_id: str, ) -> HandlerResult | None: # Some mixed specialist selections enter the definition rail before # evidence. The same construction operator must be prior there too. projected = self._project_registered_source_action( text, {"k102_session_id": session_id}, "definition", ) return projected if projected is not None else super()._handle_definition(session_id, text, turn_id)
def answer(self, *args: Any, **kwargs: Any) -> dict[str, Any]: audit: dict[str, Any] = {} token = _K131_AUDIT.set(audit) try: output = super().answer(*args, **kwargs) finally: _K131_AUDIT.reset(token) output["registered_source_action_ingress"] = { "schema_version": SCHEMA, "lineage_sha256": self._k131_lineage_sha256, "development_source": "opened_immutable_k129_failure", "prospective_claim": False, "audit": audit, "whole_construction_precedes_local_lexical_retrieval": True, "answer_values_encoded": 0, "domain_entities_encoded": 0, "traditional_language_model": False, "transformer": False, "pretrained_embedding_encoder": False, "autoregressive_carrier": False, "model_calls": 0, "gradient_steps": 0, } output["runtime"].update({ "registered_source_action_ingress_model_calls": 0, "registered_source_action_ingress_gradient_steps": 0, }) output["schema_version"] = SCHEMA output["turn_manifest_sha256"] = digest(output) return output
__all__ = ["RegisteredSourceActionIngressAgent", "SCHEMA"]root/wander-train/appraisal_v1.pyAdded+194
root/wander-train/chat_context_v1.pyAdded+372
root/wander-train/chem_agents_v1.pyAdded+586
root/wander-train/code_organ_v2.pyAdded+474
root/wander-train/code_organ_v3.pyAdded+488
root/wander-train/exact_router_v1.pyAdded+143
root/wander-train/general_reader_v1.pyAdded+471
root/wander-train/math_organ_v2.pyAdded+508
root/wander-train/oracle_cube_reader_v1_3.pyAdded+447
root/wander-train/oracle_game_combine_v1.pyAdded+209
root/wander-train/oracle_program_ir_v1.pyAdded+256
root/wander-train/oracle_release_conceptnet.pyAdded+142
root/wander-train/oracle_release_runtime_aa.pyAdded+135
root/wander-train/oracle_release_runtime_ac.pyAdded+140
root/wander-train/oracle_release_runtime_ag.pyAdded+104
root/wander-train/oracle_release_runtime_ah.pyAdded+76
root/wander-train/oracle_release_runtime_aj.pyAdded+72
root/wander-train/oracle_release_runtime_am.pyAdded+55
root/wander-train/oracle_release_runtime_c.pyAdded+113
root/wander-train/oracle_release_runtime_e.pyAdded+126
root/wander-train/oracle_release_runtime_h.pyAdded+70
root/wander-train/oracle_release_runtime_k.pyAdded+73
root/wander-train/oracle_release_runtime_n.pyAdded+17
root/wander-train/oracle_release_runtime_p.pyAdded+34
root/wander-train/oracle_release_runtime_q.pyAdded+148
root/wander-train/oracle_release_runtime_s.pyAdded+50
root/wander-train/oracle_release_runtime_u.pyAdded+44
root/wander-train/oracle_release_runtime_w58.pyAdded+212
root/wander-train/oracle_release_runtime_w59.pyAdded+164
root/wander-train/oracle_release_runtime_w60.pyAdded+64
root/wander-train/oracle_release_runtime_w71.pyAdded+245
root/wander-train/oracle_sibling_evidential_v3.pyAdded+92
root/wander-train/oracle_tritree_v1.pyAdded+473
root/wander-train/oracle_tritree_v2.pyAdded+479
root/wander-train/organ_dialogue_v1.pyAdded+125
root/wander-train/organ_self_v1.pyAdded+308
root/wander-train/path_memory_v1.pyAdded+171
root/wander-train/pubchem_periodic_table.csvAdded+119
root/wander-train/relation_forms_v2.pyAdded+118
root/wander-train/stage5c58_cycling_cognitive_substrate.pyAdded+480
root/wander-train/stage5h1_generic_dataset_expert.pyAdded+377
root/wander-train/stage5h3_hrr_relational_state_transducer.pyAdded+363
root/wander-train/stage5k102_persistent_typed_discourse_agent.pyAdded+1614
root/wander-train/stage5k104_relational_ingress_equivalence_agent.pyAdded+228
root/wander-train/stage5k108_universal_terminal_proof_projection_agent.pyAdded+127
root/wander-train/stage5k115_copular_definition_equivalence_agent.pyAdded+229
root/wander-train/stage5k117_caller_context_isolation_agent.pyAdded+175
root/wander-train/stage5k11_quadratic_inverse_solver.pyAdded+348
root/wander-train/stage5k121_authenticated_context_operator_agent.pyAdded+243
root/wander-train/stage5k131_registered_source_action_ingress_agent.pyAdded+210