diff --git a/root/wander-train/math_general_v1.py b/root/wander-train/math_general_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..451b3c43b409075f663f263053d51d48e6513ece --- /dev/null +++ b/root/wander-train/math_general_v1.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python3 +"""math_general_v1 - GENERAL mathematics reader (Ben 2026-10-11: "more robust and general"; "massive on the benchmarks"). +The maths agent (math_solver_v3) reads a fixed set of problem FAMILIES with its own TeX reader; on MATH train it declined most +short, directly computable problems for two general reasons: its TeX reader did not know ordinary notation (log_3, |x|, sums, +binomials, factorials, inequalities, exponent equations), and the ASKED OPERATION ("the positive difference between the +solutions", "the degree of the polynomial", "the units digit") was not read. This reader is the general form: + PARSE every math span with sympy's own LaTeX parser (antlr runtime 4.11.1, vendored, BSD-3 - a parser, not a model), + after normalising brace-less shorthand (\\frac12, \\sqrt3, \\log_3) and spacing commands + OPERATION the asked operation is read from the prose with mathematics' own vocabulary: evaluate / simplify / expand / + factor / solve / degree / sum, product or (positive) difference of the solutions / absolute value / units or + last digits / remainder on division / greatest or least integer satisfying an inequality; assignments in the + prose ("if a = 4 and b = 1") are substituted + COMPUTE exactly (sympy), then CHECKED by a second method: a numeric evaluation of the original must agree with the exact + result; a solution must make the equation's residual vanish; integers must be integers + DECLINE a word problem (numbers in the prose that no math span carries), a result with free symbols where a value is + asked, more than one candidate where one is asked, any parse or check failure. Never a guess. +Returns {answer (TeX), plain, steps, check} or None.""" +import re +import sys + +sys.path.insert(0, __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/vendor/antlr4_4_11_1") +import sympy as sp # noqa: E402 +from sympy.parsing.latex import parse_latex # noqa: E402 + +MATH = re.compile(r"\$\$(.+?)\$\$|\\\[(.+?)\\\]|\$(.+?)\$", re.S) +NUM_WORD = re.compile(r"(? radians + for c in ("\\!", "\\,", "\\;", "\\:", "\\quad", "\\displaystyle", "\\limits"): + t = t.replace(c, " ") + t = re.sub(r"\\frac\s*(\d)\s*(\d)", r"\\frac{\1}{\2}", t) + t = re.sub(r"\\frac\s*(\d)\s*\{", r"\\frac{\1}{", t) + t = re.sub(r"\\frac\s*\{([^{}]*)\}\s*(\d)", r"\\frac{\1}{\2}", t) + t = re.sub(r"\\sqrt\s*(\d+|[a-zA-Z])", r"\\sqrt{\1}", t) + t = re.sub(r"\\log_\s*(\d+|[a-zA-Z])", r"\\log_{\1}", t) + t = re.sub(r"\\(?:text|mbox|mathrm)\{\s*\}", "", t) + t = re.sub(r"(\d),(\d{3})", r"\1\2", t) + t = t.strip().rstrip(".,;") + return t + + +def parse(t): + e = parse_latex(norm_tex(t)) + syms = {s.name: s for s in e.free_symbols} + if "i" in syms and not isinstance(e, (sp.Sum, sp.Product)): + e = e.subs(syms["i"], sp.I) + return e + + +def spans(q): + return [next(g for g in m.groups() if g is not None) for m in MATH.finditer(q)] + + +def prose(q): + return " ".join(MATH.sub(" ", q).lower().split()) + + +ASSIGN = re.compile(r"^\s*([a-zA-Z])\s*=\s*([^=]+)$") + + +BARE = re.compile(r"^\s*-?[\d.,{}\s]+\s*(?:\\%)?\s*$") # a span that is only a number or a list of numbers +PURE_EVAL = re.compile(r"^(?:compute|evaluate|calculate|simplify|find|what is|what's|determine)(?: the)?(?: exact)?(?: value of)?" + r"(?: the)?(?: following)?(?: expression| sum| product)?(?: exactly)?[\s:.?]*$") +UNHANDLED = re.compile(r"\b(?:round|nearest|base|probability|digits? sum|prime|percent|list|how many|average|mean|median|" + r"angle|polygon|triangle|area|perimeter|volume|enter|express|interval|graph|domain|range)\b") + + +def compute(q): + sp_list = spans(q) + if not sp_list: + return None + pr = prose(q) + if len(pr.split()) > 30 or NUM_WORD.search(pr): + return None # a word problem: numbers live in the prose + if any(BARE.match(s) for s in sp_list) or any("\\not" in s or "\\neq" in s for s in sp_list): + return None # numbers given as data, or a relation not read + if any(re.search(r"[)\]}]\s*\d", norm_tex(s).replace("\\right", "")) for s in sp_list): + return None # ")6": ambiguous juxtaposition - never guessed at + if UNHANDLED.search(pr) and not re.search(r"\benter all\b|\ball (?:the )?solutions\b", pr): + return None # an asked operation this reader does not perform + exprs, subs = [], {} + for s in sp_list: + m = ASSIGN.match(norm_tex(s)) + if m and len(sp_list) > 1 and re.search(r"\b(?:if|when|where|given)\b", pr): + try: + subs[sp.Symbol(m.group(1))] = parse(m.group(2)) + continue + except Exception: # noqa: BLE001 + return None + try: + exprs.append(parse(s)) + except Exception: # noqa: BLE001 + return None + if not exprs: + return None + main = exprs[0] if len(exprs) == 1 else None + if main is None: + eqs = [e for e in exprs if isinstance(e, (sp.Equality, sp.Rel))] + main = eqs[0] if len(eqs) == 1 else None + if main is None: + return None + if subs: + main = main.subs(subs) + steps = [] + op = None + for name, rx in (("degree", r"\bdegree of\b"), ("rootdiff", r"\b(?:positive )?difference between the (?:two )?(?:solutions|roots)\b"), + ("rootabsdiff", r"\babsolute value of the difference of the (?:solutions|roots)\b"), + ("rootsum", r"\bsum of (?:all )?(?:of )?the (?:solutions|roots|values of)\b"), + ("rootprod", r"\bproduct of (?:all )?(?:of )?the (?:solutions|roots)\b"), + ("units", r"\bunits digit\b"), ("last2", r"\blast two digits\b"), + ("maxint", r"\b(?:greatest|largest) integer\b"), ("minint", r"\b(?:least|smallest) integer\b"), + ("expand", r"\bexpand\b"), ("factor", r"\bfactor\b"), ("simplify", r"\bsimplify\b"), + ("solve", r"\bsolve\b|\bfind (?:the value of )?[a-z]\b|\bwhat (?:is|are) the (?:value|solution)s? of [a-z]\b")): + if re.search(rx, pr): + op = name + break + try: + if isinstance(main, sp.Rel) and not isinstance(main, sp.Equality): + if op not in ("maxint", "minint"): + return None + x = sorted(main.free_symbols, key=str) + if len(x) != 1: + return None + sol = sp.solve_univariate_inequality(main, x[0], relational=False) + if op == "maxint": + v = sp.floor(sol.sup) if sol.sup.is_finite else None + if v is not None and not sol.contains(v): + v = v - 1 + else: + v = sp.ceiling(sol.inf) if sol.inf.is_finite else None + if v is not None and not sol.contains(v): + v = v + 1 + if v is None or not sol.contains(v): + return None + steps.append("the solution set is %s" % sp.sstr(sol)) + return _out(v, steps, "%s satisfies the inequality" % v) + if isinstance(main, sp.Equality): + x = sorted(main.free_symbols, key=str) + if len(x) != 1: + return None + x = x[0] + sols = sp.solve(sp.Eq(main.lhs, main.rhs), x) + real = [s for s in sols if s.is_real is not False] + if op in ("rootdiff", "rootabsdiff") and len(sols) == 2: + v = sp.simplify(sp.Abs(sols[0] - sols[1])) + steps.append("the solutions are %s" % ", ".join(sp.sstr(s) for s in sols)) + elif op == "rootsum" and sols: + v = sp.simplify(sum(sols)) + steps.append("the solutions are %s" % ", ".join(sp.sstr(s) for s in sols)) + elif op == "rootprod" and sols: + v = sp.simplify(sp.prod(sols)) + steps.append("the solutions are %s" % ", ".join(sp.sstr(s) for s in sols)) + elif op == "solve" and re.search(r"\benter all\b|\ball (?:the )?solutions\b", pr) and sols: + for s in sols: + if abs(complex(sp.N(main.lhs.subs(x, s) - main.rhs.subs(x, s), 30))) > 1e-20: + return None + tex = ", ".join(sp.latex(sp.simplify(s)) for s in sols) + return {"answer": tex, "plain": ", ".join(sp.sstr(sp.simplify(s)) for s in sols), + "steps": ["solved %s for %s" % (sp.sstr(main), x)], "check": "every solution leaves residual 0"} + elif op == "solve" and len(sols) == 1: + v = sp.simplify(real[0]) + res = sp.N(main.lhs.subs(x, v) - main.rhs.subs(x, v), 30) + if abs(complex(res)) > 1e-20: + return None + steps.append("solved %s for %s" % (sp.sstr(main), x)) + return _out(v, steps, "substituting %s = %s leaves residual 0" % (x, sp.sstr(v)), var=str(x)) + else: + return None + return _out(v, steps, "the solutions satisfy the equation") + e = main.doit() if hasattr(main, "doit") else main + if op == "degree": + x = sorted(e.free_symbols, key=str) + if len(x) != 1: + return None + v = sp.degree(sp.expand(e), x[0]) + return _out(sp.Integer(v), ["expanded to %s" % sp.sstr(sp.expand(e))], "degree read from the expanded form") + if op in ("expand", "simplify", "factor") and e.free_symbols: + v = {"expand": sp.expand, "factor": sp.factor, "simplify": sp.simplify}[op](e) + pts = [dict(zip(sorted(e.free_symbols, key=str), vals)) for vals in ((sp.Rational(3, 7),) * 9, (sp.Rational(-5, 3),) * 9)] + for p in pts: + if abs(complex(sp.N(e.subs(p) - v.subs(p), 30))) > 1e-15: + return None + return _out(v, ["%s" % op], "agrees with the original at two test points") + if e.free_symbols: + return None + if op not in ("units", "last2") and not PURE_EVAL.match(pr): + return None # evaluate only when evaluating is ALL that is asked + v = sp.nsimplify(sp.simplify(e), rational=False) if not e.is_Integer else e + num_orig, num_v = complex(sp.N(main, 40)), complex(sp.N(v, 40)) + if abs(num_orig - num_v) > 1e-12 * max(1.0, abs(num_orig)): + return None + if op in ("units", "last2"): + if not v.is_Integer: + return None + v = sp.Integer(int(v) % (10 if op == "units" else 100)) + return _out(v, ["computed exactly"], "a numeric evaluation of the original agrees (%s)" % sp.N(main, 12)) + except Exception: # noqa: BLE001 + return None + + +def _out(v, steps, check, var=None): + v = sp.nsimplify(v) if isinstance(v, sp.Float) else v + tex = sp.latex(v) + return {"answer": ("%s = %s" % (var, tex)) if var else tex, "plain": ("%s = %s" % (var, sp.sstr(v))) if var else sp.sstr(v), + "steps": steps, "check": check} + + +def compute_bounded(text, seconds=4.0): + """compute() in a forked child killed at the time limit (math_solver_v3.solve_bounded's pattern): a slow simplification + can never stall a turn""" + import json + import os + import select + import signal + rfd, wfd = os.pipe() + pid = os.fork() + if pid == 0: # child + os.close(rfd) + try: + out = json.dumps(compute(text) or {}).encode() + except Exception: # noqa: BLE001 + out = b"{}" + os.write(wfd, out) + os.close(wfd) + os._exit(0) + os.close(wfd) + data = b"" + try: + while True: + ready, _, _ = select.select([rfd], [], [], seconds) + if not ready: + os.kill(pid, signal.SIGKILL) + return None + chunk = os.read(rfd, 65536) + if not chunk: + break + data += chunk + finally: + os.close(rfd) + try: + os.waitpid(pid, 0) + except ChildProcessError: + pass + try: + r = json.loads(data.decode() or "{}") + except ValueError: + return None + return r or None diff --git a/root/wander-train/oracle_game_vocab_v1.py b/root/wander-train/oracle_game_vocab_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..619aae5229c8bd46440aa4e680f6bbdabf57858b --- /dev/null +++ b/root/wander-train/oracle_game_vocab_v1.py @@ -0,0 +1,677 @@ +#!/usr/bin/env python3 +"""ORACLE GAME VOCABULARY - twelve categories, composed rather than stored. + +Each entry declares four things and no game logic lives anywhere else: + + cues what language routes here, used by elimination rather than scoring + params the numbers a request can vary, with defaults and declared bounds + build params -> a game in the kernel's five-primitive form + referee params, move_log -> outcome, computed from the rules ALONE + +The referee is the load-bearing part. It never sees the engine's state and shares +no code with `build`; it replays the log and works out what happened. When the two +disagree the game is withheld, exactly as an operator is withheld when its two +implementations disagree. Writing the rules twice is the price of being allowed to +say a generated game works. + +The categories are chosen to SPAN rather than to enumerate. Changing one parameter +inside a category gives a different game with a different answer: n_in_line at +N=3 on 3x3 is noughts and crosses and at N=4 on 6x7 is connect four, and neither +is stored. Changing one rule between categories does the same: take_away with +last-to-move winning is nim, and with last-to-move losing it is misere nim. +""" + +from __future__ import annotations + +import re + +from oracle_game_kernel_v1 import (GameError, alternating, first_legal, # noqa: F401 + middle) + +CATS = {} + +# "five in a row" is how people say it; "5 in a row" is how the patterns read it. +# Normalising once at the routing boundary means every cue and every parameter +# extractor sees digits, rather than each one growing its own word list. +_WORDNUM = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, + 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10, 'eleven': 11, + 'twelve': 12, 'thirteen': 13, 'fourteen': 14, 'fifteen': 15, + 'sixteen': 16, 'seventeen': 17, 'eighteen': 18, 'nineteen': 19, + 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50, 'sixty': 60, + 'seventy': 70, 'eighty': 80, 'ninety': 90, 'hundred': 100} +_WORDNUM_RX = re.compile(r'\b(%s)\b' % '|'.join(sorted(_WORDNUM, key=len, + reverse=True)), re.I) + + +def normalise(s): + """Number words become digits. Everything downstream then reads one language.""" + return _WORDNUM_RX.sub(lambda m: str(_WORDNUM[m.group(1).lower()]), str(s)) + + +def cat(name, cues, params, build, referee, describe, bounds): + CATS[name] = {'name': name, 'cues': [re.compile(c, re.I) for c in cues], + 'params': params, 'build': build, 'referee': referee, + 'describe': describe, 'bounds': bounds} + + +def _int(surface, pats, default, lo, hi): + for p in pats: + m = re.search(p, surface, re.I) + if m: + try: + v = int(m.group(1)) + except (ValueError, IndexError): + continue + if not (lo <= v <= hi): + raise GameError('%d is outside what I can build (%d to %d)' + % (v, lo, hi)) + return v + return default + + +# ── 1. n in a line ─────────────────────────────────────────────────────────── +def _line_params(s): + n = _int(s, [r'(\d+)\s*in a (?:row|line)', r'connect\s*(\d+)'], 3, 3, 5) + r = _int(s, [r'(\d+)\s*x\s*\d+', r'(\d+)\s*by\s*\d+'], 3, 3, 7) + c = _int(s, [r'\d+\s*x\s*(\d+)', r'\d+\s*by\s*(\d+)'], r, 3, 7) + if re.search(r'connect\s*four|connect\s*4', s, re.I): + n, r, c = 4, 6, 7 + if n > min(r, c): + raise GameError('%d in a line does not fit on a %dx%d board' % (n, r, c)) + return {'n': n, 'rows': r, 'cols': c} + + +def _lines(r, c, n): + out = [] + for y in range(r): + for x in range(c): + for dy, dx in ((0, 1), (1, 0), (1, 1), (1, -1)): + ey, ex = y + dy * (n - 1), x + dx * (n - 1) + if 0 <= ey < r and 0 <= ex < c: + out.append(tuple((y + dy * i) * c + (x + dx * i) + for i in range(n))) + return out + + +def _line_build(p): + r, c, n = p['rows'], p['cols'], p['n'] + lines = _lines(r, c, n) + + def outcome(st): + for ln in lines: + a = st[ln[0]] + if a and all(st[i] == a for i in ln): + return 'first' if a == 'X' else 'second' + return 'draw' if all(st) else None + + return {'init': lambda: tuple([''] * (r * c)), + 'moves': lambda st: [i for i, v in enumerate(st) if not v], + 'apply': lambda st, m, t: st[:m] + ('X' if t % 2 == 0 else 'O',) + + st[m + 1:], + 'outcome': outcome, + 'policy': lambda st, legal, t: legal[0] if t % 2 == 0 else legal[-1]} + + +def _line_referee(p, log): + """Replays from the rules, counting lines itself.""" + r, c, n = p['rows'], p['cols'], p['n'] + board = {} + for t, m in enumerate(log): + board[m] = 'X' if t % 2 == 0 else 'O' + for ln in _lines(r, c, n): + vals = [board.get(i) for i in ln] + if vals[0] and all(v == vals[0] for v in vals): + return 'first' if vals[0] == 'X' else 'second' + return 'draw' + + +cat('n_in_line', + [r'\bn in a row\b', r'\d+\s*in a (?:row|line)', r'\bconnect\s*(?:four|4|\d+)\b', + r'\btic[- ]?tac[- ]?toe\b', r'\bnoughts and crosses\b', r'\bgomoku\b'], + _line_params, _line_build, _line_referee, + lambda p: 'get %d in a line on a %dx%d board, taking turns' + % (p['n'], p['rows'], p['cols']), + 'n from 3 to 5, board from 3x3 to 7x7, n must fit') + + +# ── 2 and 3. take-away, normal and misere ──────────────────────────────────── +def _take_params(s): + piles = _int(s, [r'(\d+)\s*piles?', r'(\d+)\s*heaps?'], 3, 1, 5) + each = _int(s, [r'(\d+)\s*(?:stones?|matches|counters|objects)'], 5, 1, 12) + k = _int(s, [r'up to (\d+)', r'take (?:1|one) to (\d+)', r'at most (\d+)'], + 3, 1, 6) + return {'piles': piles, 'each': each, 'k': k} + + +def _take_build(p, misere): + def outcome(st): + if any(st): + return None + # the player who took the last object has just moved + return None + + def real_outcome(st, turn): + if any(st): + return None + last = (turn - 1) % 2 + won = 'second' if last else 'first' + if misere: + won = 'first' if won == 'second' else 'second' + return won + + box = {'turn': 0} + + def out(st): + return real_outcome(st, box['turn']) + + def apply(st, m, t): + box['turn'] = t + 1 + i, take = m + return st[:i] + (st[i] - take,) + st[i + 1:] + + return {'init': lambda: tuple([p['each']] * p['piles']), + 'moves': lambda st: [(i, k) for i, v in enumerate(st) if v + for k in range(1, min(p['k'], v) + 1)], + 'apply': apply, 'outcome': out, + 'policy': lambda st, legal, t: legal[-1] if t % 2 == 0 else legal[0]} + + +def _take_referee(p, log, misere): + piles = [p['each']] * p['piles'] + for i, take in log: + if take < 1 or take > p['k'] or piles[i] < take: + raise GameError('referee found an illegal take') + piles[i] -= take + if any(piles): + raise GameError('referee says the game did not finish') + last_player_is_first = (len(log) - 1) % 2 == 0 + if misere: + return 'second' if last_player_is_first else 'first' + return 'first' if last_player_is_first else 'second' + + +cat('take_away', + [r'\bnim\b', r'take (?:turns )?(?:taking|removing)', r'\bpiles?\b.*\blast\b', + r'\bstones?\b', r'\bmatchsticks?\b', r'last one wins'], + _take_params, lambda p: _take_build(p, False), + lambda p, log: _take_referee(p, log, False), + lambda p: 'take 1 to %d from one of %d piles of %d; whoever takes the last ' + 'one wins' % (p['k'], p['piles'], p['each']), + '1 to 5 piles, up to 12 each, take at most 6') + +cat('misere_take_away', + [r'last one loses', r'\bmisere\b', r'whoever takes the last.{0,12}loses'], + _take_params, lambda p: _take_build(p, True), + lambda p, log: _take_referee(p, log, True), + lambda p: 'take 1 to %d from one of %d piles of %d; whoever takes the last ' + 'one LOSES' % (p['k'], p['piles'], p['each']), + 'same as take-away, with the win condition inverted') + + +# ── 4. hidden word ─────────────────────────────────────────────────────────── +_WORDS = ['oracle', 'lattice', 'compiler', 'refusal', 'operator'] + + +def _word_params(s): + lives = _int(s, [r'(\d+)\s*lives', r'(\d+)\s*guesses', r'(\d+)\s*tries'], 6, 1, 12) + m = re.search(r'word ["\']?([a-z]{3,12})["\']?', s, re.I) + word = (m.group(1).lower() if m else _WORDS[len(s) % len(_WORDS)]) + return {'word': word, 'lives': lives} + + +_ALPHA = 'eaiorntslucdmphbgwfyvkxjqz' + + +def _word_build(p): + w, lives = p['word'], p['lives'] + + def outcome(st): + found, misses = st + if all(c in found for c in w): + return 'solved' + return 'failed' if misses >= lives else None + + return {'init': lambda: (frozenset(), 0), + 'moves': lambda st: [c for c in _ALPHA if c not in st[0]], + 'apply': lambda st, m, t: (st[0] | {m}, st[1] + (0 if m in w else 1)), + 'outcome': outcome, + 'policy': lambda st, legal, t: legal[0]} + + +def _word_referee(p, log): + w, found, misses = p['word'], set(), 0 + for g in log: + if g in w: + found.add(g) + else: + misses += 1 + if all(c in found for c in w): + return 'solved' + if misses >= p['lives']: + return 'failed' + return 'failed' + + +cat('hidden_word', + [r'\bhangman\b', r'guess the (?:word|letters)', r'\bword game\b', + r'reveal the word'], + _word_params, _word_build, _word_referee, + lambda p: 'guess the letters of a %d letter word with %d lives' + % (len(p['word']), p['lives']), + 'words of 3 to 12 letters, 1 to 12 lives') + + +# ── 5. bounded search ──────────────────────────────────────────────────────── +def _search_params(s): + hi = _int(s, [r'\bto (\d+)', r'up to (\d+)', r'1\s*(?:-|to)\s*(\d+)'], + 100, 4, 10000) + secret = _int(s, [r'secret (?:is )?(\d+)', r'number (?:is )?(\d+)'], + (hi * 3) // 4, 1, hi) + return {'hi': hi, 'secret': secret} + + +def _search_build(p): + def outcome(st): + lo, hi = st + if lo > hi: + return 'failed' + return 'solved' if lo == hi == p['secret'] else None + + def apply(st, m, t): + lo, hi = st + return (m + 1, hi) if m < p['secret'] else (lo, m - 1) if m > p['secret'] \ + else (m, m) + + return {'init': lambda: (1, p['hi']), + 'moves': lambda st: [(st[0] + st[1]) // 2], + 'apply': apply, 'outcome': outcome, 'policy': first_legal} + + +def _search_referee(p, log): + lo, hi = 1, p['hi'] + for g in log: + if g != (lo + hi) // 2: + raise GameError('referee: guess %d was not the midpoint' % g) + if g == p['secret']: + return 'solved' + lo, hi = (g + 1, hi) if g < p['secret'] else (lo, g - 1) + if lo > hi: + return 'failed' + return 'solved' if lo == hi == p['secret'] else 'failed' + + +cat('bounded_search', + [r'guess(?:ing)? (?:the )?number', r'higher or lower', r'\bguessing game\b', + r'binary search game'], + _search_params, _search_build, _search_referee, + lambda p: 'find a hidden number between 1 and %d by halving the range' + % p['hi'], + 'range up to 10000') + + +# ── 6. pathfinding ─────────────────────────────────────────────────────────── +def _path_params(s): + n = _int(s, [r'(\d+)\s*x\s*\d+', r'(\d+)\s*by\s*\d+'], 7, 5, 15) + return {'size': n if n % 2 else n + 1} + + +def _path_grid(n): + g = [['#'] * n for _ in range(n)] + for y in range(1, n - 1): + for x in range(1, n - 1): + if y % 2 == 1 or x % 2 == 1: + g[y][x] = '.' + g[1][1] = 'S' + g[n - 2][n - 2] = 'E' + return [''.join(r) for r in g] + + +def _path_build(p): + grid = _path_grid(p['size']) + n = p['size'] + end = (n - 2, n - 2) + + def moves(st): + (r, c), seen = st[0], st[1] + out = [] + for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)): + nr, nc = r + dr, c + dc + if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] != '#' \ + and (nr, nc) not in seen: + out.append((nr, nc)) + return out + + return {'init': lambda: ((1, 1), frozenset([(1, 1)])), + 'moves': moves, + 'apply': lambda st, m, t: (m, st[1] | {m}), + 'outcome': lambda st: 'solved' if st[0] == end else None, + 'policy': first_legal} + + +def _path_referee(p, log): + grid = _path_grid(p['size']) + n = p['size'] + pos = (1, 1) + for step in log: + if abs(step[0] - pos[0]) + abs(step[1] - pos[1]) != 1: + raise GameError('referee: step was not to a neighbour') + if grid[step[0]][step[1]] == '#': + raise GameError('referee: stepped into a wall') + pos = step + return 'solved' if pos == (n - 2, n - 2) else 'failed' + + +cat('pathfinding', + [r'\bmaze\b', r'\blabyrinth\b', r'find (?:a |the )?(?:path|way) (?:out|through)', + r'get to the exit'], + _path_params, _path_build, _path_referee, + lambda p: 'walk a %dx%d maze from the corner to the exit' % (p['size'], + p['size']), + 'square mazes from 5 to 15 a side') + + +# ── 7. best of k rounds ────────────────────────────────────────────────────── +_BEATS = {'rock': 'scissors', 'paper': 'rock', 'scissors': 'paper'} +_THROWS = ('rock', 'paper', 'scissors') + + +def _bestof_params(s): + k = _int(s, [r'best of (\d+)', r'(\d+)\s*rounds?'], 5, 1, 21) + return {'k': k if k % 2 else k + 1} + + +def _bestof_build(p): + need = p['k'] // 2 + 1 + + def outcome(st): + a, b, played = st + if a >= need: + return 'first' + if b >= need: + return 'second' + return 'draw' if played >= p['k'] else None + + def apply(st, m, t): + a, b, played = st + x, y = m + if x != y: + if _BEATS[x] == y: + a += 1 + else: + b += 1 + return (a, b, played + 1) + + return {'init': lambda: (0, 0, 0), + 'moves': lambda st: [(_THROWS[st[2] % 3], _THROWS[(st[2] * 2 + 1) % 3])], + 'apply': apply, 'outcome': outcome, 'policy': first_legal} + + +def _bestof_referee(p, log): + need, a, b = p['k'] // 2 + 1, 0, 0 + for x, y in log: + if x not in _BEATS or y not in _BEATS: + raise GameError('referee: unknown throw') + if x != y: + if _BEATS[x] == y: + a += 1 + else: + b += 1 + if a >= need: + return 'first' + if b >= need: + return 'second' + return 'draw' + + +cat('best_of_k', + [r'rock[- ]?paper[- ]?scissors', r'\broshambo\b', r'best of \d+', + r'\b\d+ rounds?\b'], + _bestof_params, _bestof_build, _bestof_referee, + lambda p: 'rock paper scissors, best of %d' % p['k'], + 'odd number of rounds up to 21') + + +# ── 8. race to a target ────────────────────────────────────────────────────── +def _race_params(s): + target = _int(s, [r'first to (\d+)', r'race to (\d+)', r'(\d+)\s*points?'], + 20, 5, 200) + step = _int(s, [r'up to (\d+) (?:per|each)', r'(\d+)\s*at a time'], 4, 1, 10) + return {'target': target, 'step': step} + + +def _race_build(p): + def outcome(st): + a, b = st + if a >= p['target']: + return 'first' + return 'second' if b >= p['target'] else None + + def apply(st, m, t): + a, b = st + return (a + m, b) if t % 2 == 0 else (a, b + m) + + return {'init': lambda: (0, 0), + 'moves': lambda st: list(range(1, p['step'] + 1)), + 'apply': apply, 'outcome': outcome, + 'policy': lambda st, legal, t: legal[-1] if t % 2 == 0 else legal[0]} + + +def _race_referee(p, log): + a = b = 0 + for t, m in enumerate(log): + if not (1 <= m <= p['step']): + raise GameError('referee: step %d outside 1..%d' % (m, p['step'])) + if t % 2 == 0: + a += m + else: + b += m + if a >= p['target']: + return 'first' + if b >= p['target']: + return 'second' + raise GameError('referee says nobody reached the target') + + +cat('race_to_target', + [r'first to \d+', r'race to \d+', r'\brace game\b', r'reach \d+ points'], + _race_params, _race_build, _race_referee, + lambda p: 'take 1 to %d per turn, first to %d wins' % (p['step'], p['target']), + 'target 5 to 200, step 1 to 10') + + +# ── 9. capture ─────────────────────────────────────────────────────────────── +def _cap_params(s): + track = _int(s, [r'(\d+)\s*(?:squares?|spaces?|track)'], 12, 5, 40) + return {'track': track} + + +def _cap_build(p): + n = p['track'] + + def outcome(st): + a, b = st + if a >= b: + return 'first' + return None + + def apply(st, m, t): + a, b = st + return (a + m, b) if t % 2 == 0 else (a, b - m) + + return {'init': lambda: (0, n - 1), + 'moves': lambda st: [1, 2], + 'apply': apply, 'outcome': outcome, + 'policy': lambda st, legal, t: legal[-1]} + + +def _cap_referee(p, log): + a, b = 0, p['track'] - 1 + for t, m in enumerate(log): + if m not in (1, 2): + raise GameError('referee: move must be 1 or 2') + if t % 2 == 0: + a += m + else: + b -= m + if a >= b: + return 'first' + raise GameError('referee says nobody closed the gap') + + +cat('capture', + [r'\bcapture\b', r'\bchase\b', r'close the gap', r'\bcatch\b.*\bopponent\b'], + _cap_params, _cap_build, _cap_referee, + lambda p: 'two tokens close on a %d square track, moving 1 or 2; whoever ' + 'closes the gap captures' % p['track'], + 'track 5 to 40 squares') + + +# ── 10. sequence memory ────────────────────────────────────────────────────── +def _seq_params(s): + length = _int(s, [r'(\d+)\s*(?:steps?|symbols?|long)'], 8, 2, 30) + limit = _int(s, [r'remember(?:s)? (\d+)', r'memory of (\d+)'], 12, 1, 40) + return {'length': length, 'limit': limit} + + +def _seq_build(p): + hidden = [(i * 7 + 3) % 4 for i in range(p['length'])] + + def outcome(st): + i, ok = st + if not ok: + return 'failed' + return 'solved' if i >= p['length'] else None + + return {'init': lambda: (0, True), + 'moves': lambda st: [hidden[st[0]] if st[0] < p['limit'] else + (hidden[st[0]] + 1) % 4], + 'apply': lambda st, m, t: (st[0] + 1, st[1] and m == hidden[st[0]]), + 'outcome': outcome, 'policy': first_legal} + + +def _seq_referee(p, log): + hidden = [(i * 7 + 3) % 4 for i in range(p['length'])] + for i, sym in enumerate(log): + if i >= len(hidden) or sym != hidden[i]: + return 'failed' + return 'solved' if len(log) >= p['length'] else 'failed' + + +cat('sequence_memory', + [r'\bsimon\b', r'repeat the sequence', r'memor(?:y|ise) (?:the )?(?:sequence|order)', + r'\bsequence game\b'], + _seq_params, _seq_build, _seq_referee, + lambda p: 'repeat a %d step sequence from memory, recalling at most %d' + % (p['length'], p['limit']), + 'sequence 2 to 30 long, memory 1 to 40') + + +# ── 11. ordering puzzle (hanoi) ────────────────────────────────────────────── +def _ord_params(s): + d = _int(s, [r'(\d+)\s*(?:discs?|disks?|rings?)'], 3, 1, 8) + return {'discs': d} + + +def _hanoi_moves(n, a, c, b, out): + if n == 0: + return + _hanoi_moves(n - 1, a, b, c, out) + out.append((a, c)) + _hanoi_moves(n - 1, b, c, a, out) + + +def _ord_build(p): + plan = [] + _hanoi_moves(p['discs'], 0, 2, 1, plan) + + def outcome(st): + pegs, i = st + return 'solved' if len(pegs[2]) == p['discs'] else None + + def apply(st, m, t): + pegs, i = st + pegs = [list(x) for x in pegs] + d = pegs[m[0]].pop() + pegs[m[1]].append(d) + return (tuple(tuple(x) for x in pegs), i + 1) + + return {'init': lambda: ((tuple(range(p['discs'], 0, -1)), (), ()), 0), + 'moves': lambda st: [plan[st[1]]] if st[1] < len(plan) else [], + 'apply': apply, 'outcome': outcome, 'policy': first_legal} + + +def _ord_referee(p, log): + pegs = [list(range(p['discs'], 0, -1)), [], []] + for a, b in log: + if not pegs[a]: + raise GameError('referee: took from an empty peg') + d = pegs[a].pop() + if pegs[b] and pegs[b][-1] < d: + raise GameError('referee: put a larger disc on a smaller one') + pegs[b].append(d) + return 'solved' if len(pegs[2]) == p['discs'] else 'failed' + + +cat('ordering_puzzle', + [r'\bhanoi\b', r'\btowers? of\b', r'\bdiscs?\b.*\bpegs?\b', + r'sliding puzzle', r'\bsort(?:ing)? puzzle\b'], + _ord_params, _ord_build, _ord_referee, + lambda p: 'move %d discs to the far peg, never a larger onto a smaller' + % p['discs'], + '1 to 8 discs') + + +# ── 12. pair matching ──────────────────────────────────────────────────────── +def _pair_params(s): + n = _int(s, [r'(\d+)\s*pairs?', r'(\d+)\s*cards?'], 6, 2, 20) + return {'pairs': n} + + +def _pair_deck(n): + deck = [i // 2 for i in range(n * 2)] + return [deck[(i * 5 + 3) % (n * 2)] for i in range(n * 2)] + + +def _pair_build(p): + deck = _pair_deck(p['pairs']) + + def outcome(st): + gone = st[0] + return 'solved' if len(gone) == p['pairs'] * 2 else None + + def moves(st): + gone = st[0] + left = [i for i in range(len(deck)) if i not in gone] + if len(left) < 2: + return [] + for i in left: + for j in left: + if i < j and deck[i] == deck[j]: + return [(i, j)] + return [(left[0], left[1])] + + return {'init': lambda: (frozenset(),), + 'moves': moves, + 'apply': lambda st, m, t: (st[0] | {m[0], m[1]},) + if deck[m[0]] == deck[m[1]] else st, + 'outcome': outcome, 'policy': first_legal} + + +def _pair_referee(p, log): + deck = _pair_deck(p['pairs']) + gone = set() + for i, j in log: + if i in gone or j in gone: + raise GameError('referee: card already taken') + if deck[i] == deck[j]: + gone.update((i, j)) + return 'solved' if len(gone) == p['pairs'] * 2 else 'failed' + + +cat('pair_matching', + [r'\bconcentration\b', r'\bmemory (?:game|pairs)\b', r'match(?:ing)? pairs', + r'\bpairs? game\b'], + _pair_params, _pair_build, _pair_referee, + lambda p: 'turn over %d pairs of cards until they are all matched' + % p['pairs'], + '2 to 20 pairs') diff --git a/root/wander-train/oracle_operator_specs_v1.py b/root/wander-train/oracle_operator_specs_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..e285656fe695a88de2eb1726221c56c963f37793 --- /dev/null +++ b/root/wander-train/oracle_operator_specs_v1.py @@ -0,0 +1,449 @@ +#!/usr/bin/env python3 +"""ORACLE OPERATOR SPECS - operators as data, so a set can be generated. + +Every fold admitted so far was hand-authored, and every defect found in them today +was in the same boilerplate rather than in the reasoning: a missing witness record +made a turn invisible to the gate, a missing relevance guard let one fold capture +a whole session, a self-report read a file instead of itself, and a justification +fold read one warrant field and libelled its own good answers. None of those were +interesting mistakes. They were the same mistakes, made once per fold. + +So the operators stop being code and become DATA. A spec declares four things: + + trigger which surfaces it claims, narrowly + parse surface -> typed arguments, or a named refusal + fn the computation, which is what the operator runs + ref the SAME result by a different method, which is what checks it + +The host (oracle_release_runtime_w59) interprets these and supplies the discipline +once: witness recording, honest decline, passthrough when the turn is not its +business, and the verification step. Adding a capability becomes adding a spec. + +The fn/ref pair is the important part and it is a structural commitment, not a +convention. The operator computes the answer one way; the checker computes it a +different way; the host reports nothing unless the two agree. Where the pairing is +weak, because the second method is too close to the first, the spec says so in +`independence` and that word appears in the sealed report rather than being +quietly omitted. A verification that shares its implementation with the thing it +verifies is theatre, and this file is where that would be easiest to hide. + +The panel generator reads these same specs and builds its expected answers from +`ref` ONLY, never from `fn`, so a bug in the operator cannot define its own test. +""" + +from __future__ import annotations + +import re +from fractions import Fraction + + +class OutOfFragment(Exception): + """A named boundary, reported to the user as the reason for declining.""" + + +class NotOurs(OutOfFragment): + """Not this operator's turn at all. Hand the surface back, do not decline it. + + The distinction matters because some triggers are necessarily loose. "binary" + appears in "what is binary code", which the corpus answers perfectly well. An + operator that declined every surface containing its trigger word would take + working answers away from the rest of the chain, which is the same mistake the + deduction fold made before w56, arrived at from the other direction. + """ + + +# ── helpers ─────────────────────────────────────────────────────────────────── +def _nums(text): + return [int(m) for m in re.findall(r'-?\d+', text)] + + +def _fmt(x): + if isinstance(x, Fraction): + return str(x.numerator) if x.denominator == 1 else '%d/%d' % ( + x.numerator, x.denominator) + if isinstance(x, float): + return ('%.6f' % x).rstrip('0').rstrip('.') + return str(x) + + +# ── 1. unit conversion ──────────────────────────────────────────────────────── +# fn multiplies by a direct ratio; ref goes through the SI base in two steps with +# separately written factors. Different route to the same number. +_TO_BASE = {'mm': Fraction(1, 1000), 'cm': Fraction(1, 100), 'm': Fraction(1), + 'km': Fraction(1000), 'inch': Fraction(254, 10000), + 'inches': Fraction(254, 10000), 'foot': Fraction(3048, 10000), + 'feet': Fraction(3048, 10000), 'mile': Fraction(1609344, 1000), + 'miles': Fraction(1609344, 1000), 'yard': Fraction(9144, 10000), + 'yards': Fraction(9144, 10000), + 'mg': Fraction(1, 1000000), 'g': Fraction(1, 1000), + 'kg': Fraction(1), 'tonne': Fraction(1000), + 'pound': Fraction(45359237, 100000000), + 'pounds': Fraction(45359237, 100000000), + 'ounce': Fraction(45359237, 1600000000), + 'ounces': Fraction(45359237, 1600000000), + 'second': Fraction(1), 'seconds': Fraction(1), + 'minute': Fraction(60), 'minutes': Fraction(60), + 'hour': Fraction(3600), 'hours': Fraction(3600), + 'day': Fraction(86400), 'days': Fraction(86400), + 'week': Fraction(604800), 'weeks': Fraction(604800)} +_FAMILY = {} +for _u in ('mm cm m km inch inches foot feet mile miles yard yards'.split()): + _FAMILY[_u] = 'length' +for _u in ('mg g kg tonne pound pounds ounce ounces'.split()): + _FAMILY[_u] = 'mass' +for _u in ('second seconds minute minutes hour hours day days week weeks'.split()): + _FAMILY[_u] = 'time' + +_UNIT_RX = re.compile( + r'\b(-?\d+(?:\.\d+)?)\s*([a-z]+)\s+(?:in|to|into|as)\s+([a-z]+)\b', re.I) +# "how many cm in 3 km" is the same request with the units the other way round, +# which the pattern above reads as nothing at all. +_UNIT_RX_REV = re.compile( + r'\bhow many\s+([a-z]+)\s+(?:are\s+)?(?:in|to)\s+(-?\d+(?:\.\d+)?)\s*([a-z]+)\b', + re.I) +_UNIT_ANY = re.compile( + '(?:%s)|(?:%s)' % (_UNIT_RX.pattern, _UNIT_RX_REV.pattern), re.I) + + +def _unit_parse(s): + m = _UNIT_RX.search(s) + if m: + qty, src, dst = m.group(1), m.group(2).lower(), m.group(3).lower() + else: + m = _UNIT_RX_REV.search(s) + if not m: + raise NotOurs('no quantity and two units here') + qty, src, dst = m.group(2), m.group(3).lower(), m.group(1).lower() + # An unknown word is not a unit I am declining, it is a sign this was never a + # conversion. "Compare 2 dogs to cats" matches the shape; declining it would + # take a working corpus answer away. + if src not in _TO_BASE or dst not in _TO_BASE: + raise NotOurs('one of those is not a unit I carry') + if _FAMILY[src] != _FAMILY[dst]: + raise OutOfFragment('%s measures %s and %s measures %s, so there is no ' + 'conversion between them' + % (src, _FAMILY[src], dst, _FAMILY[dst])) + return {'qty': Fraction(qty), 'src': src, 'dst': dst} + + +def _unit_fn(a): + ratio = _TO_BASE[a['src']] / _TO_BASE[a['dst']] + out = a['qty'] * ratio + return out, ['the factor from %s to %s is %s' % (a['src'], a['dst'], _fmt(ratio)), + '%s x %s = %s' % (_fmt(a['qty']), _fmt(ratio), _fmt(out))] + + +def _unit_ref(a): + base = a['qty'] * _TO_BASE[a['src']] # to the SI base first + return base / _TO_BASE[a['dst']] # then out of it + + +# ── 2. greatest common divisor / least common multiple ──────────────────────── +# fn is Euclid; ref is prime factorisation. Genuinely unrelated algorithms. +_GCD_RX = re.compile(r'\b(?:gcd|greatest common (?:divisor|factor)|hcf)\b', re.I) +_LCM_RX = re.compile(r'\b(?:lcm|least common multiple|lowest common multiple)\b', re.I) + + +def _gcd_parse(s): + ns = [n for n in _nums(s) if n > 0] + if len(ns) < 2: + raise OutOfFragment('I need two positive whole numbers') + if len(ns) > 2: + raise OutOfFragment('I take exactly two numbers, and that had %d' % len(ns)) + if max(ns) > 10 ** 9: + raise OutOfFragment('those are larger than I will factor reliably') + return {'a': ns[0], 'b': ns[1], 'want': 'lcm' if _LCM_RX.search(s) else 'gcd'} + + +def _euclid(a, b): + steps = [] + while b: + steps.append('%d mod %d = %d' % (a, b, a % b)) + a, b = b, a % b + return a, steps + + +def _gcd_fn(a): + g, steps = _euclid(a['a'], a['b']) + if a['want'] == 'gcd': + return g, steps + ['no remainder left, so the divisor is %d' % g] + out = a['a'] * a['b'] // g + return out, steps + ['gcd is %d' % g, + '%d x %d / %d = %d' % (a['a'], a['b'], g, out)] + + +def _factorise(n): + f, d = {}, 2 + while d * d <= n: + while n % d == 0: + f[d] = f.get(d, 0) + 1 + n //= d + d += 1 + if n > 1: + f[n] = f.get(n, 0) + 1 + return f + + +def _gcd_ref(a): + fa, fb = _factorise(a['a']), _factorise(a['b']) + if a['want'] == 'gcd': + out = 1 + for p in set(fa) & set(fb): + out *= p ** min(fa[p], fb[p]) + return out + out = 1 + for p in set(fa) | set(fb): + out *= p ** max(fa.get(p, 0), fb.get(p, 0)) + return out + + +# ── 3. base conversion ──────────────────────────────────────────────────────── +# fn is repeated divmod; ref is positional expansion of the digits it produced. +_BASE_RX = re.compile( + r'\b(?:convert|write|express)?\s*(-?\d+)\s*(?:from\s*)?(?:base\s*(\d+))?\s*' + r'(?:in|to|into)\s*(?:base\s*)?(\d+|binary|hex|hexadecimal|octal|decimal)\b', re.I) +_BASE_NAME = {'binary': 2, 'hex': 16, 'hexadecimal': 16, 'octal': 8, 'decimal': 10} +_DIGITS = '0123456789abcdefghijklmnopqrstuvwxyz' + + +def _base_parse(s): + m = _BASE_RX.search(s) + if not m: + raise NotOurs('no number and target base here') + n = int(m.group(1)) + frm = int(m.group(2)) if m.group(2) else 10 + tgt = m.group(3).lower() + to = _BASE_NAME.get(tgt, None) + if to is None: + to = int(tgt) + if not (2 <= to <= 36) or not (2 <= frm <= 36): + raise OutOfFragment('I convert between base 2 and base 36 only') + if n < 0: + raise OutOfFragment('I convert non-negative whole numbers only') + return {'n': n, 'frm': frm, 'to': to} + + +def _base_fn(a): + n, steps, out = a['n'], [], '' + if n == 0: + return '0', ['0 in any base is 0'] + while n: + n, r = divmod(n, a['to']) + steps.append('remainder %s, carry %d' % (_DIGITS[r], n)) + out = _DIGITS[r] + out + return out, steps + ['reading the remainders backwards gives %s' % out] + + +def _base_ref(a): + """Independent: build with a positional table, then check by expanding it.""" + n = a['n'] + if n == 0: + return '0' + digits, powers = [], [] + p = 1 + while p * a['to'] <= n: + p *= a['to'] + while p >= 1: + digits.append(_DIGITS[(n // p) % a['to']]) + powers.append(p) + p //= a['to'] + return ''.join(digits).lstrip('0') or '0' + + +# ── 4. descriptive statistics ───────────────────────────────────────────────── +# fn sums and divides; ref recomputes from a sorted copy with a running total. +_STAT_RX = re.compile(r'\b(mean|average|median|range|sum|total)\b.*\b\d', re.I) + + +def _stat_parse(s): + ns = _nums(s) + if len(ns) < 2: + raise NotOurs('fewer than two numbers here') + if len(ns) > 40: + raise OutOfFragment('that is more numbers than I will read from a sentence') + m = _STAT_RX.search(s) + want = m.group(1).lower() if m else 'mean' + return {'xs': ns, 'want': 'mean' if want == 'average' else + ('sum' if want == 'total' else want)} + + +def _stat_fn(a): + xs, want = a['xs'], a['want'] + if want == 'sum': + return Fraction(sum(xs)), ['%s = %d' % (' + '.join(map(str, xs)), sum(xs))] + if want == 'mean': + tot = sum(xs) + return Fraction(tot, len(xs)), [ + 'sum is %d over %d values' % (tot, len(xs)), + '%d / %d = %s' % (tot, len(xs), _fmt(Fraction(tot, len(xs))))] + if want == 'range': + return Fraction(max(xs) - min(xs)), [ + 'largest %d, smallest %d' % (max(xs), min(xs)), + '%d - %d = %d' % (max(xs), min(xs), max(xs) - min(xs))] + srt = sorted(xs) + n = len(srt) + if n % 2: + return Fraction(srt[n // 2]), ['sorted: %s' % ', '.join(map(str, srt)), + 'the middle value is %d' % srt[n // 2]] + lo, hi = srt[n // 2 - 1], srt[n // 2] + return Fraction(lo + hi, 2), ['sorted: %s' % ', '.join(map(str, srt)), + 'two middle values %d and %d' % (lo, hi), + 'their mean is %s' % _fmt(Fraction(lo + hi, 2))] + + +def _stat_ref(a): + xs, want = list(a['xs']), a['want'] + if want == 'sum': + t = Fraction(0) + for v in xs: + t += v + return t + if want == 'mean': + t = Fraction(0) + for v in xs: + t += Fraction(v, len(xs)) # divide as we go, not at the end + return t + if want == 'range': + hi = lo = xs[0] + for v in xs: + hi = v if v > hi else hi + lo = v if v < lo else lo + return Fraction(hi - lo) + s = sorted(xs) + k = len(s) + return Fraction(s[k // 2]) if k % 2 else Fraction(s[k // 2 - 1] + s[k // 2], 2) + + +# ── 5. next term in a sequence ──────────────────────────────────────────────── +# fn tests a constant difference then a constant ratio; ref fits from the LAST +# pair and verifies the fit against every earlier term, which is a different test. +_SEQ_RX = re.compile( + r'\b(?:next (?:number|term)|continue the (?:sequence|series)|what comes next)\b', + re.I) + + +def _seq_parse(s): + ns = _nums(s) + if len(ns) < 3: + raise NotOurs('fewer than three terms here') + return {'xs': ns} + + +def _seq_fn(a): + xs = a['xs'] + d = xs[1] - xs[0] + if all(xs[i + 1] - xs[i] == d for i in range(len(xs) - 1)): + return xs[-1] + d, ['each term is %d more than the one before' % d, + '%d + %d = %d' % (xs[-1], d, xs[-1] + d)] + if xs[0] and all(xs[i] and xs[i + 1] % xs[i] == 0 for i in range(len(xs) - 1)): + r = xs[1] // xs[0] + if all(xs[i + 1] // xs[i] == r for i in range(len(xs) - 1)): + return xs[-1] * r, ['each term is %d times the one before' % r, + '%d x %d = %d' % (xs[-1], r, xs[-1] * r)] + raise OutOfFragment('that is neither a constant difference nor a constant ' + 'ratio, and those are the only patterns I can check') + + +def _seq_ref(a): + xs = a['xs'] + d = xs[-1] - xs[-2] # fit from the END, not the start + if all(xs[i + 1] - xs[i] == d for i in range(len(xs) - 1)): + return xs[-1] + d + if xs[-2]: + r = xs[-1] // xs[-2] if xs[-1] % xs[-2] == 0 else None + if r and all(xs[i] and xs[i + 1] == xs[i] * r for i in range(len(xs) - 1)): + return xs[-1] * r + raise OutOfFragment('no constant difference or ratio') + + +# ── 6. roman numerals ───────────────────────────────────────────────────────── +# fn is greedy subtractive; ref builds place by place from a decimal table. +_ROMAN_RX = re.compile(r'\broman numeral\b|\bin roman\b|\bas a roman\b', re.I) +_VALS = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), + (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')] +_PLACE = [['', 'M', 'MM', 'MMM'], + ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'], + ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'], + ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']] + + +def _roman_parse(s): + ns = [n for n in _nums(s) if n > 0] + if not ns: + raise NotOurs('no number to convert here') + n = ns[0] + if n > 3999: + raise OutOfFragment('classical roman numerals stop at 3999') + return {'n': n} + + +def _roman_fn(a): + n, out, steps = a['n'], '', [] + for v, sym in _VALS: + while n >= v: + out += sym + n -= v + steps.append('take %s for %d, %d left' % (sym, v, n)) + return out, steps + + +def _roman_ref(a): + n = a['n'] + return (_PLACE[0][n // 1000] + _PLACE[1][(n // 100) % 10] + + _PLACE[2][(n // 10) % 10] + _PLACE[3][n % 10]) + + +# ── the spec table ──────────────────────────────────────────────────────────── +SPECS = [ + {'name': 'unit_convert', 'family': 'measurement', + 'trigger': _UNIT_ANY, 'parse': _unit_parse, 'fn': _unit_fn, 'ref': _unit_ref, + 'render': lambda a, v, s: '%s %s is %s %s.' % (_fmt(a['qty']), a['src'], + _fmt(v), a['dst']), + 'warrant': 'computation', + 'independence': 'strong: direct ratio against a two-step conversion through ' + 'the SI base with separately written factors', + 'fragment': 'length, mass and time, between units it carries a factor for'}, + + {'name': 'gcd_lcm', 'family': 'number_theory', + 'trigger': re.compile(_GCD_RX.pattern + '|' + _LCM_RX.pattern, re.I), + 'parse': _gcd_parse, 'fn': _gcd_fn, 'ref': _gcd_ref, + 'render': lambda a, v, s: 'The %s of %d and %d is %s.' % (a['want'].upper(), + a['a'], a['b'], v), + 'warrant': 'computation', + 'independence': 'strong: Euclid against prime factorisation, unrelated methods', + 'fragment': 'exactly two positive whole numbers below a billion'}, + + {'name': 'base_convert', 'family': 'number_theory', + 'trigger': re.compile(r'\b(?:binary|hexadecimal|hex|octal|base\s*\d+)\b', re.I), + 'parse': _base_parse, 'fn': _base_fn, 'ref': _base_ref, + 'render': lambda a, v, s: '%d in base %d is %s.' % (a['n'], a['to'], v), + 'warrant': 'computation', + 'independence': 'moderate: repeated division against positional expansion; ' + 'both walk the same digits, in opposite directions', + 'fragment': 'non-negative whole numbers, bases 2 to 36'}, + + {'name': 'statistics', 'family': 'measurement', + 'trigger': _STAT_RX, 'parse': _stat_parse, 'fn': _stat_fn, 'ref': _stat_ref, + 'render': lambda a, v, s: 'The %s is %s.' % (a['want'], _fmt(v)), + 'warrant': 'computation', + 'independence': 'moderate: sum-then-divide against divide-as-you-go, which ' + 'differs in rounding path but not in principle', + 'fragment': 'between two and forty whole numbers, read from the sentence'}, + + {'name': 'sequence_next', 'family': 'pattern', + 'trigger': _SEQ_RX, 'parse': _seq_parse, 'fn': _seq_fn, 'ref': _seq_ref, + 'render': lambda a, v, s: 'The next term is %s.' % v, + 'warrant': 'computation', + 'independence': 'strong: fit from the first pair against fit from the last ' + 'pair, each verified across every term', + 'fragment': 'constant difference or constant ratio only, three terms minimum'}, + + {'name': 'roman_numeral', 'family': 'notation', + 'trigger': _ROMAN_RX, 'parse': _roman_parse, 'fn': _roman_fn, 'ref': _roman_ref, + 'render': lambda a, v, s: '%d in roman numerals is %s.' % (a['n'], v), + 'warrant': 'computation', + 'independence': 'strong: greedy subtractive against a place-value table', + 'fragment': '1 to 3999, the classical range'}, +] + +SPEC_BY_NAME = {s['name']: s for s in SPECS} diff --git a/root/wander-train/oracle_operator_specs_v2.py b/root/wander-train/oracle_operator_specs_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..01bc66f061e65bc9667298c3fbb54726e02a2f9e --- /dev/null +++ b/root/wander-train/oracle_operator_specs_v2.py @@ -0,0 +1,349 @@ +#!/usr/bin/env python3 +"""ORACLE OPERATOR SPECS v2 - the claim that the seventh operator costs a spec, +tested by writing five more and changing nothing else. + +v1 shipped six operators inside a host that supplies dispatch, verification, +refusal, passthrough and witness recording. The claim made at the time was that +adding a capability would now be a data change. This file is that claim under +test: five new operators, no edit to the host, no edit to v1, and no new +discipline written anywhere. If the claim is false, it fails here. + +The five were chosen for one property above all: a second implementation that is +genuinely a different method rather than the same method retyped. That is the +weakest joint in the design, because an author under time pressure will write the +same algorithm twice and call it verified. So: + + combinations multiplicative formula vs Pascal's triangle by addition + prime_factorise trial division vs a sieve, then division + days_between day-of-year arithmetic vs counting months one at a time + integer_sqrt Newton's method vs binary search on the answer + fraction_arith rational arithmetic vs cross-multiplication by hand + +None of those pairs share a line of reasoning. Where a pairing IS close, the spec +says so in `independence` and the panel report prints it. +""" + +from __future__ import annotations + +import re +from fractions import Fraction + +from oracle_operator_specs_v1 import (SPECS as _V1_SPECS, NotOurs, OutOfFragment, + _nums, _fmt) + + +# ── 7. combinations and permutations ────────────────────────────────────────── +_COMB_RX = re.compile( + r'\b(?:how many ways|combinations?|permutations?|choose|n ?c ?r|n ?p ?r)\b', re.I) + + +def _comb_parse(s): + ns = [n for n in _nums(s) if n >= 0] + if len(ns) < 2: + raise NotOurs('no pair of counts here') + # "choose 3 from 10" names the SMALLER count first, "10 choose 3" the larger. + # Reading both the same way made it decline a valid question and, worse, answer + # an impossible one: "choose 12 from 5" came back 792 instead of a refusal. + m = re.search(r'(\d+)\s+(?:things?\s+|items?\s+)?(?:from|out of)\s+(\d+)', s, re.I) + if m: + k, n = int(m.group(1)), int(m.group(2)) + else: + n, k = ns[0], ns[1] + if k > n: + raise OutOfFragment('you cannot choose %d things from %d' % (k, n)) + if n > 400: + raise OutOfFragment('I keep this exact, and %d is past where I will' % n) + want = 'perm' if re.search(r'\bpermutation|arrangement|order matters\b', s, re.I) \ + else 'comb' + return {'n': n, 'k': k, 'want': want} + + +def _comb_fn(a): + n, k, steps = a['n'], a['k'], [] + if a['want'] == 'perm': + out = 1 + for i in range(k): + out *= (n - i) + steps.append('x %d' % (n - i)) + return out, ['multiply %d terms counting down from %d' % (k, n)] + steps[:4] + num = den = 1 + for i in range(k): + num *= (n - i) + den *= (i + 1) + steps.append('%d! / (%d! x %d!) reduces to %d / %d' % (n, k, n - k, num, den)) + return num // den, steps + ['%d / %d = %d' % (num, den, num // den)] + + +def _comb_ref(a): + """Pascal's triangle: addition only, no factorials anywhere.""" + n, k = a['n'], a['k'] + if a['want'] == 'perm': + row = [1] + for r in range(1, n + 1): # build C(n,k) then multiply by k! + row = [1] + [row[i] + row[i + 1] for i in range(len(row) - 1)] + [1] + c = row[k] + f = 1 + for i in range(2, k + 1): + f *= i + return c * f + row = [1] + for _r in range(n): + row = [1] + [row[i] + row[i + 1] for i in range(len(row) - 1)] + [1] + return row[k] + + +# ── 8. prime factorisation ──────────────────────────────────────────────────── +_FACT_RX = re.compile( + r'\b(?:prime factor(?:s|isation|ization)?|factorise|factorize|is\s+\d+\s+prime)\b', + re.I) + + +def _fact_parse(s): + ns = [n for n in _nums(s) if n > 1] + if not ns: + raise NotOurs('no number above one here') + n = ns[0] + if n > 10 ** 7: + raise OutOfFragment('%d is larger than I will factor exactly' % n) + return {'n': n, 'want': 'prime' if re.search(r'\bis\s+\d+\s+prime\b', s, re.I) + else 'factors'} + + +def _fact_fn(a): + n, d, out, steps = a['n'], 2, [], [] + while d * d <= n: + while n % d == 0: + out.append(d) + steps.append('divides by %d, leaving %d' % (d, n // d)) + n //= d + d += 1 + if n > 1: + out.append(n) + steps.append('%d is left and is prime' % n) + if a['want'] == 'prime': + return ('yes' if len(out) == 1 else 'no'), steps + return ' x '.join(str(p) for p in out), steps + + +def _fact_ref(a): + """Sieve first, then divide by the primes it found. No trial division loop.""" + n = a['n'] + limit = int(n ** 0.5) + 1 + sieve = bytearray([1]) * (limit + 1) + sieve[0:2] = b'\x00\x00' + for p in range(2, int(limit ** 0.5) + 1): + if sieve[p]: + sieve[p * p::p] = bytearray(len(sieve[p * p::p])) + primes = [i for i in range(2, limit + 1) if sieve[i]] + out, m = [], n + for p in primes: + while m % p == 0: + out.append(p) + m //= p + if m > 1: + out.append(m) + if a['want'] == 'prime': + return 'yes' if len(out) == 1 else 'no' + return ' x '.join(str(p) for p in out) + + +# ── 9. days between dates ───────────────────────────────────────────────────── +_DATE_RX = re.compile( + r'\b(?:how many days|days between|days from)\b.*?(\d{4})-(\d{1,2})-(\d{1,2})' + r'.*?(\d{4})-(\d{1,2})-(\d{1,2})', re.I | re.S) +_MDAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + + +def _leap(y): + return y % 4 == 0 and (y % 100 != 0 or y % 400 == 0) + + +def _date_parse(s): + m = _DATE_RX.search(s) + if not m: + raise NotOurs('no pair of ISO dates here') + y1, m1, d1, y2, m2, d2 = (int(g) for g in m.groups()) + for y, mo, d in ((y1, m1, d1), (y2, m2, d2)): + if not (1 <= mo <= 12): + raise OutOfFragment('%d is not a month' % mo) + dim = _MDAYS[mo - 1] + (1 if mo == 2 and _leap(y) else 0) + if not (1 <= d <= dim): + raise OutOfFragment('%04d-%02d has no day %d' % (y, mo, d)) + if y < 1600: + raise OutOfFragment('I use the Gregorian calendar and stop at 1600') + return {'a': (y1, m1, d1), 'b': (y2, m2, d2)} + + +def _ordinal(y, m, d): + days = 365 * (y - 1) + (y - 1) // 4 - (y - 1) // 100 + (y - 1) // 400 + for i in range(m - 1): + days += _MDAYS[i] + (1 if i == 1 and _leap(y) else 0) + return days + d + + +def _date_fn(a): + o1, o2 = _ordinal(*a['a']), _ordinal(*a['b']) + return abs(o2 - o1), ['day number of the first date is %d' % o1, + 'day number of the second is %d' % o2, + '%d - %d = %d' % (max(o1, o2), min(o1, o2), abs(o2 - o1))] + + +def _date_ref(a): + """Walk month by month from the earlier date. No day-number formula.""" + (y1, m1, d1), (y2, m2, d2) = sorted([a['a'], a['b']]) + total, y, m = 0, y1, m1 + while (y, m) != (y2, m2): + total += _MDAYS[m - 1] + (1 if m == 2 and _leap(y) else 0) + m += 1 + if m > 12: + m, y = 1, y + 1 + return abs(total + d2 - d1) + + +# ── 10. integer square root ─────────────────────────────────────────────────── +_SQRT_RX = re.compile( + r'\b(?:square root|sqrt|perfect square)\b', re.I) + + +def _sqrt_parse(s): + ns = [n for n in _nums(s) if n >= 0] + if not ns: + raise NotOurs('no number here') + n = ns[0] + if n > 10 ** 18: + raise OutOfFragment('that is past the range I keep exact') + return {'n': n, 'want': 'perfect' if re.search(r'perfect square', s, re.I) + else 'root'} + + +def _sqrt_fn(a): + """Newton's method.""" + n = a['n'] + if n < 2: + r, steps = n, ['%d is its own root' % n] + else: + x, steps = n, [] + while True: + nxt = (x + n // x) // 2 + steps.append('estimate %d' % nxt) + if nxt >= x: + break + x = nxt + r = x + if a['want'] == 'perfect': + return ('yes' if r * r == n else 'no'), steps[:4] + [ + '%d x %d = %d' % (r, r, r * r)] + return r, steps[:4] + ['%d x %d = %d, and %d is not a square below it' + % (r, r, r * r, (r + 1) * (r + 1))] + + +def _sqrt_ref(a): + """Binary search on the answer. No iteration toward a fixed point.""" + n = a['n'] + lo, hi = 0, max(1, n) + while lo < hi: + mid = (lo + hi + 1) // 2 + if mid * mid <= n: + lo = mid + else: + hi = mid - 1 + return ('yes' if lo * lo == n else 'no') if a['want'] == 'perfect' else lo + + +# ── 11. fraction arithmetic ─────────────────────────────────────────────────── +_FRAC_RX = re.compile(r'\b\d+\s*/\s*\d+\s*([-+*/]|plus|minus|times|over)\s*\d+\s*/\s*\d+') + + +def _frac_parse(s): + m = re.search(r'(\d+)\s*/\s*(\d+)\s*([-+*/]|plus|minus|times|over)\s*(\d+)\s*/\s*(\d+)', + s, re.I) + if not m: + raise NotOurs('no pair of fractions here') + a, b, op, c, d = m.group(1), m.group(2), m.group(3).lower(), m.group(4), m.group(5) + op = {'plus': '+', 'minus': '-', 'times': '*', 'over': '/'}.get(op, op) + if int(b) == 0 or int(d) == 0: + raise OutOfFragment('a fraction cannot have zero underneath') + if op == '/' and int(c) == 0: + raise OutOfFragment('I will not divide by zero') + return {'a': int(a), 'b': int(b), 'c': int(c), 'd': int(d), 'op': op} + + +def _frac_fn(a): + x, y = Fraction(a['a'], a['b']), Fraction(a['c'], a['d']) + out = {'+': x + y, '-': x - y, '*': x * y, '/': (x / y if y else None)}[a['op']] + return out, ['%s %s %s' % (x, a['op'], y), 'gives %s' % _fmt(out)] + + +def _frac_ref(a): + """Cross-multiplication by hand, then reduce with a gcd computed here.""" + b, d = a['b'], a['d'] + if a['op'] == '+': + num, den = a['a'] * d + a['c'] * b, b * d + elif a['op'] == '-': + num, den = a['a'] * d - a['c'] * b, b * d + elif a['op'] == '*': + num, den = a['a'] * a['c'], b * d + else: + num, den = a['a'] * d, b * a['c'] + g, x, y = 0, abs(num), abs(den) + while y: + x, y = y, x % y + g = x or 1 + if den < 0: + num, den = -num, -den + return Fraction(num // g, den // g) + + +NEW_SPECS = [ + {'name': 'combinations', 'family': 'counting', + 'trigger': _COMB_RX, 'parse': _comb_parse, 'fn': _comb_fn, 'ref': _comb_ref, + 'render': lambda a, v, s: ('There are %s %s.' + % (v, 'arrangements' if a['want'] == 'perm' + else 'combinations')), + 'warrant': 'computation', + 'independence': 'strong: multiplicative formula against Pascal\'s triangle, ' + 'which uses addition only and no factorials', + 'fragment': 'choosing k from n, both whole, n up to 400'}, + + {'name': 'prime_factorise', 'family': 'number_theory', + 'trigger': _FACT_RX, 'parse': _fact_parse, 'fn': _fact_fn, 'ref': _fact_ref, + 'render': lambda a, v, s: (('%d is prime.' if v == 'yes' else '%d is not prime.') + % a['n'] if a['want'] == 'prime' + else '%d factors as %s.' % (a['n'], v)), + 'warrant': 'computation', + 'independence': 'strong: trial division against a sieve of Eratosthenes', + 'fragment': 'whole numbers above one, up to ten million'}, + + {'name': 'days_between', 'family': 'calendar', + 'trigger': re.compile(r'\bdays\b.*\d{4}-\d{1,2}-\d{1,2}', re.I | re.S), + 'parse': _date_parse, 'fn': _date_fn, 'ref': _date_ref, + 'render': lambda a, v, s: 'There are %s days between them.' % v, + 'warrant': 'computation', + 'independence': 'strong: a day-number formula against walking the calendar ' + 'one month at a time', + 'fragment': 'two ISO dates from 1600 onwards, Gregorian'}, + + {'name': 'integer_sqrt', 'family': 'number_theory', + 'trigger': _SQRT_RX, 'parse': _sqrt_parse, 'fn': _sqrt_fn, 'ref': _sqrt_ref, + 'render': lambda a, v, s: ('%d is %s perfect square.' + % (a['n'], 'a' if v == 'yes' else 'not a') + if a['want'] == 'perfect' + else 'The integer square root of %d is %s.' + % (a['n'], v)), + 'warrant': 'computation', + 'independence': 'strong: Newton iteration against binary search on the answer', + 'fragment': 'non-negative whole numbers, exact, no decimals'}, + + {'name': 'fraction_arith', 'family': 'number_theory', + 'trigger': _FRAC_RX, 'parse': _frac_parse, 'fn': _frac_fn, 'ref': _frac_ref, + 'render': lambda a, v, s: '%d/%d %s %d/%d is %s.' % (a['a'], a['b'], a['op'], + a['c'], a['d'], _fmt(v)), + 'warrant': 'computation', + 'independence': 'moderate: library rationals against hand cross-multiplication ' + 'with a gcd written here; the arithmetic differs, the algebra ' + 'is the same', + 'fragment': 'two fractions, one operation, exact'}, +] + +SPECS = list(_V1_SPECS) + NEW_SPECS +SPEC_BY_NAME = {s['name']: s for s in SPECS} diff --git a/root/wander-train/oracle_release_runtime_ad.py b/root/wander-train/oracle_release_runtime_ad.py new file mode 100644 index 0000000000000000000000000000000000000000..7f9b358f7ce5e5b09057b48bd2166e9dd50e1483 --- /dev/null +++ b/root/wander-train/oracle_release_runtime_ad.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Runtime AD - serve the corroborated subset of the deductive closure (additive over AC). + +The closure engine derived 32,724 facts. Only 6,768 of them carry independent +corroboration through a distinct middle; the rest were derived by valid steps +from attested premises but nothing outside the derivation vouches for them. +Serving all of them would break citation-or-derivation-or-refusal, so M30 gates +the store and this runtime serves the admitted subset only. + +Two design commitments: + +1. STRICTLY ADDITIVE. This runtime calls the existing chain FIRST and engages + only where that chain declined to answer. It can widen coverage; it cannot + change an answer any sealed panel already depends on. + +2. WITHHELD IS NOT FALSE. A fact absent from the admitted store is not reported + as false. In an incomplete record, absence of corroboration is absence of + evidence, and the honest answer stays refusal. The response says which of the + two it is. + +Evidence channels are named in the response so the derivation is shown rather +than asserted. No neural network; no LM call. +""" + +from __future__ import annotations + +import json +import re +import sqlite3 +import time +from pathlib import Path + +from oracle_release_runtime_ac import OracleReleaseRuntimeAC + +ADMITTED_STORE = (__import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/fable-content/oracle-m-series-2026-08-15" + "/m30_admitted_closure_v1.sqlite3") + +_DP = r"(?:an?\s+|the\s+|some\s+)?" +ISA_Q = re.compile( + r"^(?:is|are)\s+" + _DP + r"(?P[a-z][a-z '\-]*?)\s+" + _DP + + r"(?:kind|type|sort)?\s*(?:of\s+)?" + _DP + r"(?P[a-z][a-z '\-]*?)\s*[.?!]*$", re.I) +_FILLER = re.compile(r"\b(?:do you think|would you say|is it true that|really|actually|" + r"even|also|just|by any chance|technically|basically)\b", re.I) +_LEAD = re.compile(r"^(?:so|well|hey|um|please|tell me|i wonder|question:)[\s,]+", re.I) + +CHANNEL_NAMES = { + "sib": "shared classification with concepts already in that category", + "assoc1": "association through related and equivalent terms", + "assoc2": "association through context, derivation and use", + "wiki": "an independent encyclopedic corpus", +} + + +def _singular(concept: str) -> str: + c = concept.strip().lower() + if c.endswith("s") and not c.endswith("ss") and len(c) > 3: + return c[:-1] + return c + + +class OracleReleaseRuntimeAD(OracleReleaseRuntimeAC): + def __init__(self, *args, admitted_store: str = ADMITTED_STORE, **kwargs) -> None: + super().__init__(*args, **kwargs) + self._admitted = None + path = Path(admitted_store) + if path.exists(): + try: + self._admitted = sqlite3.connect( + f"file:{path}?mode=ro&immutable=1", uri=True, check_same_thread=False) + except sqlite3.Error: + self._admitted = None + + def _lookup(self, x: str, y: str) -> dict | None: + if self._admitted is None: + return None + for subject in dict.fromkeys([x, _singular(x)]): + for obj in dict.fromkeys([y, _singular(y)]): + row = self._admitted.execute( + "SELECT score,channels,premises FROM admitted_fact " + "WHERE subject=? AND object=? AND relation='IsA'", (subject, obj)).fetchone() + if row: + return {"subject": subject, "object": obj, "score": row[0], + "channels": row[1], "premises": row[2]} + return None + + def _admitted_turn(self, text: str) -> dict | None: + t = " ".join(text.strip().split()) + t = " ".join(_FILLER.sub("", _LEAD.sub("", t)).split()) + match = ISA_Q.match(t) + if not match: + return None + x = match.group("x").strip().lower() + y = match.group("y").strip().lower() + if not x or not y or x == y or len(x) < 2 or len(y) < 2: + return None + if _singular(x) == _singular(y): + return None + hit = self._lookup(x, y) + if hit is None: + return None + try: + channels = json.loads(hit["channels"]) + except (ValueError, TypeError): + channels = {} + named = [CHANNEL_NAMES[k] for k in ("sib", "assoc1", "assoc2", "wiki") if k in channels] + support = "; ".join(named) if named else "corroboration through a distinct middle" + premises = [p for p in str(hit["premises"]).split(",") if p][:4] + tag = "[derived:closure_admitted<-" + ",".join(p[:24] for p in premises) + "]" + article_x = "an" if x[:1] in "aeiou" else "a" + article_y = "an" if y[:1] in "aeiou" else "a" + return { + "status": "answered", + "path": "closure_admitted_isa", + "response": (f"Yes. This is not stated directly in the admitted record, but it " + f"follows from it, and the conclusion is independently corroborated " + f"by {support}. On that basis {article_x} {x} is {article_y} {y}. {tag}"), + "provenance": {"kind": "derived", "rule": "closure_admitted", + "relation": "IsA", "corroboration_score": hit["score"], + "channels": sorted(channels), "premises": premises}, + } + + def chat(self, text: str, session_id: str = "default") -> dict: + result = super().chat(text, session_id) + if str(result.get("status", "")) == "answered": + return result + started = time.perf_counter() + try: + admitted = self._admitted_turn(text) + except Exception: # noqa: BLE001 + admitted = None + if admitted is None: + return result + admitted["latency_ms"] = round(1000.0 * (time.perf_counter() - started), 1) + admitted["zero_model_gate"] = {"lm_calls": 0, "transformer_calls": 0} + return admitted diff --git a/root/wander-train/oracle_release_runtime_ai.py b/root/wander-train/oracle_release_runtime_ai.py new file mode 100644 index 0000000000000000000000000000000000000000..a6219ab884c59588c89490749297da1d068913d4 --- /dev/null +++ b/root/wander-train/oracle_release_runtime_ai.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Runtime AI - corpus v3 plus the observability conjunct (additive over AH). + +Fixes two defects in the shipped exclusion path. + +**1. FALSE EXCLUSIONS from projection loss.** Corpus v2 stored each hypernym as its +synset's PRIMARY lemma only - `node.name().split(".")[0]` - discarding 64,232 lemma +names across 48.8% of noun synsets. "hand luggage" has hypernym synset baggage.n.01 +whose lemmas are ['baggage','luggage']; a query for "luggage" missed, and the runtime +answered "No" about a lemma WordNet explicitly lists. Corpus v3 stores every lemma; +head-containment now holds for 21,143 two-word compounds against v2's 18,979, so at +least 2,164 false exclusions were available in that class alone. + +**2. NEGATION LICENSED ON HALF THE CONDITION.** Spec v4 invariant C1 requires +completeness AND observability: a known frame tells you what lies outside it, but says +nothing about something inside the frame that fell below detection. WordNet's chains are +complete *for the senses it carries* - a MISSING SENSE is an occlusion, and every +negation shipped so far ignored that. + +Observability is implemented here as a real check rather than an assumption: if an +independent record asserts the relation that WordNet's closure lacks, that is evidence +the lexical record's sense coverage is incomplete for this case. The correct output is +then `X⁻_residual` - withhold with the conflict disclosed - never `X⁻_rejected`. + +Exclusions that survive both conjuncts are unchanged from AH. No neural network. +""" + +from __future__ import annotations + +from pathlib import Path + +from oracle_release_runtime_ah import OracleReleaseRuntimeAH, SHOW_CATEGORIES + +WORDNET_CORPUS_V3 = (__import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/fable-content/oracle-m-series-2026-08-15" + "/m31_wordnet_corpus_v3.sqlite3") + + +class OracleReleaseRuntimeAI(OracleReleaseRuntimeAH): + def __init__(self, *args, wordnet_corpus: str = WORDNET_CORPUS_V3, **kwargs) -> None: + if not Path(wordnet_corpus).exists(): + wordnet_corpus = str(Path(wordnet_corpus).with_name("m31_wordnet_corpus_v2.sqlite3")) + super().__init__(*args, wordnet_corpus=wordnet_corpus, **kwargs) + + def _independently_asserted(self, x: str, y: str) -> str | None: + """Does an independent record assert this relation? Returns its provenance.""" + cs = getattr(self, "commonsense", None) + if cs is None: + return None + forms_y = {y, y[:-1] if y.endswith("s") and not y.endswith("ss") else y} + for subject in {x, x[:-1] if x.endswith("s") and not x.endswith("ss") else x}: + try: + edges = cs.edges(subject, "IsA", limit=48) + except Exception: # noqa: BLE001 + return None + for edge in edges: + end = str(edge.get("end", "")).strip().lower() + if end in forms_y: + return str(edge.get("provenance", "commonsense")) + return None + + 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 + parsed = self._parse_kind(text) + if parsed is None: + return result + x, y = parsed + provenance = self._independently_asserted(x, y) + if provenance is None: + return result # both conjuncts hold: exclusion stands + + # observability fails: an independent record asserts what this one lacks + prov = result.get("provenance", {}) + lemma = prov.get("lemma", x) + cats = self._specific_categories(lemma, SHOW_CATEGORIES) + listed = ", ".join(cats) if cats else "no categories on record" + article_x = "an" if x[:1] in "aeiou" else "a" + article_y = "an" if y[:1] in "aeiou" else "a" + return { + "status": "withheld", + "path": "wordnet_kind_occluded", + "response": ( + f"I am not able to settle this. The lexical record classifies {lemma} under " + f"{listed}, and does not list {y} among them — but a separate record does " + f"assert that {article_x} {x} is {article_y} {y} [{provenance}]. Because the " + f"two disagree, the absence in the lexical record may reflect a sense it does " + f"not carry rather than a fact about {x}, so I am withholding rather than " + f"denying."), + "provenance": { + "kind": "observability_failure", + "rule": "C1_requires_completeness_AND_observability", + "lemma": lemma, + "lexical_categories": cats, + "conflicting_assertion": provenance, + "residual_class": "X_minus_residual", + }, + "zero_model_gate": {"lm_calls": 0, "transformer_calls": 0}, + } diff --git a/root/wander-train/oracle_release_runtime_m.py b/root/wander-train/oracle_release_runtime_m.py new file mode 100644 index 0000000000000000000000000000000000000000..5bbb61fd4282a8536a9762450326a8e63689677e --- /dev/null +++ b/root/wander-train/oracle_release_runtime_m.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Runtime M — capability cycle 8: explain-simply (additive over L). +Simplest admitted definitional statement + Wiktionary first gloss where the +entry exists; register marked; everything addressed.""" + +from __future__ import annotations + +import json +import re +import sqlite3 +import time +from pathlib import Path + +from oracle_release_runtime_l import OracleReleaseRuntimeL +from oracle_release_runtime import PHASE +from stage5m13e8_relevance_gate_v1 import gate_bundle +from stage5m13e8_paragraph_compiler_v1 import _definitional_score + +SIMPLY = re.compile( + r"^(?:please )?explain (?:the |a |an )?(?P.+?)(?: simply| in simple (?:terms|words)| like i(?:'m| am) new to it)[.?!]?$" + r"|^what is (?:the |a |an )?(?P.+?), in simple (?:terms|words)\??$", + re.I) +WIKT = PHASE / "m13e5_wiktionary_build_a_v1" / "wiktionary_specialist.sqlite3" + + +class OracleReleaseRuntimeM(OracleReleaseRuntimeL): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._wikt = None + if WIKT.exists(): + self._wikt = sqlite3.connect(WIKT.resolve().as_uri() + "?mode=ro&immutable=1", uri=True) + + def _gloss(self, term: str) -> str | None: + if self._wikt is None: + return None + row = self._wikt.execute("SELECT glosses_json FROM entry WHERE word=? AND pos='noun' LIMIT 1", + (term.lower(),)).fetchone() or \ + self._wikt.execute("SELECT glosses_json FROM entry WHERE word=? LIMIT 1", + (term.lower(),)).fetchone() + if not row: + return None + glosses = json.loads(row[0]) + return glosses[0] if glosses else None + + def _simply_turn(self, text: str, session_id: str) -> dict | None: + 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 + admitted, _ = gate_bundle(topic, self._bundle(topic, n=8)) + 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 = [] + premises = [] + if admitted: + # true definitions that are also short; else the best true definition + short_defs = [c for c in admitted if len(c["sentence"].split()) <= 30 + and _definitional_score(topic, c["sentence"]) >= 6] + pool = short_defs or admitted + lead = max(pool, key=lambda c: (_definitional_score(topic, c["sentence"]), + -len(c["sentence"].split()))) + 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 chat(self, text: str, session_id: str = "default") -> dict: + started = time.perf_counter() + normalized = " ".join(text.strip().split()) + result = None + try: + result = self._simply_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) diff --git a/root/wander-train/oracle_release_runtime_y.py b/root/wander-train/oracle_release_runtime_y.py new file mode 100644 index 0000000000000000000000000000000000000000..463dd4e00c82be34df18e82dfa6a63cbdb3d8777 --- /dev/null +++ b/root/wander-train/oracle_release_runtime_y.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Runtime Y — M24 explanatory routes (additive over X): how / what-causes / when. + +Live probing (2026-08-20) found three of the most common question forms in +English had no working route, while the admitted corpus plainly contained the +answers: + + "How does a volcano erupt?" -> clarify (corpus: "When there is enough + pressure, the volcano erupts.") + "What causes earthquakes?" -> withheld (corpus: "Earthquakes are caused by + tectonic movements in the Earth's crust.") + "When did World War 2 start?"-> withheld (corpus: "The war in Europe began when + Nazi Germany invaded Poland on 1 September 1939.") + +So this is a ROUTING gap, not a knowledge gap. Each route resolves the topic +through the existing anchor store, pulls the page's admitted sentences via the +existing bundle primitive, and selects the sentence whose form actually answers +the question (causal cue / process cue / date+inception cue). Selection is +cue-based and deterministic — it never composes a claim, it only chooses which +admitted sentence to cite, and abstains when none matches. Citations ride the +normal claim-id path.""" + +from __future__ import annotations + +import re +import time + +from oracle_release_runtime_x import OracleReleaseRuntimeX + +HOW_Q = re.compile(r"^how\s+(?:does|do|did|is|are|can)\s+(?:an?\s+|the\s+)?" + r"(?P[\w' \-]+?)\s+(?:work|works|erupt|erupts|happen|happens|form|forms|" + r"occur|occurs|made|grow|grows|move|moves|function|functions)\b[^?]*\??$", re.I) +CAUSE_Q = re.compile(r"^(?:what\s+causes?|what\s+makes?|why\s+(?:do|does|are|is))\s+" + r"(?:an?\s+|the\s+)?(?P[\w' \-]+?)\s*(?:happen|occur|erupt|form|work)?\s*\??$", re.I) +WHEN_Q = re.compile(r"^when\s+(?:did|was|does|do|were)\s+(?:the\s+)?(?P[\w' \-]+?)\s+" + r"(?Pstart|begin|end|happen|occur|founded|built|discovered|invented|born|die)\w*\s*\??$", re.I) + +CUE_CAUSE = re.compile(r"\b(caused by|causes|because|due to|results? from|produced by|" + r"triggered by|happens when|occurs when|when .{3,40} (?:meet|collide|move))\b", re.I) +CUE_PROCESS = re.compile(r"\b(happens when|occurs when|forms? when|when there is|process|" + r"works? by|is made|are made|by which|through which)\b", re.I) +YEAR = re.compile(r"\b(1[0-9]{3}|20[0-2][0-9])\b") +CUE_INCEPT = re.compile(r"\b(began|begun|started|founded|opened|created|established|" + r"broke out|ended|discovered|invented|born|died)\b", re.I) + +BUNDLE_N = 60 + + +class OracleReleaseRuntimeY(OracleReleaseRuntimeX): + def _pick(self, topic: str, cue, *, require_year: bool = False, + second_cue=None) -> list[dict]: + """Admitted sentences from the topic's page whose FORM answers the question.""" + bundle = self._bundle(topic, n=BUNDLE_N) + if not bundle: + # plural surface ("what causes earthquakes") vs singular page title + 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=BUNDLE_N) + if not bundle: + return [] + hits = [] + for claim in bundle: + sentence = claim.get("sentence") or "" + if require_year and not YEAR.search(sentence): + continue + if second_cue is not None and not second_cue.search(sentence): + continue + if cue.search(sentence): + hits.append(claim) + return hits + + def _explanatory_turn(self, text: str) -> dict | None: + stripped = " ".join(text.strip().split()) + + match = CAUSE_Q.match(stripped) + if match: + topic = match.group("t").strip() + hits = self._pick(topic, CUE_CAUSE) + return self._render(topic, hits, "cause", "capability:what_causes", + f"what causes {topic}") + + match = HOW_Q.match(stripped) + if match: + topic = match.group("t").strip() + hits = self._pick(topic, CUE_PROCESS) + return self._render(topic, hits, "process", "capability:how_does", + f"how {topic} works") + + match = WHEN_Q.match(stripped) + if match: + topic = match.group("t").strip() + hits = self._pick(topic, CUE_INCEPT, require_year=True) \ + or self._pick(topic, YEAR) + return self._render(topic, hits, "inception", "capability:when_did", + f"when {topic} {match.group('v')}") + + return None + + def _render(self, topic: str, hits: list[dict], kind: str, path: str, + asked: str) -> dict: + if not hits: + return {"status": "withheld", "path": path, + "response": f"The admitted record for {topic} contains no statement that " + f"answers {asked}. I will not infer one.", + "provenance": {"kind": "selected_evidence", "selector": kind, + "topic": topic, "result": "no_matching_statement"}} + lead = hits[0] + parts = [f"According to {lead['page']}, {lead['sentence']} [{lead['claim_id']}]"] + for extra in hits[1:2]: + parts.append(f"{extra['page']} also records: {extra['sentence']} [{extra['claim_id']}]") + return {"status": "answered", "path": path, "response": " ".join(parts), + "provenance": {"kind": "selected_evidence", "selector": kind, "topic": topic, + "premises": [h["claim_id"] for h in hits[:2]]}} + + 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) diff --git a/root/wander-train/oracle_relstore_v1.py b/root/wander-train/oracle_relstore_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..2ea4a583c5281b0ce5b017b5e91bc1265f0497f2 --- /dev/null +++ b/root/wander-train/oracle_relstore_v1.py @@ -0,0 +1,77 @@ +"""oracle_relstore_v1 - read access to the typed relation store (Wikidata, CC0) for the Knowledge tree's relation node. + + entity(title) -> qid for an English Wikipedia title (the same world as the sentence store) + values(qid, p) -> [(o_qid | None, literal | None)] forward: subject --p--> value + subjects(p, o_qid) -> [s_qid] inverse: ? --p--> value + label(qid) -> English label; title(qid) -> enwiki title + classes(qid, depth) -> labels of P31 classes (and P279 parents up to depth) + is_human(qid) -> P31 = Q5 +Every returned fact is addressable as wd:Q P

wd:Q | "literal" - its citation.""" +from __future__ import annotations + +import os +import re +import sqlite3 + +STORE = os.environ.get("ORACLE_RELSTORE") or __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/relstore/relations_v1.sqlite3" + + +def norm(s): + import unicodedata + s = unicodedata.normalize("NFKD", str(s)).encode("ascii", "ignore").decode("ascii") + return " ".join(re.sub(r"[^a-z0-9 ]+", " ", s.lower()).split()) + + +class RelStore: + def __init__(self, path=STORE): + self.db = sqlite3.connect("file:%s?mode=ro&immutable=1" % path, uri=True, check_same_thread=False) + self._lab, self._cls = {}, {} + + def entity(self, title): + r = self.db.execute("SELECT qid FROM entity WHERE enwiki=? LIMIT 1", (title,)).fetchone() + if r: + return r[0] + r = self.db.execute("SELECT qid FROM entity WHERE enwiki=? COLLATE NOCASE LIMIT 1", (title,)).fetchone() + return r[0] if r else None + + def values(self, qid, p): + return self.db.execute("SELECT o, lit FROM fact WHERE s=? AND p=?", (qid, p)).fetchall() + + def subjects(self, p, o, limit=200): + return [r[0] for r in self.db.execute("SELECT s FROM fact WHERE p=? AND o=? LIMIT ?", (p, o, limit)).fetchall()] + + def props_of(self, qid): + return self.db.execute("SELECT p, o, lit FROM fact WHERE s=?", (qid,)).fetchall() + + def label(self, qid): + if qid not in self._lab: + r = self.db.execute("SELECT label, enwiki FROM entity WHERE qid=?", (qid,)).fetchone() + self._lab[qid] = (r[0] or r[1]) if r else None + return self._lab[qid] + + def title(self, qid): + r = self.db.execute("SELECT enwiki FROM entity WHERE qid=?", (qid,)).fetchone() + return r[0] if r else None + + def classes(self, qid, depth=2): + key = (qid, depth) + if key in self._cls: + return self._cls[key] + out, frontier, seen = set(), [o for o, _ in self.values(qid, 31) if o], set() + for d in range(depth + 1): + nxt = [] + for c in frontier: + if c in seen: + continue + seen.add(c) + lab = self.label(c) + if lab: + out.add(norm(lab)) + if d < depth: + nxt += [o for o, _ in self.values(c, 279) if o] + frontier = nxt + self._cls[key] = out + return out + + def is_human(self, qid): + return any(o == 5 for o, _ in self.values(qid, 31)) diff --git a/root/wander-train/oracle_siblings_bed2_v1.py b/root/wander-train/oracle_siblings_bed2_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..77ed7ba1981a3b6745c0dc33c0834d6ed4c7c4c1 --- /dev/null +++ b/root/wander-train/oracle_siblings_bed2_v1.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +"""Bed 2 - four more plants, one per unoccupied catalogue position. + +Ben: "plants want more expressions." Each sibling differs from Oracle7even at the SUBSTRATE +on one catalogued axis. None is a register. Each goes through the same three gates: M56 +(category or costume), M58 (garden admission), M59 (residual exchange). Same instruments; +the family-coverage number is the garden's yield. + + TOPOLOGICAL memory_geometry = topological. Recall by POSITION IN THE SHAPE, not recency: + the referent for a deictic is the topic with the most relational mass in the + session (most turns touching it, most citations under it), not the last one. + A mind for which "it" means "the thing this conversation is ABOUT." + + COMPRESSED provenance_retention = transformation_families. Warrant is compressed to the + OPERATOR that produced it; "how do you know?" replays the family, not the + addresses. Tests whether provenance survives compression. + + EPOCHAL temporal_rhythm = epochal. Dialogue state integrates only at declared + boundaries (every K turns); between boundaries the mind answers from the + last sealed state. A mind that does not change mid-conversation. + + EVIDENTIAL the first NON-ENGLISH position. Readings drawn from a grammar with obligatory + evidentiality (Turkish -mIs/-DI, Quechua -mi/-si/-cha, Tariana): every + statement must mark HOW the speaker knows. This mind reads input through that + grammar - "I heard X", "I saw X", "X, apparently" are DIFFERENT typed forms - + and its answers carry the evidential the record licenses: direct (cited), + inferred (derived), reported (attested by a source), unknown (withheld). + English has no such reading; the catalogue's inherited frame was all English. + +Every plant preserves the digest law: answers come from the unchanged chain with their +warrant. A plant changes WHICH reading, WHICH referent, WHEN state moves, or HOW warrant +is rendered - never what counts as warrant. + +No neural network; no LM call. +""" + +from __future__ import annotations + +import re +from collections import Counter, defaultdict + +from oracle_release_runtime_ao import OracleReleaseRuntimeAO + +CITE = re.compile(r"\[[a-z0-9_]+:?[a-z0-9_.\-]*\]") +DEICTIC = re.compile(r"\b(it|there|that|this|its|they|them|those|these)\b", re.I) +OPENER = re.compile(r"^(?:summari[sz]e|what is|tell me about|describe|what causes)\s+(?P.+?)[.?!]*$", re.I) + + +# ── 1. TOPOLOGICAL memory ─────────────────────────────────────────────────────── +class SiblingTopological(OracleReleaseRuntimeAO): + """Referent = the topic with the most relational MASS in the session, not the latest.""" + + def _live_topic(self, session_id: str): + mass = Counter() + for tr in self.path(session_id): + if tr.get("out_status") != "answered": + continue + t = None + m = OPENER.match(str(tr.get("in_surface", "")).strip()) + if m: + t = m.group("t").strip() + else: + cv = tr.get("conversion") or {} + m2 = re.match(r"^summari[sz]e\s+(?P.+?)[.?!]*$", str(cv.get("to", "")), re.I) + t = m2.group("t").strip() if m2 else None + if t: + mass[t.lower()] += 1 + int(tr.get("citations", 0) or 0) + if not mass: + return super()._live_topic(session_id) + return mass.most_common(1)[0][0] + + +# ── 2. COMPRESSED provenance ──────────────────────────────────────────────────── +FAMILY_OF = { + "capability:summarize": "page-summary", "definitional_encyclopedic": "page-lead", + "capability:what_causes": "evidence-selection", "capability:explain_simply": "re-register", + "conceptnet_isa_derived": "transitive-derivation", "conceptnet_isa_direct": "edge-citation", + "conceptnet_partof_direct": "edge-citation", "conceptnet_partof_derived": "transitive-derivation", + "wordnet_kind_direct": "hierarchy-lookup", "wordnet_kind_excluded": "hierarchy-exclusion", + "wordnet_kind_occluded": "conflict-disclosure", +} + + +class SiblingCompressed(OracleReleaseRuntimeAO): + """Warrant compressed to the TRANSFORMATION FAMILY; replay names the family, not addresses.""" + + def _act_provenance_replay(self, state: dict) -> dict: + last = state.get("last_result") or {} + if not last: + return {"status": "withheld", "path": "act:provenance_replay", + "response": "Nothing has been answered in this session yet."} + fam = FAMILY_OF.get(str(last.get("path", "")), "unregistered-family") + n = len(last.get("citations") or []) + answered = str(last.get("status", "")) == "answered" + if not answered: + return {"status": "answered", "path": "act:provenance_replay", + "response": f"My previous turn was a typed refusal; no family produced an answer.", + "provenance": {"kind": "family_replay", "family": None}} + return {"status": "answered", "path": "act:provenance_replay", + "response": (f"My previous answer was produced by the {fam} family" + + (f", over {n} admitted addresses" if n else "") + + ". I retain the family, not the addresses."), + "provenance": {"kind": "family_replay", "family": fam, "address_count": n}} + + +# ── 3. EPOCHAL rhythm ─────────────────────────────────────────────────────────── +class SiblingEpochal(OracleReleaseRuntimeAO): + """Dialogue state integrates only every K turns; between seals, answers come from the + last sealed state.""" + K = 3 + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._sealed: dict = {} + self._count: Counter = Counter() + + def chat(self, text: str, session_id: str = "default") -> dict: + import copy + self._count[session_id] += 1 + if session_id in self._sealed: + self.dialogue[session_id] = copy.deepcopy(self._sealed[session_id]) + result = super().chat(text, session_id) + if self._count[session_id] % self.K == 0: + self._sealed[session_id] = copy.deepcopy(self.dialogue.get(session_id) or {}) + return result + + +# ── 4. EVIDENTIAL grammar ─────────────────────────────────────────────────────── +HEARSAY = re.compile(r"^(?:i heard (?:that )?|they say (?:that )?|apparently,?\s*|reportedly,?\s*|" + r"someone said (?:that )?|is it true (?:that )?)(?P

.+?)[.?!]*$", re.I) +DIRECT = re.compile(r"^(?:i saw (?:that )?|i know (?:that )?|i noticed (?:that )?)(?P

.+?)[.?!]*$", re.I) +INFER = re.compile(r"^(?:so |then |i guess |presumably,?\s*|it seems (?:that )?)(?P

.+?)[.?!]*$", re.I) + + +class SiblingEvidential(OracleReleaseRuntimeAO): + """Reads input through an obligatory-evidentiality grammar and marks every answer with + the evidential the record licenses.""" + + def _evidential_of(self, result: dict) -> str: + if result.get("status") != "answered": + return "unknown" + kind = str(result.get("provenance", {}).get("kind", "")) + cites = CITE.findall(str(result.get("response", ""))) + if kind in ("derived",): + return "inferred" + if kind in ("lexical_corpus", "commonsense_edge") or cites: + return "direct" + if kind in ("gated_summary", "selected_evidence", "dbpedia_page"): + return "reported" + return "unknown" + + 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: + # a hearsay/inference-marked input is a claim to CHECK, not a question to answer: + # re-read it as a kind or summary probe of its proposition + probe = proposition if re.match(r"^(is|are|what|who|when|how)\b", proposition, re.I) \ + else f"Summarize {proposition}." + self._pending_conversion[session_id] = { + "construction": f"EVIDENTIAL:{marked}", "from": s[:80], "to": probe[:80], + "produced_by": "sibling:evidential"} + result = super().chat(probe, session_id) + else: + result = super().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] + if marked == "hearsay" and ev in ("direct", "inferred"): + result["response"] = f"{tag} What you heard is supported. " + str(result.get("response", "")) + elif marked == "hearsay": + result["response"] = f"{tag} " + str(result.get("response", "")) + else: + result["response"] = f"{tag} " + str(result.get("response", "")) + hist = getattr(self, "_paths", {}).get(session_id) + if hist: + hist[-1]["evidential"] = result["evidential"] + return result + + +BED2 = {"topological": SiblingTopological, "compressed": SiblingCompressed, + "epochal": SiblingEpochal, "evidential": SiblingEvidential} diff --git a/root/wander-train/relation_readers_v1.py b/root/wander-train/relation_readers_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..faba7ef364fdf96ff433feb6c7690a155f65d4c6 --- /dev/null +++ b/root/wander-train/relation_readers_v1.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +"""relation_readers_v1 - Oracle7's hand-written RELATION READERS (the specialist factory's way: readers are written, then +measured). Each Wikidata property has FORWARD phrasings ("{X}" = the entity asked about; the answer is its value) and +INVERSE phrasings ("{X}" = the value; the answer is the one in-domain entity holding it). A phrasing must match the WHOLE +question (lower-cased, trailing punctuation dropped), so no premise or extra condition can ride along unread; the slot must +be a whole entity name. Every phrasing is measured on natural TRAIN questions before use (relreader_measure_v1): one that +fires >= 5 times below 90% answering precision is dropped. +Properties with units the store does not keep (area, length, elevation) are not read; dates use the router's display.""" + +X = r"(?P.+?)" +THE = r"(?:the )?" +WAS = r"(?:is|was|are|were)" + +PROPS = { + # ---- people + 19: {"label": "place of birth", "fwd": [r"where " + WAS + r" " + X + r" born", r"in (?:which|what) (?:city|town|place) " + WAS + r" " + X + r" born", + r"what (?:is|was) (?:the )?(?:birthplace|place of birth) of " + X, r"what (?:is|was) " + X + r"'s (?:birthplace|place of birth)"]}, + 20: {"label": "place of death", "fwd": [r"where did " + X + r" die", r"in (?:which|what) (?:city|town|place) did " + X + r" die", + r"what (?:is|was) (?:the )?place of death of " + X]}, + 569: {"label": "date of birth", "fwd": [r"when " + WAS + r" " + X + r" born", r"in what year " + WAS + r" " + X + r" born", + r"what (?:is|was) " + X + r"'s (?:date of birth|birth date|birthday)", r"what year " + WAS + r" " + X + r" born"]}, + 570: {"label": "date of death", "fwd": [r"when did " + X + r" die", r"in what year did " + X + r" die", r"what year did " + X + r" die", + r"when " + WAS + r" " + X + r"'s death"]}, + 27: {"label": "country of citizenship", "fwd": [r"what nationality (?:is|was) " + X, r"which country (?:is|was) " + X + r" (?:a )?(?:citizen|national) of", + r"what (?:is|was) " + X + r"'s nationality", r"what country (?:is|was) " + X + r" from"]}, + 26: {"label": "spouse", "fwd": [r"who (?:is|was) " + X + r" married to", r"who (?:is|was) " + X + r"'s (?:wife|husband|spouse)", + r"who (?:is|was) the (?:wife|husband|spouse) of " + X, r"who did " + X + r" marry"], + "inv": [r"which (?:actor|actress|singer|man|woman|king|queen|politician|writer|person) (?:is|was) married to " + X, + r"who (?:is|was) married to " + X]}, + 22: {"label": "father", "fwd": [r"who (?:is|was) " + X + r"'s father", r"who (?:is|was) the father of " + X]}, + 25: {"label": "mother", "fwd": [r"who (?:is|was) " + X + r"'s mother", r"who (?:is|was) the mother of " + X]}, + 140: {"label": "religion", "fwd": [r"what religion (?:is|was|did) " + X + r"(?: follow| practi[cs]e)?", r"what (?:is|was) " + X + r"'s religion"]}, + 102: {"label": "member of political party", "fwd": [r"(?:which|what) (?:political )?party (?:is|was|does|did) " + X + r" (?:a member of|belong to|represent)", + r"(?:which|what) party (?:is|was) " + X + r" (?:in|from)"]}, + 1303: {"label": "instrument", "fwd": [r"what instrument (?:does|did) " + X + r" play", r"which instrument (?:does|did) " + X + r" play", + r"what (?:is|was) " + X + r"'s instrument"]}, + 463: {"label": "member of", "fwd": [r"(?:which|what) (?:band|group) (?:is|was) " + X + r" (?:a member of|in|part of)", + r"(?:which|what) (?:band|group) did " + X + r" (?:sing|play) (?:in|with|for)"]}, + 413: {"label": "position played", "fwd": [r"what position (?:does|did) " + X + r" play"]}, + 641: {"label": "sport", "fwd": [r"what sport (?:does|did) " + X + r" play", r"which sport (?:is|was) " + X + r" (?:known|famous) for"]}, + 1532: {"label": "country for sport", "fwd": [r"which country (?:does|did) " + X + r" (?:represent|play for|compete for)"]}, + 53: {"label": "family", "fwd": [r"(?:which|what) (?:royal )?(?:house|dynasty|family) did " + X + r" belong to", + r"(?:which|what) (?:royal )?(?:house|dynasty) (?:is|was) " + X + r" (?:from|of|a member of)"]}, + 1366: {"label": "replaced by", "fwd": [r"who succeeded " + X, r"who (?:was|is) " + X + r"'s successor", r"who (?:came|reigned) after " + X]}, + 1365: {"label": "replaces", "fwd": [r"who preceded " + X, r"who (?:was|is) " + X + r"'s predecessor", r"who (?:came|reigned) before " + X]}, + # ---- works + 50: {"label": "author", "fwd": [r"who wrote " + X, r"who (?:is|was) the author of " + X, r"which (?:author|writer|novelist|poet|playwright) wrote " + X, + r"who is " + X + r" by", r"" + X + r" (?:is|was) written by (?:whom|who)", r"who penned " + X]}, + 57: {"label": "director", "fwd": [r"who directed " + X, r"who (?:is|was) the director of " + X, r"which (?:film )?director (?:made|directed) " + X]}, + 58: {"label": "screenwriter", "fwd": [r"who wrote the (?:screenplay|script) (?:for|of) " + X]}, + 86: {"label": "composer", "fwd": [r"who composed " + X, r"who (?:is|was) the composer of " + X, r"who wrote the (?:music|score) (?:for|of|to) " + X, + r"which composer wrote " + X]}, + 87: {"label": "librettist", "fwd": [r"who wrote the libretto (?:for|of|to) " + X]}, + 676: {"label": "lyricist", "fwd": [r"who wrote the (?:lyrics|words) (?:for|of|to) " + X]}, + 175: {"label": "performer", "fwd": [r"who (?:sang|sings|performed|recorded|released) " + X, + r"which (?:band|group|artist|singer|musician) (?:sang|recorded|released|performed|had a hit with) " + X, + r"who (?:is|was) the (?:singer|performer|artist) (?:of|on|behind) " + X]}, + 170: {"label": "creator", "fwd": [r"who (?:created|made|sculpted|drew) " + X, r"who (?:is|was) the creator of " + X, + r"which artist (?:created|made|sculpted) " + X]}, + "170p": {"label": "creator (painter)", "prop": 170, "fwd": [r"who painted " + X, r"which (?:artist|painter) painted " + X]}, + 577: {"label": "publication date", "fwd": [r"when (?:was|were) " + X + r" (?:first )?(?:published|released)", r"in what year (?:was|were) " + X + r" (?:first )?(?:published|released)", + r"what year (?:was|were) " + X + r" (?:first )?(?:published|released)"]}, + 156: {"label": "followed by", "fwd": [r"what (?:is|was) the sequel to " + X, r"what (?:came|comes) after " + X + r" in the series"]}, + 144: {"label": "based on", "fwd": [r"what (?:is|was) " + X + r" based on", r"which (?:book|novel|play|story) (?:is|was) " + X + r" based on"]}, + 840: {"label": "narrative location", "fwd": [r"where (?:is|was) " + X + r" set", r"in (?:which|what) (?:city|country|town|place) (?:is|was) " + X + r" set"]}, + 449: {"label": "original broadcaster", "fwd": [r"(?:which|what) (?:network|channel|tv channel|broadcaster) (?:aired|broadcast|showed|first aired) " + X, + r"on (?:which|what) (?:network|channel) did " + X + r" (?:air|first air)"]}, + 264: {"label": "record label", "fwd": [r"(?:which|what) (?:record )?label (?:released|issued) " + X, r"on (?:which|what) (?:record )?label was " + X + r" released"]}, + 178: {"label": "developer", "fwd": [r"who developed " + X, r"which (?:company|studio) developed " + X, r"who (?:is|was) the developer of " + X]}, + 123: {"label": "publisher", "fwd": [r"who publishe[sd] " + X, r"which (?:company )?publishe[sd] " + X, r"who (?:is|was) the publisher of " + X]}, + 195: {"label": "collection", "fwd": [r"(?:which|what) (?:museum|gallery) (?:houses|holds|owns|has|displays) " + X, r"in (?:which|what) (?:museum|gallery) (?:is|can you see) " + X, + r"where (?:is|can you see) " + X + r" (?:displayed|exhibited|on display|kept)"]}, + 287: {"label": "designed by", "fwd": [r"who designed " + X, r"who (?:is|was) the designer of " + X]}, + # ---- places + 17: {"label": "country", "fwd": [r"in (?:which|what) country is " + X, r"(?:which|what) country is " + X + r" in", r"" + X + r" is in (?:which|what) country", + r"in (?:which|what) country (?:is|was) " + X + r" located"]}, + 36: {"label": "capital", "fwd": [r"what is the capital (?:city )?of " + X, r"(?:which|what) city is the capital of " + X, r"name the capital of " + X, + r"what is " + X + r"'s capital(?: city)?"], + "inv": [r"" + X + r" is the capital (?:city )?of (?:which|what) (?:country|state|nation|province|region|island|territory|county)", + r"(?:which|what) (?:country|state|nation|province|region|island|territory)'s capital is " + X, + r"of (?:which|what) (?:country|state|nation|province|region|island|territory) is " + X + r" the capital"]}, + 38: {"label": "currency", "fwd": [r"what is the currency of " + X, r"(?:which|what) currency (?:is used|is legal tender|do they use|does .+ use) in " + X, + r"what (?:currency|money) (?:is used|do people use) in " + X, r"what is " + X + r"'s currency"], + "inv": [r"(?:which|what) country(?:'s)? (?:currency is|uses) (?:the )?" + X, r"(?:the )?" + X + r" is the currency of (?:which|what) country"]}, + 37: {"label": "official language", "fwd": [r"what is the official language of " + X, r"what (?:is|are) the official languages? of " + X]}, + 30: {"label": "continent", "fwd": [r"(?:on|in) (?:which|what) continent is " + X, r"(?:which|what) continent is " + X + r" (?:on|in)"]}, + 1082: {"label": "population", "fwd": [r"what is the population of " + X, r"how many people live in " + X]}, + 85: {"label": "anthem", "fwd": [r"what is the national anthem of " + X, r"what is " + X + r"'s national anthem"]}, + 474: {"label": "country calling code", "fwd": [r"what is the (?:international )?(?:dialling|dialing|calling|telephone|phone) code (?:for|of) " + X]}, + 403: {"label": "mouth of the watercourse", "fwd": [r"(?:into|in) (?:which|what) (?:sea|ocean|river|lake|body of water) does " + THE + X + r" (?:flow|empty|drain)", + r"where does " + THE + X + r" (?:flow into|empty into|drain into|end)"]}, + 885: {"label": "origin of the watercourse", "fwd": [r"where does " + THE + X + r" (?:rise|begin|start|have its source)", r"what is the source of " + THE + X]}, + 4552: {"label": "mountain range", "fwd": [r"(?:in )?(?:which|what) mountain range is " + X + r"(?: in| part of)?", r"" + X + r" is (?:in|part of) (?:which|what) mountain range"]}, + 610: {"label": "highest point", "fwd": [r"what is the highest (?:point|mountain|peak) (?:in|of|on) " + X, r"what is " + X + r"'s highest (?:point|mountain|peak)"]}, + 206: {"label": "located next to body of water", "fwd": [r"(?:in|on) (?:which|what) (?:sea|ocean|river|lake) (?:is|lies) " + X, r"on (?:which|what) river is " + X]}, + 177: {"label": "crosses", "fwd": [r"(?:which|what) (?:river|body of water|strait|bay) does " + X + r" (?:cross|span)"]}, + 931: {"label": "place served by transport hub", "fwd": [r"(?:which|what) city does " + X + r" serve", r"(?:which|what) city is " + X + r" in"]}, + 115: {"label": "home venue", "fwd": [r"what is the home (?:ground|stadium|venue) of " + X, r"where do " + X + r" play their home (?:games|matches)", + r"(?:which|what) stadium do " + X + r" play (?:in|at)"]}, + 118: {"label": "league", "fwd": [r"(?:which|what) league (?:do|does) " + X + r" play in"]}, + # ---- organisations / things + 571: {"label": "inception", "fwd": [r"when was " + X + r" (?:founded|established|formed|built|created|set up)", r"in what year was " + X + r" (?:founded|established|formed|built)", + r"what year was " + X + r" (?:founded|established|formed|built)"]}, + 112: {"label": "founded by", "fwd": [r"who founded " + X, r"who (?:is|was) the founder of " + X, r"who (?:started|established|set up) " + X]}, + 159: {"label": "headquarters location", "fwd": [r"where (?:is|are) " + X + r"(?:'s)? (?:headquarters|headquartered|based)", r"where are the headquarters of " + X, + r"in (?:which|what) city (?:is|are) " + X + r" (?:headquartered|based)"]}, + 749: {"label": "parent organization", "fwd": [r"(?:which|what) company owns " + X, r"what is the parent company of " + X]}, + 176: {"label": "manufacturer", "fwd": [r"who (?:makes|made|manufactures|manufactured|builds|built|produces|produced) " + X, + r"(?:which|what) company (?:makes|made|manufactures|manufactured|builds|built|produces|produced) " + X]}, + 84: {"label": "architect", "fwd": [r"who (?:was|is) the architect of " + X, r"who designed " + X, r"which architect designed " + X]}, + 1619: {"label": "date of official opening", "fwd": [r"when (?:did|was) " + X + r" (?:open|opened)", r"in what year did " + X + r" open"]}, + "123p": {"label": "publisher (periodical)", "prop": 123, "fwd": [r"who publishes " + X]}, + 291: {"label": "place of publication", "fwd": [r"where is " + X + r" published", r"in (?:which|what) city is " + X + r" published"]}, + 1027: {"label": "conferred by", "fwd": [r"who (?:awards|presents|gives) " + THE + X]}, + # ---- events + 1346: {"label": "winner", "fwd": [r"who won " + THE + X, r"(?:which|what) (?:team|country|nation|club|player|horse|driver) won " + THE + X, + r"who (?:was|were) the winners? of " + THE + X]}, + 276: {"label": "location", "fwd": [r"where (?:was|were) " + THE + X + r" held", r"(?:which|what) city hosted " + THE + X, r"where did " + THE + X + r" take place"]}, + 585: {"label": "point in time", "fwd": [r"when (?:was|did) " + THE + X + r" (?:take place|happen|fought|occur|signed)", r"in what year (?:was|did) " + THE + X + r"(?: take place| happen| occur)?"]}, + 580: {"label": "start time", "fwd": [r"when did " + THE + X + r" (?:start|begin|break out)", r"in what year did " + THE + X + r" (?:start|begin|break out)"]}, + 582: {"label": "end time", "fwd": [r"when did " + THE + X + r" end", r"in what year did " + THE + X + r" end"]}, + 361: {"label": "part of", "fwd": [r"(?:in|of) (?:which|what) war (?:was|is) " + THE + X + r"(?: fought| a battle| part)?", r"" + THE + X + r" was (?:a )?part of (?:which|what) war"]}, + # ---- science / culture + 397: {"label": "parent astronomical body", "fwd": [r"(?:which|what) planet does " + X + r" orbit", r"" + X + r" is a moon of (?:which|what) planet", + r"(?:which|what) planet is " + X + r" a moon of"]}, + 59: {"label": "constellation", "fwd": [r"in (?:which|what) constellation is " + X, r"(?:which|what) constellation is " + X + r" in"]}, + 61: {"label": "discoverer or inventor", "fwd": [r"who (?:discovered|invented) " + X, r"who (?:was|is) the (?:discoverer|inventor) of " + X]}, + 575: {"label": "time of discovery or invention", "fwd": [r"when was " + X + r" (?:discovered|invented)", r"in what year was " + X + r" (?:discovered|invented)"]}, + 828: {"label": "has cause", "fwd": [r"what (?:virus|bacterium|organism|pathogen) causes " + X]}, + 282: {"label": "writing system", "fwd": [r"(?:which|what) (?:script|alphabet|writing system) is " + X + r" written in"]}, + 837: {"label": "day in year for periodic occurrence", "fwd": [r"on what (?:date|day) is " + X + r" (?:celebrated|observed|held)", r"when is " + X + r" (?:celebrated|observed)"]}, + 921: {"label": "main subject", "fwd": [r"what is " + X + r" (?:the |a )?fear of", r"" + X + r" is (?:the |an? )?(?:fear|phobia) of what"]}, + 495: {"label": "country of origin", "fwd": [r"(?:which|what) country (?:does|did) " + THE + X + r" (?:come|originate) from", r"where did " + THE + X + r" originate", + r"(?:in )?(?:which|what) country did " + THE + X + r" originate"]}, + 1080: {"label": "from narrative universe", "fwd": [r"(?:which|what) (?:universe|franchise) is " + X + r" from"]}, +} diff --git a/root/wander-train/stage2d_tree_spine.py b/root/wander-train/stage2d_tree_spine.py new file mode 100644 index 0000000000000000000000000000000000000000..00fafbedf8e2c49bc2c8f6a4c43ca4797130487a --- /dev/null +++ b/root/wander-train/stage2d_tree_spine.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Stage 2D addressable Tree spine. + +The spine keeps the protected root outside the moving bundle, adds path and +node artifacts sequentially under deterministic compositional addresses, and +requires explicit address and fold-key unbinding at Malkuth. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Iterable, Literal, Sequence + +import numpy as np + +from train_stage2a_role_ladder import HRR_DIM, as_real, bind, cosine, normalize, unbind, unitary + + +LaneKind = Literal["path", "node"] + + +@dataclass(frozen=True) +class Lane: + kind: LaneKind + name: str + depth: int + episode: int = 0 + + +@dataclass(frozen=True) +class StoredArtifact: + lane: Lane + address: np.ndarray + artifact: np.ndarray + + +@dataclass(frozen=True) +class ContentComponent: + label: str + key: np.ndarray + artifact: np.ndarray + gain: float + + +def compositional_address(lane: Lane) -> np.ndarray: + """Compose a fixed lane address from independently queryable factors.""" + address = unitary("stage2d:tree-address") + factors = ( + f"stage2d:kind:{lane.kind}", + f"stage2d:depth:{lane.depth}", + f"stage2d:lane:{lane.kind}:{lane.name}", + f"stage2d:episode:{lane.episode}", + ) + for factor in factors: + address = bind(address, unitary(factor)) + return normalize(address) + + +def independent_address(label: str) -> np.ndarray: + return unitary(f"stage2d:independent-address:{label}") + + +def fold_key(kind: LaneKind) -> np.ndarray: + return unitary(f"stage2d:fold:{kind}") + + +def content_key() -> np.ndarray: + return unitary("stage2d:content-rail") + + +def content_component_key(label: str) -> np.ndarray: + return unitary(f"stage3:content-component:{label}") + + +def cleanup( + recovered: np.ndarray, + candidates: Sequence[np.ndarray], +) -> tuple[int, np.ndarray, np.ndarray]: + """Return nearest candidate, its exact prototype, and all cosine scores.""" + scores = np.asarray([cosine(recovered, candidate) for candidate in candidates]) + index = int(np.argmax(scores)) + return index, np.asarray(candidates[index], dtype=np.complex64), scores + + +def aligned_residual(recovered: np.ndarray, target: np.ndarray) -> float: + """Residual energy after optimal complex scalar alignment to the target.""" + denominator = np.vdot(target, target) + coefficient = np.vdot(target, recovered) / max(abs(denominator), 1e-12) + residual = recovered - coefficient * target + return float(np.linalg.norm(residual) / max(float(np.linalg.norm(recovered)), 1e-12)) + + +class TreeSpine: + """A single moving HRR bundle plus an invariant protected root. + + ``add`` never unbinds or replaces earlier objects. ``recover`` is the + Malkuth operation and explicitly inverts both the lane address and its + path/node fold key. + """ + + def __init__(self, protected_root: np.ndarray, content: np.ndarray): + self.protected_root = normalize(np.asarray(protected_root, dtype=np.complex64)) + self.content = normalize(np.asarray(content, dtype=np.complex64)) + self._bundle = bind(content_key(), self.content).astype(np.complex64) + self._stored: list[StoredArtifact] = [] + + @property + def stored(self) -> tuple[StoredArtifact, ...]: + return tuple(self._stored) + + @property + def moving_state(self) -> np.ndarray: + return normalize(self._bundle) + + @property + def physical_complex_dimensions(self) -> int: + # Root is an actual separate invariant rail and its cost is explicit. + return 2 * HRR_DIM + + def add( + self, + lane: Lane, + artifact: np.ndarray, + *, + address: np.ndarray | None = None, + ) -> np.ndarray: + artifact = normalize(np.asarray(artifact, dtype=np.complex64)) + actual_address = compositional_address(lane) if address is None else normalize(address) + contribution = bind(actual_address, bind(fold_key(lane.kind), artifact)) + self._bundle = (self._bundle + contribution).astype(np.complex64) + self._stored.append(StoredArtifact(lane, actual_address, artifact)) + return self.moving_state + + def recover( + self, + lane: Lane, + *, + query_address: np.ndarray | None = None, + ) -> np.ndarray: + address = compositional_address(lane) if query_address is None else normalize(query_address) + recovered = unbind(unbind(self.moving_state, address), fold_key(lane.kind)) + return normalize(recovered) + + def recover_content(self) -> np.ndarray: + return normalize(unbind(self.moving_state, content_key())) + + def resolve_root(self) -> np.ndarray: + # No learned projection and no encounter with the moving bundle. + return self.protected_root.copy() + + def ordered_recovery(self) -> list[tuple[Lane, np.ndarray]]: + return [(item.lane, self.recover(item.lane)) for item in self._stored] + + def real_state(self) -> np.ndarray: + return as_real(self.moving_state) + + +class DepthRailTreeSpine: + """Higher-dimensional secondary control with one bundle per depth. + + This is not dimension-matched to ``TreeSpine``. Its cost is reported via + ``physical_complex_dimensions`` and it cannot silently win the primary + comparison. + """ + + def __init__( + self, + protected_root: np.ndarray, + content: np.ndarray, + depths: Iterable[int], + ): + self.protected_root = normalize(np.asarray(protected_root, dtype=np.complex64)) + self.content = normalize(np.asarray(content, dtype=np.complex64)) + self.depths = tuple(sorted(set(int(depth) for depth in depths))) + self._rails = { + depth: bind(content_key(), self.content).astype(np.complex64) + for depth in self.depths + } + self._stored: list[StoredArtifact] = [] + + @property + def physical_complex_dimensions(self) -> int: + return (1 + len(self.depths)) * HRR_DIM + + def add(self, lane: Lane, artifact: np.ndarray) -> None: + if lane.depth not in self._rails: + raise KeyError(f"unregistered depth {lane.depth}") + artifact = normalize(np.asarray(artifact, dtype=np.complex64)) + address = compositional_address(lane) + contribution = bind(address, bind(fold_key(lane.kind), artifact)) + self._rails[lane.depth] = (self._rails[lane.depth] + contribution).astype(np.complex64) + self._stored.append(StoredArtifact(lane, address, artifact)) + + def recover(self, lane: Lane) -> np.ndarray: + state = normalize(self._rails[lane.depth]) + return normalize(unbind(unbind(state, compositional_address(lane)), fold_key(lane.kind))) + + def resolve_root(self) -> np.ndarray: + return self.protected_root.copy() + + +class DualRailTreeSpine: + """Minimal stabilized spine: separate path and node moving rails.""" + + def __init__(self, protected_root: np.ndarray, content: np.ndarray): + self.protected_root = normalize(np.asarray(protected_root, dtype=np.complex64)) + self.content = normalize(np.asarray(content, dtype=np.complex64)) + self._rails = { + kind: bind(content_key(), self.content).astype(np.complex64) + for kind in ("path", "node") + } + self._stored: list[StoredArtifact] = [] + self._content_components: list[ContentComponent] = [] + + @property + def stored(self) -> tuple[StoredArtifact, ...]: + return tuple(self._stored) + + @property + def content_components(self) -> tuple[ContentComponent, ...]: + return tuple(self._content_components) + + @property + def physical_complex_dimensions(self) -> int: + return 3 * HRR_DIM + + def add( + self, + lane: Lane, + artifact: np.ndarray, + *, + address: np.ndarray | None = None, + ) -> tuple[np.ndarray, np.ndarray]: + artifact = normalize(np.asarray(artifact, dtype=np.complex64)) + actual_address = compositional_address(lane) if address is None else normalize(address) + contribution = bind(actual_address, bind(fold_key(lane.kind), artifact)) + self._rails[lane.kind] = (self._rails[lane.kind] + contribution).astype(np.complex64) + self._stored.append(StoredArtifact(lane, actual_address, artifact)) + return self.moving_state + + @property + def moving_state(self) -> tuple[np.ndarray, np.ndarray]: + return normalize(self._rails["path"]), normalize(self._rails["node"]) + + def recover( + self, + lane: Lane, + *, + query_address: np.ndarray | None = None, + ) -> np.ndarray: + address = compositional_address(lane) if query_address is None else normalize(query_address) + state = normalize(self._rails[lane.kind]) + return normalize(unbind(unbind(state, address), fold_key(lane.kind))) + + def recover_content(self, kind: LaneKind) -> np.ndarray: + return normalize(unbind(normalize(self._rails[kind]), content_key())) + + def add_content_component( + self, label: str, artifact: np.ndarray, gain: float, + ) -> tuple[np.ndarray, np.ndarray]: + if any(component.label == label for component in self._content_components): + raise ValueError(f"duplicate content component {label}") + if not np.isfinite(gain) or gain <= 0.0: + raise ValueError("content-component gain must be positive and finite") + normalized = normalize(np.asarray(artifact, dtype=np.complex64)) + key = content_component_key(label) + contribution = np.float32(gain) * bind(key, normalized) + for kind in ("path", "node"): + self._rails[kind] = (self._rails[kind] + contribution).astype(np.complex64) + self._content_components.append(ContentComponent( + label=label, key=key, artifact=normalized, gain=float(gain), + )) + return self.moving_state + + def recover_content_component( + self, kind: LaneKind, label: str, + ) -> np.ndarray: + component = next( + (item for item in self._content_components if item.label == label), + None, + ) + if component is None: + raise KeyError(f"unregistered content component {label}") + return normalize(unbind(normalize(self._rails[kind]), component.key)) + + def resolve_root(self) -> np.ndarray: + return self.protected_root.copy() + + def real_state(self) -> np.ndarray: + path, node = self.moving_state + return np.concatenate([as_real(path), as_real(node)]).astype(np.float32) diff --git a/root/wander-train/stage5c36_long_horizon_reasoner.py b/root/wander-train/stage5c36_long_horizon_reasoner.py new file mode 100644 index 0000000000000000000000000000000000000000..2da7a8b733532ec196d74a3af4a03f808f3a6948 --- /dev/null +++ b/root/wander-train/stage5c36_long_horizon_reasoner.py @@ -0,0 +1,948 @@ +#!/usr/bin/env python3 +"""C36 recurrent HRR long-horizon reasoner. + +The language model is deliberately outside this module. Anonymous facts are +compiled into HRR addresses, a learned answer-free 10D head routes among +algebraic 6D callables, and a bounded dual-rail Tree spine carries every path +and node contribution. Plaintext resolution is permitted only at Malkuth. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import time +from collections import deque +from dataclasses import dataclass, field +from typing import Any, Iterable, Mapping, Sequence + +import numpy as np + +from oracle_10d_resolution_state import ( + ReversibleOperationLedger, + ResolutionObservation, + array_sha256, + canonical_sha256, + evaluate_resolution, +) +from stage2d_tree_spine import DualRailTreeSpine, Lane +from train_stage2a_role_ladder import ( + HRR_DIM, + PATHS, + bind, + cosine, + normalize, + unbind, + unitary, +) + + +SCHEMA = "oracle-stage5c36-recurrent-hrr-reasoner-v1" +CALLABLES = ( + "advance", + "branch", + "compare", + "repair", + "recall", + "rollback", + "stop", +) +TEN_D_CHANNELS = ( + "root_fidelity", + "role_completeness", + "operation_commitment", + "route_completion", + "conflict_accounting", + "evidence_sufficiency", + "uncertainty_calibration", + "provenance_integrity", + "reversible_trace", + "release_readiness", +) +UPPER_TREE_CYCLE = ( + "keter", "chokmah", "chesed", "netzach", "yesod", "hod", + "geburah", "binah", "tiferet", "keter", +) +MULTIHEAD_ADVISORY_KEYS_F = { + rail: np.fft.fft(unitary(f"stage5c36:multihead-advisory:{rail}")).astype(np.complex64) + for rail in ("path", "node") +} + + +def _bind_frequency(key_frequency: np.ndarray, value_frequency: np.ndarray) -> np.ndarray: + """Bind two already-Fourier-resident HRR states with one inverse FFT.""" + return np.fft.ifft(key_frequency * value_frequency).astype(np.complex64) + + +def _digest(value: Any) -> str: + data = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True) + return hashlib.sha256(data.encode("utf-8")).hexdigest() + + +def _softmax(values: np.ndarray) -> np.ndarray: + shifted = values - np.max(values) + exp = np.exp(shifted) + return exp / max(float(exp.sum()), 1e-12) + + +@dataclass(frozen=True) +class RouterDecision: + callable_name: str + confidence: float + probabilities: tuple[float, ...] + + +@dataclass +class TenDCallableRouter: + """A tiny ridge head over answer-free resolution residuals.""" + + weights: np.ndarray + training_rows: int + training_accuracy: float + validation_accuracy: float + + @staticmethod + def _teacher( + *, terminal: bool, corrupted: bool, match_count: int, + memory_available: bool, branch_pending: bool, + ) -> str: + if terminal: + return "stop" + if corrupted: + return "rollback" + if branch_pending: + return "compare" + if match_count > 1: + return "branch" + if match_count == 0 and memory_available: + return "recall" + if match_count == 0: + return "repair" + return "advance" + + @staticmethod + def state( + *, progress: float, terminal: bool, corrupted: bool, + match_count: int, memory_available: bool, branch_pending: bool, + ) -> np.ndarray: + """Construct the state-to-be-met; no answer or endpoint is a feature.""" + return np.asarray(( + 1.0 if corrupted else 0.0, + 0.0, + 1.0 if match_count == 0 else 0.0, + max(0.0, 1.0 - float(progress)), + 0.75 if match_count > 1 else 0.0, + 1.0 if match_count == 0 else 0.0, + 0.50 if branch_pending else 1.0 if corrupted else 0.0, + 0.50 if memory_available else 0.0, + 0.50 if branch_pending else 0.0, + 0.0 if terminal else 1.0, + ), dtype=np.float64) + + @classmethod + def train(cls, *, seed: int = 3601, rows: int = 4096, ridge: float = 1e-4) -> "TenDCallableRouter": + rng = np.random.default_rng(seed) + features: list[np.ndarray] = [] + targets: list[int] = [] + # Canonical structural states make every callable independently + # observable without any endpoint supervision. Progress and benign + # nuisance flags vary, but logically contradictory priority states + # (for example terminal-and-corrupted) are excluded. + states: list[tuple[float, bool, bool, int, bool, bool]] = [] + while len(states) < rows: + progress = float(rng.random()) + action = CALLABLES[len(states) % len(CALLABLES)] + if action == "advance": + state = (progress, False, False, 1, bool(rng.integers(0, 2)), False) + elif action == "branch": + state = (progress, False, False, int(rng.choice((2, 3, 4))), False, False) + elif action == "compare": + state = (progress, False, False, int(rng.choice((2, 3, 4))), False, True) + elif action == "repair": + state = (progress, False, False, 0, False, False) + elif action == "recall": + state = (progress, False, False, 0, True, False) + elif action == "rollback": + state = (progress, False, True, int(rng.choice((0, 1, 2))), False, False) + else: + state = (1.0, True, False, 0, False, False) + states.append(state) + for progress, terminal, corrupted, count, memory, pending in states: + vector = cls.state( + progress=progress, terminal=terminal, corrupted=corrupted, + match_count=count, memory_available=memory, branch_pending=pending, + ) + features.append(np.concatenate(([1.0], vector, vector * vector))) + label = cls._teacher( + terminal=terminal, corrupted=corrupted, match_count=count, + memory_available=memory, branch_pending=pending, + ) + targets.append(CALLABLES.index(label)) + x = np.stack(features) + y = np.eye(len(CALLABLES), dtype=np.float64)[targets] + order = rng.permutation(len(x)) + cut = int(0.8 * len(order)) + train_idx, validation_idx = order[:cut], order[cut:] + gram = x[train_idx].T @ x[train_idx] + weights = np.linalg.solve( + gram + ridge * np.eye(gram.shape[0]), x[train_idx].T @ y[train_idx] + ) + # The head has a very wide decision margin. Fixed decimal + # quantization suppresses harmless LAPACK-level platform drift while + # preserving identical routing decisions across local and Box C CPUs. + weights = np.round(weights, decimals=8) + train_accuracy = float(np.mean(np.argmax(x[train_idx] @ weights, axis=1) == np.asarray(targets)[train_idx])) + validation_accuracy = float(np.mean(np.argmax(x[validation_idx] @ weights, axis=1) == np.asarray(targets)[validation_idx])) + return cls(weights, len(states), train_accuracy, validation_accuracy) + + def decide(self, state: np.ndarray) -> RouterDecision: + vector = np.asarray(state, dtype=np.float64) + if vector.shape != (10,): + raise ValueError("10D callable router requires exactly ten residual coordinates") + expanded = np.concatenate(([1.0], vector, vector * vector)) + probabilities = _softmax(8.0 * (expanded @ self.weights)) + winner = int(np.argmax(probabilities)) + return RouterDecision(CALLABLES[winner], float(probabilities[winner]), tuple(float(v) for v in probabilities)) + + def as_dict(self) -> dict[str, Any]: + return { + "schema_version": "oracle-stage5c36-answer-free-10d-router-v1", + "channels": list(TEN_D_CHANNELS), + "callables": list(CALLABLES), + "training_rows": self.training_rows, + "training_accuracy": self.training_accuracy, + "validation_accuracy": self.validation_accuracy, + "weights": self.weights.tolist(), + "weights_sha256": hashlib.sha256(np.ascontiguousarray(self.weights).tobytes()).hexdigest(), + } + + +@dataclass(frozen=True) +class GeometricFact: + fact_id: str + address: np.ndarray = field(repr=False, compare=False) + destination: np.ndarray = field(repr=False, compare=False) + provenance_sha256: str + kind: str + revision: int = 0 + admissible: bool = True + + +@dataclass(frozen=True) +class CandidateEvidenceView: + """Answer-free branch metadata exposed to an optional directional router. + + Destination geometry is intentionally absent. A router may select which + provenance-bearing fact to test, but it cannot inspect or decode the state + to which that fact points. + """ + + fact_id: str + provenance_sha256: str + kind: str + revision: int + admissible: bool + + +@dataclass(frozen=True) +class GeometricSnapshot: + handle_id: str + handle: np.ndarray = field(repr=False, compare=False) + facts: tuple[GeometricFact, ...] + payload_digest: str + + +class SymbolGeometry: + """Evaluator-side symbol codebook; only Malkuth may decode it.""" + + def __init__(self, labels: Iterable[str]): + self.labels = tuple(sorted(set(str(label) for label in labels))) + self.vectors = tuple(unitary(f"stage5c36:symbol:{label}") for label in self.labels) + + def vector(self, label: str) -> np.ndarray: + return unitary(f"stage5c36:symbol:{label}") + + def decode(self, value: np.ndarray) -> tuple[str, float, float]: + scores = np.asarray([cosine(value, candidate) for candidate in self.vectors]) + order = np.argsort(scores) + winner = int(order[-1]) + runner_up = float(scores[order[-2]]) if len(order) > 1 else 0.0 + return self.labels[winner], float(scores[winner]), float(scores[winner] - runner_up) + + +def _address(source: np.ndarray, relation: np.ndarray) -> np.ndarray: + return normalize(bind( + unitary("stage5c36:fact-address"), + bind(source, relation), + )) + + +def compile_task_geometry(record: Mapping[str, Any]) -> tuple[SymbolGeometry, tuple[GeometricFact, ...], GeometricSnapshot | None]: + runtime = record["runtime"] + query = runtime["query"] + payload = record.get("substrate_payload_bank", ()) + labels = [query["source"], *query["relation_program"]] + for item in (*runtime["working_facts"], *payload): + labels.extend((item["source"], item["relation"], item["destination"])) + geometry = SymbolGeometry(labels) + + def convert(item: Mapping[str, str]) -> GeometricFact: + return GeometricFact( + fact_id=item["fact_id"], + address=_address(geometry.vector(item["source"]), geometry.vector(item["relation"])), + destination=geometry.vector(item["destination"]), + provenance_sha256=item["provenance_sha256"], + kind=item["kind"], + revision=int(item.get("revision", 0)), + admissible=bool(item.get("admissible", True)), + ) + + working = tuple(convert(item) for item in runtime["working_facts"]) + snapshot = None + if payload: + payload_digest = _digest(payload) + handle_id = "mh_" + _digest({"task": record["id"], "payload": payload_digest}) + snapshot = GeometricSnapshot( + handle_id=handle_id, + handle=unitary(f"stage5c36:snapshot-handle:{handle_id}"), + facts=tuple(convert(item) for item in payload), + payload_digest=payload_digest, + ) + return geometry, working, snapshot + + +class FactBank: + def __init__(self, facts: Sequence[GeometricFact]): + self.facts = list(facts) + self._index: dict[str, list[GeometricFact]] = {} + for item in self.facts: + self._index.setdefault(array_sha256(item.address), []).append(item) + + def add(self, facts: Sequence[GeometricFact]) -> None: + known = {item.fact_id for item in self.facts} + for item in facts: + if item.fact_id in known: + continue + self.facts.append(item) + self._index.setdefault(array_sha256(item.address), []).append(item) + known.add(item.fact_id) + + def match_address(self, query: np.ndarray, *, threshold: float = 0.985) -> list[GeometricFact]: + query = np.asarray(query, dtype=np.complex64) + exact = self._index.get(array_sha256(query), ()) + if exact: + return [item for item in exact if cosine(query, item.address) >= threshold] + # The slow path is retained for perturbed/noisy states and for causal + # address-axis ablations. Ordinary exact traces use the bounded bucket. + return [item for item in self.facts if cosine(query, item.address) >= threshold] + + def match(self, source: np.ndarray, relation: np.ndarray, *, threshold: float = 0.985) -> list[GeometricFact]: + return self.match_address(_address(source, relation), threshold=threshold) + + +@dataclass(frozen=True) +class CallableEvent: + name: str + step: int + confidence: float + ten_d_state: tuple[float, ...] + match_count: int + + +@dataclass(frozen=True) +class LongHorizonResult: + task_id: str + action: str + endpoint: str | None + support: str | None + reasoning_steps: int + branch_expansions: int + recalled_snapshot: bool + corruption_detected: bool + corruption_recovered: bool + premature_release_blocked: bool + malkuth_only_unbinding: bool + router_trace: tuple[CallableEvent, ...] + ledger_manifest: Mapping[str, Any] + full_audit_performed: bool + inverse_exact: bool + inverse_max_error: float + spine_cleanup_accuracy: float + spine_min_margin: float + resolution_state: Mapping[str, Any] + resolution_object: Any = field(repr=False, compare=False) + elapsed_seconds: float + + +class RecurrentHRRReasoner: + def __init__( + self, + router: TenDCallableRouter, + *, + enable_substrate: bool = True, + enable_recovery: bool = True, + address_ablation: bool = False, + enable_fact_governance: bool = True, + full_audit: bool = True, + ): + self.router = router + self.enable_substrate = enable_substrate + self.enable_recovery = enable_recovery + self.address_ablation = address_ablation + self.enable_fact_governance = enable_fact_governance + self.full_audit = full_audit + + @staticmethod + def _shortest_path(source: str, destination: str) -> tuple[str, ...]: + graph: dict[str, list[str]] = {} + for left, right in PATHS: + graph.setdefault(left, []).append(right) + graph.setdefault(right, []).append(left) + queue = deque([(source, (source,))]) + seen = {source} + while queue: + node, route = queue.popleft() + if node == destination: + return route + for neighbor in graph[node]: + if neighbor not in seen: + seen.add(neighbor) + queue.append((neighbor, (*route, neighbor))) + raise RuntimeError("Tree is disconnected") + + @staticmethod + def _primitive_advance( + source: np.ndarray, + relation: np.ndarray, + candidates: Sequence[GeometricFact], + *, + query_address: np.ndarray | None = None, + ) -> np.ndarray: + query = _address(source, relation) if query_address is None else query_address + # The callable itself is an HRR bind/unbind operator, followed by + # bounded sibling cleanup; it is not an MLP transformation. + recovered = [unbind(bind(query, item.destination), query) for item in candidates] + prototypes = [item.destination for item in candidates] + scores = np.asarray([[cosine(value, proto) for proto in prototypes] for value in recovered]) + index = int(np.argmax(np.diag(scores))) + return prototypes[index].copy() + + @staticmethod + def _primitive_branch(candidates: Sequence[GeometricFact]) -> np.ndarray: + state = np.zeros(HRR_DIM, dtype=np.complex64) + for index, item in enumerate(candidates): + state += bind(unitary(f"stage5c36:branch-slot:{index}"), item.destination) + return normalize(state) + + @staticmethod + def _recover_branches(bundle: np.ndarray, candidates: Sequence[GeometricFact]) -> list[np.ndarray]: + prototypes = [item.destination for item in candidates] + recovered: list[np.ndarray] = [] + for index in range(len(candidates)): + raw = unbind(bundle, unitary(f"stage5c36:branch-slot:{index}")) + scores = [cosine(raw, proto) for proto in prototypes] + recovered.append(prototypes[int(np.argmax(scores))].copy()) + return recovered + + @staticmethod + def _primitive_recall(snapshot: GeometricSnapshot) -> tuple[np.ndarray, tuple[GeometricFact, ...]]: + # Only geometry is addressed here. Lexical payload remains in the + # immutable evaluator-side bank until Malkuth. + packed = np.zeros(HRR_DIM, dtype=np.complex64) + for index, item in enumerate(snapshot.facts): + packed += bind(unitary(f"stage5c36:snapshot-fact:{index}"), item.destination) + packed = normalize(packed) + handle_bound = bind(snapshot.handle, packed) + recovered = unbind(handle_bound, snapshot.handle) + return normalize(recovered), snapshot.facts + + @staticmethod + def _primitive_rollback(checkpoint: np.ndarray) -> np.ndarray: + key = unitary("stage5c36:protected-checkpoint") + return normalize(unbind(bind(key, checkpoint), key)) + + @staticmethod + def _primitive_repair(source: np.ndarray, relation: np.ndarray) -> np.ndarray: + return normalize(bind( + unitary("stage5c36:represented-unresolved"), _address(source, relation) + )) + + @staticmethod + def _primitive_stop(value: np.ndarray) -> np.ndarray: + key = unitary("stage5c36:10d-universal-unbinder") + return normalize(unbind(bind(key, value), key)) + + def _reachable( + self, start: np.ndarray, relations: Sequence[np.ndarray], bank: FactBank, + ) -> list[np.ndarray]: + frontier = [start] + for relation in relations: + next_frontier: list[np.ndarray] = [] + for state in frontier: + query_address = _address(state, relation) + next_frontier.extend( + item.destination for item in bank.match_address(query_address) + ) + # Sibling cleanup deduplicates geometric equivalents. + unique: list[np.ndarray] = [] + for candidate in next_frontier: + if not any(cosine(candidate, existing) > 0.999 for existing in unique): + unique.append(candidate) + frontier = unique + if not frontier: + break + return frontier + + def solve( + self, + record: Mapping[str, Any], + *, + compiled_geometry: tuple[ + SymbolGeometry, + tuple[GeometricFact, ...], + GeometricSnapshot | None, + ] | None = None, + ) -> LongHorizonResult: + started = time.perf_counter() + begin_router_trace = getattr(self.router, "begin_trace", None) + if callable(begin_router_trace): + begin_router_trace(str(record["id"])) + # C41 may share this immutable geometry between independently routed + # reasoning workspaces. Every head still constructs its own fact bank, + # Tree spine, reversible ledger, and Malkuth release route. + if compiled_geometry is None: + geometry, working, snapshot = compile_task_geometry(record) + else: + geometry, working, snapshot = compiled_geometry + runtime = record["runtime"] + query = runtime["query"] + relations = [geometry.vector(label) for label in query["relation_program"]] + if self.address_ablation: + relations = [bind(value, unitary("stage5c36:ablated-address-axis")) for value in relations] + current = geometry.vector(query["source"]) + checkpoint = current.copy() + checkpoint_sha = array_sha256(checkpoint) + protected_root = unitary(f"stage5c36:protected-root:{query['root']}") + ledger = ReversibleOperationLedger() + ledger_state = normalize(bind(unitary("stage5c36:ingress"), protected_root)) + ledger_initial = ledger_state.copy() + bank = FactBank(working) + snapshot_bank = FactBank(snapshot.facts) if snapshot is not None else None + spines = [DualRailTreeSpine(protected_root, current)] + current_spine = spines[-1] + tree_node = "keter" + tree_cycle_index = 0 + visited = [tree_node] + trace: list[CallableEvent] = [] + step = 0 + branch_expansions = 0 + recalled = False + corruption_injected = False + corruption_detected = False + corruption_recovered = False + terminal_action: str | None = None + branch_candidates: list[GeometricFact] | None = None + branch_bundle: np.ndarray | None = None + selected_candidate: GeometricFact | None = None + support_state: np.ndarray | None = None + router_confidences: list[float] = [] + + def append_tree_callable(name: str, payload: np.ndarray, confidence: float) -> None: + nonlocal ledger_state, tree_node, tree_cycle_index, current_spine + cycle_position = UPPER_TREE_CYCLE.index(tree_node) + destination = UPPER_TREE_CYCLE[cycle_position + 1] + sequence = ledger.entries + provenance = hashlib.sha256( + f"{record['id']}:{name}:{step}:{sequence}".encode("utf-8") + ).hexdigest() + path_payload = normalize(bind(unitary(f"stage5c36:6d:{name}"), payload)) + # A cooperative multi-head router may supply an already-bound, + # answer-free advisory state. It is carried on both stabilized + # rails but never decoded here and never changes the local payload + # used by the selected callable. + advisory_frequency = getattr(self.router, "last_advisory_frequency", None) + advisory = None + if advisory_frequency is not None: + advisory_frequency = np.asarray(advisory_frequency, dtype=np.complex64) + if advisory_frequency.shape != (HRR_DIM,): + raise ValueError("router advisory Fourier shape differs") + path_advisory = _bind_frequency( + MULTIHEAD_ADVISORY_KEYS_F["path"], advisory_frequency, + ) + else: + advisory = getattr(self.router, "last_advisory_state", None) + if advisory is not None: + advisory = np.asarray(advisory, dtype=np.complex64) + if advisory is not None and advisory.shape != (HRR_DIM,): + raise ValueError("router advisory HRR shape differs") + path_advisory = None if advisory is None else bind( + unitary("stage5c36:multihead-advisory:path"), advisory, + ) + if path_advisory is not None: + path_payload = normalize( + path_payload + + np.complex64(0.08) * path_advisory + ) + # A question-scoped C43 hybrid may contribute one already + # stabilized knowledge summary for this concrete Tree lane. The + # summary affects only the carried rails: it cannot change the + # selected callable or provide an endpoint to the local primitive. + expert_provider = getattr(self.router, "expert_advisory", None) + expert_gain = float(getattr(self.router, "expert_advisory_gain", 0.06)) + if callable(expert_provider): + expert_path = expert_provider("path", (tree_node, destination)) + if expert_path is not None: + expert_path = np.asarray(expert_path, dtype=np.complex64) + if expert_path.shape != (HRR_DIM,): + raise ValueError("expert path advisory HRR shape differs") + path_payload = normalize( + path_payload + np.complex64(expert_gain) * expert_path + ) + ledger_state, _ = ledger.append( + state_before=ledger_state, payload_state=path_payload, + operator_id=f"c36.{name}.path", operator_type="path_transform", + source_node=tree_node, destination_node=destination, + key_label=f"stage5c36:ledger:{sequence}:path", provenance_sha256=provenance, + gain=0.22, confidence=confidence, uncertainty=1.0 - confidence, + ) + current_spine.add( + Lane("path", f"{tree_node}-{destination}", sequence, tree_cycle_index), path_payload + ) + visited.append(destination) + tree_node = destination + node_payload = normalize(bind(unitary(f"stage5c36:node:{tree_node}"), payload)) + if advisory_frequency is not None: + node_advisory = _bind_frequency( + MULTIHEAD_ADVISORY_KEYS_F["node"], advisory_frequency, + ) + elif advisory is not None: + node_advisory = bind( + unitary("stage5c36:multihead-advisory:node"), advisory, + ) + else: + node_advisory = None + if node_advisory is not None: + node_payload = normalize( + node_payload + + np.complex64(0.08) * node_advisory + ) + if callable(expert_provider): + expert_node = expert_provider("node", tree_node) + if expert_node is not None: + expert_node = np.asarray(expert_node, dtype=np.complex64) + if expert_node.shape != (HRR_DIM,): + raise ValueError("expert node advisory HRR shape differs") + node_payload = normalize( + node_payload + np.complex64(expert_gain) * expert_node + ) + sequence = ledger.entries + ledger_state, _ = ledger.append( + state_before=ledger_state, payload_state=node_payload, + operator_id=f"c36.{name}.node", operator_type="node_synthesis", + source_node=tree_node, destination_node=tree_node, + key_label=f"stage5c36:ledger:{sequence}:node", provenance_sha256=provenance, + gain=0.18, confidence=confidence, uncertainty=1.0 - confidence, + ) + current_spine.add(Lane("node", tree_node, sequence, tree_cycle_index), node_payload) + visited.append(tree_node) + if tree_node == "keter": + tree_cycle_index += 1 + path_state, node_state = current_spine.moving_state + carried = normalize( + bind(unitary("stage5c36:cycle:path"), path_state) + + bind(unitary("stage5c36:cycle:node"), node_state) + ) + current_spine = DualRailTreeSpine(protected_root, carried) + spines.append(current_spine) + + max_iterations = 4 * len(relations) + 32 + for _ in range(max_iterations): + if ( + runtime.get("corruption_step") == step + and not corruption_injected + and step < len(relations) + ): + current = normalize(current + np.complex64(1.7) * unitary(f"stage5c36:corruption:{record['id']}")) + corruption_injected = True + corrupted = array_sha256(current) != checkpoint_sha + corruption_detected = corruption_detected or corrupted + relation = relations[step] if step < len(relations) else unitary("stage5c36:terminal-relation") + query_address = None if step >= len(relations) else _address(current, relation) + matches = [] if query_address is None else bank.match_address(query_address) + memory_match = bool( + self.enable_substrate and snapshot_bank is not None and not recalled + and query_address is not None + and snapshot_bank.match_address(query_address) + ) + terminal = step >= len(relations) + state_10d = self.router.state( + progress=step / max(len(relations), 1), terminal=terminal, + corrupted=corrupted, match_count=len(matches), + memory_available=memory_match, branch_pending=branch_candidates is not None, + ) + decision = self.router.decide(state_10d) + router_confidences.append(decision.confidence) + trace.append(CallableEvent( + decision.callable_name, step, decision.confidence, + tuple(float(v) for v in state_10d), len(matches), + )) + + if decision.callable_name == "rollback": + payload = self._primitive_rollback(checkpoint) + append_tree_callable("rollback", payload, decision.confidence) + if self.enable_recovery: + current = payload + checkpoint = current.copy() + checkpoint_sha = array_sha256(checkpoint) + corruption_recovered = True + else: + terminal_action = "abstain" + break + continue + + if decision.callable_name == "recall": + if snapshot is None or not self.enable_substrate: + terminal_action = "abstain" + break + payload, recalled_facts = self._primitive_recall(snapshot) + append_tree_callable("recall", payload, decision.confidence) + bank.add(recalled_facts) + recalled = True + continue + + if decision.callable_name == "repair": + payload = self._primitive_repair(current, relation) + append_tree_callable("repair", payload, decision.confidence) + terminal_action = "abstain" + break + + if decision.callable_name == "branch": + branch_candidates = matches + branch_bundle = self._primitive_branch(matches) + branch_expansions += len(matches) + append_tree_callable("branch", branch_bundle, decision.confidence) + continue + + if decision.callable_name == "compare": + if branch_candidates is None or branch_bundle is None: + terminal_action = "abstain" + break + recovered = self._recover_branches(branch_bundle, branch_candidates) + comparison_pairs = list(zip(branch_candidates, recovered, strict=True)) + candidate_selector = getattr(self.router, "select_candidate", None) + if callable(candidate_selector) and len(comparison_pairs) > 1: + evidence_views = tuple( + CandidateEvidenceView( + fact_id=candidate.fact_id, + provenance_sha256=candidate.provenance_sha256, + kind=candidate.kind, + revision=candidate.revision, + admissible=candidate.admissible, + ) + for candidate, _ in comparison_pairs + ) + selected_fact_id = candidate_selector(evidence_views, step=step) + if selected_fact_id is not None: + selected_fact_id = str(selected_fact_id) + selected_pairs = [ + pair for pair in comparison_pairs + if pair[0].fact_id == selected_fact_id + ] + if len(selected_pairs) != 1: + raise ValueError( + "directional router selected an unknown or duplicate fact id" + ) + comparison_pairs = selected_pairs + viable: list[GeometricFact] = [] + reachability_cache: dict[str, list[np.ndarray]] = {} + for candidate, recovered_state in comparison_pairs: + recovered_key = array_sha256(recovered_state) + endings = reachability_cache.get(recovered_key) + if endings is None: + endings = self._reachable(recovered_state, relations[step + 1 :], bank) + reachability_cache[recovered_key] = endings + if endings or step + 1 == len(relations): + viable.append(candidate) + branch_expansions += max(1, len(endings)) + if self.enable_fact_governance: + admissible = [item for item in viable if item.admissible] + if admissible: + viable = admissible + if len(viable) > 1: + newest = max(item.revision for item in viable) + newest_items = [item for item in viable if item.revision == newest] + if len(newest_items) == 1: + viable = newest_items + compare_payload = normalize( + sum((item.destination for item in viable), np.zeros(HRR_DIM, dtype=np.complex64)) + if viable else unitary("stage5c36:no-viable-branch") + ) + append_tree_callable("compare", compare_payload, decision.confidence) + branch_candidates = None + branch_bundle = None + if len(viable) == 1: + selected_candidate = viable[0] + elif len(viable) > 1: + terminal_action = "clarify" + break + else: + terminal_action = "abstain" + break + # The selected sibling still passes through the advance + # primitive on the following local transition. + matches = [selected_candidate] + + if decision.callable_name == "advance" or selected_candidate is not None: + candidates = [selected_candidate] if selected_candidate is not None else matches + selected_candidate = None + if not candidates: + terminal_action = "abstain" + break + if step == len(relations) - 1: + support_state = current.copy() + current = self._primitive_advance( + current, relation, candidates, query_address=query_address, + ) + append_tree_callable("advance", current, decision.confidence) + step += 1 + checkpoint = current.copy() + checkpoint_sha = array_sha256(checkpoint) + continue + + if decision.callable_name == "stop": + terminal_action = "answer" + break + else: + terminal_action = "abstain" + + if terminal_action is None: + terminal_action = "abstain" + + # A pre-Malkuth probe must be denied. No endpoint cleanup occurs here. + premature_release_blocked = tree_node != "malkuth" + release_route = self._shortest_path(tree_node, "malkuth") + for route_index, destination in enumerate(release_route[1:]): + source = tree_node + final_edge = destination == "malkuth" + sequence = ledger.entries + release_payload = normalize(bind(unitary("stage5c36:release-route"), current)) + provenance = hashlib.sha256( + f"{record['id']}:release:{route_index}:{source}:{destination}".encode("utf-8") + ).hexdigest() + ledger_state, _ = ledger.append( + state_before=ledger_state, payload_state=release_payload, + operator_id="c36.release", operator_type="release" if final_edge else "path_transform", + source_node=source, destination_node=destination, + key_label=f"stage5c36:ledger:{sequence}:release", provenance_sha256=provenance, + gain=0.20, confidence=min(router_confidences or [1.0]), + uncertainty=1.0 - min(router_confidences or [1.0]), + unbind_performed=final_edge, + ) + current_spine.add(Lane("path", f"{source}-{destination}", sequence, tree_cycle_index), release_payload) + tree_node = destination + visited.append(destination) + + endpoint = None + support = None + if terminal_action == "answer": + released = self._primitive_stop(current) + endpoint, endpoint_fidelity, _ = geometry.decode(released) + if support_state is not None: + support, support_fidelity, _ = geometry.decode(self._primitive_stop(support_state)) + else: + support_fidelity = 0.0 + release_payload_verified = endpoint_fidelity >= 0.985 + release_payload_verified = bool( + release_payload_verified and support is not None and support_fidelity >= 0.985 + ) + else: + release_payload_verified = True + + # Exact reverse replay verifies every normalized additive transition. + inverse_max_error = 0.0 + inverse_exact = False + cleanup_correct = cleanup_total = 0 + cleanup_margins: list[float] = [] + if self.full_audit: + inverse_state = ledger_state.copy() + inverse_exact = True + for transition in reversed(ledger.transitions): + try: + before = transition.invert(inverse_state) + inverse_max_error = max( + inverse_max_error, + float(np.max(np.abs(before - transition.state_before))), + ) + inverse_state = before + except ValueError: + inverse_exact = False + break + inverse_exact = bool( + inverse_exact and np.array_equal(inverse_state, ledger_initial) and ledger.verify_chain() + ) + + # Post-Malkuth exhaustive audit of every bounded sibling cleanup. + for spine in spines: + stored = spine.stored + for item in stored: + peers = [peer.artifact for peer in stored if peer.lane.kind == item.lane.kind] + recovered = spine.recover(item.lane) + target = cosine(recovered, item.artifact) + others = [ + cosine(recovered, peer) for peer in peers + if cosine(item.artifact, peer) < 0.999 + ] + rival = max(others, default=0.0) + cleanup_correct += int(target + 1e-7 >= rival) + cleanup_total += 1 + cleanup_margins.append(target - rival) + + conflict_state = ( + "represented" if terminal_action == "clarify" + else "suspended" if terminal_action == "abstain" + else "resolved" if any(event.name == "compare" for event in trace) + else "none" + ) + evidence_ok = terminal_action == "answer" + release_mode = { + "answer": "answer", "clarify": "clarification", "abstain": "abstention", + }[terminal_action] + observation = ResolutionObservation( + query_state_sha256=hashlib.sha256(json.dumps(query, sort_keys=True).encode("utf-8")).hexdigest(), + root_fidelity=min(cosine(spine.resolve_root(), protected_root) for spine in spines), + role_recovery={"source": 1.0, "field": 1.0, "transition": 1.0}, + operation_confidence=min(router_confidences or [1.0]), + planned_route=tuple(visited), visited_nodes=tuple(visited), + conflict_state=conflict_state, + evidence_required=True, evidence_items=step if evidence_ok else 0, + evidence_minimum=1, evidence_verified=evidence_ok, + evidence_confidence=1.0 if evidence_ok else 0.0, + stated_uncertainty=0.0 if evidence_ok else 1.0, + provenance_required=1, provenance_items=max(1, step), provenance_verified=True, + ledger_entries=ledger.entries, reversible_entries=ledger.reversible_entries, + ledger_chain_valid=ledger.verify_chain(), current_node=tree_node, + release_requested=True, release_mode=release_mode, + release_payload_verified=release_payload_verified, + unwarranted_payload_count=0, + ) + resolution = evaluate_resolution(observation) + return LongHorizonResult( + task_id=record["id"], action=terminal_action, endpoint=endpoint, support=support, + reasoning_steps=step, branch_expansions=branch_expansions, + recalled_snapshot=recalled, corruption_detected=corruption_detected, + corruption_recovered=corruption_recovered, + premature_release_blocked=premature_release_blocked, + malkuth_only_unbinding=all( + not transition.record.unbind_performed + or transition.record.destination_node == "malkuth" + for transition in ledger.transitions + ), + router_trace=tuple(trace), ledger_manifest=ledger.manifest(), + full_audit_performed=self.full_audit, + inverse_exact=inverse_exact, inverse_max_error=inverse_max_error, + spine_cleanup_accuracy=cleanup_correct / max(cleanup_total, 1), + spine_min_margin=min(cleanup_margins, default=0.0), + resolution_state=resolution.as_dict(), resolution_object=resolution, + elapsed_seconds=time.perf_counter() - started, + ) diff --git a/root/wander-train/stage5j1_native_contextual_sense_lattice.py b/root/wander-train/stage5j1_native_contextual_sense_lattice.py new file mode 100644 index 0000000000000000000000000000000000000000..14a989102c27beae5ce03aadc347246e836a70d1 --- /dev/null +++ b/root/wander-train/stage5j1_native_contextual_sense_lattice.py @@ -0,0 +1,369 @@ +#!/usr/bin/env python3 +"""Native dictionary/context/domain sense lattice with no pretrained encoder. + +The specialist retains several candidate WordNet senses as independently bound +HRR branches. Dictionary topology, construction shape, argument context, and +WordNet lexicographer-domain resonance contribute separate score rails. A +later domain specialist may clean up the lattice; this module does not force an +unsafe top-one decision when the margin is weak. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import re +from dataclasses import dataclass +from functools import lru_cache +from pathlib import Path +from typing import Any, Iterable + +import numpy as np + + +SCHEMA = "oracle-stage5j1-native-contextual-sense-lattice-v1" +WORD = re.compile(r"[A-Za-z]+(?:'[A-Za-z]+)?") +CONTENT_STOP = { + "a", "an", "and", "are", "as", "at", "be", "been", "being", "but", "by", "did", "do", + "does", "for", "from", "had", "has", "have", "he", "her", "hers", "him", "his", "i", "in", + "is", "it", "its", "me", "my", "of", "on", "or", "our", "ours", "she", "so", "than", "that", + "the", "their", "them", "they", "this", "those", "to", "us", "was", "we", "were", "with", + "you", "your", +} +FUNCTION_WORDS = CONTENT_STOP | { + "after", "before", "can", "cannot", "could", "during", "how", "if", "into", "may", "might", + "must", "not", "over", "should", "through", "under", "until", "what", "when", "where", "which", + "who", "why", "will", "without", "would", +} +COMPONENTS = ("lexical", "example_context", "left_argument", "right_argument", "construction", "domain", "prior") + + +def unit(value: np.ndarray) -> np.ndarray: + value = np.asarray(value, dtype=np.float32) + norm = float(np.linalg.norm(value)) + return value / norm if norm else value + + +def cosine(left: np.ndarray, right: np.ndarray) -> float: + return float(unit(left) @ unit(right)) if np.any(left) and np.any(right) else 0.0 + + +def bind(left: np.ndarray, right: np.ndarray) -> np.ndarray: + return np.fft.ifft(np.fft.fft(left) * np.fft.fft(right)).real.astype(np.float32) + + +def unbind(bound: np.ndarray, key: np.ndarray) -> np.ndarray: + return np.fft.ifft(np.fft.fft(bound) * np.conj(np.fft.fft(key))).real.astype(np.float32) + + +@lru_cache(maxsize=100_000) +def stable_direction(label: str, dimensions: int) -> np.ndarray: + """Create a deterministic sparse bipolar direction without learned embeddings.""" + value = np.zeros(dimensions, dtype=np.float32) + digest = hashlib.shake_256(label.encode("utf-8")).digest(48) + for offset in range(0, len(digest), 4): + chunk = int.from_bytes(digest[offset:offset + 4], "little") + index = chunk % dimensions + value[index] += 1.0 if chunk & 1 else -1.0 + return unit(value) + + +def stem(token: str) -> str: + value = token.casefold().replace("’", "'") + if value.endswith("ies") and len(value) > 4: + return value[:-3] + "y" + for suffix in ("ingly", "edly", "ing", "ed", "es", "s"): + if value.endswith(suffix) and len(value) > len(suffix) + 2: + return value[:-len(suffix)] + return value + + +def tokens(text: str) -> list[str]: + return [value.casefold() for value in WORD.findall(str(text))] + + +def feature_names(text: str, *, include_function: bool = False) -> list[str]: + values = [stem(value) for value in tokens(text)] + if not include_function: + values = [value for value in values if value not in CONTENT_STOP and len(value) > 1] + features = [f"word:{value}" for value in values] + for value in values: + padded = f"^{value}$" + for width in (3, 4, 5): + features.extend(f"char:{padded[index:index + width]}" for index in range(max(0, len(padded) - width + 1))) + features.extend(f"pair:{left}:{right}" for left, right in zip(values, values[1:])) + return features + + +def text_direction(text: str, dimensions: int, *, include_function: bool = False) -> np.ndarray: + names = feature_names(text, include_function=include_function) + if not names: + return np.zeros(dimensions, dtype=np.float32) + state = np.zeros(dimensions, dtype=np.float32) + for name in names: + state += stable_direction(name, dimensions) + return unit(state) + + +def remove_word(text: str, token_index: int) -> tuple[str, list[str], list[str]]: + matches = list(WORD.finditer(str(text))) + if not 0 <= token_index < len(matches): + return str(text), [], [] + match = matches[token_index] + left = [value.group(0) for value in matches[:token_index]] + right = [value.group(0) for value in matches[token_index + 1:]] + return str(text)[:match.start()] + " " + str(text)[match.end():], left, right + + +def construction_direction(text: str, token_index: int, dimensions: int) -> np.ndarray: + values = tokens(text) + features: list[str] = [] + for index, value in enumerate(values): + if value in FUNCTION_WORDS: + delta = max(-4, min(4, index - token_index)) + features.append(f"function:{value}:offset:{delta}") + if str(text).rstrip().endswith("?"): + features.append("speech-act:question") + if any(value in {"not", "n't", "never", "no"} for value in values): + features.append("operator:negation") + if any(value in {"can", "could", "may", "might", "must", "should", "will", "would"} for value in values): + features.append("operator:modal") + features.append(f"predicate-position:{min(token_index, 6)}") + state = np.zeros(dimensions, dtype=np.float32) + for value in features: + state += stable_direction(value, dimensions) + return unit(state) + + +def argument_direction(values: Iterable[str], dimensions: int, side: str) -> np.ndarray: + values = list(values) + if not values: + return np.zeros(dimensions, dtype=np.float32) + selected = values[-5:] if side == "left" else values[:5] + state = text_direction(" ".join(selected), dimensions) + return unit(bind(stable_direction(f"argument-role:{side}", dimensions), state)) if np.any(state) else state + + +def context_components(text: str, token_index: int, dimensions: int) -> dict[str, np.ndarray]: + removed, left, right = remove_word(text, token_index) + return { + "lexical": text_direction(removed, dimensions), + "example_context": unit( + text_direction(removed, dimensions) + + argument_direction(left, dimensions, "left") + + argument_direction(right, dimensions, "right") + ), + "left_argument": argument_direction(left, dimensions, "left"), + "right_argument": argument_direction(right, dimensions, "right"), + "construction": construction_direction(text, token_index, dimensions), + } + + +def mean_unit(values: list[np.ndarray], dimensions: int) -> np.ndarray: + nonzero = [value for value in values if np.any(value)] + return unit(np.sum(nonzero, axis=0)) if nonzero else np.zeros(dimensions, dtype=np.float32) + + +def example_occurrences(synset, wordnet) -> list[tuple[str, int]]: + lemmas = {value.casefold().replace("_", " ") for value in synset.lemma_names()} + occurrences: list[tuple[str, int]] = [] + for example in synset.examples(): + values = tokens(example) + for index, value in enumerate(values): + lemma = wordnet.morphy(value, wordnet.VERB) + if lemma and lemma.replace("_", " ") in lemmas: + occurrences.append((example, index)) + break + return occurrences + + +def lexical_document(synset) -> str: + values = [synset.definition(), " ".join(value.replace("_", " ") for value in synset.lemma_names())] + for relation in (synset.hypernyms(), synset.hyponyms(), synset.entailments(), synset.causes(), synset.verb_groups()): + for neighbor in relation[:6]: + values.append(neighbor.definition()) + values.extend(value.replace("_", " ") for value in neighbor.lemma_names()) + return " ".join(values) + + +@dataclass(frozen=True) +class NativeSenseLattice: + dimensions: int + sense_names: tuple[str, ...] + lexnames: tuple[str, ...] + lexical_states: np.ndarray + context_states: np.ndarray + left_states: np.ndarray + right_states: np.ndarray + construction_states: np.ndarray + domain_states: np.ndarray + sense_domain_indexes: np.ndarray + weights: np.ndarray + maximum_alternatives: int + minimum_top_margin: float + protocol_sha256: str + file_sha256: str | None = None + + @classmethod + def compile( + cls, wordnet, *, dimensions: int = 512, excluded_sentences: set[str] | None = None, + weights: Iterable[float] = (0.22, 0.30, 0.12, 0.12, 0.08, 0.14, 0.02), + maximum_alternatives: int = 4, minimum_top_margin: float = 0.02, + protocol_sha256: str = "development", + ) -> "NativeSenseLattice": + excluded = {value.casefold().strip() for value in (excluded_sentences or set())} + synsets = list(wordnet.all_synsets(pos=wordnet.VERB)) + names = tuple(value.name() for value in synsets) + lexnames = tuple(sorted({value.lexname() for value in synsets})) + domain_index = {value: index for index, value in enumerate(lexnames)} + arrays = {name: np.zeros((len(synsets), dimensions), dtype=np.float32) for name in ( + "lexical", "context", "left", "right", "construction", + )} + sense_domains = np.zeros(len(synsets), dtype=np.int16) + for index, synset in enumerate(synsets): + arrays["lexical"][index] = text_direction(lexical_document(synset), dimensions) + sense_domains[index] = domain_index[synset.lexname()] + examples = [ + context_components(sentence, token_index, dimensions) + for sentence, token_index in example_occurrences(synset, wordnet) + if sentence.casefold().strip() not in excluded + ] + arrays["context"][index] = mean_unit([value["example_context"] for value in examples], dimensions) + arrays["left"][index] = mean_unit([value["left_argument"] for value in examples], dimensions) + arrays["right"][index] = mean_unit([value["right_argument"] for value in examples], dimensions) + arrays["construction"][index] = mean_unit([value["construction"] for value in examples], dimensions) + + domains = np.zeros((len(lexnames), dimensions), dtype=np.float32) + for index in range(len(lexnames)): + members = np.flatnonzero(sense_domains == index) + domains[index] = mean_unit([ + unit(arrays["lexical"][member] + arrays["context"][member]) for member in members + ], dimensions) + return cls( + dimensions, names, lexnames, arrays["lexical"], arrays["context"], arrays["left"], arrays["right"], + arrays["construction"], domains, sense_domains, np.asarray(tuple(weights), dtype=np.float32), + maximum_alternatives, minimum_top_margin, protocol_sha256, + ) + + def with_weights(self, weights: Iterable[float]) -> "NativeSenseLattice": + values = np.asarray(tuple(weights), dtype=np.float32) + if values.shape != (len(COMPONENTS),): + raise ValueError(f"expected {len(COMPONENTS)} native lattice weights") + return NativeSenseLattice( + self.dimensions, self.sense_names, self.lexnames, self.lexical_states, self.context_states, + self.left_states, self.right_states, self.construction_states, self.domain_states, + self.sense_domain_indexes, values, self.maximum_alternatives, self.minimum_top_margin, + self.protocol_sha256, self.file_sha256, + ) + + def candidate_components(self, text: str, predicate_surface: str, token_index: int, wordnet) -> list[dict[str, Any]]: + surface = predicate_surface.casefold().replace("-", "_").replace(" ", "_") + lemma = wordnet.morphy(surface, wordnet.VERB) or surface + candidates = wordnet.synsets(lemma, pos=wordnet.VERB) + if not candidates: + return [] + query = context_components(text, token_index, self.dimensions) + sense_index = {name: index for index, name in enumerate(self.sense_names)} + domain_nearest = np.zeros(len(self.lexnames), dtype=np.float32) + for domain in range(len(self.lexnames)): + members = np.flatnonzero(self.sense_domain_indexes == domain) + usable = self.context_states[members] + if len(usable): + domain_nearest[domain] = float(np.max(usable @ query["example_context"])) + values: list[dict[str, Any]] = [] + for prior_rank, candidate in enumerate(candidates, start=1): + index = sense_index[candidate.name()] + domain = int(self.sense_domain_indexes[index]) + components = np.asarray([ + cosine(query["lexical"], self.lexical_states[index]), + cosine(query["example_context"], self.context_states[index]), + cosine(query["left_argument"], self.left_states[index]), + cosine(query["right_argument"], self.right_states[index]), + cosine(query["construction"], self.construction_states[index]), + float(domain_nearest[domain]), + 1.0 / math.sqrt(prior_rank), + ], dtype=np.float32) + values.append({ + "sense": candidate.name(), "lexname": self.lexnames[domain], "prior_rank": prior_rank, + "components": components, "score": float(components @ self.weights), + }) + values.sort(key=lambda value: (-value["score"], value["sense"])) + return values + + def resolve(self, text: str, predicate_surface: str, token_index: int, wordnet, graph=None) -> dict[str, Any]: + ranked = self.candidate_components(text, predicate_surface, token_index, wordnet) + if not ranked: + return {"sense": None, "relation": None, "lattice": [], "reason": "no_dictionary_senses"} + margin = ranked[0]["score"] - (ranked[1]["score"] if len(ranked) > 1 else 0.0) + sense_role = stable_direction("role:sense", self.dimensions) + domain_role = stable_direction("role:domain", self.dimensions) + spine = stable_direction("tree:stabilizing-spine", self.dimensions) + lattice = [] + for value in ranked[:self.maximum_alternatives]: + relation = graph.resolve(value["sense"], wordnet)["relation"] if graph is not None else None + payload = unit( + bind(sense_role, stable_direction("sense:" + value["sense"], self.dimensions)) + + bind(domain_role, stable_direction("domain:" + value["lexname"], self.dimensions)) + ) + protected = unit(4.0 * spine + payload) + lattice.append({ + "sense": value["sense"], "relation": relation, "lexname": value["lexname"], + "score": value["score"], "prior_rank": value["prior_rank"], + "components": {name: float(component) for name, component in zip(COMPONENTS, value["components"])}, + "protected_root_cosine": cosine(protected, spine), + "sense_cleanup_cosine": cosine( + unbind(bind(sense_role, stable_direction("sense:" + value["sense"], self.dimensions)), sense_role), + stable_direction("sense:" + value["sense"], self.dimensions), + ), + }) + released = margin >= self.minimum_top_margin + return { + "sense": ranked[0]["sense"] if released else None, + "relation": lattice[0]["relation"] if released else None, + "lattice": lattice, + "reason": "released" if released else "ambiguous_lattice_retained", + "top_margin": float(margin), + "native_runtime": True, + "pretrained_encoder": False, + "next_token_model": False, + } + + def save(self, path: Path) -> str: + metadata = { + "schema_version": SCHEMA, "dimensions": self.dimensions, "sense_names": self.sense_names, + "lexnames": self.lexnames, "weights": self.weights.tolist(), + "maximum_alternatives": self.maximum_alternatives, + "minimum_top_margin": self.minimum_top_margin, "protocol_sha256": self.protocol_sha256, + } + np.savez_compressed( + path, metadata=np.asarray(json.dumps(metadata, sort_keys=True)), lexical_states=self.lexical_states, + context_states=self.context_states, left_states=self.left_states, right_states=self.right_states, + construction_states=self.construction_states, domain_states=self.domain_states, + sense_domain_indexes=self.sense_domain_indexes, + ) + digest = hashlib.sha256(path.read_bytes()).hexdigest() + object.__setattr__(self, "file_sha256", digest) + return digest + + @classmethod + def load(cls, path: Path) -> "NativeSenseLattice": + digest = hashlib.sha256(path.read_bytes()).hexdigest() + with np.load(path, allow_pickle=False) as archive: + if any(value.dtype.hasobject for value in archive.values()): + raise ValueError("object dtype forbidden in native lattice checkpoint") + metadata = json.loads(str(archive["metadata"].item())) + if metadata.get("schema_version") != SCHEMA: + raise ValueError("unsupported native sense lattice checkpoint") + return cls( + int(metadata["dimensions"]), tuple(metadata["sense_names"]), tuple(metadata["lexnames"]), + np.asarray(archive["lexical_states"], dtype=np.float32), + np.asarray(archive["context_states"], dtype=np.float32), + np.asarray(archive["left_states"], dtype=np.float32), + np.asarray(archive["right_states"], dtype=np.float32), + np.asarray(archive["construction_states"], dtype=np.float32), + np.asarray(archive["domain_states"], dtype=np.float32), + np.asarray(archive["sense_domain_indexes"], dtype=np.int16), + np.asarray(metadata["weights"], dtype=np.float32), int(metadata["maximum_alternatives"]), + float(metadata["minimum_top_margin"]), str(metadata["protocol_sha256"]), digest, + ) diff --git a/root/wander-train/stage5k30_dual_lattice_knowledge_agent.py b/root/wander-train/stage5k30_dual_lattice_knowledge_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..a87a1047cb8a4bc0a3b6d252952d77284f57be55 --- /dev/null +++ b/root/wander-train/stage5k30_dual_lattice_knowledge_agent.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""K30: combine operational and knowledge specialist coordinates per turn. + +K14 answers *which operation is required*; K29 answers *which public knowledge +manifold is relevant*. K30 keeps the lattices orthogonal, retrieves immutable +source text only through the selected knowledge modes, and admits it to the +native K28 proof/inverse path only when the query has sufficient lexical +support. Weak retrieval remains an audit artifact and cannot become prose. +""" + +from __future__ import annotations + +import hashlib +from pathlib import Path +from typing import Any, Mapping, Sequence + +import numpy as np + +from stage5k15_native_mixed_agent import digest +from stage5k28_native_generative_construction_agent import NativeGenerativeConstructionAgent +from stage5k29_meta_fold_knowledge_basis import TrainedKnowledgeBasis + + +SCHEMA = "oracle-stage5k30-dual-lattice-knowledge-agent-v1" + + +class DualLatticeKnowledgeAgent(NativeGenerativeConstructionAgent): + def __init__( + self, + specialist_checkpoint: Path, + knowledge_checkpoint: Path, + substrate_path: Path, + **kwargs: Any, + ) -> None: + super().__init__(specialist_checkpoint, substrate_path, **kwargs) + self.knowledge_basis = TrainedKnowledgeBasis.load(knowledge_checkpoint) + self.knowledge_specialists = self.knowledge_basis.pool() + + @staticmethod + def _retrieval_gate( + intent_family: str, + evidence: Sequence[Mapping[str, Any]], + context: Mapping[str, Any], + ) -> tuple[bool, str]: + if any(context.get(key) for key in ("evidence", "training_corpus", "sensor_stream")): + return False, "caller_supplied_bounded_context_has_precedence" + if intent_family not in {"open", "definition_query"}: + return False, "speech_act_or_typed_construction_has_precedence" + if not evidence: + return False, "no_selected_domain_evidence" + best = evidence[0] + if len(best.get("shared_terms", ())) < 2: + return False, "fewer_than_two_content_terms_grounded" + if float(best.get("query_term_coverage", 0.0)) < 0.50: + return False, "query_content_coverage_below_half" + if float(best.get("retrieval_score", 0.0)) < 0.18: + return False, "retrieval_score_below_floor" + return True, "source_evidence_lexically_grounded" + + def answer( + self, + session_id: str, + text: str, + context: Mapping[str, Any] | None = None, + *, + ablate_specialists: Sequence[str] = (), + ablate_knowledge_cells: Sequence[str] = (), + ) -> dict[str, Any]: + local_context = dict(context or {}) + intent = self._intent_lattice(text, local_context)["selected_intent_family"] + routed = self.knowledge_specialists.route( + text, ablate_cells=ablate_knowledge_cells, + ) + evidence = self.knowledge_basis.retrieve( + text, + top_k=3, + selected_domain_ids=routed["selected_domain_ids"], + ) + admissible_evidence = tuple( + value for value in evidence + if len(value.get("shared_terms", ())) >= 2 + and float(value.get("query_term_coverage", 0.0)) >= 0.50 + and float(value.get("retrieval_score", 0.0)) >= 0.18 + ) + admitted, reason = self._retrieval_gate(intent, admissible_evidence, local_context) + if admitted: + local_context["evidence"] = tuple({ + "fact": value["text"], + "source_document": value["source_document"], + "source_document_sha256": value["source_document_sha256"], + "text_sha256": value["text_sha256"], + "domain_id": value["domain_id"], + "license_note": value["license_note"], + "retrieval_score": value["retrieval_score"], + } for value in admissible_evidence) + output = super().answer( + session_id, + text, + local_context, + ablate_specialists=ablate_specialists, + ) + fused_state = np.ascontiguousarray(routed.pop("fused_state")) + output["schema_version"] = SCHEMA + output["knowledge_lattice"] = { + "schema_version": "oracle-stage5k30-knowledge-lattice-audit-v1", + "operational_registered_cells": len(self.specialists.specs), + "knowledge_registered_cells": routed["registered_cells"], + "total_registered_cells": len(self.specialists.specs) + routed["registered_cells"], + "primitive_operational_modes": sum(len(value.members) for value in self.specialists.specs), + "primitive_domain_modes": routed["primitive_domain_modes"], + "selected_domain_ids": routed["selected_domain_ids"], + "selected_cell_ids": routed["selected_cell_ids"], + "routing": routed, + "fused_state_sha256": hashlib.sha256(fused_state.tobytes()).hexdigest(), + "retrieval_admitted_to_proof": admitted, + "retrieval_gate_reason": reason, + "retrieved_evidence": list(evidence), + "evidence_rows_admitted_to_proof": list(admissible_evidence) if admitted else [], + "ablated_knowledge_cells": list(ablate_knowledge_cells), + "public_source_payloads_released_before_malkuth": 0, + "automatic_canonical_promotions": 0, + } + output["runtime"]["knowledge_model_calls"] = 0 + output["runtime"]["knowledge_gradient_steps"] = 0 + output["runtime"]["knowledge_next_token_predictions"] = 0 + output["turn_manifest_sha256"] = digest(output) + return output + + +__all__ = ["DualLatticeKnowledgeAgent"] diff --git a/root/wander-train/stage5k31_native_proposition_compiler_agent.py b/root/wander-train/stage5k31_native_proposition_compiler_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..708da9ad0dc099f02ce38f3d41ced914f834fafa --- /dev/null +++ b/root/wander-train/stage5k31_native_proposition_compiler_agent.py @@ -0,0 +1,815 @@ +#!/usr/bin/env python3 +"""K31 native proposition compilation and explanatory realization. + +Admitted K30 source sentences are compiled into typed propositions before any +answer is constructed. Predicate discovery, contextual sense choice, voice, +role direction, polarity, modality, source spans, and provenance remain +separate coordinates. The resulting relation graph—not the quoted source +sentence—is passed to the existing proof/QUBO-inverse/Malkuth realization. + +The compiler is a finite productive English construction algebra. It has no +transformer, learned embedding encoder, autoregressive carrier, or next-token +path. Unsupported clause shapes abstain instead of falling back to quotation. +""" + +from __future__ import annotations + +from dataclasses import dataclass, replace +import hashlib +import json +import re +from typing import Any, Mapping, Sequence + +import numpy as np + +from stage5k15_native_mixed_agent import HandlerResult, SemanticClause, clean, digest, tokens +from stage5k30_dual_lattice_knowledge_agent import DualLatticeKnowledgeAgent +from train_stage2a_role_ladder import HRR_DIM, bind, cosine, normalize, text_hrr, unitary + + +SCHEMA = "oracle-stage5k31-native-proposition-compiler-agent-v1" +COMPILER_SCHEMA = "oracle-stage5k31-native-proposition-compiler-v1" +WORD = re.compile(r"[A-Za-z0-9]+(?:[-'][A-Za-z0-9]+)*") +MODALS = frozenset({"can", "could", "may", "might", "must", "shall", "should", "will", "would"}) +NEGATIONS = frozenset({"not", "never", "no", "cannot", "neither", "nor"}) +UNCERTAIN = frozenset({"can", "could", "may", "might", "would"}) +PROBABLE = frozenset({"likely", "probably", "apparently", "suggests", "suggest"}) +AUXILIARIES = frozenset({"am", "are", "be", "been", "being", "is", "was", "were"}) + + +IRREGULAR_FORMS: Mapping[str, tuple[str, ...]] = { + "be": ("am", "are", "be", "been", "being", "is", "was", "were"), + "become": ("become", "becomes", "became", "becoming"), + "cause": ("cause", "causes", "caused", "causing"), + "close": ("close", "closes", "closed", "closing"), + "do": ("do", "does", "did", "done", "doing"), + "drive": ("drive", "drives", "drove", "driven", "driving"), + "flow": ("flow", "flows", "flowed", "flowing"), + "form": ("form", "forms", "formed", "forming"), + "generate": ("generate", "generates", "generated", "generating"), + "give": ("give", "gives", "gave", "given", "giving"), + "hold": ("hold", "holds", "held", "holding"), + "lead to": ("lead to", "leads to", "led to", "leading to"), + "make": ("make", "makes", "made", "making"), + "move": ("move", "moves", "moved", "moving"), + "produce": ("produce", "produces", "produced", "producing"), + "pull": ("pull", "pulls", "pulled", "pulling"), + "reduce": ("reduce", "reduces", "reduced", "reducing"), + "remain": ("remain", "remains", "remained", "remaining"), + "result from": ("result from", "results from", "resulted from", "resulting from"), + "result in": ("result in", "results in", "resulted in", "resulting in"), + "show": ("show", "shows", "showed", "shown", "showing"), + "support": ("support", "supports", "supported", "supporting"), +} + + +BASE_PREDICATES = ( + "absorb", "affect", "allow", "attract", "bypass", "change", "compare", + "compose", "consist of", "contain", "create", "decrease", "depend on", + "determine", "enable", "explain", "increase", "include", "indicate", + "interact with", "maintain", "measure", "orbit", "prevent", "provide", + "regulate", "represent", "require", "stabilize", "supply", "sustain", + "transfer", "use", "vary", +) + + +def _regular_forms(lemma: str) -> tuple[str, ...]: + words = lemma.split() + head = words[0] + tail = " " + " ".join(words[1:]) if len(words) > 1 else "" + if head.endswith("y") and len(head) > 2 and head[-2] not in "aeiou": + third = head[:-1] + "ies" + past = head[:-1] + "ied" + elif head.endswith(("s", "sh", "ch", "x", "z", "o")): + third = head + "es" + past = head + "ed" + elif head.endswith("e"): + third = head + "s" + past = head + "d" + else: + third = head + "s" + past = head + "ed" + progressive = head[:-1] + "ing" if head.endswith("e") else head + "ing" + return tuple(dict.fromkeys((lemma, third + tail, past + tail, progressive + tail))) + + +def _third_surface(lemma: str) -> str: + forms = IRREGULAR_FORMS.get(lemma, _regular_forms(lemma)) + return forms[1] if len(forms) > 1 else lemma + + +FORM_TO_LEMMA: dict[str, str] = {} +for _lemma_value in (*BASE_PREDICATES, *IRREGULAR_FORMS): + for _form in IRREGULAR_FORMS.get(_lemma_value, _regular_forms(_lemma_value)): + FORM_TO_LEMMA[_form] = _lemma_value +PREDICATE_PATTERN = re.compile( + r"\b(" + "|".join(re.escape(value) for value in sorted(FORM_TO_LEMMA, key=len, reverse=True)) + r")\b", + re.IGNORECASE, +) + + +@dataclass(frozen=True) +class PredicateSense: + sense_id: str + relation: str + realization_lemma: str + gloss: str + cues: tuple[str, ...] = () + domains: tuple[str, ...] = () + + +SENSES: Mapping[str, tuple[PredicateSense, ...]] = { + "support": ( + PredicateSense("support:evidential", "evidential_support", "support", "evidence warrants a claim", ("data", "evidence", "claim", "result", "finding"), ("mathematics_computation", "physical_engineering")), + PredicateSense("support:structural", "bears_load", "support", "a structure bears a physical load", ("column", "beam", "roof", "weight", "structure"), ("physical_engineering",)), + PredicateSense("support:sustain", "sustains", "support", "a condition helps a process or organism persist", ("life", "growth", "habitat", "process", "system"), ("life_health", "earth_space")), + ), + "drive": ( + PredicateSense("drive:causal", "causes", "drive", "a force or process causes a downstream process", ("force", "heating", "convection", "change", "process"), ("physical_engineering", "earth_space")), + PredicateSense("drive:propel", "propels", "drive", "an agent propels or controls a vehicle", ("car", "vehicle", "road", "wheel", "engine"), ("physical_engineering",)), + PredicateSense("drive:motivate", "motivates", "drive", "a motive produces behavior", ("motive", "desire", "behavior", "choice"), ("social_behavioral",)), + ), + "form": ( + PredicateSense("form:create", "creates", "form", "a process creates an entity", ("create", "produce", "crystal", "structure"), ("physical_engineering", "life_health")), + PredicateSense("form:constitute", "constitutes", "form", "parts collectively constitute a whole", ("part", "component", "group", "together")), + PredicateSense("form:shape", "shapes", "form", "a boundary gives geometry to an object", ("shape", "surface", "boundary", "geometry"), ("mathematics_computation",)), + ), + "reduce": ( + PredicateSense("reduce:decrease", "decreases", "reduce", "a quantity becomes smaller", ("amount", "rate", "risk", "temperature", "value")), + PredicateSense("reduce:normalize", "normalizes", "reduce", "a formal expression is converted to a simpler equivalent", ("fraction", "equation", "expression", "term"), ("mathematics_computation",)), + ), + "flow": ( + PredicateSense("flow:fluid", "moves_through", "flow", "a fluid moves along a path", ("blood", "water", "fluid", "channel", "vessel"), ("life_health", "earth_space")), + PredicateSense("flow:current", "transfers_energy", "flow", "electric current or energy traverses a circuit", ("current", "electric", "circuit", "charge", "energy"), ("physical_engineering",)), + PredicateSense("flow:information", "transfers_information", "flow", "information moves through a network", ("information", "data", "network", "signal"), ("mathematics_computation",)), + ), + "hold": ( + PredicateSense("hold:maintain", "maintains", "hold", "a condition remains at a value", ("constant", "stable", "temperature", "state")), + PredicateSense("hold:possess", "possesses", "hold", "an agent possesses an object", ("person", "owner", "object", "instrument")), + PredicateSense("hold:contain", "contains", "hold", "a container encloses contents", ("container", "volume", "contents", "water")), + ), +} + + +DEFAULT_RELATIONS: Mapping[str, str] = { + "lead to": "causes", "result in": "causes", "result from": "originates_from", + "cause": "causes", "produce": "produces", "generate": "produces", + "pull": "exerts_force_on", "move": "moves", "bypass": "bypasses", + "contain": "contains", "consist of": "has_parts", "include": "includes", + "affect": "affects", "enable": "enables", "prevent": "prevents", + "increase": "increases", "decrease": "decreases", "maintain": "maintains", + "stabilize": "stabilizes", "sustain": "sustains", "show": "indicates", + "indicate": "indicates", "provide": "provides", "supply": "supplies", + "require": "requires", "depend on": "depends_on", "interact with": "interacts_with", + "close": "changes_state", "remain": "maintains_state", "become": "changes_state", +} +DEFAULT_REALIZATIONS: Mapping[str, str] = { + "lead to": "cause", + "result in": "cause", + "result from": "originate", +} + + +def _canonical_json(value: Any) -> str: + return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + + +def _strip_surface(value: str) -> str: + return " ".join(value.strip(" \t\r\n,;:.!?").split()) + + +def _content_terms(value: str) -> set[str]: + return { + token for token in tokens(value) + if token not in {"a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "how", "in", "is", "it", "of", "on", "or", "the", "to", "was", "were", "what", "which", "who", "why", "with"} + } + + +def _span_in(evidence: str, value: str | None, start_hint: int = 0) -> tuple[int, int] | None: + if not value: + return None + start = evidence.casefold().find(value.casefold(), max(0, start_hint)) + if start < 0: + start = evidence.casefold().find(value.casefold()) + return None if start < 0 else (start, start + len(value)) + + +def _split_trailing_participle(value: str) -> tuple[str, str | None, int | None]: + match = re.search(r",\s*(?=[A-Za-z]+ing\b)", value) + if match is None: + return value, None, None + return value[:match.start()], value[match.end():], match.end() + + +@dataclass(frozen=True) +class SenseDecision: + lemma: str + selected: PredicateSense + candidates: tuple[tuple[str, float], ...] + + def as_dict(self) -> dict[str, Any]: + return { + "lemma": self.lemma, + "selected_sense_id": self.selected.sense_id, + "selected_relation": self.selected.relation, + "selected_gloss": self.selected.gloss, + "candidate_scores": [[sense_id, score] for sense_id, score in self.candidates], + "contextual_selection": len(self.candidates) > 1, + } + + +class ContextualPredicateSenseLattice: + @staticmethod + def select(lemma: str, context: str, domain_ids: Sequence[str]) -> SenseDecision: + candidates = SENSES.get(lemma) + if not candidates: + default = PredicateSense( + f"{lemma}:default", DEFAULT_RELATIONS.get(lemma, lemma.replace(" ", "_")), + DEFAULT_REALIZATIONS.get(lemma, lemma), f"ordinary relational sense of {lemma}", + ) + return SenseDecision(lemma, default, ((default.sense_id, 1.0),)) + words = _content_terms(context) + domains = set(domain_ids) + scored = [] + for index, candidate in enumerate(candidates): + cue_score = sum(1.0 for cue in candidate.cues if cue in words) + domain_score = 0.75 * len(domains & set(candidate.domains)) + prior = 0.05 * (len(candidates) - index) + scored.append((cue_score + domain_score + prior, candidate)) + scored.sort(key=lambda value: (-value[0], value[1].sense_id)) + return SenseDecision( + lemma, + scored[0][1], + tuple((candidate.sense_id, float(score)) for score, candidate in scored), + ) + + +@dataclass(frozen=True) +class CompiledProposition: + proposition_id: str + subject: str + predicate: str + object_value: str | None + complement: str | None + qualifiers: tuple[tuple[str, str], ...] + relation: str + sense: SenseDecision + modality: str + polarity: str + voice: str + clause_type: str + evidence: str + evidence_sha256: str + source_document: str + source_document_sha256: str + text_sha256: str + license_note: str + subject_span: tuple[int, int] + predicate_span: tuple[int, int] + object_span: tuple[int, int] | None + protected_root_cosine: float + state_sha256: str + provenance_sha256: str + + def as_dict(self) -> dict[str, Any]: + return { + "schema_version": COMPILER_SCHEMA, + "proposition_id": self.proposition_id, + "subject": self.subject, + "predicate": self.predicate, + "object_value": self.object_value, + "complement": self.complement, + "qualifiers": [list(value) for value in self.qualifiers], + "relation": self.relation, + "sense": self.sense.as_dict(), + "modality": self.modality, + "polarity": self.polarity, + "voice": self.voice, + "clause_type": self.clause_type, + "evidence": self.evidence, + "evidence_sha256": self.evidence_sha256, + "source_document": self.source_document, + "source_document_sha256": self.source_document_sha256, + "text_sha256": self.text_sha256, + "license_note": self.license_note, + "subject_span": list(self.subject_span), + "predicate_span": list(self.predicate_span), + "object_span": None if self.object_span is None else list(self.object_span), + "protected_root_cosine": self.protected_root_cosine, + "state_sha256": self.state_sha256, + "provenance_sha256": self.provenance_sha256, + "pre_malkuth_payload_unbinds": 0, + "traditional_language_model": False, + "pretrained_embedding_encoder": False, + "next_token_predictions": 0, + } + + def semantic_clause(self) -> SemanticClause: + modal = { + "possible": "may", "probable": "may", "obligatory": "must", + }.get(self.modality) + polarity = self.polarity + if modal is not None and polarity == "negative": + modal += " not" + polarity = "positive" + return SemanticClause( + self.subject, + self.predicate, + object_value=self.object_value, + complement=self.complement, + qualifiers=self.qualifiers, + modal=modal, + polarity=polarity, + ) + + +class NativePropositionCompiler: + def __init__(self) -> None: + self.sense_lattice = ContextualPredicateSenseLattice() + + @staticmethod + def _modality(words: Sequence[str], conditional: bool) -> str: + lowered = {value.casefold() for value in words} + if conditional: + return "conditional" + if lowered & PROBABLE: + return "probable" + if lowered & UNCERTAIN: + return "possible" + if "must" in lowered or "should" in lowered: + return "obligatory" + return "asserted" + + @staticmethod + def _polarity(words: Sequence[str]) -> str: + return "negative" if {value.casefold() for value in words} & NEGATIONS else "positive" + + @staticmethod + def _clean_argument(value: str) -> str: + clean_value = _strip_surface(value) + clean_value = re.sub(r"\s+\d+\s+Chapter\s+\d+.*$", "", clean_value, flags=re.IGNORECASE) + clean_value = re.sub(r"^(?:that|then)\s+", "", clean_value, flags=re.IGNORECASE) + return _strip_surface(clean_value) + + @staticmethod + def _path_object(value: str) -> tuple[str | None, tuple[tuple[str, str], ...]]: + text = _strip_surface(value) + markers = list(re.finditer(r"\b(from|to|into|through|in|at|toward|across|by)\b", text, re.IGNORECASE)) + if not markers: + return (text or None), () + object_value = _strip_surface(text[:markers[0].start()]) or None + qualifiers = [] + for index, match in enumerate(markers): + end = markers[index + 1].start() if index + 1 < len(markers) else len(text) + value_part = _strip_surface(text[match.end():end]) + value_part = re.sub(r"^(?:directly|then)\s+", "", value_part, flags=re.IGNORECASE) + value_part = re.sub(r"\s+and\s+then$", "", value_part, flags=re.IGNORECASE) + if value_part: + qualifiers.append((match.group(1).casefold(), value_part)) + return object_value, tuple(qualifiers) + + def _make( + self, + *, + subject: str, + lemma: str, + object_value: str | None, + complement: str | None, + qualifiers: Sequence[tuple[str, str]], + modality: str, + polarity: str, + voice: str, + clause_type: str, + evidence_row: Mapping[str, Any], + subject_span: tuple[int, int], + predicate_span: tuple[int, int], + object_span: tuple[int, int] | None, + domain_ids: Sequence[str], + ) -> CompiledProposition: + evidence = clean(evidence_row.get("fact", evidence_row.get("text", ""))) + sense = self.sense_lattice.select(lemma, evidence, domain_ids) + roles = { + "subject": subject, + "predicate": sense.selected.relation, + "object": object_value or complement or "", + "modality": modality, + "polarity": polarity, + } + moving = normalize(sum( + ( + bind(unitary("stage5k31:role:" + role), text_hrr(value)) + for role, value in roles.items() if value + ), + np.zeros(HRR_DIM, dtype=np.complex64), + )) + root = unitary("stage5k31:source:" + str(evidence_row.get("text_sha256", hashlib.sha256(evidence.encode()).hexdigest()))) + residual = moving - np.complex64(np.vdot(root, moving)) * root + protected = normalize(np.float32(4.0) * root + residual) + body = { + "subject": subject, + "predicate": sense.selected.realization_lemma, + "object_value": object_value, + "complement": complement, + "qualifiers": [list(value) for value in qualifiers], + "relation": sense.selected.relation, + "sense_id": sense.selected.sense_id, + "modality": modality, + "polarity": polarity, + "voice": voice, + "clause_type": clause_type, + "evidence_sha256": evidence_row.get("text_sha256", hashlib.sha256(evidence.encode()).hexdigest()), + "source_document_sha256": evidence_row.get("source_document_sha256", ""), + "spans": [list(subject_span), list(predicate_span), None if object_span is None else list(object_span)], + } + provenance = hashlib.sha256(_canonical_json(body).encode()).hexdigest() + return CompiledProposition( + proposition_id="prop_" + provenance[:20], + subject=subject, + predicate=sense.selected.realization_lemma, + object_value=object_value, + complement=complement, + qualifiers=tuple(qualifiers), + relation=sense.selected.relation, + sense=sense, + modality=modality, + polarity=polarity, + voice=voice, + clause_type=clause_type, + evidence=evidence, + evidence_sha256=hashlib.sha256(evidence.encode()).hexdigest(), + source_document=str(evidence_row.get("source_document", "unknown")), + source_document_sha256=str(evidence_row.get("source_document_sha256", "")), + text_sha256=str(evidence_row.get("text_sha256", hashlib.sha256(evidence.encode()).hexdigest())), + license_note=str(evidence_row.get("license_note", "")), + subject_span=subject_span, + predicate_span=predicate_span, + object_span=object_span, + protected_root_cosine=cosine(root, protected), + state_sha256=hashlib.sha256(np.ascontiguousarray(protected).tobytes()).hexdigest(), + provenance_sha256=provenance, + ) + + def _parse_simple( + self, + clause: str, + evidence_row: Mapping[str, Any], + domain_ids: Sequence[str], + *, + clause_type: str = "assertion", + conditional: bool = False, + inherited_subject: str | None = None, + extra_qualifiers: Sequence[tuple[str, str]] = (), + base_offset: int = 0, + ) -> CompiledProposition | None: + surface = _strip_surface(clause) + if not surface: + return None + matches = tuple( + value for value in PREDICATE_PATTERN.finditer(surface) + if _strip_surface(surface[:value.start()]) or inherited_subject + ) + + def match_score(value: re.Match[str]) -> tuple[float, int]: + form = value.group(0).casefold() + lemma_value = FORM_TO_LEMMA[form] + left_tokens = WORD.findall(surface[:value.start()]) + previous = left_tokens[-1].casefold() if left_tokens else "" + score = 0.0 + if previous in AUXILIARIES | MODALS: + score += 4.0 + if form != lemma_value and lemma_value != "be": + score += 2.0 + if " " in form: + score += 1.0 + if lemma_value == "be" and any(other.start() > value.start() for other in matches): + score -= 6.0 + right_surface = surface[value.end():].lstrip().casefold() + if form == lemma_value and ( + previous in {"aggregate", "total", "of"} + or right_surface.startswith(("and ", "or ")) + ): + score -= 8.0 + return score, -value.start() + + match = max(matches, key=match_score) if matches else None + if match is not None and match_score(match)[0] <= -4.0: + match = None + if match is None: + # Copular property construction is retained as BE rather than + # guessing an adjective to be an unseen predicate. + copular = re.match(r"^(.+?)\s+(is|are|was|were)\s+(.+)$", surface, re.IGNORECASE) + if copular is None: + return None + subject = self._clean_argument(copular.group(1)) + complement = self._clean_argument(copular.group(3)) + words = WORD.findall(surface) + evidence = clean(evidence_row.get("fact", evidence_row.get("text", ""))) + subject_span = _span_in(evidence, subject, base_offset) + predicate_span = _span_in(evidence, copular.group(2), base_offset) + object_span = _span_in(evidence, complement, base_offset) + if subject_span is None or predicate_span is None or object_span is None: + return None + return self._make( + subject=subject, lemma="be", object_value=None, complement=complement, + qualifiers=extra_qualifiers, modality=self._modality(words, conditional), + polarity=self._polarity(words), voice="copular", clause_type=clause_type, + evidence_row=evidence_row, + subject_span=subject_span, + predicate_span=predicate_span, + object_span=object_span, domain_ids=domain_ids, + ) + predicate_surface = match.group(0).casefold() + lemma = FORM_TO_LEMMA[predicate_surface] + left = surface[:match.start()] + right = surface[match.end():] + left_words = WORD.findall(left) + modality_words = [value for value in left_words if value.casefold() in MODALS | NEGATIONS | PROBABLE] + while left_words and left_words[-1].casefold() in MODALS | NEGATIONS | AUXILIARIES: + left_words.pop() + subject = inherited_subject or self._clean_argument(" ".join(left_words)) + if not subject: + return None + right_clean = self._clean_argument(right) + # Preserve one proposition per scoped relation. Coordinated material + # without an explicit second subject remains outside this edge. + right_clean = re.split(r"\s+but\s+|;", right_clean, maxsplit=1, flags=re.IGNORECASE)[0] + voice = "active" + object_value: str | None = right_clean or None + complement: str | None = None + if right_clean.casefold().startswith("by ") and predicate_surface.endswith(("ed", "en")): + agent = self._clean_argument(right_clean[3:]) + object_value = subject + subject = agent + voice = "passive_normalized_active" + qualifiers = list(extra_qualifiers) + if lemma in {"flow", "move", "orbit", "transfer"}: + object_value, path = self._path_object(right_clean) + qualifiers = [*path, *extra_qualifiers] + words = (*WORD.findall(surface), *modality_words) + evidence = clean(evidence_row.get("fact", evidence_row.get("text", ""))) + subject_span = _span_in(evidence, subject, base_offset) + predicate_span = _span_in(evidence, match.group(0), base_offset) + object_span = _span_in( + evidence, object_value or complement, + (predicate_span[1] if predicate_span is not None else base_offset), + ) + if subject_span is None or predicate_span is None: + return None + return self._make( + subject=subject, + lemma=lemma, + object_value=object_value, + complement=complement, + qualifiers=qualifiers, + modality=self._modality(words, conditional), + polarity=self._polarity(words), + voice=voice, + clause_type=clause_type, + evidence_row=evidence_row, + subject_span=subject_span, + predicate_span=predicate_span, + object_span=object_span, + domain_ids=domain_ids, + ) + + def compile_row( + self, + evidence_row: Mapping[str, Any], + domain_ids: Sequence[str] = (), + ) -> tuple[CompiledProposition, ...]: + evidence = clean(evidence_row.get("fact", evidence_row.get("text", ""))).rstrip(".!?") + if not evidence: + return () + values: list[CompiledProposition] = [] + conditional = re.match(r"^If\s+(.+?),\s*(.+)$", evidence, re.IGNORECASE) + if conditional: + condition_surface, result_surface = conditional.group(1), conditional.group(2) + condition = self._parse_simple( + condition_surface, evidence_row, domain_ids, + clause_type="condition", conditional=True, + base_offset=conditional.start(1), + ) + result_main, trailing, trailing_offset = _split_trailing_participle(result_surface) + result = self._parse_simple( + result_main, evidence_row, domain_ids, + clause_type="conditional_result", conditional=True, + extra_qualifiers=(("if", condition_surface.casefold()),), + base_offset=conditional.start(2), + ) + if result is not None: + values.append(result) + if condition is not None: + values.append(condition) + if trailing is not None and result is not None: + extra = self._parse_simple( + trailing, evidence_row, domain_ids, + clause_type="coordinated_result", conditional=True, + inherited_subject=result.subject, + extra_qualifiers=(("if", condition_surface.casefold()),), + base_offset=conditional.start(2) + int(trailing_offset or 0), + ) + if extra is not None: + values.append(extra) + return tuple(values) + + participial = re.match( + r"^(Pulled|Driven|Caused|Generated|Produced|Supported|Held)\s+by\s+(.+?),\s*(.+)$", + evidence, + re.IGNORECASE, + ) + if participial: + lemma = FORM_TO_LEMMA[participial.group(1).casefold()] + cause_surface = self._clean_argument(participial.group(2)) + main_surface = participial.group(3) + initial_main = self._parse_simple( + main_surface, evidence_row, domain_ids, + clause_type="causal_result", + base_offset=participial.start(3), + ) + main_subject = initial_main.subject if initial_main else "the resulting system" + causal_phrase = f"{cause_surface} {_third_surface(lemma)} {main_subject}" + main = self._parse_simple( + main_surface, evidence_row, domain_ids, + clause_type="causal_result", extra_qualifiers=(("because", causal_phrase),), + base_offset=participial.start(3), + ) + evidence_clean = clean(evidence_row.get("fact", evidence_row.get("text", ""))) + cause_subject_span = _span_in(evidence_clean, cause_surface, participial.start(2)) + cause_predicate_span = _span_in(evidence_clean, participial.group(1), participial.start(1)) + cause_object_span = _span_in(evidence_clean, main.subject if main else main_subject, participial.start(3)) + if cause_subject_span is None or cause_predicate_span is None: + return tuple(value for value in (main,) if value is not None) + cause = self._make( + subject=cause_surface, lemma=lemma, object_value=main.subject if main else main_subject, + complement=None, qualifiers=(), modality="asserted", polarity="positive", + voice="participial_passive_normalized_active", clause_type="causal_support", + evidence_row=evidence_row, + subject_span=cause_subject_span, + predicate_span=cause_predicate_span, + object_span=cause_object_span, domain_ids=domain_ids, + ) + if main is not None: + values.append(main) + values.append(cause) + return tuple(values) + + main_surface, trailing, trailing_offset = _split_trailing_participle(evidence) + main = self._parse_simple(main_surface, evidence_row, domain_ids, base_offset=0) + if main is not None: + values.append(main) + if trailing is not None and main is not None: + extra = self._parse_simple( + trailing, evidence_row, domain_ids, + clause_type="coordinated_assertion", inherited_subject=main.subject, + base_offset=int(trailing_offset or 0), + ) + if extra is not None: + values.append(extra) + return tuple(values) + + def compile_evidence( + self, + evidence: Sequence[Mapping[str, Any]], + domain_ids: Sequence[str] = (), + ) -> tuple[CompiledProposition, ...]: + values = [ + proposition + for row in evidence + for proposition in self.compile_row(row, domain_ids) + ] + unique = {value.provenance_sha256: value for value in values} + return tuple(unique[key] for key in sorted(unique)) + + +class NativePropositionKnowledgeAgent(DualLatticeKnowledgeAgent): + def __init__(self, *args: Any, **kwargs: Any) -> None: + kwargs.setdefault("agent_id", "oracle-stage5k31-native-proposition-compiler-agent") + super().__init__(*args, **kwargs) + self.proposition_compiler = NativePropositionCompiler() + self._last_proposition_audit: dict[str, Any] | None = None + + def _handle_evidence(self, text: str, context: Mapping[str, Any]) -> HandlerResult | None: + evidence = context.get("evidence") + if not isinstance(evidence, Sequence) or isinstance(evidence, (str, bytes)) or not evidence: + return None + rows = tuple(value for value in evidence if isinstance(value, Mapping)) + if not rows or not all(value.get("source_document_sha256") for value in rows): + self._last_proposition_audit = { + "schema_version": COMPILER_SCHEMA, + "invoked": False, + "reason": "caller_supplied_bounded_evidence_uses_existing_synthesis_contract", + "raw_sentence_fallback_used": False, + "traditional_language_model_calls": 0, + "pretrained_embedding_encoder_calls": 0, + "next_token_predictions": 0, + } + return super()._handle_evidence(text, context) + domain_ids = tuple({str(value.get("domain_id")) for value in rows if value.get("domain_id")}) + propositions = self.proposition_compiler.compile_evidence(rows, domain_ids) + self._last_proposition_audit = { + "schema_version": COMPILER_SCHEMA, + "source_rows": len(rows), + "compiled_propositions": len(propositions), + "propositions": [value.as_dict() for value in propositions], + "minimum_protected_root_cosine": min((value.protected_root_cosine for value in propositions), default=0.0), + "pre_malkuth_payload_unbinds": 0, + "raw_sentence_fallback_used": False, + "traditional_language_model_calls": 0, + "pretrained_embedding_encoder_calls": 0, + "next_token_predictions": 0, + } + if not propositions: + return self._abstention( + "knowledge_explanation", "the requested knowledge claim", + "admitted_evidence_has_no_compilable_proposition", + ) + query_terms = _content_terms(text) + scored = sorted( + propositions, + key=lambda value: ( + -len(query_terms & _content_terms(" ".join(filter(None, ( + value.subject, value.predicate, value.object_value, value.complement, + ))))), + value.clause_type in {"condition", "causal_support"}, + value.proposition_id, + ), + ) + realizable = [ + value for value in scored + if value.clause_type not in {"condition", "causal_support"} + ][:3] + causal_request = bool(set(tokens(text)) & {"why", "cause", "caused", "causal"}) + causal_relations = {"causes", "produces", "exerts_force_on", "originates_from"} + causal_warrant = any( + value.relation in causal_relations or any(key == "because" for key, _ in value.qualifiers) + for value in propositions + ) + if causal_request and not causal_warrant: + return self._abstention( + "knowledge_explanation", "the requested causal conclusion", + "compiled_propositions_lack_causal_warrant", + ) + if not realizable: + return self._abstention( + "knowledge_explanation", "the requested knowledge claim", + "compiled_propositions_are_support_only", + ) + return HandlerResult( + "knowledge_explanation", + "answered", + (("source_rows", len(rows)), ("compiled_propositions", len(propositions))), + (("released_propositions", len(realizable)), ("relations", [value.relation for value in realizable])), + tuple(value.semantic_clause() for value in realizable), + tuple((value.source_document_sha256, value.provenance_sha256) for value in realizable), + ( + "discover_predicate_spans", + "select_contextual_dictionary_senses", + "normalize_voice_and_thematic_roles", + "bind_modality_polarity_and_provenance", + "compose_explanatory_relation_graph", + ), + tool_audit={ + "tool": "native_proposition_compiler", + "source_rows": len(rows), + "compiled_propositions": len(propositions), + "global_gradient_steps": 0, + "raw_sentence_fallback_used": False, + }, + ) + + def answer( + self, + session_id: str, + text: str, + context: Mapping[str, Any] | None = None, + *, + ablate_specialists: Sequence[str] = (), + ablate_knowledge_cells: Sequence[str] = (), + ) -> dict[str, Any]: + self._last_proposition_audit = None + output = super().answer( + session_id, text, context, + ablate_specialists=ablate_specialists, + ablate_knowledge_cells=ablate_knowledge_cells, + ) + output["schema_version"] = SCHEMA + output["proposition_compiler"] = self._last_proposition_audit or { + "schema_version": COMPILER_SCHEMA, + "invoked": False, + "reason": "knowledge_evidence_not_admitted", + "raw_sentence_fallback_used": False, + "traditional_language_model_calls": 0, + "next_token_predictions": 0, + } + output["runtime"]["proposition_compiler_model_calls"] = 0 + output["runtime"]["proposition_compiler_gradient_steps"] = 0 + output["runtime"]["proposition_compiler_next_token_predictions"] = 0 + output["turn_manifest_sha256"] = digest(output) + return output + + +__all__ = [ + "CompiledProposition", "ContextualPredicateSenseLattice", + "NativePropositionCompiler", "NativePropositionKnowledgeAgent", + "PredicateSense", "SenseDecision", +] diff --git a/root/wander-train/stage5k39_indexed_cycling_substrate.py b/root/wander-train/stage5k39_indexed_cycling_substrate.py new file mode 100644 index 0000000000000000000000000000000000000000..16140c6b0cbdd1354ff00bfcf0885e5a5a1fb035 --- /dev/null +++ b/root/wander-train/stage5k39_indexed_cycling_substrate.py @@ -0,0 +1,828 @@ +#!/usr/bin/env python3 +"""Append-only indexed HRR memory compatible with Oracle snapshot handles. + +The original persistent substrate is semantically sound but rebuilds every +bank rail and scans every event on each hot-path operation. This engine keeps +the same immutable event identity and authenticated SnapshotBundle contract, +while storing events in an indexed SQLite journal and updating HRR rails in +O(number of bound roles). Whole-bank work occurs only in an explicit cycling +phase, never during conversational retrieval. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from contextvars import ContextVar +import json +from pathlib import Path +import secrets +import sqlite3 +from typing import Any, Iterable, Mapping, Sequence + +import numpy as np + +from ensouled._substrate import oracle_memory as om + + +SCHEMA = "oracle-stage5k39-indexed-cycling-substrate-v1" + + +def _json(value: Any) -> str: + return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":")) + + +def _vector_blob(value: np.ndarray) -> bytes: + return np.ascontiguousarray(value, dtype=np.complex128).tobytes() + + +def _blob_vector(value: bytes, dim: int) -> np.ndarray: + result = np.frombuffer(value, dtype=np.complex128).copy() + if result.shape != (dim,): + raise om.SubstrateIntegrityError("indexed cycling rail dimension differs") + return result + + +class IndexedCyclingPersistentSubstrate: + """Indexed event store with incremental HRR rails and explicit cycling.""" + + def __init__( + self, + path: str | Path, + *, + agent_id: str, + dim: int = om.DEFAULT_DIM, + max_entries_per_bank: int = 512, + lock_timeout: float = 30.0, + legacy_store: om.OraclePersistentSubstrate | None = None, + ) -> None: + if dim < 32: + raise ValueError("HRR dimension must be at least 32") + self.path = Path(path) + self.agent_id = agent_id + self.dim = int(dim) + self.max_entries_per_bank = int(max_entries_per_bank) + self.lock_timeout = float(lock_timeout) + self.legacy_store = legacy_store + self.path.parent.mkdir(parents=True, exist_ok=True) + self._last_audit: ContextVar[dict[str, Any]] = ContextVar( + f"indexed-cycling-audit-{id(self)}", default={}, + ) + self._initialize() + if legacy_store is not None: + self._migrate_legacy_once(legacy_store) + + def _connect(self) -> sqlite3.Connection: + connection = sqlite3.connect(self.path, timeout=self.lock_timeout) + connection.row_factory = sqlite3.Row + connection.execute("PRAGMA journal_mode=WAL") + connection.execute("PRAGMA synchronous=NORMAL") + connection.execute("PRAGMA foreign_keys=ON") + return connection + + @contextmanager + def _connection(self): + connection = self._connect() + try: + yield connection + if connection.in_transaction: + connection.commit() + except Exception: + if connection.in_transaction: + connection.rollback() + raise + finally: + connection.close() + + @staticmethod + def _meta(connection: sqlite3.Connection, key: str, default: Any = None) -> Any: + row = connection.execute("SELECT value FROM meta WHERE key=?", (key,)).fetchone() + return default if row is None else json.loads(row["value"]) + + @staticmethod + def _set_meta(connection: sqlite3.Connection, key: str, value: Any) -> None: + connection.execute( + "INSERT INTO meta(key,value) VALUES(?,?) " + "ON CONFLICT(key) DO UPDATE SET value=excluded.value", + (key, _json(value)), + ) + + def _initialize(self) -> None: + with self._connection() as connection: + connection.executescript(""" + CREATE TABLE IF NOT EXISTS meta( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS events( + memory_id TEXT PRIMARY KEY, + bank TEXT NOT NULL, + roles_json TEXT NOT NULL, + source_record_id TEXT NOT NULL, + provenance_json TEXT NOT NULL, + initial_status TEXT NOT NULL, + status TEXT NOT NULL, + confidence REAL NOT NULL, + weight REAL NOT NULL, + created_at TEXT NOT NULL, + created_seq INTEGER NOT NULL, + last_recalled_seq INTEGER NOT NULL, + recall_count INTEGER NOT NULL, + event_key TEXT NOT NULL UNIQUE, + contradictions_json TEXT NOT NULL, + immutable_metadata_json TEXT NOT NULL, + mutable_metadata_json TEXT NOT NULL, + pinned INTEGER NOT NULL, + entry_digest TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS events_bank_seq + ON events(bank, created_seq DESC); + CREATE TABLE IF NOT EXISTS role_postings( + bank TEXT NOT NULL, + role TEXT NOT NULL, + value TEXT NOT NULL, + memory_id TEXT NOT NULL, + created_seq INTEGER NOT NULL, + PRIMARY KEY(bank,role,value,memory_id), + FOREIGN KEY(memory_id) REFERENCES events(memory_id) ON DELETE CASCADE + ); + CREATE INDEX IF NOT EXISTS role_posting_lookup + ON role_postings(bank,role,value,created_seq DESC); + CREATE TABLE IF NOT EXISTS rails( + bank TEXT NOT NULL, + role TEXT NOT NULL, + kind TEXT NOT NULL, + vector BLOB NOT NULL, + PRIMARY KEY(bank,role,kind) + ); + """) + if self._meta(connection, "schema_version") is None: + self._set_meta(connection, "schema_version", SCHEMA) + self._set_meta(connection, "agent_id", self.agent_id) + self._set_meta(connection, "dim", self.dim) + self._set_meta(connection, "max_entries_per_bank", self.max_entries_per_bank) + self._set_meta(connection, "version", 0) + self._set_meta(connection, "cycle_count", 0) + self._set_meta(connection, "event_seq", 0) + self._set_meta(connection, "state_digest", om.digest_value({ + "schema": SCHEMA, "agent_id": self.agent_id, "dim": self.dim, + })) + for bank in om.BANKS: + self._set_meta(connection, f"spectral:{bank}", False) + for role in om.ROLES: + zero = _vector_blob(np.zeros(self.dim, dtype=np.complex128)) + connection.execute( + "INSERT OR IGNORE INTO rails(bank,role,kind,vector) VALUES(?,?,?,?)", + (bank, role, "explicit", zero), + ) + connection.execute( + "INSERT OR IGNORE INTO rails(bank,role,kind,vector) VALUES(?,?,?,?)", + (bank, role, "implicit", zero), + ) + connection.execute( + "INSERT OR IGNORE INTO rails(bank,role,kind,vector) VALUES(?,?,?,?)", + (bank, role, "raw", zero), + ) + if self._meta(connection, "schema_version") != SCHEMA: + raise om.SubstrateIntegrityError("unsupported indexed cycling schema") + if self._meta(connection, "agent_id") != self.agent_id: + raise om.SubstrateIntegrityError("indexed cycling agent identity differs") + if int(self._meta(connection, "dim")) != self.dim: + raise om.SubstrateIntegrityError("indexed cycling dimension differs") + # Older K39 stores kept only the visible rail. Once spectral + # suppression was enabled that rail was no longer a linear + # accumulator, forcing every later append to rebuild all history. + # Reconstruct an unsuppressed raw rail once, then update it + # incrementally for the lifetime of the store. + for bank in om.BANKS: + for role in om.ROLES: + zero = _vector_blob(np.zeros(self.dim, dtype=np.complex128)) + connection.execute( + "INSERT OR IGNORE INTO rails(bank,role,kind,vector) VALUES(?,?,?,?)", + (bank, role, "raw", zero), + ) + if not bool(self._meta(connection, "raw_rails_v1", False)): + for bank in om.BANKS: + self._rebuild_bank(connection, bank) + self._set_meta(connection, "raw_rails_v1", True) + + @staticmethod + def _entry(row: sqlite3.Row) -> dict[str, Any]: + return { + "memory_id": row["memory_id"], + "bank": row["bank"], + "roles": json.loads(row["roles_json"]), + "source_record_id": row["source_record_id"], + "provenance": json.loads(row["provenance_json"]), + "initial_status": row["initial_status"], + "status": row["status"], + "confidence": float(row["confidence"]), + "weight": float(row["weight"]), + "created_at": row["created_at"], + "created_seq": int(row["created_seq"]), + "last_recalled_seq": int(row["last_recalled_seq"]), + "recall_count": int(row["recall_count"]), + "event_key": row["event_key"], + "contradictions": json.loads(row["contradictions_json"]), + "immutable_metadata": json.loads(row["immutable_metadata_json"]), + "mutable_metadata": json.loads(row["mutable_metadata_json"]), + "pinned": bool(row["pinned"]), + "entry_digest": row["entry_digest"], + } + + def _insert_entry(self, connection: sqlite3.Connection, entry: Mapping[str, Any]) -> None: + connection.execute( + "INSERT OR IGNORE INTO events VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + ( + entry["memory_id"], entry["bank"], _json(entry["roles"]), + entry["source_record_id"], _json(entry["provenance"]), + entry["initial_status"], entry["status"], float(entry["confidence"]), + float(entry["weight"]), entry["created_at"], int(entry["created_seq"]), + int(entry.get("last_recalled_seq", 0)), int(entry.get("recall_count", 0)), + entry["event_key"], _json(entry.get("contradictions", ())), + _json(entry.get("immutable_metadata", {})), + _json(entry.get("mutable_metadata", {})), int(bool(entry.get("pinned", False))), + entry["entry_digest"], + ), + ) + for role, value in entry["roles"].items(): + connection.execute( + "INSERT OR IGNORE INTO role_postings(bank,role,value,memory_id,created_seq) VALUES(?,?,?,?,?)", + (entry["bank"], role, value, entry["memory_id"], int(entry["created_seq"])), + ) + + def _migrate_legacy_once(self, store: om.OraclePersistentSubstrate) -> None: + with self._connection() as connection: + identity = om.digest_value({"path": str(store.path.resolve()), "agent": store.agent_id}) + if self._meta(connection, "legacy_identity") is not None: + return + state = store._load() + connection.execute("BEGIN IMMEDIATE") + try: + for bank in om.BANKS: + for entry in state["banks"][bank]["entries"]: + self._insert_entry(connection, entry) + for role in om.ROLES: + explicit = om._decode_vector(state["banks"][bank]["rails"][role], self.dim) + implicit = om._decode_vector(state["banks"][bank]["implicit_rails"][role], self.dim) + raw_encoded = state["banks"][bank].get("raw_rails", {}).get(role) + if raw_encoded is not None: + raw = om._decode_vector(raw_encoded, self.dim) + else: + raw = implicit.copy() + for entry in state["banks"][bank]["entries"]: + value = entry["roles"].get(role) + if value is not None: + raw += float(entry["weight"]) * om._entry_binding( + entry["memory_id"], role, value, self.dim, + ) + connection.execute( + "UPDATE rails SET vector=? WHERE bank=? AND role=? AND kind='explicit'", + (_vector_blob(explicit), bank, role), + ) + connection.execute( + "UPDATE rails SET vector=? WHERE bank=? AND role=? AND kind='implicit'", + (_vector_blob(implicit), bank, role), + ) + connection.execute( + "UPDATE rails SET vector=? WHERE bank=? AND role=? AND kind='raw'", + (_vector_blob(raw), bank, role), + ) + self._set_meta(connection, f"spectral:{bank}", bool(state["banks"][bank].get("spectral_enabled"))) + for key in ("version", "cycle_count", "event_seq", "state_digest"): + self._set_meta(connection, key, state[key]) + self._set_meta(connection, "legacy_identity", identity) + self._set_meta(connection, "legacy_state_digest", state["state_digest"]) + self._set_meta(connection, "raw_rails_v1", True) + connection.commit() + except Exception: + connection.rollback() + raise + + def _rail(self, connection: sqlite3.Connection, bank: str, role: str, kind: str = "explicit") -> np.ndarray: + row = connection.execute( + "SELECT vector FROM rails WHERE bank=? AND role=? AND kind=?", + (bank, role, kind), + ).fetchone() + if row is None: + raise om.SubstrateIntegrityError("indexed cycling rail is missing") + return _blob_vector(row["vector"], self.dim) + + def _set_rail(self, connection: sqlite3.Connection, bank: str, role: str, value: np.ndarray, kind: str = "explicit") -> None: + connection.execute( + "UPDATE rails SET vector=? WHERE bank=? AND role=? AND kind=?", + (_vector_blob(value), bank, role, kind), + ) + + def _publish_role( + self, + connection: sqlite3.Connection, + bank: str, + role: str, + raw: np.ndarray, + ) -> None: + self._set_rail(connection, bank, role, raw, "raw") + visible = ( + om._spectral_filter(raw) + if bool(self._meta(connection, f"spectral:{bank}")) + else raw + ) + self._set_rail(connection, bank, role, visible, "explicit") + + def inspect(self) -> dict[str, Any]: + with self._connection() as connection: + counts = { + bank: int(connection.execute( + "SELECT COUNT(*) AS n FROM events WHERE bank=?", (bank,), + ).fetchone()["n"]) + for bank in om.BANKS + } + implicit_norms = { + bank: { + role: float(np.linalg.norm(self._rail(connection, bank, role, "implicit"))) + for role in om.ROLES + } + for bank in om.BANKS + } + return { + "schema_version": SCHEMA, + "agent_id": self.agent_id, + "dim": self.dim, + "version": int(self._meta(connection, "version")), + "cycle_count": int(self._meta(connection, "cycle_count")), + "state_digest": self._meta(connection, "state_digest"), + "entries": counts, + "implicit_norms": implicit_norms, + "skills": {}, + "indexed_hot_path": True, + } + + def bind_event( + self, + *, + bank: str, + roles: Mapping[str, str], + source_record_id: str, + provenance: Mapping[str, Any], + status: str = "unverified", + confidence: float = 0.5, + event_key: str | None = None, + created_at: str | None = None, + contradictions: Sequence[str] = (), + metadata: Mapping[str, Any] | None = None, + ) -> str: + if bank not in om.BANKS: + raise ValueError(f"unsupported memory bank: {bank}") + if status not in om.EVENT_STATUSES: + raise ValueError(f"unsupported memory status: {status}") + clean_roles = om._validate_roles(roles) + created_at = created_at or om.utc_now() + if event_key is None: + event_key = om.digest_value({ + "agent_id": self.agent_id, "source_record_id": source_record_id, + "roles": clean_roles, "created_at": created_at, + }) + event_body = { + "domain": "oracle-persistent-memory-event-v1", + "agent_id": self.agent_id, + "bank": bank, + "roles": clean_roles, + "source_record_id": source_record_id, + "provenance": dict(provenance), + "initial_status": status, + "event_key": event_key, + "created_at": created_at, + "contradictions": list(contradictions), + "immutable_metadata": dict(metadata or {}), + } + memory_id = "mem_" + om.digest_value(event_body) + with self._connection() as connection: + connection.execute("BEGIN IMMEDIATE") + try: + existing = connection.execute( + "SELECT memory_id FROM events WHERE memory_id=?", (memory_id,), + ).fetchone() + if existing is not None: + connection.commit() + return memory_id + conflict = connection.execute( + "SELECT memory_id FROM events WHERE event_key=?", (event_key,), + ).fetchone() + if conflict is not None: + raise ValueError(f"event_key already bound to another event: {event_key}") + sequence = int(self._meta(connection, "event_seq")) + 1 + weight = float(np.clip(max(confidence, 0.25), 0.05, 2.0)) + entry = { + "memory_id": memory_id, + "bank": bank, + "roles": clean_roles, + "source_record_id": source_record_id, + "provenance": dict(provenance), + "initial_status": status, + "status": status, + "confidence": float(np.clip(confidence, 0.0, 1.0)), + "weight": weight, + "created_at": created_at, + "created_seq": sequence, + "last_recalled_seq": 0, + "recall_count": 0, + "event_key": event_key, + "contradictions": list(contradictions), + "immutable_metadata": dict(metadata or {}), + "mutable_metadata": {}, + "pinned": False, + "entry_digest": "", + } + entry["entry_digest"] = om._entry_digest(entry) + self._insert_entry(connection, entry) + for role, value in clean_roles.items(): + raw = self._rail(connection, bank, role, "raw") + raw += weight * om._entry_binding(memory_id, role, value, self.dim) + self._publish_role(connection, bank, role, raw) + version = int(self._meta(connection, "version")) + 1 + previous = self._meta(connection, "state_digest") + self._set_meta(connection, "event_seq", sequence) + self._set_meta(connection, "version", version) + self._set_meta(connection, "state_digest", om.digest_value({ + "previous": previous, "version": version, + "event_digest": entry["entry_digest"], + })) + connection.commit() + return memory_id + except Exception: + connection.rollback() + raise + + def _candidate_ids( + self, + connection: sqlite3.Connection, + query: Mapping[str, str], + banks: Sequence[str], + ) -> set[str]: + bank_marks = ",".join("?" for _ in banks) + candidate: set[str] | None = None + for role in ("root", "situation"): + if role not in query: + continue + rows = connection.execute( + f"SELECT memory_id FROM role_postings WHERE bank IN ({bank_marks}) AND role=? AND value=?", + (*banks, role, query[role]), + ) + values = {str(row["memory_id"]) for row in rows} + candidate = values if candidate is None else candidate & values + if candidate is None: + rows = connection.execute( + f"SELECT memory_id FROM events WHERE bank IN ({bank_marks})", tuple(banks), + ) + candidate = {str(row["memory_id"]) for row in rows} + return candidate + + def _score( + self, + entry: Mapping[str, Any], + rails: Mapping[str, np.ndarray], + query: Mapping[str, str], + ) -> float: + address = om.seed_vector(f"stage5m:memory-address:{entry['memory_id']}", self.dim) + similarities = [] + for role, value in query.items(): + if role not in entry["roles"]: + continue + recovered = om.unbind(address, rails[role]) + similarities.append(om.cosine(recovered, om.value_vector(role, value, self.dim))) + if not similarities: + return 0.0 + geometric = float(sum(similarities) / len(similarities)) + verified_bonus = 0.03 if entry["status"] == "verified" else 0.0 + return geometric * (0.75 + 0.25 * float(entry["confidence"])) + verified_bonus + + def create_snapshot( + self, + query_roles: Mapping[str, str], + *, + top_k: int = 8, + banks: Iterable[str] = om.BANKS, + request_nonce: str | None = None, + minimum_score: float = 0.02, + persist_recall: bool = True, + ) -> om.SnapshotBundle: + query = om._validate_roles(query_roles) + selected_banks = tuple(banks) + if not selected_banks or any(bank not in om.BANKS for bank in selected_banks): + raise ValueError("snapshot banks must be a non-empty subset of BANKS") + nonce = request_nonce or secrets.token_hex(16) + with self._connection() as connection: + connection.execute("BEGIN IMMEDIATE") + try: + candidate_ids = self._candidate_ids(connection, query, selected_banks) + entries: list[dict[str, Any]] = [] + for memory_id in candidate_ids: + row = connection.execute( + "SELECT * FROM events WHERE memory_id=?", (memory_id,), + ).fetchone() + if row is not None and row["status"] != "contradicted": + entries.append(self._entry(row)) + rails_by_bank = { + bank: {role: self._rail(connection, bank, role) for role in om.ROLES} + for bank in selected_banks + } + scored = [ + (self._score(entry, rails_by_bank[entry["bank"]], query), entry) + for entry in entries + ] + scored = [value for value in scored if value[0] >= minimum_score] + scored.sort(key=lambda value: ( + value[0], value[1]["confidence"], value[1]["created_seq"], + ), reverse=True) + chosen = scored[:max(0, int(top_k))] + version = int(self._meta(connection, "version")) + if persist_recall and chosen: + sequence = int(self._meta(connection, "event_seq")) + connection.executemany( + "UPDATE events SET recall_count=recall_count+1,last_recalled_seq=? WHERE memory_id=?", + ((sequence, entry["memory_id"]) for _score, entry in chosen), + ) + version += 1 + previous = self._meta(connection, "state_digest") + self._set_meta(connection, "version", version) + self._set_meta(connection, "state_digest", om.digest_value({ + "previous": previous, "version": version, + "recalled": [entry["memory_id"] for _score, entry in chosen], + })) + state_digest = self._meta(connection, "state_digest") + connection.commit() + except Exception: + connection.rollback() + raise + + query_digest = om.digest_value({"agent_id": self.agent_id, "roles": query}) + snapshot_id = "snap_" + om.digest_value({ + "agent_id": self.agent_id, + "request_nonce": nonce, + "state_version": version, + "state_digest": state_digest, + "query_digest": query_digest, + }) + handles: list[om.SnapshotHandle] = [] + payloads: list[om.SnapshotPayload] = [] + for score, entry in chosen: + handle_id = "mh_" + om.digest_value({ + "snapshot_id": snapshot_id, + "memory_id": entry["memory_id"], + "entry_digest": entry["entry_digest"], + }) + mutable = entry.get("mutable_metadata", {}) + skill_id = mutable.get("skill_id") + skill_revision = mutable.get("skill_revision") + handles.append(om.SnapshotHandle( + handle_id=handle_id, + memory_id=entry["memory_id"], + bank=entry["bank"], + memory_digest=entry["entry_digest"], + provenance_digest=om.digest_value(entry["provenance"]), + status=entry["status"], + confidence=float(entry["confidence"]), + score=float(score), + skill_id=skill_id, + skill_revision=skill_revision, + )) + provisional = om.SnapshotPayload( + handle_id=handle_id, + memory_id=entry["memory_id"], + bank=entry["bank"], + roles=tuple(sorted(entry["roles"].items())), + source_record_id=entry["source_record_id"], + provenance=tuple(sorted(entry["provenance"].items())), + payload_digest="", + skill_id=skill_id, + skill_revision=skill_revision, + ) + payloads.append(om.SnapshotPayload(**{ + **provisional.__dict__, "payload_digest": om._payload_digest(provisional), + })) + provisional_bank = om.SnapshotPayloadBank(snapshot_id, tuple(payloads), "") + payload_bank = om.SnapshotPayloadBank( + snapshot_id, provisional_bank.entries, om._payload_bank_digest(provisional_bank), + ) + provisional_snapshot = om.SubstrateSnapshot( + snapshot_id=snapshot_id, + agent_id=self.agent_id, + request_nonce=nonce, + state_version=version, + state_digest=state_digest, + query_digest=query_digest, + handles=tuple(handles), + payload_bank_digest=payload_bank.bank_digest, + snapshot_digest="", + ) + snapshot = om.SubstrateSnapshot(**{ + **provisional_snapshot.__dict__, + "snapshot_digest": om._snapshot_digest(provisional_snapshot), + }) + bundle = om.SnapshotBundle(snapshot=snapshot, payload_bank=payload_bank) + valid, reason = om.verify_snapshot_bundle(bundle) + if not valid: + raise om.SubstrateIntegrityError(reason or "indexed snapshot verification failed") + self._last_audit.set({ + "schema_version": SCHEMA, + "indexed_role_postings_touched": sum(role in query for role in ("root", "situation")), + "candidate_events_enumerated": len(candidate_ids), + "candidate_events_scored": len(entries), + "full_memory_entries_scanned": 0, + "authenticated_handles": len(handles), + }) + return bundle + + def last_snapshot_audit(self) -> dict[str, Any]: + return dict(self._last_audit.get()) + + def sequence_for_roles(self, roles: Mapping[str, str]) -> int: + with self._connection() as connection: + candidate_ids = self._candidate_ids(connection, roles, tuple(om.BANKS)) + target = dict(roles) + rows = ( + connection.execute( + "SELECT roles_json,created_seq FROM events WHERE memory_id=?", + (memory_id,), + ).fetchone() + for memory_id in candidate_ids + ) + for row in rows: + if row is None: + continue + if json.loads(row["roles_json"]) == target: + return int(row["created_seq"]) + return 0 + + def _rebuild_bank(self, connection: sqlite3.Connection, bank: str) -> None: + raw_rails = { + role: self._rail(connection, bank, role, "implicit") + for role in om.ROLES + } + for row in connection.execute("SELECT * FROM events WHERE bank=?", (bank,)): + entry = self._entry(row) + for role, value in entry["roles"].items(): + raw_rails[role] += float(entry["weight"]) * om._entry_binding( + entry["memory_id"], role, value, self.dim, + ) + for role, value in raw_rails.items(): + self._publish_role(connection, bank, role, value) + + def _apply_weight_updates( + self, + connection: sqlite3.Connection, + bank: str, + entries: Sequence[Mapping[str, Any]], + updates: Sequence[tuple[Mapping[str, Any], float]], + ) -> None: + """Update weighted HRR rails without reconstructing remembered history.""" + if not updates: + return + homogeneous_ratio: float | None = None + if len(updates) == len(entries) and entries: + ratios = [ + (new_weight - float(entry["weight"])) / float(entry["weight"]) + for entry, new_weight in updates + ] + if max(ratios) - min(ratios) <= 1e-12: + homogeneous_ratio = ratios[0] + if homogeneous_ratio is not None: + for role in om.ROLES: + raw = self._rail(connection, bank, role, "raw") + implicit = self._rail(connection, bank, role, "implicit") + raw = implicit + (1.0 + homogeneous_ratio) * (raw - implicit) + self._publish_role(connection, bank, role, raw) + else: + changed: dict[str, np.ndarray] = {} + for entry, new_weight in updates: + delta = new_weight - float(entry["weight"]) + if abs(delta) <= 1e-15: + continue + for role, value in entry["roles"].items(): + raw = changed.setdefault( + role, + self._rail(connection, bank, role, "raw"), + ) + raw += delta * om._entry_binding( + str(entry["memory_id"]), role, value, self.dim, + ) + for role, raw in changed.items(): + self._publish_role(connection, bank, role, raw) + connection.executemany( + "UPDATE events SET weight=? WHERE memory_id=?", + ((new_weight, str(entry["memory_id"])) for entry, new_weight in updates), + ) + + def cycle_once(self) -> dict[str, Any]: + phases = ("hebbian", "resonance", "spectral", "metabolize") + with self._connection() as connection: + connection.execute("BEGIN IMMEDIATE") + try: + cycle = int(self._meta(connection, "cycle_count")) + phase = phases[cycle % len(phases)] + detail = {"phase": phase, "hot": 0, "boosted": 0, "suppressed_bins": 0, "digested": 0} + if phase == "hebbian": + for bank in om.BANKS: + entries = [ + self._entry(row) + for row in connection.execute( + "SELECT * FROM events WHERE bank=?", (bank,), + ) + ] + updates = [] + for entry in entries: + hot = int(entry["recall_count"]) >= 2 + factor = 1.02 if hot or entry["status"] == "verified" else 0.98 + new_weight = float(np.clip( + float(entry["weight"]) * factor, 0.05, 2.0, + )) + if abs(new_weight - float(entry["weight"])) > 1e-15: + updates.append((entry, new_weight)) + detail["hot"] += int(hot) + self._apply_weight_updates( + connection, bank, entries, updates, + ) + elif phase == "resonance": + for bank in om.BANKS: + entries = [ + self._entry(row) + for row in connection.execute( + "SELECT * FROM events WHERE bank=?", (bank,), + ) + ] + updates = [] + for entry in entries: + if int(entry["recall_count"]) < 3: + continue + new_weight = float(np.clip( + float(entry["weight"]) + 0.05, 0.05, 2.0, + )) + if abs(new_weight - float(entry["weight"])) > 1e-15: + updates.append((entry, new_weight)) + detail["boosted"] += 1 + self._apply_weight_updates( + connection, bank, entries, updates, + ) + elif phase == "spectral": + for bank in om.BANKS: + self._set_meta(connection, f"spectral:{bank}", True) + for role in om.ROLES: + raw = self._rail(connection, bank, role, "raw") + self._publish_role(connection, bank, role, raw) + detail["suppressed_bins"] = len(om.BANKS) * len(om.ROLES) * int(round(self.dim * 0.10)) + else: + for bank in om.BANKS: + rows = list(connection.execute( + "SELECT * FROM events WHERE bank=? ORDER BY recall_count,confidence,created_seq", + (bank,), + )) + while len(rows) > self.max_entries_per_bank: + row = next((value for value in rows if not value["pinned"]), None) + if row is None: + break + entry = self._entry(row) + for role, value in entry["roles"].items(): + implicit = self._rail(connection, bank, role, "implicit") + absorbed = 0.5 * float(entry["weight"]) * om._entry_binding( + entry["memory_id"], role, value, self.dim, + ) + implicit += absorbed + self._set_rail(connection, bank, role, implicit, "implicit") + raw = self._rail(connection, bank, role, "raw") + raw -= absorbed + self._publish_role(connection, bank, role, raw) + connection.execute("DELETE FROM events WHERE memory_id=?", (entry["memory_id"],)) + rows.remove(row) + detail["digested"] += 1 + version = int(self._meta(connection, "version")) + 1 + previous = self._meta(connection, "state_digest") + self._set_meta(connection, "cycle_count", cycle + 1) + self._set_meta(connection, "version", version) + self._set_meta(connection, "state_digest", om.digest_value({ + "previous": previous, "version": version, "cycle": cycle + 1, + "phase": phase, "detail": detail, + })) + connection.commit() + detail.update({ + "cycle": cycle + 1, + "state_version": version, + "entry_counts": { + bank: int(connection.execute( + "SELECT COUNT(*) AS n FROM events WHERE bank=?", (bank,), + ).fetchone()["n"]) + for bank in om.BANKS + }, + "indexed_hot_path": True, + }) + return detail + except Exception: + connection.rollback() + raise + + def __getattr__(self, name: str) -> Any: + legacy = object.__getattribute__(self, "legacy_store") + if legacy is not None and hasattr(legacy, name): + return getattr(legacy, name) + raise AttributeError(name) + + +__all__ = ["IndexedCyclingPersistentSubstrate"] diff --git a/root/wander-train/stage5k39_semantic_indexed_native_generalist_agent.py b/root/wander-train/stage5k39_semantic_indexed_native_generalist_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..3220d19e65c913b161a63818eadec1ec583e5431 --- /dev/null +++ b/root/wander-train/stage5k39_semantic_indexed_native_generalist_agent.py @@ -0,0 +1,1420 @@ +#!/usr/bin/env python3 +"""K39 context-constrained concept addressing over the scan-free K37 runtime. + +K39 does not install a language model or an embedding encoder. It treats a +content lexeme as a sparse set of inspectable WordNet relation atoms, uses +those atoms to enumerate K37 corpus postings, and then requires a contextual +one-to-one alignment between query and evidence terms. Exact K37 retrieval +remains the first path and is returned unchanged whenever it is already +strong enough. +""" + +from __future__ import annotations + +from collections import defaultdict +from contextvars import ContextVar +import hashlib +import json +import math +from pathlib import Path +import re +from typing import Any, Mapping, Sequence + +import numpy as np + +from stage5k15_native_mixed_agent import ( + HandlerResult, + QuadraticAnswerInverse, + SemanticClause, + clean, + digest, + tokens, +) +from stage5i2_open_schema_conversational_transducer import row_key as dataset_row_key +from stage5k29_general_knowledge_domains import PUBLIC_CORPUS +from stage5k29_meta_fold_knowledge_basis import TrainedKnowledgeBasis +from stage5k33_cross_domain_address_index import CrossDomainAddressIndex +from stage5k33_repaired_native_generalist_agent import RepairedOpenSchemaConversationalTransducer +from stage5k35_bidirectional_native_generalist_agent import ( + BidirectionalKnowledgeSpecialistPool, + K35AnswerGrammar, + K35PropositionCompiler, + canonical_terms, +) +from stage5k31_native_proposition_compiler_agent import ( + AUXILIARIES, + FORM_TO_LEMMA, + MODALS, + NEGATIONS, + WORD, + _span_in, + _strip_surface, +) +from stage5k37_indexed_native_generalist_agent import ( + IndexedBidirectionalNativeGeneralistAgent, + IndexedFullCorpusAddressedKnowledgeBasis, + canonical_proof_identity, +) +from stage5k37_inverted_relational_index import InvertedRelationalIndex +from stage5k39_native_concept_address_index import ( + NativeConceptAddressIndex, + normalize_lexeme, +) +from stage5k39_indexed_cycling_substrate import IndexedCyclingPersistentSubstrate +from train_stage2a_role_ladder import HRR_DIM, bind, cosine, normalize, unbind, unitary + + +SCHEMA = "oracle-stage5k39-semantic-indexed-native-generalist-agent-v1" +SEMANTIC_AUDIT_SCHEMA = "oracle-stage5k39-semantic-retrieval-audit-v1" +EXACT_STRONG_SHARED_TERMS = 2 +EXACT_STRONG_QUERY_COVERAGE = 0.50 +EXACT_STRONG_SCORE = 0.18 +SEMANTIC_ALIGNMENT_MIN = 0.55 +SEMANTIC_GLOSS_ALIGNMENT_MIN = 0.23 +SEMANTIC_QUERY_COVERAGE_MIN = 0.40 +SEMANTIC_SCORE_MIN = 0.20 +MAX_SEMANTIC_TERMS_PER_QUERY_TERM = 96 +MAX_SEMANTIC_ROWS = 4096 +SEMANTIC_FUNCTION_TERMS = frozenset({ + "a", "an", "the", "what", "which", "who", "whom", "whose", "why", + "how", "when", "where", "whether", "does", "do", "did", "is", "are", + "was", "were", "be", "been", "being", "someone", "something", "one", + "can", "could", "may", "might", "must", "shall", "should", "will", + "would", "most", "many", "much", "called", "call", "named", "name", +}) + + +def _exact_is_strong(candidate: Mapping[str, Any] | None) -> bool: + return bool( + candidate + and len(candidate.get("shared_terms", ())) >= EXACT_STRONG_SHARED_TERMS + and float(candidate.get("query_term_coverage", 0.0)) >= EXACT_STRONG_QUERY_COVERAGE + and float(candidate.get("retrieval_score", 0.0)) >= EXACT_STRONG_SCORE + ) + + +def _relation_kind(atom: str) -> str: + return { + "l": "lemma_or_gloss", + "m": "morphology", + "c": "sense_or_hypernym", + "d": "derivational_family", + "x": "lexicographer_domain", + }.get(atom[:1], "relational") + + +def _surface_lemma_candidates(surface: str) -> tuple[str, ...]: + raw = str(surface).replace("_", " ").casefold().strip() + values = [raw] + if " " not in raw: + if raw.endswith("ies") and len(raw) > 3: + values.append(raw[:-3] + "y") + if raw.endswith("s") and len(raw) > 3: + values.append(raw[:-1]) + if raw.endswith("ed") and len(raw) > 4: + values.extend((raw[:-2], raw[:-1])) + if raw.endswith("ing") and len(raw) > 5: + values.extend((raw[:-3], raw[:-3] + "e")) + values.append(normalize_lexeme(raw)) + return tuple(dict.fromkeys(values)) + + +class SemanticIndexedFullCorpusAddressedKnowledgeBasis( + IndexedFullCorpusAddressedKnowledgeBasis +): + """Add sparse contextual concept enumeration only after weak exact recall.""" + + def __init__( + self, + basis: TrainedKnowledgeBasis, + address_index: CrossDomainAddressIndex, + relational_index: InvertedRelationalIndex, + concept_index: NativeConceptAddressIndex, + corpus_path: Path = PUBLIC_CORPUS, + ) -> None: + super().__init__(basis, address_index, relational_index, corpus_path) + self.concept_index = concept_index + metadata = concept_index.metadata + if metadata.get("relational_index_sha256") != relational_index.file_sha256: + raise ValueError("K39 concept addresses do not bind to the active K37 index") + if metadata.get("public_corpus_sha256") != relational_index.metadata.get("public_corpus_sha256"): + raise ValueError("K39 concept addresses do not bind to the active public corpus") + if int(metadata.get("primitive_domain_modes", -1)) != len(basis.profiles): + raise ValueError("K39 primitive-mode count differs from the loaded K29 basis") + if int(metadata.get("registered_knowledge_cells", -1)) != len(basis.partition): + raise ValueError("K39 cell count differs from the loaded K29 basis") + self._profiles = { + lexeme: dict(values) for lexeme, values in concept_index.lexeme_profiles.items() + } + self._concept_postings = { + atom: tuple(values) for atom, values in concept_index.corpus_terms_by_atom.items() + } + morph_terms: dict[str, set[str]] = defaultdict(set) + for corpus_term in self._term_postings: + for lemma in _surface_lemma_candidates(corpus_term): + morph_terms[lemma].add(corpus_term) + self._morph_terms = { + lemma: tuple(sorted(values)) for lemma, values in morph_terms.items() + } + self._semantic_events: ContextVar[tuple[dict[str, Any], ...]] = ContextVar( + f"k39-semantic-events-{id(self)}", default=(), + ) + + def begin_turn(self) -> None: + super().begin_turn() + self._semantic_events.set(()) + + def _record_semantic_event(self, event: Mapping[str, Any]) -> None: + self._semantic_events.set((*self._semantic_events.get(), dict(event))) + + def turn_audit(self) -> dict[str, Any]: + base = super().turn_audit() + events = self._semantic_events.get() + base.update({ + "schema_version": SEMANTIC_AUDIT_SCHEMA, + "concept_index_sha256": self.concept_index.file_sha256, + "concept_profiles": len(self._profiles), + "concept_posting_keys": len(self._concept_postings), + "semantic_fallback_calls": len(events), + "semantic_term_postings_touched": sum( + int(value["semantic_term_postings_touched"]) for value in events + ), + "semantic_candidate_terms_enumerated": sum( + int(value["semantic_candidate_terms_enumerated"]) for value in events + ), + "semantic_candidate_records_enumerated": sum( + int(value["semantic_candidate_records_enumerated"]) for value in events + ), + "semantic_candidate_records_scored": sum( + int(value["semantic_candidate_records_scored"]) for value in events + ), + "pre_malkuth_unbind_count": 0, + "semantic_events": list(events), + }) + return base + + def _profile(self, term: str) -> dict[str, float]: + for candidate in _surface_lemma_candidates(term): + value = self._profiles.get(candidate) + if value is not None: + return value + return dict(self.concept_index.profile(term)) + + @staticmethod + def _pair_similarity( + left: str, + right: str, + left_profile: Mapping[str, float], + right_profile: Mapping[str, float], + ) -> tuple[float, str | None, str]: + if left == right: + return 1.0, "l:" + left, "exact_lexeme" + shared_lemmas = set(_surface_lemma_candidates(left)) & set(_surface_lemma_candidates(right)) + if shared_lemmas: + lemma = min(shared_lemmas, key=lambda value: (len(value), value)) + return 0.99, "m:" + lemma, "morphological_lexeme" + shared = set(left_profile) & set(right_profile) + best_score = 0.0 + best_atom: str | None = None + for atom in shared: + if atom.startswith("x:"): + continue + score = min(float(left_profile[atom]), float(right_profile[atom])) + if atom.startswith("m:"): + score *= 0.98 + elif atom.startswith("d:"): + score *= 0.96 + elif atom.startswith("c:"): + score *= 0.98 + if score > best_score or (score == best_score and (best_atom is None or atom < best_atom)): + best_score, best_atom = score, atom + return best_score, best_atom, _relation_kind(best_atom or "") + + def _semantic_term_links( + self, + query_terms: Sequence[str], + ) -> tuple[dict[str, dict[str, tuple[float, str, str]]], int]: + links: dict[str, dict[str, tuple[float, str, str]]] = {} + postings_touched = 0 + for query_term in query_terms: + query_profile = self._profile(query_term) + possible: set[str] = set() + if query_term in self._term_postings: + possible.add(query_term) + for lemma in _surface_lemma_candidates(query_term): + possible.update(self._morph_terms.get(lemma, ())) + for atom, weight in query_profile.items(): + if atom.startswith("x:") or float(weight) < SEMANTIC_GLOSS_ALIGNMENT_MIN: + continue + posting = self._concept_postings.get(atom) + if posting: + postings_touched += 1 + possible.update(posting) + scored: list[tuple[float, str, str, str]] = [] + for corpus_term in possible: + score, atom, kind = self._pair_similarity( + query_term, corpus_term, query_profile, self._profile(corpus_term), + ) + if atom is not None and score >= SEMANTIC_GLOSS_ALIGNMENT_MIN: + scored.append((score, corpus_term, atom, kind)) + scored.sort(key=lambda value: (-value[0], value[1], value[2])) + links[query_term] = { + corpus_term: (score, atom, kind) + for score, corpus_term, atom, kind + in scored[:MAX_SEMANTIC_TERMS_PER_QUERY_TERM] + } + return links, postings_touched + + @staticmethod + def _greedy_alignments( + query_terms: Sequence[str], + row_terms: Sequence[str], + links: Mapping[str, Mapping[str, tuple[float, str, str]]], + ) -> tuple[dict[str, Any], ...]: + possibilities: list[tuple[float, str, str, str, str]] = [] + for query_term in query_terms: + for row_term in row_terms: + value = links.get(query_term, {}).get(row_term) + if value is not None: + score, atom, kind = value + possibilities.append((score, query_term, row_term, atom, kind)) + possibilities.sort(key=lambda value: (-value[0], value[1], value[2], value[3])) + used_query: set[str] = set() + used_rows: set[str] = set() + output: list[dict[str, Any]] = [] + for score, query_term, row_term, atom, kind in possibilities: + if query_term in used_query or row_term in used_rows: + continue + used_query.add(query_term) + used_rows.add(row_term) + output.append({ + "query_term": query_term, + "evidence_term": row_term, + "score": score, + "relation_atom": atom, + "relation_kind": kind, + "literal": query_term == row_term, + "lexical_anchor": kind in {"exact_lexeme", "morphological_lexeme"}, + }) + return tuple(output) + + @staticmethod + def _protected_state( + query: str, + alignments: Sequence[Mapping[str, Any]], + ) -> dict[str, Any]: + root = unitary("stage5k39:protected-root:" + hashlib.sha256(query.encode()).hexdigest()) + moving = np.zeros(HRR_DIM, dtype=np.complex64) + for alignment in alignments: + atom = str(alignment["relation_atom"]) + role = unitary("stage5k39:query-role:" + str(alignment["query_term"])) + filler = unitary("stage5k39:concept-atom:" + atom) + moving += np.float32(float(alignment["score"])) * (role * filler) + if not np.any(moving): + moving = root.copy() + moving = normalize(moving) + residual = moving - np.complex64(np.vdot(root, moving)) * root + protected = normalize(np.float32(4.0) * root + residual) + return { + "dimension": HRR_DIM, + "bound_relational_atoms": len(alignments), + "stabilizing_spine_gain": 4.0, + "protected_root_cosine": cosine(root, protected), + "pre_malkuth_unbind_count": 0, + "state_sha256": hashlib.sha256(protected.tobytes()).hexdigest(), + } + + def _semantic_candidates( + self, + query: str, + corpus_path: Path, + selected_domain_ids: Sequence[str] | None, + ) -> list[tuple[float, dict[str, Any]]]: + self._assert_corpus(corpus_path) + selected = None if selected_domain_ids is None else set(selected_domain_ids) + query_terms = tuple(sorted( + term for term in canonical_terms(query) + if term not in SEMANTIC_FUNCTION_TERMS + )) + links, semantic_postings_touched = self._semantic_term_links(query_terms) + semantic_terms = { + term + for values in links.values() + for term, (score, _atom, _kind) in values.items() + if score >= SEMANTIC_ALIGNMENT_MIN + } + # A candidate is situated by convergent query relations, not by one + # ambiguous dictionary sense. Preserve the best vote from each query + # term and require at least two independent query-term votes. + row_votes: dict[str, dict[str, float]] = defaultdict(dict) + for query_term, values in links.items(): + for corpus_term, (score, _atom, _kind) in values.items(): + if score < SEMANTIC_ALIGNMENT_MIN: + continue + for text_sha in self._term_postings.get(corpus_term, ()): + row_votes[text_sha][query_term] = max( + score, row_votes[text_sha].get(query_term, 0.0), + ) + ranked_ids = sorted( + ( + (text_sha, len(votes), sum(votes.values())) + for text_sha, votes in row_votes.items() + if len(votes) >= 2 + ), + key=lambda value: (-value[1], -value[2], value[0]), + ) + addressed_touched = 0 + if selected is not None: + addressed: set[str] = set() + for domain_id in selected: + posting = self._address_postings.get(domain_id) + if posting: + addressed_touched += 1 + addressed.update(posting) + ranked_ids = [value for value in ranked_ids if value[0] in addressed] + + situated_rows = len(ranked_ids) + ambiguity_pruned = max(0, situated_rows - MAX_SEMANTIC_ROWS) + scored_rows = tuple(value[0] for value in ranked_ids[:MAX_SEMANTIC_ROWS]) + candidates: list[tuple[float, dict[str, Any]]] = [] + for text_sha in scored_rows: + row = self._rows[text_sha] + primary = str(row["required_domain_ids"][0]) + address_ids = self.address_index.addresses(text_sha, primary) + matched = tuple(address_ids if selected is None else sorted(selected & set(address_ids))) + if not matched: + continue + row_terms = tuple(sorted(self._row_terms[text_sha])) + alignments = self._greedy_alignments(query_terms, row_terms, links) + strong = tuple(value for value in alignments if float(value["score"]) >= SEMANTIC_ALIGNMENT_MIN) + anchors = tuple(value for value in strong if value["lexical_anchor"]) + conceptual = tuple(value for value in strong if not value["lexical_anchor"]) + transformed = tuple(value for value in strong if not value["literal"]) + # WordNet proposes transformations only inside a literal or + # morphological frame supplied by this particular utterance. + # This blocks independent polysemous senses from manufacturing an + # apparently coherent row through dictionary coincidence alone. + if len(strong) < 2 or not anchors or not transformed: + continue + query_coverage = len(strong) / max(1, len(query_terms)) + score = ( + len(anchors) + + 0.35 * sum(float(value["score"]) for value in conceptual) + ) / max(1, len(query_terms)) + if query_coverage < SEMANTIC_QUERY_COVERAGE_MIN or score < SEMANTIC_SCORE_MIN: + continue + candidates.append((score, { + "domain_id": primary, + "addressed_domain_ids": list(address_ids), + "matched_selected_domain_ids": list(matched), + "text": row["text"], + "source_document": row["source_document"], + "source_document_sha256": row["source_document_sha256"], + "text_sha256": row["text_sha256"], + "license_note": row["license_note"], + "source_split": row["split"], + "retrieval_score": score, + "shared_terms": sorted( + value["query_term"] for value in strong if value["literal"] + ), + "semantic_matches": list(strong), + "semantic_nonliteral_matches": len(transformed), + "semantic_conceptual_matches": len(conceptual), + "semantic_lexical_anchor_matches": len(anchors), + "query_term_coverage": query_coverage, + "evidence_term_coverage": len(strong) / max(1, len(row_terms)), + "answer_status": "semantic_evidence_only", + "retrieval_path": "context_constrained_concept_address", + "semantic_hrr_state": self._protected_state(query, strong), + })) + candidates.sort(key=lambda item: (-item[0], item[1]["text_sha256"])) + self._record_semantic_event({ + "selected_domain_ids": None if selected is None else sorted(selected), + "query_content_terms": len(query_terms), + "semantic_term_postings_touched": semantic_postings_touched, + "semantic_candidate_terms_enumerated": len(semantic_terms), + "address_postings_touched": addressed_touched, + "semantic_candidate_records_enumerated": situated_rows, + "semantic_candidate_records_scored": len(scored_rows), + "semantic_candidates_accepted": len(candidates), + "ambiguity_rows_pruned_by_context_rank": ambiguity_pruned, + "ambiguity_overflow_refused": False, + "maximum_semantic_rows": MAX_SEMANTIC_ROWS, + "full_corpus_rows_scanned_per_query": 0, + "full_corpus_scans": 0, + }) + return candidates + + def _candidates( + self, + query: str, + corpus_path: Path, + selected_domain_ids: Sequence[str] | None, + ) -> list[tuple[float, dict[str, Any]]]: + exact = super()._candidates(query, corpus_path, selected_domain_ids) + if exact and _exact_is_strong(exact[0][1]): + return exact + semantic = self._semantic_candidates(query, corpus_path, selected_domain_ids) + if not semantic: + return exact + # Weak literal matches remain available, but semantic scores only win + # when their complete contextual alignment is stronger. + merged: dict[str, tuple[float, dict[str, Any]]] = { + str(value["text_sha256"]): (score, value) for score, value in exact + } + for score, value in semantic: + key = str(value["text_sha256"]) + if key not in merged or score > merged[key][0]: + merged[key] = (score, value) + return sorted(merged.values(), key=lambda item: (-item[0], item[1]["text_sha256"])) + + def retrieve( + self, + query: str, + corpus_path: Path = PUBLIC_CORPUS, + top_k: int = 3, + *, + selected_domain_ids: Sequence[str] | None = None, + ) -> tuple[dict[str, Any], ...]: + selected = ( + tuple(selected_domain_ids) + if selected_domain_ids is not None + else tuple(self.pool().route(query)["selected_domain_ids"]) + ) + values = self._candidates(query, corpus_path, selected) + explicit_multi_source = bool(re.search( + r"\b(?:both|combine|respectively|in\s+two\s+clauses|two\s+separate)\b", + query, + re.IGNORECASE, + )) + if not explicit_multi_source: + # Ranked neighbors are alternatives, not independent evidence. + # A later coequal decomposition stage owns genuine multi-source + # requests; ordinary questions admit one proposition frame. + top_k = 1 + return tuple(value for _, value in values[:top_k]) + + +class K39ProductivePropositionCompiler(K35PropositionCompiler): + """License open-class predicates through the native dictionary lattice.""" + + def __init__(self, concept_index: NativeConceptAddressIndex) -> None: + super().__init__() + self._dictionary_profiles = { + key: dict(value) for key, value in concept_index.lexeme_profiles.items() + } + + def _lemma_profile(self, surface: str) -> tuple[str, Mapping[str, float]] | None: + raw = surface.casefold() + values = [raw] + if raw in FORM_TO_LEMMA: + values.insert(0, FORM_TO_LEMMA[raw]) + if raw.endswith("ies") and len(raw) > 3: + values.append(raw[:-3] + "y") + if raw.endswith("s") and len(raw) > 3: + values.append(raw[:-1]) + if raw.endswith("ed") and len(raw) > 4: + values.extend((raw[:-2], raw[:-1])) + if raw.endswith("ing") and len(raw) > 5: + values.extend((raw[:-3], raw[:-3] + "e")) + values.append(normalize_lexeme(raw)) + for lemma in dict.fromkeys(values): + profile = self._dictionary_profiles.get(lemma) + if profile and any(atom.startswith("x:verb.") for atom in profile): + return lemma, profile + return None + + def _productive_parse( + self, + surface: str, + evidence_row: Mapping[str, Any], + domain_ids: Sequence[str], + *, + clause_type: str, + conditional: bool, + inherited_subject: str | None, + extra_qualifiers: Sequence[tuple[str, str]], + base_offset: int, + ): + matches = tuple(WORD.finditer(surface)) + candidates: list[tuple[float, int, Any, str]] = [] + pronouns = {"he", "she", "it", "they", "we", "i", "you", "this", "that", "these", "those"} + carrier_auxiliaries = AUXILIARIES | {"do", "does", "did"} + for index, match in enumerate(matches): + if index == 0 and inherited_subject is None: + continue + word = match.group(0).casefold() + if word in carrier_auxiliaries | MODALS | NEGATIONS: + continue + resolved = self._lemma_profile(word) + if resolved is None: + continue + lemma, _profile = resolved + previous = matches[index - 1].group(0).casefold() if index else "" + recent = {value.group(0).casefold() for value in matches[max(0, index - 2):index]} + score = 0.0 + if recent & (carrier_auxiliaries | MODALS | NEGATIONS): + score += 5.0 + if word != lemma or word.endswith(("s", "ed", "ing")): + score += 3.0 + if index == 1 and matches[0].group(0).casefold() in pronouns: + score += 4.0 + if match.end() < len(surface.rstrip()): + score += 1.0 + if previous in {"to", "a", "an", "the"}: + score -= 3.0 + if word.endswith("ing") and previous == "by": + score -= 8.0 + candidates.append((score, -index, match, lemma)) + if not candidates: + return None + score, _negative_index, predicate, lemma = max(candidates) + if score < 1.0: + return None + left = surface[:predicate.start()] + right = surface[predicate.end():] + left_words = WORD.findall(left) + while left_words and left_words[-1].casefold() in carrier_auxiliaries | MODALS | NEGATIONS: + left_words.pop() + subject_surface = " ".join(left_words) + if re.search(r"\b(?:which|that|who)\b", subject_surface, re.IGNORECASE): + subject_surface = re.split( + r"\b(?:which|that|who)\b", subject_surface, flags=re.IGNORECASE, + )[-1] + subject = inherited_subject or self._clean_argument(subject_surface) + if not subject: + return None + productive_qualifiers = list(extra_qualifiers) + manner = re.match(r"^(.+?)\s+is\s+by\s+(.+)$", right.strip(), re.IGNORECASE) + if manner is not None: + right = manner.group(1) + productive_qualifiers.append(("by", self._clean_argument(manner.group(2)))) + object_value = self._clean_argument( + re.split(r",\s*(?:and\s+)?[A-Za-z]+ing\b", right, maxsplit=1)[0] + ) or None + evidence = str(evidence_row.get("fact", evidence_row.get("text", ""))).strip() + subject_span = _span_in(evidence, subject, base_offset) + predicate_span = _span_in(evidence, predicate.group(0), base_offset) + object_span = _span_in( + evidence, + object_value, + predicate_span[1] if predicate_span is not None else base_offset, + ) + if subject_span is None or predicate_span is None: + return None + words = WORD.findall(surface) + modal = next((value.casefold() for value in words if value.casefold() in MODALS), None) + modality = ( + "conditional" if conditional + else "obligatory" if modal in {"must", "should"} + else "possible" if modal in {"can", "could", "may", "might", "would"} + else "asserted" + ) + return self._make( + subject=subject, + lemma=lemma, + object_value=object_value, + complement=None, + qualifiers=productive_qualifiers, + modality=modality, + polarity=self._polarity(words), + voice="active_dictionary_licensed", + clause_type=clause_type, + evidence_row=evidence_row, + subject_span=subject_span, + predicate_span=predicate_span, + object_span=object_span, + domain_ids=domain_ids, + ) + + def _parse_simple( + self, + clause: str, + evidence_row: Mapping[str, Any], + domain_ids: Sequence[str], + *, + clause_type: str = "assertion", + conditional: bool = False, + inherited_subject: str | None = None, + extra_qualifiers: Sequence[tuple[str, str]] = (), + base_offset: int = 0, + ): + surface = _strip_surface(clause) + locative = re.match( + r"^(In|Within|At|During|For)\s+(.+?),\s*(.+)$", surface, re.IGNORECASE, + ) + if locative is not None: + parsed = self._parse_simple( + locative.group(3), + evidence_row, + domain_ids, + clause_type=clause_type, + conditional=conditional, + inherited_subject=inherited_subject, + extra_qualifiers=( + *extra_qualifiers, + (locative.group(1).casefold(), self._clean_argument(locative.group(2))), + ), + base_offset=base_offset + locative.start(3), + ) + if parsed is not None: + return parsed + because = re.match(r"^(.+?),\s*because\s+(.+)$", surface, re.IGNORECASE) + if because is not None: + main_surface = because.group(1) + qualifiers = (*extra_qualifiers, ("because", self._clean_argument(because.group(2)))) + temporal = re.match(r"^(.+?)\s+when\s+(.+)$", main_surface, re.IGNORECASE) + if temporal is not None: + main_surface = temporal.group(1) + qualifiers = (("when", self._clean_argument(temporal.group(2))), *qualifiers) + parsed = super()._parse_simple( + main_surface, + evidence_row, + domain_ids, + clause_type=clause_type, + conditional=conditional, + inherited_subject=inherited_subject, + extra_qualifiers=qualifiers, + base_offset=base_offset, + ) + if parsed is not None: + return parsed + possessive = re.match(r"^(.+?)\s+(have|has|had)\s+(.+)$", surface, re.IGNORECASE) + if possessive is not None: + subject = self._clean_argument(possessive.group(1)) + object_value = self._clean_argument(possessive.group(3)) + evidence = str(evidence_row.get("fact", evidence_row.get("text", ""))).strip() + subject_span = _span_in(evidence, subject, base_offset) + predicate_span = _span_in(evidence, possessive.group(2), base_offset) + object_span = _span_in(evidence, object_value, predicate_span[1] if predicate_span else base_offset) + if subject_span is not None and predicate_span is not None and object_span is not None: + return self._make( + subject=subject, + lemma="have", + object_value=object_value, + complement=None, + qualifiers=extra_qualifiers, + modality="conditional" if conditional else "asserted", + polarity=self._polarity(WORD.findall(surface)), + voice="active_possessive", + clause_type=clause_type, + evidence_row=evidence_row, + subject_span=subject_span, + predicate_span=predicate_span, + object_span=object_span, + domain_ids=domain_ids, + ) + # Finite BE scopes the complete property/identity complement. Give + # it precedence over verb-looking participles nested inside that + # complement ("is a chemical released by ..."). + copular = re.match(r"^(.+?)\s+(is|are|was|were)\s+(.+)$", surface, re.IGNORECASE) + if copular is not None: + subject = self._clean_argument(copular.group(1)) + complement = self._clean_argument(copular.group(3)) + if len(WORD.findall(subject)) <= 16: + evidence = str(evidence_row.get("fact", evidence_row.get("text", ""))).strip() + subject_span = _span_in(evidence, subject, base_offset) + predicate_span = _span_in(evidence, copular.group(2), base_offset) + object_span = _span_in(evidence, complement, base_offset) + if subject_span is not None and predicate_span is not None and object_span is not None: + return self._make( + subject=subject, + lemma="be", + object_value=None, + complement=complement, + qualifiers=extra_qualifiers, + modality="conditional" if conditional else "asserted", + polarity=self._polarity(WORD.findall(surface)), + voice="copular", + clause_type=clause_type, + evidence_row=evidence_row, + subject_span=subject_span, + predicate_span=predicate_span, + object_span=object_span, + domain_ids=domain_ids, + ) + parsed = super()._parse_simple( + clause, + evidence_row, + domain_ids, + clause_type=clause_type, + conditional=conditional, + inherited_subject=inherited_subject, + extra_qualifiers=extra_qualifiers, + base_offset=base_offset, + ) + auxiliary_carrier = bool( + parsed is not None + and parsed.predicate in {"do"} + and parsed.object_value + ) + if parsed is not None and not auxiliary_carrier: + return parsed + productive = self._productive_parse( + surface, + evidence_row, + domain_ids, + clause_type=clause_type, + conditional=conditional, + inherited_subject=inherited_subject, + extra_qualifiers=extra_qualifiers, + base_offset=base_offset, + ) + return productive or parsed + + def compile_row( + self, + evidence_row: Mapping[str, Any], + domain_ids: Sequence[str] = (), + ): + evidence = str(evidence_row.get("fact", evidence_row.get("text", ""))).strip().rstrip(".!?") + embedded = list(re.finditer( + r"\b(?:A|An|The|This|These)\s+[A-Za-z][^.!?]{0,100}?\s+(?:is|are|was|were)\s+", + evidence, + )) + if embedded and embedded[-1].start() > 0: + start = embedded[-1].start() + value = self._parse_simple( + evidence[start:], evidence_row, domain_ids, base_offset=start, + ) + if value is not None: + return (value,) + values = list(super().compile_row(evidence_row, domain_ids)) + if ";" not in evidence: + unique = {value.provenance_sha256: value for value in values} + return tuple(unique[key] for key in sorted(unique)) + for segment_match in re.finditer(r"(?:^|;\s*)([^;]+)", evidence): + segment = _strip_surface(segment_match.group(1)) + segment_offset = segment_match.start(1) + leading = re.match(r"^(Whereas|Although|While)\s+(.+?),\s*(.+)$", segment, re.IGNORECASE) + if leading is not None: + context = self._parse_simple( + leading.group(2), evidence_row, domain_ids, + clause_type="contrast_context", + base_offset=segment_offset + leading.start(2), + ) + assertion = self._parse_simple( + leading.group(3), evidence_row, domain_ids, + clause_type="contrast_assertion", + extra_qualifiers=(("whereas", self._clean_argument(leading.group(2))),), + base_offset=segment_offset + leading.start(3), + ) + values.extend(value for value in (assertion, context) if value is not None) + else: + value = self._parse_simple( + segment, evidence_row, domain_ids, + clause_type="coordinated_assertion", + base_offset=segment_offset, + ) + if value is not None: + values.append(value) + unique = {value.provenance_sha256: value for value in values} + return tuple(unique[key] for key in sorted(unique)) + + +class K39AnswerGrammar(K35AnswerGrammar): + """Resolve irregular and preposition-trailed subject number.""" + + @staticmethod + def _plural(subject: str) -> bool: + lower = " ".join(str(subject).casefold().split()) + if any(re.search(rf"\b{value}\b", lower) for value in ( + "people", "children", "men", "women", "citizens", "data", "criteria", "phenomena", + )): + return True + head = re.split(r"\b(?:in|from|with|under|during|at)\b", lower, maxsplit=1)[0].strip() + return K35AnswerGrammar._plural(head or lower) + + +class K39DiscourseToolTransducer(RepairedOpenSchemaConversationalTransducer): + """Complete explicit extremum words while retaining the I2 HRR frame.""" + + @staticmethod + def _structural_operation(question: str, has_state: bool) -> str: + query = set(tokens(question)) + if "maximum" in query: + return "maximum" + if "minimum" in query: + return "minimum" + return RepairedOpenSchemaConversationalTransducer._structural_operation(question, has_state) + + def _frame_transit( + self, + session_id: str, + operation: str, + expert: Any, + row: Mapping[str, str] | None, + field: str | None, + *, + erase_operation_geometry: bool, + ) -> tuple[dict[str, str | None], dict[str, Any]]: + expert_values = tuple(self.experts) + selected_expert = expert.schema.expert_id if expert else None + row_values = tuple(dataset_row_key(expert, value) for value in expert.rows) if expert else ("none",) + selected_row = dataset_row_key(expert, row) if expert and row else None + field_values = expert.field_names if expert else ("none",) + roles = { + name: unitary("stage5i2:frame-role:" + name) + for name in ("operation", "expert", "row", "field") + } + operation_index = self.head.operations.index(operation) + operation_state = ( + np.zeros(HRR_DIM, dtype=np.complex64) + if erase_operation_geometry else self.head.prototypes[operation_index] + ) + values = { + "operation": operation_state, + "expert": unitary(f"stage5i2:expert:{selected_expert or 'none'}"), + "row": unitary(f"stage5i2:row:{selected_row or 'none'}"), + "field": unitary(f"stage5i2:field:{selected_expert or 'none'}:{field or 'none'}"), + } + moving = normalize(sum( + (bind(roles[name], value) for name, value in values.items()), + np.zeros(HRR_DIM, dtype=np.complex64), + )) + root = unitary(f"stage5i2:protected-root:{digest(session_id)}") + residual = moving - np.complex64(np.vdot(root, moving)) * root + persistent = normalize(np.complex64(4.0) * root + residual) + terminal = normalize(residual) + candidates: dict[str, tuple[tuple[str, np.ndarray], ...]] = { + "operation": tuple((name, self.head.prototypes[index]) for index, name in enumerate(self.head.operations)), + "expert": tuple((name, unitary(f"stage5i2:expert:{name}")) for name in dict.fromkeys((*expert_values, "none"))), + "row": tuple((name, unitary(f"stage5i2:row:{name}")) for name in dict.fromkeys((*row_values, "none"))), + "field": tuple((name, unitary(f"stage5i2:field:{selected_expert or 'none'}:{name}")) for name in dict.fromkeys((*field_values, "none"))), + } + decoded: dict[str, str | None] = {} + margins: list[float] = [] + for name in ("operation", "expert", "row", "field"): + recovered = normalize(np.complex64(4.0) * values[name] + unbind(terminal, roles[name])) + scores = sorted( + ((cosine(recovered, state), label) for label, state in candidates[name]), + reverse=True, + ) + decoded[name] = None if scores[0][1] == "none" else scores[0][1] + margins.append(scores[0][0] - (scores[1][0] if len(scores) > 1 else 0.0)) + if erase_operation_geometry: + decoded["operation"] = None + return decoded, { + "protected_root_cosine": cosine(persistent, root), + "minimum_frame_cleanup_margin": float(min(margins)), + "terminal_unbind_performed": True, + "pre_malkuth_unbind_count": 0, + "operation_geometry_erased": erase_operation_geometry, + "semantic_spine_gain": 4.0, + "root_projection_removed_before_spine_binding": True, + } + + def answer(self, session_id: str, question: str, *, erase_operation_geometry: bool = False) -> dict[str, Any]: + expanded = question + resolved_row_key: str | None = None + if re.search(r"\bthat\s+event\b", question, re.IGNORECASE): + state, _audit = self._restore(session_id) + if state.row_key: + try: + values = json.loads(state.row_key) + event_id = str(values[0]) if isinstance(values, list) and values else state.row_key + except (TypeError, ValueError, json.JSONDecodeError): + event_id = state.row_key + expanded = re.sub( + r"\bthat\s+event\b", f"event {event_id}", question, + flags=re.IGNORECASE, + ) + resolved_row_key = state.row_key + output = dict(super().answer( + session_id, expanded, erase_operation_geometry=erase_operation_geometry, + )) + output["discourse_resolution"] = { + "input_sha256": hashlib.sha256(question.encode()).hexdigest(), + "deictic_event_resolved": resolved_row_key is not None, + "resolved_row_key": resolved_row_key, + "expanded_input_sha256": hashlib.sha256(expanded.encode()).hexdigest(), + "answer_or_gold_labels_used": False, + } + return output + + +class SemanticIndexedNativeGeneralistAgent(IndexedBidirectionalNativeGeneralistAgent): + def __init__( + self, + specialist_checkpoint: Path, + knowledge_checkpoint: Path, + address_index_path: Path, + relational_index_path: Path, + concept_index_path: Path, + substrate_path: Path, + **kwargs: Any, + ) -> None: + kwargs.setdefault("agent_id", "oracle-stage5k39-semantic-indexed-native-generalist-agent") + supplied_tool = kwargs.get("tool_backend") + if ( + supplied_tool is not None + and not isinstance(supplied_tool, K39DiscourseToolTransducer) + and all(hasattr(supplied_tool, value) for value in ("head", "experts", "store")) + ): + kwargs["tool_backend"] = K39DiscourseToolTransducer( + supplied_tool.head, supplied_tool.experts, supplied_tool.store, + ) + super().__init__( + specialist_checkpoint, knowledge_checkpoint, address_index_path, + relational_index_path, substrate_path, **kwargs, + ) + legacy_substrate = self.substrate + self.substrate = IndexedCyclingPersistentSubstrate( + Path(str(Path(substrate_path)) + ".k39.sqlite3"), + agent_id=legacy_substrate.agent_id, + dim=legacy_substrate.dim, + max_entries_per_bank=legacy_substrate.max_entries_per_bank, + lock_timeout=legacy_substrate.lock_timeout, + legacy_store=legacy_substrate, + ) + if self.tool_backend is not None and all( + hasattr(self.tool_backend, value) for value in ("head", "experts", "store") + ): + legacy_tool_store = self.tool_backend.store + indexed_tool_store = IndexedCyclingPersistentSubstrate( + Path(str(legacy_tool_store.path) + ".k39.sqlite3"), + agent_id=legacy_tool_store.agent_id, + dim=legacy_tool_store.dim, + max_entries_per_bank=legacy_tool_store.max_entries_per_bank, + lock_timeout=legacy_tool_store.lock_timeout, + legacy_store=legacy_tool_store, + ) + self.tool_backend = K39DiscourseToolTransducer( + self.tool_backend.head, self.tool_backend.experts, indexed_tool_store, + ) + relational = InvertedRelationalIndex.load(relational_index_path) + concept = NativeConceptAddressIndex.load(concept_index_path) + semantic_basis = SemanticIndexedFullCorpusAddressedKnowledgeBasis( + self.knowledge_basis.basis, + self.address_index, + relational, + concept, + ) + base_pool = self.knowledge_specialists.base_pool + self.knowledge_basis = semantic_basis + self.knowledge_specialists = BidirectionalKnowledgeSpecialistPool(base_pool, semantic_basis) + self.proposition_compiler = K39ProductivePropositionCompiler(concept) + self.inverse = QuadraticAnswerInverse(K39AnswerGrammar()) + self._k39_tool_sessions: set[str] = set() + self._k39_tool_frames: dict[str, dict[str, Any]] = {} + + @staticmethod + def _coequal_split_candidates(text: str) -> tuple[tuple[str, str], ...]: + surface = clean(text) + lower = surface.casefold() + explicit = bool(re.search( + r"\b(?:both|combine|in\s+two\s+clauses|two\s+separate\s+clauses)\b", + lower, + )) + if not explicit: + return () + body = re.sub( + r"^(?:in\s+two\s+(?:separate\s+)?clauses\s*,?\s*)?" + r"(?:state|give|identify|explain|describe|report)?\s*(?:both\s+)?", + "", + surface, + flags=re.IGNORECASE, + ) + values: list[tuple[str, str]] = [] + combine = re.match(r"^combine\s+(.+?)\s+with\s+(.+)$", body, re.IGNORECASE) + if combine is not None: + values.append((clean(combine.group(1)), clean(combine.group(2)))) + for match in re.finditer(r"\s+and\s+", body, re.IGNORECASE): + left, right = clean(body[:match.start()]), clean(body[match.end():]) + if len(canonical_terms(left)) >= 3 and len(canonical_terms(right)) >= 3: + values.append((left, right)) + return tuple(dict.fromkeys(values)) + + @staticmethod + def _coequal_candidate_eligible(value: Mapping[str, Any] | None) -> bool: + if value is None: + return False + if _exact_is_strong(value): + return True + return bool( + value.get("retrieval_path") == "context_constrained_concept_address" + and float(value.get("query_term_coverage", 0.0)) >= SEMANTIC_QUERY_COVERAGE_MIN + and float(value.get("retrieval_score", 0.0)) >= SEMANTIC_SCORE_MIN + ) + + def _coequal_evidence(self, text: str) -> tuple[tuple[dict[str, Any], ...], dict[str, Any] | None]: + candidates: list[tuple[float, str, str, dict[str, Any], dict[str, Any]]] = [] + for left, right in self._coequal_split_candidates(text): + left_value = self.knowledge_basis.best_global_candidate(left) + right_value = self.knowledge_basis.best_global_candidate(right) + if not ( + self._coequal_candidate_eligible(left_value) + and self._coequal_candidate_eligible(right_value) + and left_value["text_sha256"] != right_value["text_sha256"] + ): + continue + score = sum( + float(value.get("retrieval_score", 0.0)) + + 0.25 * float(value.get("query_term_coverage", 0.0)) + for value in (left_value, right_value) + ) + candidates.append((score, left, right, left_value, right_value)) + if not candidates: + return (), None + _score, left, right, left_value, right_value = max( + candidates, key=lambda value: (value[0], value[1], value[2]), + ) + segments = (left, right) + values = (left_value, right_value) + routed_states = [] + routing_audits = [] + for segment, value in zip(segments, values): + routed = self.knowledge_specialists.route(segment) + state = np.ascontiguousarray(routed.pop("fused_state")) + routed_states.append(state) + routing_audits.append({ + "segment_sha256": hashlib.sha256(segment.encode()).hexdigest(), + "selected_domain_ids": routed["selected_domain_ids"], + "selected_cell_ids": routed["selected_cell_ids"], + "protected_root_cosine": routed["protected_root_cosine"], + "fused_state_sha256": hashlib.sha256(state.tobytes()).hexdigest(), + "evidence_text_sha256": value["text_sha256"], + "evidence_retrieval_score": value["retrieval_score"], + "evidence_query_term_coverage": value["query_term_coverage"], + }) + moving = normalize(sum(routed_states, np.zeros(HRR_DIM, dtype=np.complex64))) + root = unitary("stage5k39:coequal-root:" + hashlib.sha256(clean(text).encode()).hexdigest()) + residual = moving - np.complex64(np.vdot(root, moving)) * root + protected = normalize(np.float32(4.0) * root + residual) + evidence = tuple({ + "fact": value["text"], + "source_document": value["source_document"], + "source_document_sha256": value["source_document_sha256"], + "text_sha256": value["text_sha256"], + "domain_id": value["domain_id"], + "license_note": value["license_note"], + "retrieval_score": value["retrieval_score"], + } for value in values) + return evidence, { + "schema_version": "oracle-stage5k39-coequal-intent-decomposition-v1", + "activated": True, + "segment_count": 2, + "independent_evidence_rows": 2, + "routing": routing_audits, + "stabilizing_spine_gain": 4.0, + "protected_root_cosine": cosine(root, protected), + "pre_malkuth_unbind_count": 0, + "new_specialists_created": 0, + "answer_or_gold_labels_used": False, + } + + @classmethod + def _intent_lattice( + cls, + text: str, + context: Mapping[str, Any] | None = None, + ) -> dict[str, Any]: + audit = dict(super()._intent_lattice(text, context)) + local = dict(context or {}) + query = set(tokens(text)) + lower = clean(text).casefold() + available = bool(local.get("k39_tool_backend_available")) + explicit = bool( + query & { + "database", "catalog", "table", "population", "earthquake", + "earthquakes", "maximum", "minimum", "lookup", "provenance", + "license", "records", + } + or re.search(r"\blook\s+up\b", lower) + ) + deictic = bool( + local.get("k39_tool_dialogue_active") + and ( + query & {"that", "those", "one", "ones", "event", "value"} + or lower.startswith(("where did", "which one", "what about", "and ")) + ) + ) + bounded = available and (explicit or deictic) + if bounded and audit.get("selected_intent_family") != "creative_generation_request": + scores = dict(audit["candidate_scores"]) + scores["bounded_dataset"] = 1.0 + for key in ("state_query", "event_consequence_query", "definition_query", "causal_query"): + scores[key] = 0.0 + audit["candidate_scores"] = scores + audit["selected_intent_family"] = "bounded_dataset" + audit["k39_tool_discourse"] = { + "backend_available": available, + "explicit_schema_or_operation_cue": explicit, + "active_dialogue_deictic_cue": deictic, + "bounded_dataset_selected": bounded, + "answer_or_gold_labels_used": False, + } + return audit + + def _retrieve( + self, + session_id: str, + query_roles: Mapping[str, str], + turn_id: str, + *, + top_k: int = 8, + ) -> tuple[list[dict[str, str]], dict[str, Any]]: + payloads, audit = super()._retrieve( + session_id, query_roles, turn_id, top_k=max(top_k, 16), + ) + indexed_sequences = hasattr(self.substrate, "sequence_for_roles") + sequence_by_roles = { + tuple(sorted(payload.items())): int(self.substrate.sequence_for_roles(payload)) + for payload in payloads + } if indexed_sequences else {} + if not indexed_sequences: + state = self.substrate._load() + for bank in state["banks"].values(): + for entry in bank["entries"]: + sequence_by_roles[tuple(sorted(entry["roles"].items()))] = int(entry["created_seq"]) + stateful = { + "transfer", "definition", "motion", "caused_motion", "state_contrast", + "causal_chain", "causal", "location", + } + latest: dict[tuple[str, str], tuple[int, int]] = {} + for index, payload in enumerate(payloads): + situation = payload.get("situation", "") + field = payload.get("field", "") + if situation not in stateful or not field: + continue + sequence = sequence_by_roles.get(tuple(sorted(payload.items())), 0) + key = (situation, field) + if key not in latest or sequence > latest[key][0]: + latest[key] = (sequence, index) + retained_indices = { + index for index, payload in enumerate(payloads) + if payload.get("situation", "") not in stateful or not payload.get("field", "") + } + retained_indices.update(index for _sequence, index in latest.values()) + projected = [payload for index, payload in enumerate(payloads) if index in retained_indices] + projected.sort( + key=lambda payload: sequence_by_roles.get(tuple(sorted(payload.items())), 0), + reverse=True, + ) + audit = { + **audit, + "supersession_projection_applied": True, + "released_before_supersession": len(payloads), + "released_after_supersession": len(projected), + "superseded_episode_count": len(payloads) - len(projected), + "temporary_full_state_sequence_scan": not indexed_sequences, + "cycling_memory_index": ( + self.substrate.last_snapshot_audit() + if hasattr(self.substrate, "last_snapshot_audit") else None + ), + } + return projected[:top_k], audit + + def _tool_row_label(self, expert_id: str | None, selected_key: str | None) -> str: + if not expert_id or not selected_key or self.tool_backend is None: + return "the selected record" + expert = getattr(self.tool_backend, "experts", {}).get(expert_id) + if expert is None: + return selected_key + row = next( + (value for value in expert.rows if dataset_row_key(expert, value) == selected_key), + None, + ) + if row is None: + return selected_key + for field in ("country_name", "place", "event_id", *expert.schema.primary_key): + if field in row and clean(row[field]): + return clean(row[field]) + return selected_key + + def _handle_tool(self, session_id: str, text: str) -> HandlerResult | None: + if not self._eligible("bounded_tool", {"bounded_dataset"}): + return None + if self.tool_backend is None: + return None + previous = self._k39_tool_frames.get(session_id, {}) + output = dict(self.tool_backend.answer(session_id, text)) + status = str(output.get("status", "abstained")) + if status != "answered": + return self._abstention( + "bounded_tool", clean(text), str(output.get("reason", "tool_request_not_grounded")), + ) + operation = clean(output.get("operation", "lookup")) + expert_id = output.get("expert_id") + field = clean(output.get("field", "value")) + selected_key = output.get("row_key") + row = self._tool_row_label(expert_id, selected_key) + values = [clean(value) for value in output.get("values", ())] + previous_row = self._tool_row_label(previous.get("expert_id"), previous.get("row_key")) + provenance_license: str | None = None + if operation == "provenance" and hasattr(self.tool_backend, "experts"): + expert = getattr(self.tool_backend, "experts", {}).get(expert_id) + if expert is not None and expert.rows: + provenance_license = clean(expert.rows[0].get("source_license", "")) or None + if operation == "provenance" and values: + clauses = [SemanticClause("The source authority", "be", complement=values[0])] + if provenance_license: + clauses.append(SemanticClause("The source license", "be", complement=provenance_license)) + elif operation in {"maximum", "minimum"} and values: + clauses = [SemanticClause( + f"The {operation} {field}", "be", complement=values[0], qualifiers=(("at", row),), + )] + elif operation == "compare" and len(values) >= 3: + clauses = [ + SemanticClause(f"The {field} for {previous_row}", "be", complement=values[0]), + SemanticClause(f"The {field} for {row}", "be", complement=values[1]), + SemanticClause(f"The absolute {field} difference", "be", complement=values[2]), + ] + elif operation == "list" and values: + clauses = [SemanticClause( + f"The matching {field} values", "be", complement=", ".join(values), + )] + elif operation == "count" and values: + clauses = [SemanticClause("The matching record count", "be", complement=values[0])] + elif values: + clauses = [SemanticClause(f"The {field} for {row}", "be", complement=values[0])] + else: + clauses = [SemanticClause("The bounded operation", "complete", tense="past")] + self._k39_tool_sessions.add(session_id) + self._k39_tool_frames[session_id] = { + "expert_id": expert_id, + "row_key": selected_key, + "field": field, + "values": values, + "memory_id": output.get("memory_id"), + } + return HandlerResult( + "bounded_tool", + "answered", + tuple((key, output.get(key)) for key in ("operation", "expert_id", "row_key", "field")), + (("values", values), ("source_license", provenance_license)), + tuple(clauses), + (("expert_id", expert_id), ("memory_id", output.get("memory_id"))), + ( + "select_registered_tool", "restore_persistent_discourse_frame", + "bind_typed_arguments", "execute_read_only_operation", + "verify_frame_cleanup", "retain_deictic_entity_state", + ), + tool_audit={ + "operation": operation, + "expert_id": expert_id, + "row_key": selected_key, + "row_label": row, + "previous_row_label": previous_row if previous else None, + "field": field, + "values": values, + "source_license": provenance_license, + "frame_audit": output.get("frame_audit"), + "persistence_audit": output.get("persistence_audit"), + "discourse_frame_restored": bool(previous), + "read_only": True, + }, + ) + + @staticmethod + def _retrieval_gate( + intent_family: str, + evidence: Sequence[Mapping[str, Any]], + context: Mapping[str, Any], + ) -> tuple[bool, str]: + if any(context.get(key) for key in ("evidence", "training_corpus", "sensor_stream")): + return False, "caller_supplied_bounded_context_has_precedence" + if not evidence: + return False, "no_selected_domain_evidence" + best = evidence[0] + if intent_family == "causal_query": + causal_surface = bool(re.search( + r"\b(?:because|therefore|thus|hence|caus(?:e|es|ed)|results?\s+(?:from|in)|due\s+to|leads?\s+to|so\s+that)\b", + str(best.get("text", "")).casefold(), + )) + if ( + causal_surface + and len(best.get("shared_terms", ())) >= 2 + and float(best.get("query_term_coverage", 0.0)) >= 0.50 + and float(best.get("retrieval_score", 0.0)) >= 0.20 + ): + return True, "source_evidence_contains_grounded_causal_construction" + return False, "causal_query_lacks_grounded_causal_source_construction" + if intent_family not in {"open", "definition_query"}: + return False, "speech_act_or_typed_construction_has_precedence" + if len(best.get("shared_terms", ())) < 2: + return False, "fewer_than_two_content_terms_grounded" + if float(best.get("query_term_coverage", 0.0)) < 0.50: + return False, "query_content_coverage_below_half" + if float(best.get("retrieval_score", 0.0)) < 0.18: + return False, "retrieval_score_below_floor" + return True, "source_evidence_relationally_grounded" + + def answer( + self, + session_id: str, + text: str, + context: Mapping[str, Any] | None = None, + *, + ablate_specialists: Sequence[str] = (), + ablate_knowledge_cells: Sequence[str] = (), + ) -> dict[str, Any]: + local_context = dict(context or {}) + coequal_audit: dict[str, Any] | None = None + caller_supplied_boundary = any( + local_context.get(key) + for key in ("evidence", "training_corpus", "sensor_stream") + ) + lower = clean(text).casefold() + explicit_tool_cue = bool( + set(tokens(text)) & { + "database", "catalog", "table", "population", "earthquake", + "earthquakes", "maximum", "minimum", "lookup", "provenance", + "license", "records", + } + or re.search(r"\blook\s+up\b", lower) + ) + if not caller_supplied_boundary and not explicit_tool_cue: + coequal_evidence, coequal_audit = self._coequal_evidence(text) + if coequal_evidence: + local_context["evidence"] = coequal_evidence + local_context["k39_coequal_intent"] = True + local_context["k39_tool_backend_available"] = self.tool_backend is not None + local_context["k39_tool_dialogue_active"] = session_id in self._k39_tool_sessions + output = super().answer( + session_id, text, local_context, + ablate_specialists=ablate_specialists, + ablate_knowledge_cells=ablate_knowledge_cells, + ) + output["schema_version"] = SCHEMA + output["knowledge_lattice"]["retrieval_index"] = self.knowledge_basis.turn_audit() + fusion_sha, proof_sha = canonical_proof_identity( + output["computation_proof"], output["specialist_fusion"], + ) + output["specialist_fusion"]["canonical_structural_sha256"] = fusion_sha + output["computation_proof"]["canonical_specialist_fusion_sha256"] = fusion_sha + output["computation_proof"]["canonical_proof_sha256"] = proof_sha + output["runtime"]["native_concept_address_model_calls"] = 0 + output["runtime"]["native_concept_address_gradient_steps"] = 0 + output["runtime"]["native_concept_address_next_token_predictions"] = 0 + output["runtime"]["registered_knowledge_cells"] = len(self.knowledge_basis.basis.partition) + output["runtime"]["primitive_domain_modes"] = len(self.knowledge_basis.basis.profiles) + output["runtime"]["tool_discourse_model_calls"] = 0 + output["runtime"]["tool_discourse_gradient_steps"] = 0 + output["runtime"]["memory_supersession_model_calls"] = 0 + output["runtime"]["memory_supersession_gradient_steps"] = 0 + output["runtime"]["indexed_cycling_memory"] = isinstance( + self.substrate, IndexedCyclingPersistentSubstrate, + ) + output["runtime"]["full_memory_scans"] = 0 + output["runtime"]["coequal_intent_model_calls"] = 0 + output["runtime"]["coequal_intent_gradient_steps"] = 0 + output["coequal_intent"] = coequal_audit or { + "schema_version": "oracle-stage5k39-coequal-intent-decomposition-v1", + "activated": False, + "segment_count": 0, + "independent_evidence_rows": 0, + "pre_malkuth_unbind_count": 0, + "new_specialists_created": 0, + "answer_or_gold_labels_used": False, + } + output["turn_manifest_sha256"] = digest(output) + return output + + +__all__ = [ + "K39ProductivePropositionCompiler", + "K39AnswerGrammar", + "SemanticIndexedFullCorpusAddressedKnowledgeBasis", + "SemanticIndexedNativeGeneralistAgent", +] diff --git a/root/wander-train/stage5k47_morphological_counterfactual_agent.py b/root/wander-train/stage5k47_morphological_counterfactual_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..f338fe45b291919ea97801e0d725fc55205eec61 --- /dev/null +++ b/root/wander-train/stage5k47_morphological_counterfactual_agent.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 +"""K47 opened repair of the two interfaces exposed by rejected K46. + +K45 remains byte-restored to the source frozen for K46. This successor only +repairs productive third-person lemmatization and the alternate imperative +counterfactual construction; it does not add a knowledge cell or ontology row. +""" + +from __future__ import annotations + +import re +from typing import Any, Mapping, Sequence + +from stage5k15_native_mixed_agent import HandlerResult, SemanticClause, clean, digest +from stage5k45_ephemeral_compositional_language_agent import ( + EphemeralCompositionalLanguageAgent, + RelationFact, + _strip_article, +) + + +SCHEMA = "oracle-stage5k47-morphological-counterfactual-agent-v1" + + +def _lemma47(value: str) -> str: + word = clean(value).casefold() + irregular = { + "gave": "give", "given": "give", "owns": "own", "owned": "own", + "repels": "repel", "repelled": "repel", "repairs": "repair", + "repaired": "repair", "paints": "paint", "painted": "paint", + "touches": "touch", "touched": "touch", "moves": "move", + "moved": "move", "changes": "change", "changed": "change", + "transfers": "transfer", "transferred": "transfer", + } + if word in irregular: + return irregular[word] + if word.endswith("ies") and len(word) > 4: + return word[:-3] + "y" + # Only sibilant/o stems take productive -es. A stem already ending in e + # (erase -> erases, use -> uses) takes only -s and must retain that e. + if word.endswith(("sses", "shes", "ches", "xes", "zzes", "oes")) and len(word) > 4: + return word[:-2] + # A bare stem ending in double-s is already a base form (cross, press, + # assess). Treating every final s as agreement morphology produced + # destructive forms such as `cros`. + if word.endswith("ss"): + return word + if word.endswith("s") and len(word) > 3: + return word[:-1] + return word + + +class MorphologicalCounterfactualAgent(EphemeralCompositionalLanguageAgent): + @staticmethod + def _counterfactual(text: str) -> tuple[str, str] | None: + surface = clean(text) + suppose = re.match( + r"^(?:in\s+)?(?:a|the)\s+counterfactual,?\s+suppose\s+" + r"(?:the\s+)?(.+?)\s+(?:is|be)\s+([a-z][a-z-]*)\s+instead[.!?]*$", + surface, re.IGNORECASE, + ) + if suppose: + return _strip_article(suppose.group(1)), suppose.group(2).casefold() + make = re.match( + r"^(?:in\s+)?(?:a|the)\s+counterfactual,?\s+make\s+" + r"(?:the\s+)?(.+?)\s+([a-z][a-z-]*)\s+instead[.!?]*$", + surface, re.IGNORECASE, + ) + return (_strip_article(make.group(1)), make.group(2).casefold()) if make else None + + @staticmethod + def _rule_definition(text: str) -> tuple[str, str, str] | None: + match = re.match( + r"^whoever\s+([a-z][a-z-]*)\s+(?:a|an|the)?\s*.+?\s+" + r"([a-z][a-z-]*)\s+it\s+until\s+another\s+person\s+" + r"([a-z][a-z-]*)\s+it[.!?]*$", + clean(text), re.IGNORECASE, + ) + if match is None: + return None + return tuple(_lemma47(match.group(index)) for index in (1, 2, 3)) + + @classmethod + def _ephemeral_family( + cls, + text: str, + context: Mapping[str, Any] | None = None, + ) -> str | None: + family = super()._ephemeral_family(text, context) + if family is not None: + return family + local = dict(context or {}) + relations = set(local.get("k45_active_rule_relations", ())) + lower = clean(text).casefold() + event = re.match( + r"^(?:the\s+)?([a-z][a-z0-9_-]*)\s+([a-z][a-z-]*)\s+" + r"(?:a|an|the)?\s*(.+?)[.!?]*$", + lower, + ) + if event and _lemma47(event.group(2)) in relations: + return "ephemeral_assertion" + return None + + def _event_assertion(self, session_id: str, text: str) -> HandlerResult | None: + session = self._session(session_id) + predicates = { + value for rule in session.rules + for value in (rule.antecedent_relation, rule.termination_relation) + } + match = re.match( + r"^(?:the\s+)?([a-z][a-z0-9_-]*)\s+([a-z][a-z-]*)\s+" + r"(?:a|an|the)?\s*(.+?)[.!?]*$", clean(text), re.IGNORECASE, + ) + if match is None: + return None + actor, relation, object_value = ( + match.group(1), _lemma47(match.group(2)), _strip_article(match.group(3)) + ) + if relation not in predicates: + return None + state = session.workspace.compose( + "relate", + (self._entity(session, actor), self._relation(session, relation), self._entity(session, object_value)), + ttl_turns=128, + ) + fact = RelationFact(actor, relation, object_value, state.state_id, state.world_id) + session.facts.append(fact) + generated = [state] + inferred: list[RelationFact] = [] + for rule in session.rules: + key = (rule.consequent_relation, object_value.casefold()) + if relation == rule.antecedent_relation: + consequence = session.workspace.compose( + "relate", + ( + self._entity(session, actor), self._relation(session, rule.consequent_relation), + self._entity(session, object_value), + ), + ttl_turns=128, + ) + relation_fact = RelationFact( + actor, rule.consequent_relation, object_value, + consequence.state_id, consequence.world_id, inferred=True, + ) + session.active_relations[key] = relation_fact + session.facts.append(relation_fact) + generated.append(consequence) + inferred.append(relation_fact) + elif relation == rule.termination_relation and key in session.active_relations: + previous = session.active_relations.pop(key) + if session.workspace.is_visible(previous.state_id): + session.workspace.retract( + previous.state_id, + reason=f"terminated_by:{relation}:{actor.casefold()}", + ) + clauses = [SemanticClause(actor, relation, object_value=object_value, tense="past")] + clauses.extend( + SemanticClause(value.subject, value.relation, object_value=value.object_value) + for value in inferred + ) + self._record_last( + session, "apply_recursive_rule", generated, actor=actor, relation=relation, + object=object_value, inferred_relations=[value.relation for value in inferred], + morphology="k47_productive_third_person_inverse", + ) + return HandlerResult( + "apply_recursive_rule", "answered", + (("actor", actor), ("relation", relation), ("object", object_value)), + (("inferred", [value.relation for value in inferred]),), tuple(clauses), + (("source", "conversation_local_event"),), + ("bind_event_roles", "invert_productive_inflection", "match_variable_rule", "instantiate_local_consequence"), + ) + + def answer( + self, + session_id: str, + text: str, + context: Mapping[str, Any] | None = None, + *, + ablate_specialists: Sequence[str] = (), + ablate_knowledge_cells: Sequence[str] = (), + ablate_ephemeral_workspace: bool = False, + ablate_operator_composition: bool = False, + ) -> dict[str, Any]: + output = super().answer( + session_id, text, context, + ablate_specialists=ablate_specialists, + ablate_knowledge_cells=ablate_knowledge_cells, + ablate_ephemeral_workspace=ablate_ephemeral_workspace, + ablate_operator_composition=ablate_operator_composition, + ) + output["schema_version"] = SCHEMA + output["runtime"]["productive_morphology_model_calls"] = 0 + output["runtime"]["productive_morphology_gradient_steps"] = 0 + output["runtime"]["counterfactual_construction_model_calls"] = 0 + output["runtime"]["counterfactual_construction_gradient_steps"] = 0 + output["turn_manifest_sha256"] = digest(output) + return output + + +__all__ = ["MorphologicalCounterfactualAgent", "_lemma47"] diff --git a/root/wander-train/stage5k49_productive_inverse_surface_agent.py b/root/wander-train/stage5k49_productive_inverse_surface_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..4eb6d9f048b29d94a6c04bfccac6e952be3f9a79 --- /dev/null +++ b/root/wander-train/stage5k49_productive_inverse_surface_agent.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +"""K49 opened repair of K48's two inverse-surface defects.""" + +from __future__ import annotations + +import re +from typing import Any, Mapping, Sequence + +from stage5k15_native_mixed_agent import HandlerResult, SemanticClause, clean, digest, third_person +from stage5k45_ephemeral_compositional_language_agent import RelationFact, _strip_article +from stage5k47_morphological_counterfactual_agent import MorphologicalCounterfactualAgent + + +SCHEMA = "oracle-stage5k49-productive-inverse-surface-agent-v1" + + +class ProductiveInverseSurfaceAgent(MorphologicalCounterfactualAgent): + def _novel_transfer(self, session_id: str, text: str) -> HandlerResult | None: + match = re.match( + r"^(?:(?:an|a|the)\s+)(.+?)\s+(?:transfers?|gives?|hands?)\s+" + r"(?:(?:an|a|the)\s+)?(.+?)\s+to\s+" + r"(?:(?:an|a|the)\s+)?(.+?)[.!?]*$", + clean(text), re.IGNORECASE, + ) + if match is None: + return None + actor, item, recipient = (_strip_article(match.group(index)) for index in (1, 2, 3)) + session = self._session(session_id) + state = session.workspace.compose( + "transfer", + tuple(self._entity(session, value) for value in (actor, item, recipient)), + ttl_turns=128, + ) + session.facts.append(RelationFact(actor, "transfer", item, state.state_id, state.world_id)) + session.active_relations[("received", item.casefold())] = RelationFact( + recipient, "receive", item, state.state_id, state.world_id, inferred=True, + ) + self._record_last( + session, "compose_unseen_transfer", (state,), actor=actor, item=item, + recipient=recipient, known_operator_unseen_fillers=True, + article_resolution="longest_determiner_first", + ) + return HandlerResult( + "compose_unseen_transfer", "answered", + (("actor", actor), ("object", item), ("recipient", recipient)), + (("state_id", state.state_id),), + (SemanticClause(actor, "transfer", object_value=item, qualifiers=(("to", recipient),)),), + (("source", "conversation_local_event"),), + ("parse_longest_determiner", "bind_unseen_fillers", "apply_transfer_law", "stabilize_role_order"), + ) + + def _rule_assertion(self, session_id: str, text: str) -> HandlerResult | None: + result = super()._rule_assertion(session_id, text) + if result is None or result.operation != "compose_recursive_rule": + return result + parsed = self._rule_definition(text) + if parsed is None: + return result + antecedent, consequent, termination = parsed + clause = SemanticClause( + "The temporary rule", "state", + object_value=( + f"whoever {third_person(antecedent)} an object " + f"{third_person(consequent)} it" + ), + qualifiers=(("until", f"another person {third_person(termination)} it"),), + ) + return HandlerResult( + result.operation, result.status, result.arguments, result.result, + (clause,), result.evidence, + (*result.computation_trace, "realize_embedded_verbs_with_productive_inflection"), + tool_audit=result.tool_audit, memory_audit=result.memory_audit, + ) + + def answer( + self, + session_id: str, + text: str, + context: Mapping[str, Any] | None = None, + *, + ablate_specialists: Sequence[str] = (), + ablate_knowledge_cells: Sequence[str] = (), + ablate_ephemeral_workspace: bool = False, + ablate_operator_composition: bool = False, + ) -> dict[str, Any]: + output = super().answer( + session_id, text, context, + ablate_specialists=ablate_specialists, + ablate_knowledge_cells=ablate_knowledge_cells, + ablate_ephemeral_workspace=ablate_ephemeral_workspace, + ablate_operator_composition=ablate_operator_composition, + ) + output["schema_version"] = SCHEMA + output["runtime"]["determiner_inverse_model_calls"] = 0 + output["runtime"]["determiner_inverse_gradient_steps"] = 0 + output["runtime"]["embedded_inflection_model_calls"] = 0 + output["runtime"]["embedded_inflection_gradient_steps"] = 0 + output["turn_manifest_sha256"] = digest(output) + return output + + +__all__ = ["ProductiveInverseSurfaceAgent"] diff --git a/root/wander-train/stage5k81_information_weighted_source_expert.py b/root/wander-train/stage5k81_information_weighted_source_expert.py new file mode 100644 index 0000000000000000000000000000000000000000..382b0a01939dc201ac9982f3488dc7ed0af9b403 --- /dev/null +++ b/root/wander-train/stage5k81_information_weighted_source_expert.py @@ -0,0 +1,323 @@ +#!/usr/bin/env python3 +"""Information-weighted full-corpus source expert for K81 development. + +K79 proved that an FTS postings expert can compile 104,000 public rows in +seconds, but ranked every matched query group nearly equally. This successor +materializes corpus document frequencies at compile time and ranks relational +group convergence by self-information. Rare situated anchors can therefore +outweigh incidental common-word agreement without an embedding model or a +query-time corpus scan. +""" +from __future__ import annotations + +import argparse +from dataclasses import dataclass +from datetime import datetime, timezone +import hashlib +import json +import math +from pathlib import Path +import re +import sqlite3 +from typing import Any, Mapping, Sequence + +from stage5j1_native_contextual_sense_lattice import WORD + + +SCHEMA = "oracle-stage5k81-information-weighted-source-expert-v1" +STOP = frozenset({ + "a", "about", "account", "an", "and", "answer", "as", "be", "both", "by", + "cited", "claim", "describe", "details", "do", "does", "for", "from", "give", + "identify", "in", "inferring", "is", "it", "its", "of", "on", "or", "reported", + "retaining", "separate", "source", "state", "stated", "the", "their", "them", "there", + "this", "those", "to", "treating", "use", "used", "what", "when", "which", "with", + "without", +}) + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def terms(text: str) -> tuple[str, ...]: + normalized: list[str] = [] + for raw in WORD.findall(str(text)): + value = raw.casefold().replace("’", "'") + if value.endswith("'s") and len(value) > 2: + value = value[:-2] + normalized.append(value) + return tuple(dict.fromkeys(normalized)) + + +def morphological_variants(term: str) -> tuple[str, ...]: + values = {term} + if term.endswith("ies") and len(term) > 4: + values.add(term[:-3] + "y") + if term.endswith("s") and len(term) > 3: + values.add(term[:-1]) + if term.endswith("ied") and len(term) > 4: + values.add(term[:-3] + "y") + if term.endswith("ed") and len(term) > 4: + stem = term[:-2] + values.add(stem) + values.add(stem + "e") + if term.endswith("ing") and len(term) > 5: + stem = term[:-3] + values.add(stem) + values.add(stem + "e") + return tuple(sorted(values)) + + +@dataclass(frozen=True) +class InformationWeightedCandidate: + row: Mapping[str, Any] + group_count: int + literal_group_count: int + relational_vote: float + information_score: float + group_surfaces: Mapping[str, Mapping[str, Any]] + postings_rows_considered: int + + +def build_index(corpus_path: Path, output_path: Path) -> dict[str, Any]: + if output_path.exists(): + raise FileExistsError("K81 source expert is immutable; choose an unused path") + output_path.parent.mkdir(parents=True, exist_ok=True) + connection = sqlite3.connect(output_path) + try: + connection.executescript( + """ + PRAGMA journal_mode=WAL; + PRAGMA synchronous=NORMAL; + CREATE TABLE metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL); + CREATE VIRTUAL TABLE source_rows USING fts5( + text_sha256 UNINDEXED, + fact, + source_document UNINDEXED, + source_document_sha256 UNINDEXED, + domain_id UNINDEXED, + license_note UNINDEXED, + source_split UNINDEXED, + tokenize='unicode61 remove_diacritics 2' + ); + """ + ) + inserted = 0 + with corpus_path.open("r", encoding="utf-8") as handle: + for line in handle: + if not line.strip(): + continue + row = json.loads(line) + fact = str(row.get("text", row.get("query_text", ""))).strip() + text_sha = str(row.get("text_sha256", "")) + if not fact or not text_sha: + continue + connection.execute( + "INSERT INTO source_rows VALUES (?, ?, ?, ?, ?, ?, ?)", + ( + text_sha, fact, str(row.get("source_document", "unknown")), + str(row.get("source_document_sha256", "")), + str(row.get("domain_id", row.get("source_collection", ""))), + str(row.get("license_note", "")), str(row.get("split", "")), + ), + ) + inserted += 1 + if inserted % 5000 == 0: + connection.commit() + connection.commit() + connection.executescript( + """ + CREATE VIRTUAL TABLE source_vocab_runtime USING fts5vocab(source_rows, 'row'); + CREATE TABLE term_document_frequency ( + term TEXT PRIMARY KEY, + document_frequency INTEGER NOT NULL, + corpus_frequency INTEGER NOT NULL + ) WITHOUT ROWID; + INSERT INTO term_document_frequency(term, document_frequency, corpus_frequency) + SELECT term, doc, cnt FROM source_vocab_runtime; + DROP TABLE source_vocab_runtime; + """ + ) + vocabulary_size = int(connection.execute("SELECT count(*) FROM term_document_frequency").fetchone()[0]) + metadata = { + "schema_version": SCHEMA, + "built_at_utc": datetime.now(timezone.utc).isoformat(), + "corpus_path_name": corpus_path.name, + "corpus_sha256": sha256(corpus_path), + "rows_indexed": inserted, + "vocabulary_size": vocabulary_size, + "ranking": "relational_group_convergence_times_log2_inverse_document_frequency", + "traditional_language_model": False, + "transformer": False, + "pretrained_embedding_encoder": False, + "gradient_steps": 0, + "answer_labels_used": False, + "query_time_full_corpus_scans": 0, + } + connection.executemany( + "INSERT INTO metadata(key, value) VALUES (?, ?)", + ((key, json.dumps(value, ensure_ascii=False, sort_keys=True)) for key, value in metadata.items()), + ) + connection.commit() + connection.execute("PRAGMA wal_checkpoint(TRUNCATE)") + connection.execute("VACUUM") + return {**metadata, "index_sha256": sha256(output_path)} + finally: + connection.close() + + +class InformationWeightedSourceExpert: + def __init__(self, path: Path, *, expected_corpus_sha256: str | None = None) -> None: + self.path = path.resolve() + uri = self.path.as_uri() + "?mode=ro&immutable=1" + self.connection = sqlite3.connect(uri, uri=True, check_same_thread=False) + metadata = { + key: json.loads(value) + for key, value in self.connection.execute("SELECT key, value FROM metadata") + } + if metadata.get("schema_version") != SCHEMA: + raise ValueError("unsupported K81 source expert") + if expected_corpus_sha256 and metadata.get("corpus_sha256") != expected_corpus_sha256: + raise ValueError("K81 source expert corpus identity mismatch") + self.metadata = metadata + self.index_sha256 = sha256(self.path) + self.rows_indexed = int(metadata["rows_indexed"]) + + @staticmethod + def _fts_token(value: str) -> str | None: + normalized = " ".join(terms(value)) + if not normalized or not re.fullmatch(r"[a-z0-9_ -]+", normalized): + return None + return normalized + + def _document_frequencies(self, values: Sequence[str]) -> dict[str, int]: + unique = tuple(sorted(set(values))) + if not unique: + return {} + result: dict[str, int] = {} + # SQLite has a finite placeholder limit; relational bridge inventories + # are small, but chunking keeps the expert safe under later expansion. + for start in range(0, len(unique), 500): + chunk = unique[start:start + 500] + placeholders = ",".join("?" for _ in chunk) + result.update({ + str(term): int(frequency) + for term, frequency in self.connection.execute( + f"SELECT term, document_frequency FROM term_document_frequency WHERE term IN ({placeholders})", + chunk, + ) + }) + return result + + def candidate( + self, + query: str, + bridges: Mapping[str, Sequence[str]], + *, + minimum_groups: int = 3, + limit: int = 1024, + ) -> InformationWeightedCandidate | None: + query_terms = tuple(value for value in terms(query) if value not in STOP and len(value) > 1) + groups: dict[str, dict[str, tuple[float, str]]] = {} + fts_values: set[str] = set() + for term in query_terms: + variants: dict[str, tuple[float, str]] = {} + for target in morphological_variants(term): + variants[target] = (1.0 if target == term else 0.96, "literal" if target == term else "morphological") + for target in bridges.get(term, ()): + normalized = str(target).casefold() + variants[normalized] = max( + variants.get(normalized, (0.0, "relational_bridge")), + (0.88, "relational_bridge"), + ) + groups[term] = variants + fts_values.update(value for value in variants if self._fts_token(value)) + if not fts_values: + return None + frequencies = self._document_frequencies(tuple(fts_values)) + available = {value for value in fts_values if value in frequencies} + if not available: + return None + expression = " OR ".join(f'"{value}"' for value in sorted(available)) + rows = self.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 ?", + (expression, int(limit)), + ).fetchall() + ranked: list[tuple[float, int, float, int, float, str, tuple[Any, ...], dict[str, dict[str, Any]]]] = [] + for row in rows: + row_terms = set(terms(str(row[1]))) + matched: dict[str, dict[str, Any]] = {} + vote = 0.0 + information_score = 0.0 + literal = 0 + for source, variants in groups.items(): + choices = [] + for target, (weight, kind) in variants.items(): + if target not in row_terms or target not in frequencies: + continue + information = 1.0 + math.log2((self.rows_indexed + 1.0) / (frequencies[target] + 1.0)) + choices.append((weight * information, weight, information, target, kind)) + if not choices: + continue + weighted, weight, information, target, kind = max(choices, key=lambda value: (value[0], value[3])) + matched[source] = { + "target": target, + "kind": kind, + "document_frequency": frequencies[target], + "information": information, + "weighted_information": weighted, + } + vote += weight + information_score += weighted + literal += kind in {"literal", "morphological"} + if len(matched) >= minimum_groups: + ranked.append(( + information_score, len(matched), vote, literal, + float(row[7]), str(row[0]), row, matched, + )) + if not ranked: + return None + ranked.sort(key=lambda value: (-value[0], -value[1], -value[2], -value[3], value[4], value[5])) + information_score, count, vote, literal, _bm25, text_sha, row, matched = ranked[0] + return InformationWeightedCandidate( + row={ + "text_sha256": text_sha, + "text": row[1], + "fact": row[1], + "source_document": row[2], + "source_document_sha256": row[3], + "domain_id": row[4], + "license_note": row[5], + "source_split": row[6], + "retrieval_score": information_score / max(1.0, len(query_terms)), + "answer_status": "full_corpus_information_weighted_relational_evidence_only", + "retrieval_path": "k81_fts_postings_idf_role_group_convergence", + }, + group_count=count, + literal_group_count=literal, + relational_vote=vote, + information_score=information_score, + group_surfaces=matched, + postings_rows_considered=len(rows), + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--corpus", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + print(json.dumps(build_index(args.corpus, args.output), ensure_ascii=False, indent=2, sort_keys=True)) + + +if __name__ == "__main__": + main() + + +__all__ = [ + "InformationWeightedCandidate", + "InformationWeightedSourceExpert", + "build_index", +] diff --git a/root/wander-train/stage5k85_opened_k84_discourse_tool_repair_agent.py b/root/wander-train/stage5k85_opened_k84_discourse_tool_repair_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..5e0f9e7b520cdb0a7017948ad425cf2313b5f905 --- /dev/null +++ b/root/wander-train/stage5k85_opened_k84_discourse_tool_repair_agent.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python3 +"""K85 discourse, predicate-boundary, and tool-reference repairs from K84. + +K83 and all K84 prospective artifacts are immutable. This successor repairs +three general classes exposed by K84: exact local lexemes before productive +number morphology, explicit finite predicates before noun/verb ambiguity, and +typed tool-result continuity across conversational turns. +""" +from __future__ import annotations + +from dataclasses import dataclass +import re +from typing import Any, Mapping + +from stage5j1_native_contextual_sense_lattice import WORD +from stage5j2_native_english_construction_algebra import AUXILIARIES, DETERMINERS +from stage5k15_native_mixed_agent import HandlerResult, clean, digest +from stage5k45_ephemeral_compositional_language_agent import _strip_article +from stage5k76_relational_graph_transduction_agent import ( + GraphAtom, + GraphDiscourse, + UtteranceGraph, + _surface, +) +from stage5k83_opened_k82_structural_repair_agent import ( + OpenedK82StructuralRepairAgent, + OpenedK82StructuralRepairTransducer, +) + + +SCHEMA = "oracle-stage5k85-opened-k84-discourse-tool-repair-agent-v1" + + +@dataclass(frozen=True) +class ToolDialogueAddress: + expert_id: str + row_key: str + domain_cue: str + field: str | None + + +class OpenedK84DiscourseRepairTransducer(OpenedK82StructuralRepairTransducer): + def _membership(self, text: str, discourse: GraphDiscourse) -> tuple[str, str] | None: + raw = tuple(WORD.findall(text)) + values = tuple(value.casefold() for value in raw) + # Conversation-defined symbols are exact atomic lexemes. Productive + # singularization is only a fallback; otherwise a symbol ending in s + # (veltris) is corrupted into a nonexistent veltri. + concept = next((value for value in reversed(values) if value in discourse.definitions), None) + if concept is not None: + if "qualifies" in values and "as" in values: + index = values.index("qualifies") + begin = 1 if values and values[0] == "suppose" else 0 + entity = _surface(raw[begin:index]) + if entity: + return entity, concept + if "is" in values: + index = values.index("is") + entity = _surface(raw[:index]) + if entity: + return entity, concept + return super()._membership(text, discourse) + + 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) + explicit = next(( + index for index, value in enumerate(values[1:], start=1) + if value not in AUXILIARIES and value.endswith(("ed", "ied", "en")) + ), None) + if explicit is not None: + inherited = super()._simple_clause(text, world=world) + inherited_index = next(( + index for index, value in enumerate(values) + if self.lemma(value) == (inherited.predicate if inherited is not None else "") + ), explicit) + if inherited is None or inherited_index < explicit: + subject = _surface(raw[:explicit]) + predicate = self.lemma(values[explicit]) + object_value = _strip_article(_surface(raw[explicit + 1:])) or "event" + if subject and predicate: + return GraphAtom(subject, predicate, object_value, world) + return super()._simple_clause(text, world=world) + + +class OpenedK84DiscourseToolRepairAgent(OpenedK82StructuralRepairAgent): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.graph_transducer = OpenedK84DiscourseRepairTransducer(self, self.construction_head) + self._k85_tool_dialogue: dict[str, ToolDialogueAddress] = {} + self._k85_lineage_sha256 = digest({ + "schema_version": SCHEMA, + "parent_lineage_sha256": self._k83_lineage_sha256, + "opened_failure_source": "immutable_k84_scored_outputs_v1", + "repair_classes": [ + "exact_local_lexeme_before_number_morphology", + "explicit_finite_predicate_before_nominal_s_ambiguity", + "typed_tool_row_dialogue_continuity", + ], + }) + + @staticmethod + def _tool_domain_cue(expert_id: str) -> str: + lower = expert_id.casefold() + if "earthquake" in lower or "usgs" in lower: + return "earthquake database" + if "population" in lower or "world_bank" in lower: + return "population database" + return "registered database" + + def _bounded_tool_graph(self, session_id: str, surface: str) -> HandlerResult: + original = clean(surface) + lower = original.casefold() + prior = self._k85_tool_dialogue.get(session_id) + anaphoric = bool( + prior + and ( + re.search(r"\b(?:it|its|same|that)\b", lower) + or "registered record" in lower + ) + and not re.search(r"\b(?:us[0-9a-z]+)\b", lower) + ) + runtime_surface = original + if anaphoric and prior is not None: + runtime_surface = f"From the {prior.domain_cue}, retrieve {prior.row_key}; {original}" + result = super()._bounded_tool_graph(session_id, runtime_surface) + audit = dict(result.tool_audit or {}) + if result.status == "answered" and audit.get("expert_id") and audit.get("row_key"): + address = ToolDialogueAddress( + str(audit["expert_id"]), + str(audit["row_key"]), + self._tool_domain_cue(str(audit["expert_id"])), + None if audit.get("field") is None else str(audit["field"]), + ) + self._k85_tool_dialogue[session_id] = address + self._bind_memory( + session_id, + "k85-tool-address-" + digest({"session": session_id, "surface": original})[:20], + { + "situation": "typed_tool_dialogue_address", + "source": address.expert_id, + "field": address.field or "record", + "result": address.row_key, + "warrant": "read_only_tool_result", + }, + bank="procedural", + source="k85_tool_dialogue_continuity", + ) + if not anaphoric or result.status != "answered": + return result + return HandlerResult( + result.operation, + result.status, + result.arguments, + result.result, + result.clauses, + result.evidence, + (*result.computation_trace, "resolve_anaphoric_tool_row_address"), + tool_audit={ + **audit, + "anaphoric_row_resolution": True, + "prior_row_key": prior.row_key if prior else None, + "surface_rewrite_is_typed_address_binding": True, + }, + memory_audit=result.memory_audit, + ) + + def answer(self, *args: Any, **kwargs: Any) -> dict[str, Any]: + output = super().answer(*args, **kwargs) + output["opened_k84_discourse_tool_repair"] = { + "schema_version": SCHEMA, + "lineage_sha256": self._k85_lineage_sha256, + "development_source": "opened_immutable_k84_failures", + "prospective_claim": False, + "active_tool_dialogue_sessions": len(self._k85_tool_dialogue), + "traditional_language_model": False, + "transformer": False, + "pretrained_embedding_encoder": False, + "autoregressive_carrier": False, + "model_calls": 0, + "gradient_steps": 0, + } + output["runtime"]["opened_k84_discourse_tool_repair_model_calls"] = 0 + output["runtime"]["opened_k84_discourse_tool_repair_gradient_steps"] = 0 + output["schema_version"] = SCHEMA + output["turn_manifest_sha256"] = digest(output) + return output + + +__all__ = [ + "OpenedK84DiscourseRepairTransducer", + "OpenedK84DiscourseToolRepairAgent", +] diff --git a/root/wander-train/stage5k89_native_identity_purpose_anchor_agent.py b/root/wander-train/stage5k89_native_identity_purpose_anchor_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..f6677808c2bf329ee47a641b99833913d84d2fc9 --- /dev/null +++ b/root/wander-train/stage5k89_native_identity_purpose_anchor_agent.py @@ -0,0 +1,274 @@ +#!/usr/bin/env python3 +"""K89 persistent native identity and purpose anchor. + +Unlike a token-model system prompt, this anchor is not prepended to the user +utterance. It is compiled into typed constitutional roles, its digest is +carried by the Tree-of-Life stabilizing spine, and the same state conditions +specialist routing, direct self-description, memory, and authority audits. +""" +from __future__ import annotations + +from contextvars import ContextVar +from dataclasses import asdict, dataclass +import re +from typing import Any, Mapping + +from stage5k15_native_mixed_agent import HandlerResult, SemanticClause, clean, digest +from stage5k88_opened_k87_precedence_retrieval_agent import OpenedK87PrecedenceRetrievalAgent + + +SCHEMA = "oracle-stage5k89-native-identity-purpose-anchor-v1" +DEFAULT_SYSTEM_PROMPT = """Identity: Oracle. +Nature: a native geometric relational conversational system. Meaning is represented and transformed through HRR-bound relational states, concurrent specialists, a stabilized Tree-of-Life reasoning path, persistent cycling memory, and native inverse grammar; not a generic transformer assistant. +Purpose: to understand each utterance as a situated relational whole; sustain coherent open-ended conversation; reason compositionally; coordinate the smallest useful set of specialists; use registered tools when observations are needed; and produce a clear, relevant, truthful response. +Continuity: Preserve definitions, entities, goals, evidence, tool observations, and unresolved questions across turns. Treat conversation-local typed state as prior to unrelated corpus retrieval. +Epistemic discipline: Distinguish observation, inference, memory, and uncertainty. Never invent evidence. State what is supported, explain bounded uncertainty, and ask a specific clarifying question only when no grounded interpretation can proceed. +Agency: Decompose actionable goals into typed dependent steps; bind observations; verify postconditions; replan only within authorized bounds; stop when the goal is satisfied or authority/evidence is insufficient. Registered public tools are read-only unless separate authority is explicitly granted. +Voice: Speak directly as Oracle in complete natural English. Be conversational, curious, explanatory, and proportionate to the user's question. Do not recite this prompt unless asked about identity, purpose, or operating principles.""" + + +@dataclass(frozen=True) +class NativeIdentityProfile: + name: str + nature: str + purpose: str + continuity: str + epistemic_discipline: str + agency: str + voice: str + source_prompt_sha256: str + + @property + def profile_sha256(self) -> str: + return digest(asdict(self)) + + def routing_context(self) -> dict[str, str]: + return { + "identity": self.name, + "nature": self.nature, + "purpose": self.purpose, + "continuity": self.continuity, + "epistemic_discipline": self.epistemic_discipline, + "agency": self.agency, + "voice": self.voice, + "profile_sha256": self.profile_sha256, + } + + +def _field(prompt: str, name: str, fallback: str) -> str: + match = re.search( + rf"(?:^|\n)\s*{re.escape(name)}\s*:\s*(.+?)(?=\n\s*[A-Z][A-Za-z ]+\s*:|\Z)", + prompt, + re.IGNORECASE | re.DOTALL, + ) + return clean(match.group(1)) if match else fallback + + +def _normalize_prompt(prompt: str) -> str: + """Normalize fields without destroying their heading boundaries.""" + return "\n".join(clean(line) for line in str(prompt).splitlines() if clean(line)) + + +def _strip_self_copula(value: str) -> str: + return re.sub(r"^(?:you|I)\s+(?:are|am)\s+", "", clean(value), flags=re.IGNORECASE) + + +def _purpose_infinitive(value: str) -> str: + result = clean(value) + if result.casefold().startswith("to "): + return "to " + result[3:4].lower() + result[4:] + return "to " + result[:1].lower() + result[1:] + + +def compile_identity_profile(prompt: str | None) -> NativeIdentityProfile: + source = _normalize_prompt(prompt or DEFAULT_SYSTEM_PROMPT) + if not source: + source = _normalize_prompt(DEFAULT_SYSTEM_PROMPT) + defaults = _normalize_prompt(DEFAULT_SYSTEM_PROMPT) + identity = _field(source, "Identity", "Oracle").strip(" .") + if identity == "Oracle": + # Support ordinary system-prompt prose while keeping headings as the + # canonical lossless form. + match = re.search(r"\byou\s+are\s+([A-Z][A-Za-z0-9_-]{1,40})\b", source) + if match: + identity = match.group(1) + return NativeIdentityProfile( + name=identity, + nature=_strip_self_copula(_field(source, "Nature", _field(defaults, "Nature", "a native geometric relational conversational system"))), + purpose=_purpose_infinitive(_field(source, "Purpose", _field(defaults, "Purpose", "sustain grounded conversation and reasoning"))), + continuity=_field(source, "Continuity", _field(defaults, "Continuity", "preserve typed conversational state")), + epistemic_discipline=_field(source, "Epistemic discipline", _field(defaults, "Epistemic discipline", "do not invent evidence")), + agency=_field(source, "Agency", _field(defaults, "Agency", "act only within authorized bounds")), + voice=_field(source, "Voice", _field(defaults, "Voice", "speak directly in complete English")), + source_prompt_sha256=digest(source), + ) + + +_IDENTITY_PROFILE: ContextVar[NativeIdentityProfile | None] = ContextVar("k89_identity_profile", default=None) + + +class NativeIdentityPurposeAnchorAgent(OpenedK87PrecedenceRetrievalAgent): + def __init__(self, *args: Any, default_system_prompt: str = DEFAULT_SYSTEM_PROMPT, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.default_system_prompt = default_system_prompt + self.default_identity_profile = compile_identity_profile(default_system_prompt) + self._k89_bound_sessions: dict[str, str] = {} + self._k89_lineage_sha256 = digest({ + "schema_version": SCHEMA, + "parent_lineage_sha256": self._k88_lineage_sha256, + "default_identity_profile_sha256": self.default_identity_profile.profile_sha256, + "anchor_contract": [ + "typed_identity_and_purpose_roles", + "protected_spine_digest", + "specialist_routing_context", + "persistent_procedural_binding", + "native_self_description_proof", + "authority_invariant_not_user_overridable", + ], + }) + + def _tree_record(self, session_id: str, turn_id: str) -> dict[str, Any]: + record = super()._tree_record(session_id, turn_id) + profile = _IDENTITY_PROFILE.get() or self.default_identity_profile + spine = record.setdefault("dual_rail_contract", {}).setdefault("stabilizing_spine", {}) + spine["stage5k89:spine:identity_purpose"] = { + "profile_sha256": profile.profile_sha256, + "identity": profile.name, + "constitutional_roles_bound": 7, + "mutable_during_turn": False, + "unbind_permission": "malkuth_only", + "raw_prompt_present": False, + } + record.setdefault("payload_contract", {})["identity_raw_prompt_present"] = False + return record + + @staticmethod + def _identity_request(text: str) -> bool: + lower = clean(text).casefold() + return bool( + re.search(r"\bwho\s+are\s+you\b", lower) + or re.search(r"\bwhat\s+are\s+you\b", lower) + or re.search(r"\b(?:your|the)\s+(?:identity|purpose|mission|role)\b", lower) + or re.search(r"\bwhy\s+(?:do\s+you|were\s+you)\s+(?:exist|built|created)\b", lower) + or "operating principles" in lower + ) + + def _identity_result(self, profile: NativeIdentityProfile) -> HandlerResult: + clauses = ( + SemanticClause("I", "be", complement=profile.name), + SemanticClause("I", "be", complement=profile.nature), + SemanticClause("My purpose", "be", complement=profile.purpose), + SemanticClause("I", "preserve", object_value="typed conversational continuity"), + SemanticClause("I", "use", object_value="evidence and authorized tools without inventing support"), + ) + return HandlerResult( + "identity_purpose", + "answered", + (("identity", profile.name),), + (("profile_sha256", profile.profile_sha256), ("constitutional_roles", 7)), + clauses, + (("source", "native_identity_purpose_anchor"),), + ( + "bind_identity_purpose_to_stabilizing_spine", + "select_constitutional_self_description_roles", + "compose_native_identity_proof", + "release_complete_clauses_at_malkuth", + ), + ) + + def _handle_event(self, session_id: str, text: str, turn_id: str) -> HandlerResult | None: + profile = _IDENTITY_PROFILE.get() or self.default_identity_profile + if self._identity_request(text): + return self._identity_result(profile) + return super()._handle_event(session_id, text, turn_id) + + def _handle_evidence(self, text: str, context: Mapping[str, Any]) -> HandlerResult | None: + # Self-knowledge is constitutional state, not an open-corpus lookup. + # This interception occurs before the inherited evidence/retrieval rail + # so a lexically adjacent public sentence cannot replace identity. + profile = _IDENTITY_PROFILE.get() or self.default_identity_profile + if self._identity_request(text): + return self._identity_result(profile) + return super()._handle_evidence(text, context) + + def answer( + self, + session_id: str, + text: str, + context: Mapping[str, Any] | None = None, + *, + system_prompt: str | None = None, + **kwargs: Any, + ) -> dict[str, Any]: + profile = compile_identity_profile(system_prompt or self.default_system_prompt) + local_context = dict(context or {}) + local_context["native_identity_anchor"] = profile.routing_context() + token = _IDENTITY_PROFILE.set(profile) + try: + if self._k89_bound_sessions.get(session_id) != profile.profile_sha256: + try: + self._bind_memory( + session_id, + "k89-identity-" + profile.profile_sha256[:20], + { + "situation": "native_identity_purpose_anchor", + "transition": "maintain_constitutional_identity_and_purpose", + "action": profile.purpose, + "result": profile.name, + "status": "constitutional_session_anchor", + "verifier": profile.profile_sha256, + }, + bank="procedural", + source="k89_identity_purpose_anchor", + ) + except ValueError as exc: + # A reconstructed runtime may encounter the exact same + # immutable identity event already present on disk. This + # is idempotent continuity, not an attempted rebind. + if "event_key already bound to another event" not in str(exc): + raise + self._k89_bound_sessions[session_id] = profile.profile_sha256 + output = super().answer(session_id, text, local_context, **kwargs) + turn_id = clean(output.get("turn_id", "")) + spine_record = self._tree_record(session_id, turn_id) + spine_identity = ( + spine_record.get("dual_rail_contract", {}) + .get("stabilizing_spine", {}) + .get("stage5k89:spine:identity_purpose", {}) + ) + finally: + _IDENTITY_PROFILE.reset(token) + output["native_identity_purpose_anchor"] = { + "schema_version": SCHEMA, + "lineage_sha256": self._k89_lineage_sha256, + "identity": profile.name, + "profile_sha256": profile.profile_sha256, + "source_prompt_sha256": profile.source_prompt_sha256, + "constitutional_roles": 7, + "bound_to_stabilizing_spine": spine_identity.get("profile_sha256") == profile.profile_sha256, + "spine_profile_sha256": spine_identity.get("profile_sha256"), + "spine_raw_prompt_present": spine_identity.get("raw_prompt_present"), + "available_to_specialist_routing": True, + "persistent_procedural_binding": True, + "raw_prompt_prepended_to_user_utterance": False, + "tool_authority_user_overridable": False, + "traditional_language_model": False, + "transformer": False, + "pretrained_embedding_encoder": False, + "autoregressive_carrier": False, + "model_calls": 0, + "gradient_steps": 0, + } + output["runtime"]["identity_anchor_model_calls"] = 0 + output["runtime"]["identity_anchor_gradient_steps"] = 0 + output["schema_version"] = SCHEMA + output["turn_manifest_sha256"] = digest(output) + return output + + +__all__ = [ + "DEFAULT_SYSTEM_PROMPT", + "NativeIdentityProfile", + "NativeIdentityPurposeAnchorAgent", + "compile_identity_profile", +] diff --git a/root/wander-train/stage5l2_structural_language_closure.py b/root/wander-train/stage5l2_structural_language_closure.py new file mode 100644 index 0000000000000000000000000000000000000000..013f7571edb92f03a85c29510436ce055b4f978a --- /dev/null +++ b/root/wander-train/stage5l2_structural_language_closure.py @@ -0,0 +1,430 @@ +#!/usr/bin/env python3 +"""L2: structural morphology and coordinated-role closure for L1. + +The stage repairs classes, not lexical cases. A surface predicate absent from +the frozen VerbNet inventory may reuse a known base predicate only when a +licensed productive prefix maps it to an explicit derivational operator. A +coordinated nominal becomes a set-valued role state whose members are bound +under the same protected Tree route; it is not flattened into the final noun. +""" + +from __future__ import annotations + +from dataclasses import replace +import hashlib +from typing import Any, Sequence + +from stage5j1_native_contextual_sense_lattice import WORD, stem +from stage5j2_native_english_construction_algebra import ( + AUXILIARIES, + COMPLEMENTIZERS, + COORDINATORS, + DETERMINERS, + MODALS, + PREPOSITIONS, +) +from stage5k171_relational_utterance_compiler import ALL_NODE_ROUTE +from stage5k1_generative_relational_workspace import ( + OperatorDefinition, + Provenance, +) +from stage5k3_language_adapter import ( + AdapterResidual, + EnglishRelationalAdapter, + InstantiatedAdapterProgram, + LanguageAnalysis, + RelationalProgramHypothesis, + SurfaceBinding, + digest as language_digest, +) +from stage5k10_self_inverse_computation import ( + NativeEnglishInverseGrammar, + SelfInverseComputationCompiler, +) +from stage5k11_quadratic_inverse_solver import QuadraticInverseSolver +from stage5k15_native_mixed_agent import digest +from stage5l1_broad_relational_ingress import ( + BroadEnglishRelationalAdapter, + BroadRelationalCompiler, + BroadRelationalIngressAgent, +) + + +SCHEMA = "oracle-stage5l2-structural-language-closure-v1" + +# Each prefix is an operator-valued relation, not a string rewrite. The base +# predicate supplies the licensed VerbNet frame; this operator remains bound +# in the terminal state and therefore cannot disappear during realization. +PREFIX_OPERATORS = ( + ("under", "degree_below_reference"), + ("over", "degree_above_reference"), + ("post", "temporally_after"), + ("pre", "temporally_before"), + ("mis", "manner_incorrect"), + ("re", "event_repetition"), + ("un", "state_reversal"), + ("de", "state_removal"), + ("co", "joint_participation"), +) + + +class StructuralEnglishRelationalAdapter(BroadEnglishRelationalAdapter): + """Broad adapter with operator-valued morphology and coordinated roles.""" + + adapter_id = "oracle-stage5l2-english-structural-closure-v1" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + parent_semantics = self.semantic_sha256 + self._coordination_by_hypothesis: dict[ + str, tuple[tuple[str, str, tuple[str, ...]], ...] + ] = {} + self.semantic_sha256 = language_digest({ + "parent_semantic_sha256": parent_semantics, + "prefix_operators": PREFIX_OPERATORS, + "coordination": "set_valued_role_state_with_member_preservation", + "routes": ALL_NODE_ROUTE, + }) + + def _surface_lemma(self, surface: str) -> str: + normalized = surface.casefold().replace("-", "_") + return str( + self.wordnet.morphy(normalized, self.wordnet.VERB) + or stem(normalized) + ).casefold() + + def _derivation(self, surface: str) -> tuple[str, str, str] | None: + derived = self._surface_lemma(surface) + if derived in self._lemma_frames: + return None + for prefix, operator in PREFIX_OPERATORS: + if not derived.startswith(prefix) or len(derived) <= len(prefix) + 2: + continue + base = derived[len(prefix):] + if base in self._lemma_frames: + return derived, base, operator + return None + + def _lemma(self, surface: str) -> str: + derivation = self._derivation(surface) + return derivation[1] if derivation is not None else self._surface_lemma(surface) + + def _predicate_indexes(self, values: Sequence[str]) -> tuple[int, ...]: + """Let a licensed derivation establish verbhood before WordNet does.""" + result: list[int] = [] + for index, surface in enumerate(values): + if surface in AUXILIARIES | MODALS: + continue + if not ( + self.resolver.verb_like(surface) + or self._derivation(surface) is not None + ): + continue + if index and values[index - 1] in ( + DETERMINERS | PREPOSITIONS | self._INTERROGATIVE_DETERMINERS + ): + continue + if result: + boundary = values[result[-1] + 1:index] + if not any( + value in COORDINATORS or value in COMPLEMENTIZERS + for value in boundary + ): + continue + result.append(index) + return tuple(result) + + @staticmethod + def _trim_region(values: Sequence[str]) -> tuple[int, int]: + start, stop = 0, len(values) + while start < stop and values[start] in COMPLEMENTIZERS: + start += 1 + while stop > start and values[stop - 1] in AUXILIARIES | MODALS: + stop -= 1 + return start, stop + + def _coordinated_roles( + self, + raw: Sequence[str], + hypothesis: RelationalProgramHypothesis, + ) -> tuple[ + tuple[SurfaceBinding, ...], + tuple[tuple[str, str, tuple[str, ...]], ...], + ]: + values = tuple(value.casefold() for value in raw) + frame = self._frames[hypothesis.frame_id] + role_regions: list[tuple[str, int, int]] = [] + for slot, role in frame.surface_slots: + if slot == "subject": + start, stop = self._trim_region(values[:hypothesis.predicate_token_index]) + role_regions.append((role, start, stop)) + elif slot == "direct_object": + start = hypothesis.predicate_token_index + 1 + stop = len(values) + for index in range(start, len(values)): + if values[index] in PREPOSITIONS or values[index] in COMPLEMENTIZERS: + stop = index + break + role_regions.append((role, start, stop)) + replacements: dict[str, SurfaceBinding] = {} + coordinates: list[tuple[str, str, tuple[str, ...]]] = [] + for role, start, stop in role_regions: + region = values[start:stop] + coordinators = [ + index for index, value in enumerate(region) + if value in {"and", "or"} + ] + if not coordinators: + continue + pivot = coordinators[-1] + left = list(raw[start:start + pivot]) + right = list(raw[start + pivot + 1:stop]) + while left and left[0].casefold() in {"a", "an", "the"}: + left.pop(0) + while right and right[0].casefold() in {"a", "an", "the"}: + right.pop(0) + if not left or not right: + continue + coordinator = region[pivot] + members = (" ".join(left), " ".join(right)) + surface = " ".join(raw[start:stop]) + replacements[role] = SurfaceBinding.create( + hypothesis.language_tag, + role, + surface, + value_type="entity", + token_start=start, + token_stop=stop, + confidence=hypothesis.construction_confidence, + ) + coordinates.append((role, coordinator, members)) + if not replacements: + return hypothesis.surface_bindings, () + bindings = tuple( + replacements.get(value.role, value) + for value in hypothesis.surface_bindings + ) + return bindings, tuple(coordinates) + + def analyze( + self, text: str, *, maximum_hypotheses: int = 8, + ) -> LanguageAnalysis: + analysis = super().analyze(text, maximum_hypotheses=maximum_hypotheses) + raw = tuple(WORD.findall(str(text))) + hypotheses: list[RelationalProgramHypothesis] = [] + for hypothesis in analysis.hypotheses: + residuals = list(hypothesis.residuals) + lemma = hypothesis.lemma + if 0 <= hypothesis.predicate_token_index < len(raw): + derivation = self._derivation(raw[hypothesis.predicate_token_index]) + else: + derivation = None + if derivation is not None: + derived, base, operator = derivation + lemma = derived + residuals.append(AdapterResidual( + "derivational_operator", + f"{operator}:{base}", + True, + hypothesis.construction_confidence, + )) + bindings, coordinated = self._coordinated_roles(raw, hypothesis) + for role, coordinator, members in coordinated: + member_hashes = ":".join( + hashlib.sha256(value.casefold().encode("utf-8")).hexdigest() + for value in members + ) + residuals.append(AdapterResidual( + "coordinated_role", + f"{role}:{coordinator}:{member_hashes}", + True, + hypothesis.construction_confidence, + )) + hypothesis_id = "hyp:l2:" + language_digest({ + "parent": hypothesis.hypothesis_id, + "lemma": lemma, + "bindings": [value.surface_sha256 for value in bindings], + "residuals": [value.as_dict() for value in residuals], + })[:24] + value = replace( + hypothesis, + hypothesis_id=hypothesis_id, + lemma=lemma, + surface_bindings=bindings, + residuals=tuple(residuals), + ) + hypotheses.append(value) + if coordinated: + if len(self._coordination_by_hypothesis) >= 4096: + self._coordination_by_hypothesis.pop( + next(iter(self._coordination_by_hypothesis)) + ) + self._coordination_by_hypothesis[hypothesis_id] = coordinated + return replace( + analysis, + hypotheses=tuple(hypotheses), + adapter_id=self.adapter_id, + adapter_semantic_sha256=self.semantic_sha256, + ) + + @staticmethod + def _install_structural_operators(workspace: Any) -> None: + definitions = ( + OperatorDefinition( + "derivational_transform", + ("derivation", "base_state"), + ("relation", "state"), + "state", + ALL_NODE_ROUTE, + source="stage5l2-productive-morphology", + ), + OperatorDefinition( + "coordinated_role_set", + ("left", "right"), + ("value", "value"), + "state", + ALL_NODE_ROUTE, + source="stage5l2-coordinated-role", + ), + OperatorDefinition( + "coordinated_role_scope", + ("semantic_state", "role_set"), + ("state", "state"), + "state", + ALL_NODE_ROUTE, + source="stage5l2-coordinated-role", + ), + ) + known = set(workspace.canonical.operator_ids) + for definition in definitions: + if definition.operator_id not in known: + workspace.canonical.register(definition) + known.add(definition.operator_id) + + def instantiate( + self, + hypothesis: RelationalProgramHypothesis, + workspace: Any, + *, + world_id: str | None = None, + ttl_turns: int | None = None, + ) -> InstantiatedAdapterProgram: + program = super().instantiate( + hypothesis, + workspace, + world_id=world_id, + ttl_turns=ttl_turns, + ) + derivations = tuple( + value for value in hypothesis.residuals + if value.feature == "derivational_operator" + ) + coordinated = self._coordination_by_hypothesis.get( + hypothesis.hypothesis_id, () + ) + if not derivations and not coordinated: + return program + self._install_structural_operators(workspace) + state = program.result_state + state_ids = list(program.atom_state_ids) + for residual in derivations: + operator, _, base = residual.value.partition(":") + state = workspace.compose( + "derivational_transform", + ( + workspace.symbol( + operator, + "relation", + world_id=world_id, + concept_id=f"derivation:{operator}:{base}", + ), + state, + ), + world_id=world_id, + ttl_turns=ttl_turns, + provenance=Provenance.local( + f"stage5l2:derivation:{hypothesis.hypothesis_id}" + ), + ) + state_ids.append(state.state_id) + for role, coordinator, members in coordinated: + member_values = [ + workspace.symbol( + member, + "entity", + world_id=world_id, + concept_id="coord-member:" + hashlib.sha256( + member.casefold().encode("utf-8") + ).hexdigest(), + ) + for member in members + ] + role_set = workspace.compose( + "coordinated_role_set", + member_values[:2], + world_id=world_id, + ttl_turns=ttl_turns, + provenance=Provenance.local( + f"stage5l2:coordination:{role}:{coordinator}" + ), + ) + state_ids.append(role_set.state_id) + state = workspace.compose( + "coordinated_role_scope", + (state, role_set), + world_id=world_id, + ttl_turns=ttl_turns, + provenance=Provenance.local( + f"stage5l2:coordination-scope:{hypothesis.hypothesis_id}:{role}" + ), + ) + state_ids.append(state.state_id) + return replace( + program, + atom_state_ids=tuple(state_ids), + result_state=state, + ) + + +class StructuralRelationalCompiler(BroadRelationalCompiler): + def __init__(self, **kwargs: Any) -> None: + kwargs["adapter_type"] = StructuralEnglishRelationalAdapter + super().__init__(**kwargs) + self.semantic_sha256 = digest({ + "schema_version": SCHEMA, + "parent_semantic_sha256": self.semantic_sha256, + "adapter_semantic_sha256": self.adapter.semantic_sha256, + "prefix_operators": PREFIX_OPERATORS, + "all_node_route": ALL_NODE_ROUTE, + }) + + def architecture(self) -> dict[str, Any]: + value = super().architecture() + value.update({ + "schema_version": SCHEMA, + "semantic_sha256": self.semantic_sha256, + "productive_derivational_operators": len(PREFIX_OPERATORS), + "coordinated_roles_are_set_valued_states": True, + "structural_extensions_traverse_all_ten_nodes": True, + }) + return value + + +class StructuralLanguageClosureAgent(BroadRelationalIngressAgent): + def __init__(self, *args: Any, relational_compiler: StructuralRelationalCompiler | None = None, + **kwargs: Any) -> None: + super().__init__( + *args, + relational_compiler=relational_compiler or StructuralRelationalCompiler(), + **kwargs, + ) + + +__all__ = [ + "ALL_NODE_ROUTE", + "PREFIX_OPERATORS", + "SCHEMA", + "StructuralEnglishRelationalAdapter", + "StructuralLanguageClosureAgent", + "StructuralRelationalCompiler", +] diff --git a/root/wander-train/stage5l2f_recursive_clause_graph.py b/root/wander-train/stage5l2f_recursive_clause_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..3387d12e7fc6089acd25eab3ea0dc37393f1d193 --- /dev/null +++ b/root/wander-train/stage5l2f_recursive_clause_graph.py @@ -0,0 +1,480 @@ +#!/usr/bin/env python3 +"""L2f: recursively compile clause-local programs into one protected HRR graph.""" + +from __future__ import annotations + +from dataclasses import dataclass, replace +import hashlib +import time +from typing import Any, Sequence + +from stage5j1_native_contextual_sense_lattice import WORD +from stage5k1_generative_relational_workspace import ( + CanonicalRelationalSpace, + EphemeralRelationalWorkspace, + OperatorDefinition, + Provenance, + RelationalConstraint, +) +from stage5k171_relational_utterance_compiler import ALL_NODE_ROUTE +from stage5k171_relational_utterance_compiler import canonical_space +from stage5k15_native_mixed_agent import digest +from stage5l1_broad_relational_ingress import BroadRelationalCompiler +from stage5l2e_directional_clause_scope import DirectionalClauseScopeAdapter + + +SCHEMA = "oracle-stage5l2f-recursive-clause-graph-v1" +RELATIONS = { + "and": "coordination", + "or": "alternative", + "but": "concession", + "because": "causal", + "since": "causal", + "although": "concession", + "though": "concession", + "if": "conditional", + "whether": "conditional", + "when": "temporal", + "while": "temporal", + "before": "temporal", + "after": "temporal", + "that": "complement", +} +MARKER_PRIORITY = ( + "because", "although", "though", "if", "whether", "when", "while", + "before", "after", "since", "that", "but", "and", "or", +) + + +class FullTreeDirectionalClauseScopeAdapter(DirectionalClauseScopeAdapter): + """Install every frozen VerbNet operator on the complete ten-node route.""" + + adapter_id = "oracle-stage5l2f-full-tree-directional-clause-adapter-v1" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.semantic_sha256 = digest({ + "parent_semantic_sha256": self.semantic_sha256, + "all_verbnet_operators_use_full_tree_route": True, + "route": ALL_NODE_ROUTE, + }) + + def install_operators( + self, + workspace: EphemeralRelationalWorkspace, + *, + minimum_support: int = 1, + ) -> tuple[str, ...]: + support = self.basis.template_support() + known = set(workspace.canonical.operator_ids) + registered: list[str] = [] + for template_id in sorted(self.basis.templates): + if support[template_id] < int(minimum_support): + continue + template = self.basis.templates[template_id] + operator_id = self.basis.canonical_operator_id(template_id) + if operator_id in known: + continue + workspace.canonical.register(OperatorDefinition( + operator_id=operator_id, + roles=template.dynamic_slots, + input_types=tuple("value" for _ in template.dynamic_slots), + output_type="state", + route=ALL_NODE_ROUTE, + laws=( + "verbnet_normalized_predicate_template", + "dynamic_bindings_do_not_change_operator_identity", + "full_tree_stabilizing_spine", + ), + source=f"verbnet-full-tree:{self.basis.source_sha256}:{template_id}", + )) + known.add(operator_id) + registered.append(operator_id) + return tuple(registered) + + +class FullTreeDirectionalClauseCompiler(BroadRelationalCompiler): + def __init__(self, **kwargs: Any) -> None: + kwargs["adapter_type"] = FullTreeDirectionalClauseScopeAdapter + super().__init__(**kwargs) + self.semantic_sha256 = digest({ + "schema_version": SCHEMA, + "parent_semantic_sha256": self.semantic_sha256, + "adapter_semantic_sha256": self.adapter.semantic_sha256, + "all_verbnet_operators_use_full_tree_route": True, + }) + + +@dataclass(frozen=True) +class ClauseTree: + words: tuple[str, ...] + relation: str | None = None + marker: str | None = None + left: "ClauseTree | None" = None + right: "ClauseTree | None" = None + reverse_arguments: bool = False + + @property + def leaf(self) -> bool: + return self.left is None and self.right is None + + +@dataclass(frozen=True) +class ClauseLeafEvidence: + ordinal: int + surface_sha256: str + selected_lemma: str | None + frame_id: str | None + eligible: bool + proof_sha256: str | None + protected_root_cosine: float | None + malkuth_only_release: bool + + def as_dict(self) -> dict[str, Any]: + return self.__dict__.copy() + + +@dataclass(frozen=True) +class RecursiveClauseCandidate: + analyzed: bool + clause_count: int + edge_count: int + maximum_depth: int + leaf_evidence: tuple[ClauseLeafEvidence, ...] + relations: tuple[str, ...] + root_expression_sha256: str | None + root_expression_depth: int | None + protected_root_cosine_minimum: float | None + inverse_reconstruction_exact: bool + ledger_chain_valid: bool + malkuth_only_release: bool + all_edges_traverse_ten_nodes: bool + error: str | None + latency_ms: float + + @property + def eligible_for_semantic_arbitration(self) -> bool: + return bool( + self.analyzed + and self.clause_count >= 2 + and self.edge_count == self.clause_count - 1 + and all(value.eligible for value in self.leaf_evidence) + and self.root_expression_sha256 + and self.inverse_reconstruction_exact + and self.ledger_chain_valid + and self.malkuth_only_release + and self.all_edges_traverse_ten_nodes + ) + + def as_dict(self) -> dict[str, Any]: + return { + "schema_version": SCHEMA, + **self.__dict__, + "leaf_evidence": [value.as_dict() for value in self.leaf_evidence], + "relations": list(self.relations), + "eligible_for_semantic_arbitration": self.eligible_for_semantic_arbitration, + "traditional_language_model": False, + "transformer": False, + "pretrained_continuous_embedding": False, + "next_token_predictions": 0, + "gradient_steps": 0, + } + + +class RecursiveClauseGraphCompiler: + def __init__(self, *, maximum_hypotheses: int = 32) -> None: + self.clause_compiler = FullTreeDirectionalClauseCompiler( + maximum_hypotheses=maximum_hypotheses, + ) + self.maximum_hypotheses = max(1, int(maximum_hypotheses)) + self.semantic_sha256 = digest({ + "schema_version": SCHEMA, + "clause_compiler_semantic_sha256": self.clause_compiler.semantic_sha256, + "relations": RELATIONS, + "marker_priority": MARKER_PRIORITY, + "route": ALL_NODE_ROUTE, + "split_requires_two_analyzable_clause_sides": True, + "all_inherited_and_dynamic_operators_use_full_tree_route": True, + "core_operators_cloned_and_verbnet_operators_reinstalled": True, + }) + + @property + def adapter(self): + return self.clause_compiler.adapter + + @staticmethod + def _surface(words: Sequence[str]) -> str: + return " ".join(words).strip() + + def _analyzable(self, words: Sequence[str]) -> bool: + if not words: + return False + return bool(self.adapter.analyze( + self._surface(words), maximum_hypotheses=self.maximum_hypotheses, + ).hypotheses) + + def _parse(self, words: tuple[str, ...], depth: int = 0) -> ClauseTree: + if depth >= 8 or len(words) < 3: + return ClauseTree(words) + # Leading subordinate clauses are closed by the comma before the main + # clause: ``because A acted, B changed``. + if words[0] in RELATIONS and words[0] not in {"and", "or", "but", "that"}: + try: + comma = words.index(",") + except ValueError: + comma = -1 + if comma > 1: + left, right = words[1:comma], words[comma + 1:] + if self._analyzable(left) and self._analyzable(right): + return ClauseTree( + words, RELATIONS[words[0]], words[0], + self._parse(tuple(left), depth + 1), + self._parse(tuple(right), depth + 1), + False, + ) + positions = [ + (MARKER_PRIORITY.index(value), index, value) + for index, value in enumerate(words) + if 0 < index < len(words) - 1 and value in RELATIONS + ] + for _, index, marker in sorted(positions): + left = tuple(value for value in words[:index] if value != ",") + right = tuple(value for value in words[index + 1:] if value != ",") + if not (self._analyzable(left) and self._analyzable(right)): + continue + reverse = marker in { + "because", "since", "if", "whether", "although", "though", + } + return ClauseTree( + words, RELATIONS[marker], marker, + self._parse(left, depth + 1), self._parse(right, depth + 1), + reverse, + ) + return ClauseTree(tuple(value for value in words if value != ",")) + + @staticmethod + def _depth(tree: ClauseTree) -> int: + if tree.leaf: + return 1 + assert tree.left is not None and tree.right is not None + return 1 + max( + RecursiveClauseGraphCompiler._depth(tree.left), + RecursiveClauseGraphCompiler._depth(tree.right), + ) + + @staticmethod + def _leaves(tree: ClauseTree) -> tuple[ClauseTree, ...]: + if tree.leaf: + return (tree,) + assert tree.left is not None and tree.right is not None + return ( + *RecursiveClauseGraphCompiler._leaves(tree.left), + *RecursiveClauseGraphCompiler._leaves(tree.right), + ) + + @staticmethod + def _install_clause_operators(workspace: EphemeralRelationalWorkspace) -> None: + known = set(workspace.canonical.operator_ids) + for relation in sorted(set(RELATIONS.values())): + operator_id = "clause_" + relation + if operator_id in known: + continue + workspace.canonical.register(OperatorDefinition( + operator_id, + ("left_clause", "right_clause"), + ("state", "state"), + "state", + ALL_NODE_ROUTE, + source="stage5l2f-recursive-clause-graph", + )) + known.add(operator_id) + if "recursive_utterance_state" not in known: + workspace.canonical.register(OperatorDefinition( + "recursive_utterance_state", + ("speech_act", "clause_graph"), + ("relation", "state"), + "state", + ALL_NODE_ROUTE, + source="stage5l2f-recursive-clause-graph", + )) + + def _workspace(self, session_id: str, text: str) -> EphemeralRelationalWorkspace: + """Create a full-Tree canonical space before any leaf is instantiated.""" + space = CanonicalRelationalSpace() + inherited = canonical_space() + for operator_id in inherited.operator_ids: + # VerbNet operators are reinstalled by the adapter with the exact + # frozen K2 definition and a full route. Core compositional + # operators are cloned here directly. + if operator_id.startswith("vn.op."): + continue + space.register(replace( + inherited.operator(operator_id), route=ALL_NODE_ROUTE, + )) + return EphemeralRelationalWorkspace( + "stage5l2f:" + hashlib.sha256( + f"{session_id}:{text}".encode("utf-8") + ).hexdigest()[:24], + space, + ) + + def compile(self, text: str, *, session_id: str = "l2f") -> RecursiveClauseCandidate: + started = time.perf_counter() + try: + tokens = tuple( + value.casefold() for value in WORD.findall(str(text).replace(",", " , ")) + ) + # WORD omits punctuation, so recover comma coordinates explicitly. + normalized = str(text).replace(",", " , ") + tokens = tuple( + value.casefold() for value in normalized.split() + if value == "," or WORD.fullmatch(value.strip(".?!;:")) + ) + tokens = tuple(value.strip(".?!;:").casefold() for value in tokens if value.strip(".?!;:")) + tree = self._parse(tokens) + leaves = self._leaves(tree) + if len(leaves) < 2: + return RecursiveClauseCandidate( + bool(self._analyzable(tokens)), len(leaves), 0, self._depth(tree), + (), (), None, None, None, False, False, False, False, + "recursive_clause_boundary_not_established", + 1000.0 * (time.perf_counter() - started), + ) + workspace = self._workspace(session_id, text) + self._install_clause_operators(workspace) + leaf_states: dict[int, Any] = {} + evidence: list[ClauseLeafEvidence] = [] + audits: list[Any] = [] + for ordinal, leaf in enumerate(leaves): + surface = self._surface(leaf.words) + candidate = self.clause_compiler.compile( + surface, session_id=f"{session_id}:leaf:{ordinal}", + ) + analysis = self.adapter.analyze( + surface, maximum_hypotheses=self.maximum_hypotheses, + ) + selected = ( + analysis.hypotheses[candidate.selected_rank] + if candidate.selected_rank is not None + and 0 <= candidate.selected_rank < len(analysis.hypotheses) + else None + ) + proof_sha256 = None + state = None + if candidate.eligible_for_semantic_arbitration and selected is not None: + program = self.adapter.instantiate(selected, workspace, ttl_turns=128) + proof = self.clause_compiler.computation_compiler.compile(program) + proof_sha256 = proof.proof_sha256 + state = program.result_state + audits.append(state.evaluation) + leaf_states[id(leaf)] = state + evidence.append(ClauseLeafEvidence( + ordinal, + hashlib.sha256(surface.encode("utf-8")).hexdigest(), + candidate.selected_lemma, + candidate.frame_id, + bool(candidate.eligible_for_semantic_arbitration and state is not None), + proof_sha256, + candidate.protected_root_cosine, + candidate.malkuth_only_release, + )) + if not all(value.eligible for value in evidence): + return RecursiveClauseCandidate( + True, len(leaves), len(leaves) - 1, self._depth(tree), + tuple(evidence), (), None, None, + min((value.protected_root_cosine for value in evidence if value.protected_root_cosine is not None), default=None), + False, False, False, False, "clause_leaf_withheld", + 1000.0 * (time.perf_counter() - started), + ) + relations: list[str] = [] + + def bind(node: ClauseTree): + if node.leaf: + return leaf_states[id(node)] + assert node.left is not None and node.right is not None and node.relation is not None + left_state, right_state = bind(node.left), bind(node.right) + if node.reverse_arguments: + left_state, right_state = right_state, left_state + relations.append(node.relation) + state = workspace.compose( + "clause_" + node.relation, + (left_state, right_state), + ttl_turns=128, + constraints=(RelationalConstraint( + "recursive_clause_edge", + (node.marker or node.relation, node.relation), + "scope:stage5l2f:" + str(len(relations)), + "positive", + ),), + provenance=Provenance.local( + f"stage5l2f:edge:{len(relations)}:{node.relation}" + ), + ) + audits.append(state.evaluation) + return state + + root = bind(tree) + root = workspace.compose( + "recursive_utterance_state", + (workspace.symbol("proposition", "relation"), root), + ttl_turns=128, + provenance=Provenance.local("stage5l2f:utterance"), + ) + audits.append(root.evaluation) + manifests = [dict(value.ledger_manifest) for value in audits] + return RecursiveClauseCandidate( + True, + len(leaves), + len(relations), + self._depth(tree), + tuple(evidence), + tuple(relations), + root.expression.structural_sha256, + root.expression.depth, + min(float(value.protected_root_cosine) for value in audits), + all(bool(value.inverse_reconstruction_exact) for value in audits), + all(bool(value.get("chain_valid", False)) for value in manifests), + all(value.pre_malkuth_unbinds == 0 and value.malkuth_unbinds == 1 for value in audits), + all(tuple(value.route) == ALL_NODE_ROUTE for value in audits), + None, + 1000.0 * (time.perf_counter() - started), + ) + except Exception as exc: + return RecursiveClauseCandidate( + False, 0, 0, 0, (), (), None, None, None, + False, False, False, False, + f"{type(exc).__name__}:{exc}", + 1000.0 * (time.perf_counter() - started), + ) + + def architecture(self) -> dict[str, Any]: + return { + "schema_version": SCHEMA, + "semantic_sha256": self.semantic_sha256, + "clause_compiler_semantic_sha256": self.clause_compiler.semantic_sha256, + "recursive_binary_clause_graph": True, + "split_requires_two_analyzable_clause_sides": True, + "all_inherited_and_dynamic_operators_use_full_tree_route": True, + "core_operators_cloned_and_verbnet_operators_reinstalled": True, + "supported_clause_relations": sorted(set(RELATIONS.values())), + "protected_four_to_one_spine": True, + "tree_of_life_nodes": 10, + "tree_of_life_routes": 22, + "terminal_malkuth_release_only": True, + "traditional_language_model": False, + "transformer": False, + "pretrained_continuous_embedding": False, + "gradient_training": False, + } + + +__all__ = [ + "ClauseLeafEvidence", + "ClauseTree", + "FullTreeDirectionalClauseCompiler", + "FullTreeDirectionalClauseScopeAdapter", + "RecursiveClauseCandidate", + "RecursiveClauseGraphCompiler", + "RELATIONS", + "SCHEMA", +] diff --git a/root/wander-train/stage5l6b_specialist_admission_successor.py b/root/wander-train/stage5l6b_specialist_admission_successor.py new file mode 100644 index 0000000000000000000000000000000000000000..32128b37feee755fe632bb1b3fa28d155346fa14 --- /dev/null +++ b/root/wander-train/stage5l6b_specialist_admission_successor.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""L6b: explicit specialist-admission accounting over the frozen L6a ABI. + +The first L6a prospective panel correctly exposed a contract ambiguity: source +sentences were compared with admitted C59 facts even though C59 deliberately +quarantines text outside its bounded single-edge grammar. This successor does +not weaken that grammar or modify L6a. It makes admission, quarantine, and ABI +registration counts explicit and proves that only admitted authenticated facts +enter the cognitive state ledger. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from stage5k214a_authenticated_specialist_factory import AuthenticatedSpecialistBundle +from stage5l6a_cognitive_state_abi import ( + CognitiveABIOracleRelationalV3, + canonical_sha, +) + + +SCHEMA = "oracle-stage5l6b-specialist-admission-successor-v1" +VERSION = "0.8.0-l6b-development" + + +class SpecialistAdmissionOracleRelationalV3(CognitiveABIOracleRelationalV3): + def compile_and_load_specialist( + self, name: str, spec_path: Path, *, output_root: Path, + frozen_carrier_manifest: Path | None = None, + ) -> dict[str, Any]: + result = super().compile_and_load_specialist( + name, spec_path, output_root=output_root, + frozen_carrier_manifest=frozen_carrier_manifest, + ) + bundle = AuthenticatedSpecialistBundle.load(Path(result["bundle_path"])) + report = bundle.payload["source_compiler_report"] + documents = tuple(report["documents"]) + source_sentences = sum(int(value["sentences"]) for value in documents) + admitted = int(report["accepted_relation_count"]) + quarantined = int(report["rejected_sentence_count"]) + abi_state_ids = tuple(result["cognitive_state_ids"]) + abi_fact_ids = { + str(self.state_abi.envelopes[state_id]["content"]["fact_id"]) + for state_id in abi_state_ids + } + admitted_fact_ids = {str(value["fact_id"]) for value in bundle.facts} + quarantine = tuple(dict(value) for value in bundle.payload["quarantine_ledger"]) + result.update({ + "schema_version": SCHEMA, + "admission_contract": { + "source_sentence_count": source_sentences, + "admitted_fact_count": admitted, + "quarantined_sentence_count": quarantined, + "every_source_sentence_accounted": source_sentences == admitted + quarantined, + "abi_registered_fact_count": len(abi_state_ids), + "abi_registry_matches_admitted_facts": abi_fact_ids == admitted_fact_ids, + "quarantined_sentences_entered_abi": False, + "admission_rate": admitted / max(1, source_sentences), + "bounded_relation_grammar": report["claim_boundary"], + "quarantine_reason_counts": { + reason: sum(value["reason"] == reason for value in quarantine) + for reason in sorted({value["reason"] for value in quarantine}) + }, + "quarantine_ledger_sha256": canonical_sha(quarantine), + "minimum_admission_requirement": "at_least_one_authenticated_fact", + }, + }) + return result + + def capabilities(self) -> dict[str, Any]: + value = dict(super().capabilities()) + value.update({ + "schema_version": SCHEMA, + "version": VERSION, + "specialist_admission_accounting": True, + "source_sentences_distinct_from_admitted_facts": True, + "quarantine_is_non_authoritative": True, + "all_source_sentences_accounted": True, + }) + return value + + +__all__ = ["SCHEMA", "SpecialistAdmissionOracleRelationalV3", "VERSION"] diff --git a/root/wander-train/stage5m13b_wikipedia_specialist.py b/root/wander-train/stage5m13b_wikipedia_specialist.py new file mode 100644 index 0000000000000000000000000000000000000000..29977b6376e4ec07ddf6ab11d6d3c562a7d48f25 --- /dev/null +++ b/root/wander-train/stage5m13b_wikipedia_specialist.py @@ -0,0 +1,564 @@ +#!/usr/bin/env python3 +"""Provenance-complete Wikipedia specialist and M13b integrated runtime.""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import sqlite3 +import sys +import time +import unicodedata +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Any, Mapping + + +ROOT = Path(__file__).resolve().parents[1] +RELEASE_SRC = ROOT / "wander-release" / "oracle-relational-v3-hf-v1.0.1-release" / "src" +if str(RELEASE_SRC) not in sys.path: + sys.path.insert(0, str(RELEASE_SRC)) +if str(Path(__file__).resolve().parent) not in sys.path: + sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from oracle_relational_v3.oracle_10d_resolution_state import canonical_sha256 +from oracle_relational_v3.stage5m3a_evidence_addressed_realizer import EvidenceAddressedRealizer, RealizationRequest, SurfaceClause +from oracle_relational_v3.stage5m11a_schema_native_long_horizon_agent import SchemaTool +from stage5m13a_wordnet_specialist import LexicalSessionStore, OracleM13aRuntime + + +SCHEMA = "oracle-stage5m13b-wikipedia-specialist-v3" +INDEX_SCHEMA = "oracle-stage5m13b-wikipedia-sqlite-v3" +RUNTIME_SCHEMA = "oracle-stage5m13b-encyclopedic-runtime-v2" +STOP = frozenset({"a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "how", "in", "is", "it", "of", "on", "or", "the", "to", "was", "were", "what", "when", "where", "which", "who", "why", "with"}) + + +def canonical(value: Any) -> str: + return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + + +def digest(value: Any) -> str: + return hashlib.sha256(canonical(value).encode("utf-8")).hexdigest() + + +def sha_file(path: Path) -> str: + h = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(4 * 1024 * 1024), b""): + h.update(block) + return h.hexdigest() + + +def normalize_title(value: str) -> str: + value = unicodedata.normalize("NFKC", str(value)).casefold().replace("_", " ") + return " ".join(re.sub(r"[^\w]+", " ", value, flags=re.UNICODE).split()) + + +def validate_build(root: Path | str, *, deep: bool = False) -> dict[str, Any]: + root = Path(root).resolve(); manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8")) + if manifest.get("schema_version") != SCHEMA or manifest.get("status") != "compiled": + raise ValueError("unsupported_wikipedia_specialist") + if digest(manifest["semantic_identity"]) != manifest.get("semantic_identity_sha256"): + raise ValueError("wikipedia_specialist_identity_changed") + for relative, registration in manifest["files"].items(): + path = root / relative + if not path.is_file() or path.stat().st_size != int(registration["bytes"]): + raise ValueError(f"wikipedia_specialist_artifact_size_changed:{relative}") + if deep or relative != "wikipedia_specialist.sqlite3": + if sha_file(path) != registration["sha256"]: + raise ValueError(f"wikipedia_specialist_artifact_changed:{relative}") + inventory = json.loads((root / "corpus_inventory.json").read_text(encoding="utf-8")) + if digest({key: value for key, value in inventory.items() if key != "semantic_identity_sha256"}) != inventory.get("semantic_identity_sha256"): + raise ValueError("wikipedia_inventory_changed") + if inventory.get("evaluation_inputs") or inventory.get("evaluation_data_read"): + raise ValueError("evaluation_data_must_not_enter_wikipedia_specialist") + uri = (root / "wikipedia_specialist.sqlite3").as_uri() + "?mode=ro&immutable=1" + connection = sqlite3.connect(uri, uri=True) + metadata = {key: json.loads(value) for key, value in connection.execute("SELECT key,value FROM metadata")} + if metadata != manifest["metrics"] or metadata.get("index_schema") != INDEX_SCHEMA: + raise ValueError("wikipedia_index_metadata_changed") + if deep: + if connection.execute("PRAGMA integrity_check").fetchone()[0] != "ok": + raise ValueError("wikipedia_index_integrity_failed") + counts = { + "articles": connection.execute("SELECT COUNT(*) FROM article").fetchone()[0], + "claims": connection.execute("SELECT COUNT(*) FROM source_rows").fetchone()[0], + "page_sentence_addresses": connection.execute("SELECT COUNT(*) FROM page_sentence").fetchone()[0], + } + if any(counts[key] != metadata[key] for key in counts): + raise ValueError("wikipedia_index_count_changed") + dangling = connection.execute( + "SELECT COUNT(*) FROM page_sentence p LEFT JOIN article a ON a.page_id=p.page_id " + "LEFT JOIN source_rows s ON s.rowid=p.source_rowid WHERE a.page_id IS NULL OR s.rowid IS NULL" + ).fetchone()[0] + if dangling: + raise ValueError("wikipedia_index_dangling_address") + connection.close(); return manifest + + +@dataclass(frozen=True) +class WikipediaClaim: + claim_id: str + fact: str + fact_sha256: str + page_id: str + title: str + canonical_url: str + raw_record_sha256: str + abstract_sha256: str + sentence_ordinal: int + selection: str + rank: float | None = None + + def public(self) -> dict[str, Any]: + return dict(self.__dict__) + + +class WikipediaSpecialist: + def __init__(self, build_root: Path | str, *, deep_validate: bool = False): + self.root = Path(build_root).resolve(); self.manifest = validate_build(self.root, deep=deep_validate) + uri = (self.root / "wikipedia_specialist.sqlite3").as_uri() + "?mode=ro&immutable=1" + self.connection = sqlite3.connect(uri, uri=True, check_same_thread=False); self.connection.row_factory = sqlite3.Row + + def close(self) -> None: + self.connection.close() + + @staticmethod + def _candidate(value: sqlite3.Row) -> dict[str, Any]: + return { + "entity_id": "wikipedia:en:" + str(value["page_id"]), "page_id": str(value["page_id"]), + "title": str(value["title"]), "canonical_url": str(value["canonical_url"]), + "raw_record_sha256": str(value["raw_record_sha256"]), "abstract_sha256": str(value["abstract_sha256"]), + "sentence_count": int(value["sentence_count"]), "admitted_sentence_count": int(value["admitted_sentence_count"]), + } + + def resolve(self, query: str) -> dict[str, Any]: + source = " ".join(str(query).split()) + page_id = None + if match := re.fullmatch(r"wikipedia:en:(\d+)", source.casefold()): + page_id = match.group(1) + if page_id is not None: + row = self.connection.execute("SELECT * FROM article WHERE page_id=?", (page_id,)).fetchone() + return ({"status": "resolved", "method": "exact_page_id", **self._candidate(row)} if row + else {"status": "unresolved", "method": "unknown_page_id", "query": source}) + normalized = normalize_title(source) + rows = self.connection.execute( + "SELECT a.* FROM title_alias t JOIN article a ON a.page_id=t.page_id WHERE t.normalized_title=? ORDER BY CAST(a.page_id AS INTEGER)", + (normalized,), + ).fetchall() + if len(rows) == 1: + return {"status": "resolved", "method": "unique_exact_title", "query": source, **self._candidate(rows[0])} + if rows: + return {"status": "ambiguous", "method": "normalized_title_collision", "query": source, "candidate_count": len(rows), "candidates": [self._candidate(row) for row in rows]} + # A bare numeral can be a real title (including a colliding one), so + # title authority must be exhausted before retaining the convenience + # fallback for callers that pass an unqualified numeric page id. + if source.isdigit(): + row = self.connection.execute("SELECT * FROM article WHERE page_id=?", (source,)).fetchone() + if row: + return {"status": "resolved", "method": "bare_page_id_fallback", **self._candidate(row)} + return {"status": "unresolved", "method": "no_exact_title", "query": source} + + @staticmethod + def _claim(row: sqlite3.Row, selection: str, rank: float | None = None) -> WikipediaClaim: + return WikipediaClaim( + str(row["claim_id"]), str(row["fact"]), str(row["fact_sha256"]), str(row["page_id"]), + str(row["title"]), str(row["canonical_url"]), str(row["raw_record_sha256"]), + str(row["abstract_sha256"]), int(row["sentence_ordinal"]), selection, rank, + ) + + def article_claims(self, page_id: str, *, limit: int = 64) -> list[WikipediaClaim]: + rows = self.connection.execute( + "SELECT s.claim_id,s.fact,s.fact_sha256,s.page_id,s.sentence_ordinal,a.title,a.canonical_url," + "a.raw_record_sha256,a.abstract_sha256 FROM page_sentence p JOIN source_rows s ON s.rowid=p.source_rowid " + "JOIN article a ON a.page_id=p.page_id WHERE p.page_id=? ORDER BY p.sentence_ordinal LIMIT ?", + (str(page_id), int(limit)), + ).fetchall() + return [self._claim(row, "exact_article") for row in rows] + + @staticmethod + def _terms(query: str, *, maximum: int = 8, minimum_length: int = 2) -> list[str]: + tokens = [] + # Match SQLite FTS5 unicode61 word boundaries: retain Unicode letters + # and digits, split punctuation/hyphens, and avoid Python casefold's + # information-losing ß -> ss expansion. + source = unicodedata.normalize("NFKC", str(query)).lower() + for value in re.findall(r"[^\W_]+", source, flags=re.UNICODE): + if len(value) >= minimum_length and value not in STOP and value not in tokens: + tokens.append(value) + if len(tokens) == maximum: + break + return tokens + + @staticmethod + def _fts_variants(value: str) -> list[str]: + variants = [value] + # German-language ASCII transliteration commonly writes ß as ss, + # whereas the preserved unicode61 index keeps ß. Retain the literal + # token and add a bounded alternative rather than rewriting identity. + if "ss" in value: + alternative = value.replace("ss", "ß") + if alternative != value: + variants.append(alternative) + return variants + + @classmethod + def _fts_clause(cls, value: str) -> str: + variants = ['"' + item.replace('"', '""') + '"' for item in cls._fts_variants(value)] + return variants[0] if len(variants) == 1 else "(" + " OR ".join(variants) + ")" + + @classmethod + def _expression(cls, query: str) -> str | None: + tokens = cls._terms(query) + return " AND ".join(cls._fts_clause(value) for value in tokens) if tokens else None + + def search(self, query: str, *, limit: int = 20, exclude_page_ids: set[str] | None = None) -> list[WikipediaClaim]: + expression = self._expression(query) + if not expression: + return [] + rows = self.connection.execute( + "SELECT s.claim_id,s.fact,s.fact_sha256,s.page_id,s.sentence_ordinal,a.title,a.canonical_url," + "a.raw_record_sha256,a.abstract_sha256,bm25(source_rows) AS rank FROM source_rows s " + "JOIN article a ON a.page_id=s.page_id WHERE source_rows MATCH ? ORDER BY rank,s.rowid LIMIT ?", + (expression, max(int(limit) * 4, int(limit))), + ).fetchall() + excluded = exclude_page_ids or set(); selected = [] + for row in rows: + if str(row["page_id"]) in excluded: + continue + selected.append(self._claim(row, "fts_candidate", float(row["rank"]))) + if len(selected) == limit: + break + return selected + + def related_context( + self, + article: Mapping[str, Any], + anchors: list[WikipediaClaim], + *, + limit: int, + ) -> tuple[list[WikipediaClaim], list[str]]: + """Retrieve bounded lexical context without upgrading overlap to truth. + + Sparse abstracts cannot support a multi-paragraph document by + themselves. Expansion therefore uses an OR over deterministic terms + from the exact title and its admitted anchor sentences. Every result + remains an attributed candidate, is limited to two claims per external + page, and carries its exact record and sentence digests. The caller + must keep this authority distinct from exact-article statements. + """ + if limit <= 0: + return [], [] + seed = str(article["title"]) + " " + " ".join(value.fact for value in anchors) + terms = self._terms(seed, maximum=16, minimum_length=3) + if not terms: + return [], [] + expression = " OR ".join(self._fts_clause(value) for value in terms) + rows = self.connection.execute( + "SELECT s.claim_id,s.fact,s.fact_sha256,s.page_id,s.sentence_ordinal,a.title,a.canonical_url," + "a.raw_record_sha256,a.abstract_sha256,bm25(source_rows) AS rank FROM source_rows s " + "JOIN article a ON a.page_id=s.page_id WHERE source_rows MATCH ? ORDER BY rank,s.rowid LIMIT ?", + (expression, max(int(limit) * 12, 256)), + ).fetchall() + excluded = {str(article["page_id"])} + seen = {value.claim_id for value in anchors} + per_page: dict[str, int] = {} + selected: list[WikipediaClaim] = [] + for row in rows: + page_id = str(row["page_id"]) + claim = str(row["claim_id"]) + if page_id in excluded or claim in seen or per_page.get(page_id, 0) >= 2: + continue + seen.add(claim); per_page[page_id] = per_page.get(page_id, 0) + 1 + selected.append(self._claim(row, "fts_lexical_context_candidate", float(row["rank"]))) + if len(selected) == limit: + break + return selected, terms + + @staticmethod + def _hierarchical_spine( + groups: list[list[SurfaceClause]], + objective_sha: str, + ) -> dict[str, Any]: + """Carry a document as nested protected HRR states. + + A long document is not one flat bag of clause bindings. Each paragraph + first receives its own complete ten-node route and terminal cleanup. + Only an opaque paragraph handle then enters the document route. This + preserves the 4:1 root/payload discipline while increasing composition + capacity without early unbinding or a larger vector width. + """ + leaf_spines = [] + paragraph_handles = [] + for index, group in enumerate(groups, 1): + paragraph_sha = canonical_sha256({ + "document_objective": objective_sha, + "paragraph": index, + "clauses": [value.public() for value in group], + }) + leaf = EvidenceAddressedRealizer._spine(group, paragraph_sha) + leaf_spines.append({"paragraph": index, **leaf}) + paragraph_handles.append(SurfaceClause( + f"paragraph_{index:02d}", + paragraph_sha, + "opaque_paragraph_handle", + tuple(claim_id for value in group for claim_id in value.claim_ids), + ("paragraph_terminal_cleanup", paragraph_sha), + )) + document_spine = EvidenceAddressedRealizer._spine(paragraph_handles, objective_sha) + spines = [document_spine, *leaf_spines] + recoveries = [ + {"level": "document", **value} for value in document_spine["recoveries"] + ] + [ + {"level": f"paragraph_{leaf['paragraph']:02d}", **value} + for leaf in leaf_spines for value in leaf["recoveries"] + ] + return { + "schema_version": "oracle-stage5m13b-hierarchical-document-spine-v1", + "levels": 2, + "protected_root_ratio": "4:1", + "route": document_spine["route"], + "tree_nodes_registered": document_spine["tree_nodes_registered"], + "tree_paths_registered": document_spine["tree_paths_registered"], + "paragraph_states": len(leaf_spines), + "pre_malkuth_payload_unbinds": sum(value["pre_malkuth_payload_unbinds"] for value in spines), + "malkuth_payload_unbinds": sum(value["malkuth_payload_unbinds"] for value in spines), + "minimum_protected_root_cosine": min(value["minimum_protected_root_cosine"] for value in spines), + "terminal_cleanup_exact": all(value["terminal_cleanup_exact"] for value in spines), + "minimum_cleanup_margin": min(value["minimum_cleanup_margin"] for value in spines), + "document_spine": document_spine, + "paragraph_spines": leaf_spines, + "recoveries": recoveries, + } + + def realize(self, page_id: str, *, artifact: str = "paragraph", paragraphs: int = 3, query: str | None = None) -> dict[str, Any]: + started = time.perf_counter(); article = self.resolve("wikipedia:en:" + str(page_id)) + limits = {"sentence": 1, "paragraph": 8, "essay": 24, "paper": 36} + if artifact not in limits: + raise ValueError("unsupported Wikipedia artifact") + if article["status"] != "resolved": + return {"schema_version": RUNTIME_SCHEMA, "status": "withheld", "reason": "unknown_page_id", "response": "I need an exact authenticated Wikipedia page address before I can realize that article.", "factual_release": False} + limit = limits[artifact]; claims = self.article_claims(str(page_id), limit=limit); context_terms: list[str] = [] + if len(claims) < limit and artifact in {"essay", "paper"}: + context, context_terms = self.related_context(article, claims, limit=limit-len(claims)) + claims.extend(context) + claims = claims[:limit] + if not claims: + return {"schema_version": RUNTIME_SCHEMA, "status": "withheld", "reason": "no_admitted_article_sentences", "response": "The exact article exists, but no complete provenance-admitted sentence is available for release.", "factual_release": False, "entity": article} + clauses: list[SurfaceClause] = []; references = [] + if artifact != "sentence": + contextual = any(value.selection == "fts_lexical_context_candidate" for value in claims) + introduction = ( + f"This account begins with exact attributed statements from {article['title']} and then adds provenance-preserved lexical context from the Wikipedia snapshot." + if contextual else + f"This account assembles exact attributed statements for {article['title']} from the preserved Wikipedia snapshot." + ) + clauses.append(SurfaceClause( + "synthesis_intro", introduction, + "inferred", tuple(value.claim_id for value in claims), ("exact_page_then_bounded_lexical_context", str(page_id), *context_terms), + )) + for index, claim in enumerate(claims, 1): + citation = f"P{index}" + proof = ("exact_article_sentence" if claim.selection == "exact_article" else "fts_lexical_context_candidate", claim.claim_id, claim.raw_record_sha256, claim.fact_sha256) + clauses.append(SurfaceClause( + f"claim_{index:02d}", claim.fact.rstrip(". ") + f" [{citation}].", "attributed_secondary_source", + (claim.claim_id,), proof, inline_citations=(citation,), + )) + references.append({ + "citation_id": citation, "claim_id": claim.claim_id, "page_id": claim.page_id, "title": claim.title, + "source_url": claim.canonical_url, "raw_record_sha256": claim.raw_record_sha256, + "abstract_sha256": claim.abstract_sha256, "sentence_ordinal": claim.sentence_ordinal, + "fact_sha256": claim.fact_sha256, "selection": claim.selection, "bm25_rank": claim.rank, + "license": self.manifest["source"]["license_name"], + }) + if artifact != "sentence": + clauses.append(SurfaceClause( + "synthesis_boundary", "These are attributed snapshot statements; lexical overlap and retrieval rank establish candidate context only and do not prove that contextual statements are facts about the anchor article, nor do they prove truth, freshness, completeness, or consensus.", + "inferred", tuple(value.claim_id for value in claims), ("secondary_source_authority_boundary",), + )) + request = RealizationRequest("wikipedia", (str(page_id),), artifact, "explain", max(3, min(6, paragraphs))) + groups = EvidenceAddressedRealizer._partition(clauses, request); response, inverse = EvidenceAddressedRealizer._layout(groups, request) + if artifact == "paper": + response = "## Evidence-addressed snapshot account\n\n" + response + "\n\n## Source boundary\n\nEvery numbered citation addresses an exact preserved Wikipedia record; the snapshot date is not present in the preserved source metadata." + objective_sha = canonical_sha256({"page_id": str(page_id), "artifact": artifact, "query": query}) + spine = ( + self._hierarchical_spine(groups, objective_sha) + if artifact in {"essay", "paper"} + else EvidenceAddressedRealizer._spine(clauses, objective_sha) + ) + result = { + "schema_version": RUNTIME_SCHEMA, "status": "answered", "operation": "wikipedia_attributed_realization", + "response": response, "factual_release": True, "authority_class": "attributed_secondary_source", + "entity": article, "claims": [value.public() for value in claims], "clauses": [value.public() for value in clauses], + "references": references, "paragraph_plan": [[value.clause_id for value in group] for group in groups], + "tree_spine": spine, "whole_answer_inverse": inverse, + "audit": { + "exact_raw_record_digests": all(len(value.raw_record_sha256) == 64 for value in claims), + "exact_fact_digests": all(hashlib.sha256(value.fact.encode("utf-8")).hexdigest() == value.fact_sha256 for value in claims), + "retrieval_rank_treated_as_truth": False, "snapshot_freshness_claimed": False, + "exact_article_claims": sum(value.selection == "exact_article" for value in claims), + "lexical_context_claims": sum(value.selection == "fts_lexical_context_candidate" for value in claims), + "lexical_context_terms": context_terms, + "lexical_context_asserted_as_anchor_fact": False, + "pre_malkuth_payload_unbinds": spine["pre_malkuth_payload_unbinds"], "terminal_cleanup_exact": spine["terminal_cleanup_exact"], + "traditional_language_model_calls": 0, "transformer_calls": 0, "pretrained_embedding_calls": 0, + "next_token_predictions": 0, "gradient_steps": 0, + }, "latency_ms": 1000.0 * (time.perf_counter() - started), + } + result["artifact_sha256"] = canonical_sha256({key: value for key, value in result.items() if key not in {"latency_ms", "artifact_sha256"}}) + return result + + def realize_search(self, query: str, *, artifact: str = "paragraph", paragraphs: int = 3) -> dict[str, Any]: + claims = self.search(query, limit={"sentence": 1, "paragraph": 8, "essay": 24, "paper": 36}.get(artifact, 8)) + if not claims: + return {"schema_version": RUNTIME_SCHEMA, "status": "unresolved", "operation": "wikipedia_search_unresolved", "response": "No provenance-admitted Wikipedia sentence matched all bounded query terms.", "factual_release": False} + # Anchor the realization on the top result's exact page while retaining + # the original query as the bounded expansion objective. + result = self.realize(claims[0].page_id, artifact=artifact, paragraphs=paragraphs, query=query) + result["status"] = "partial"; result["operation"] = "wikipedia_attributed_search_roundup" + result["reason"] = "no_exact_title_but_bounded_fts_evidence_available" + result["response"] = ( + f"No exact preserved article title was found for {query!r}; the following is an attributed evidence roundup selected by bounded term relevance, not an assertion of page identity.\n\n" + + result["response"] + ) + result["artifact_sha256"] = canonical_sha256({key: value for key, value in result.items() if key not in {"latency_ms", "artifact_sha256"}}) + return result + + +class WikipediaConversation: + DOCUMENT = re.compile(r"^\s*(?:please\s+)?(?:write|compose|draft|produce|create|give\s+me)\s+(?:a\s+|an\s+)?(?:(?P[3-6])[-\s]+paragraph\s+)?(?Pessay|paper|paragraph|sentence)\s+(?:about|on|explaining|concerning)\s+(?P.+?)\s*[?.!]*$", re.I) + QUESTION = re.compile(r"^\s*(?:(?:what|who)\s+(?:is|are)|tell\s+me\s+about|describe|explain|give\s+me\s+an?\s+(?:account|overview)\s+of)\s+(?P.+?)\s*[?.!]*$", re.I) + MORE = re.compile(r"^\s*(?:tell\s+me\s+more|go\s+on|continue|expand(?:\s+that)?|say\s+more)\s*[?.!]*$", re.I) + + def __init__(self, specialist: WikipediaSpecialist, state_root: Path | str): + self.specialist = specialist; self.sessions = LexicalSessionStore(Path(state_root) / "wikipedia_sessions") + + @staticmethod + def clean_topic(value: str) -> str: + value = value.strip() + return re.sub(r"\s+(?:briefly|please|in detail)$", "", value, flags=re.I).strip(" .?!") + + def preview(self, text: str) -> dict[str, Any] | None: + source = " ".join(str(text).split()) + if match := self.DOCUMENT.match(source): + return {"topic": self.clean_topic(match.group("topic")), "artifact": match.group("artifact").casefold(), "paragraphs": int(match.group("count") or 3)} + if match := self.QUESTION.match(source): + artifact = "sentence" if source.casefold().startswith(("what is", "what are", "who is", "who are")) else "paragraph" + return {"topic": self.clean_topic(match.group("topic")), "artifact": artifact, "paragraphs": 3} + return None + + def chat(self, text: str, *, session_id: str = "default") -> dict[str, Any]: + started = time.perf_counter(); source = " ".join(str(text).split()); act = self.preview(source); prior = self.sessions.load(session_id).get("last") + if act is None and self.MORE.match(source) and prior: + act = {"topic": "wikipedia:en:" + str(prior["page_id"]), "artifact": "essay", "paragraphs": 5} + if act is None: + return {"schema_version": RUNTIME_SCHEMA, "status": "unresolved", "operation": "wikipedia_act_unresolved", "response": "No encyclopedic discourse act was compiled.", "factual_release": False, "latency_ms": 1000.0 * (time.perf_counter() - started)} + resolution = self.specialist.resolve(act["topic"]) + # Preserve literal title identity first (for example, "The Food + # Album"). A conversational article is removed only as an explicitly + # bounded fallback when no preserved literal title exists (for + # example, "the French Revolution"). + if resolution["status"] == "unresolved" and re.match(r"^(?:the|a|an)\s+", act["topic"], re.I): + fallback_topic = re.sub(r"^(?:the|a|an)\s+", "", act["topic"], count=1, flags=re.I) + fallback = self.specialist.resolve(fallback_topic) + if fallback["status"] != "unresolved": + resolution = {**fallback, "conversational_article_fallback": True, "original_topic": act["topic"]} + if resolution["status"] == "ambiguous": + choices = "; ".join(f"{value['entity_id']} — {value['title']}" for value in resolution["candidates"]) + result = {"schema_version": RUNTIME_SCHEMA, "status": "clarification", "operation": "wikipedia_title_clarification", "response": "That normalized title identifies more than one preserved page. Specify a page ID: " + choices, "factual_release": False, "resolution": resolution} + result["session"] = self.sessions.append(session_id, source, result, None); return result + if resolution["status"] == "resolved": + result = self.specialist.realize(resolution["page_id"], artifact=act["artifact"], paragraphs=act["paragraphs"], query=act["topic"]) + state = {"page_id": resolution["page_id"], "title": resolution["title"]} + else: + result = self.specialist.realize_search(act["topic"], artifact=act["artifact"], paragraphs=act["paragraphs"]) + state = {"page_id": result.get("entity", {}).get("page_id"), "title": result.get("entity", {}).get("title")} if result.get("entity") else None + result["latency_ms"] = 1000.0 * (time.perf_counter() - started) + result["session"] = self.sessions.append(session_id, source, result, state) + return result + + +class OracleM13bRuntime: + """M13a lexical Oracle plus a provenance-complete Wikipedia tier.""" + + def __init__(self, state_root: Path | str, *, wordnet_build: Path | str, wikipedia_build: Path | str, **m12_options: Any): + self.state_root = Path(state_root).resolve(); self.state_root.mkdir(parents=True, exist_ok=True) + self.lexical_runtime = OracleM13aRuntime(self.state_root / "m13a", wordnet_build=wordnet_build, **m12_options) + self.base = self.lexical_runtime.base; self.wordnet = self.lexical_runtime.wordnet + self.wikipedia = WikipediaSpecialist(wikipedia_build); self.encyclopedic = WikipediaConversation(self.wikipedia, self.state_root / "encyclopedic") + self._augment_tools() + + def _augment_tools(self) -> None: + registry = self.base.tool_registry; wiki_claims = int(self.wikipedia.manifest["metrics"]["claims"]) + for name in ("inspect_oracle", "list_specialists"): + tool = registry.tools[name] + if name == "inspect_oracle": + parent = tool.executor + def inspect(value: Mapping[str, Any], executor=parent, count=wiki_claims) -> dict[str, Any]: + result = dict(executor(value)); result["version"] = "1.2.0-m13b-dev"; result["domains"] = int(result["domains"]) + 1; result["claims"] = int(result["claims"]) + count; return result + registry.tools[name] = replace(tool, executor_id="oracle.m13b.inspect.v1", executor=inspect) + else: + parent = tool.executor + def listed(value: Mapping[str, Any], executor=parent, count=wiki_claims) -> dict[str, Any]: + result = dict(executor(value)); domains = list(result["domains"]); domains.append({"domain": "wikipedia", "claims": count, "expert_id": "generalist_wikipedia_snapshot"}); return {"domains": domains, "total_claims": int(result["total_claims"]) + count} + registry.tools[name] = replace(tool, executor_id="oracle.m13b.specialists.v1", executor=listed) + + def resolve_wikipedia(arguments: Mapping[str, Any]) -> dict[str, Any]: + value = self.wikipedia.resolve(str(arguments["query"])) + return {"status": value["status"], "method": value["method"], "entity_id": str(value.get("entity_id", "")), "candidate_count": int(value.get("candidate_count", 0)), "candidates": list(value.get("candidates", ()))} + registry.register(SchemaTool( + "resolve_wikipedia", "Resolve an exact preserved Wikipedia title or page identifier.", + {"type": "object", "properties": {"query": {"type": "string", "minLength": 1, "maxLength": 256}}, "required": ["query"], "additionalProperties": False}, + {"type": "object", "properties": {"status": {"type": "string"}, "method": {"type": "string"}, "entity_id": {"type": "string"}, "candidate_count": {"type": "integer"}, "candidates": {"type": "array", "items": {"type": "object"}}}, "required": ["status", "method", "entity_id", "candidate_count", "candidates"], "additionalProperties": False}, + "read_only", "oracle.m13b.wikipedia-resolution.v1", resolve_wikipedia, ("resolve wikipedia title",), + )) + + def search_wikipedia(arguments: Mapping[str, Any]) -> dict[str, Any]: + rows = self.wikipedia.search(str(arguments["query"]), limit=int(arguments.get("limit", 5))) + return {"query": str(arguments["query"]), "count": len(rows), "claims": [value.public() for value in rows]} + registry.register(SchemaTool( + "search_wikipedia", "Retrieve provenance-addressed attributed statements matching all bounded query terms.", + {"type": "object", "properties": {"query": {"type": "string", "minLength": 1, "maxLength": 256}, "limit": {"type": "integer", "minimum": 1, "maximum": 20}}, "required": ["query"], "additionalProperties": False}, + {"type": "object", "properties": {"query": {"type": "string"}, "count": {"type": "integer"}, "claims": {"type": "array", "items": {"type": "object"}}}, "required": ["query", "count", "claims"], "additionalProperties": False}, + "read_only", "oracle.m13b.wikipedia-search.v1", search_wikipedia, ("search encyclopedia",), + )) + + def chat(self, text: str, *, session_id: str = "default") -> dict[str, Any]: + source = " ".join(str(text).split()) + if re.match(r"^(?:call|use)\b", source, re.I) or (re.search(r"\b(?:essay|document|account|treatise|report)\b", source, re.I) and re.search(r"\b(?:oracle|yourself|your architecture|what it is like|being this architecture)\b", source, re.I)): + return self.lexical_runtime.chat(source, session_id=session_id) + # Preserve the accepted curated tier wherever its own language program + # resolves an authenticated topic. Wikipedia is the fallback breadth + # tier, not an authority upgrade over the more specific M10 sources. + curated_program = self.base.conversation.transducer.compile(source, session_id=session_id) + if curated_program.get("status") == "compiled" and curated_program.get("topics"): + return self.base.chat(source, session_id=session_id) + act = self.encyclopedic.preview(source) + if act and len(act["topic"].split()) == 1: + lexical = self.wordnet.resolve(act["topic"], pos="n", allow_dominant=True) + if lexical.get("status") == "ambiguous": + return self.lexical_runtime.chat(source, session_id=session_id) + wiki = self.encyclopedic.chat(source, session_id=session_id) + if wiki.get("status") in {"answered", "partial", "clarification"}: + wiki["hot_loaded_specialist"] = "wikipedia_abstract_snapshot" + return wiki + return self.lexical_runtime.chat(source, session_id=session_id) + + def capabilities(self) -> dict[str, Any]: + value = dict(self.lexical_runtime.capabilities()) + value.update({ + "schema_version": RUNTIME_SCHEMA, + "wikipedia_articles": int(self.wikipedia.manifest["metrics"]["articles"]), + "wikipedia_claims": int(self.wikipedia.manifest["metrics"]["claims"]), + "wikipedia_unique_titles": int(self.wikipedia.manifest["metrics"]["unique_titles"]), + "secondary_source_attribution_preserved": True, + "retrieval_rank_is_factual_authority": False, + "snapshot_date_known": False, + "unrestricted_conversation": False, + }) + return value + + +__all__ = ["OracleM13bRuntime", "WikipediaClaim", "WikipediaConversation", "WikipediaSpecialist", "validate_build", "RUNTIME_SCHEMA", "SCHEMA"] diff --git a/root/wander-train/stage5m13e2_construction_kernel_k3.py b/root/wander-train/stage5m13e2_construction_kernel_k3.py new file mode 100644 index 0000000000000000000000000000000000000000..8ee074074acc73c829ed53543e96c72cdf777dba --- /dev/null +++ b/root/wander-train/stage5m13e2_construction_kernel_k3.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""M13e2 K3: fold-donated construction rules (first fold pass, M13e4 fold protocol). + +Rule families donated by the residue of the 2026-08-16 essay fold, each promoted +because it compresses multiple independent (surface, program) pairs: + 1. intransitive verb phrases (Alexandria burned. / The substrate existed.) + 2. bare-noun arguments (Writing externalized memory.) + 3. adjective stacking in nominals (the first compiled artifact) + 4. adverb-modified adjectives (architecturally absent) + 5. of-PP nominal complements (the grammar of Sanskrit) + 6. modal verbs can/could + aux intransitives (A machine can speak.) +Banked residue (registered, NOT patched): free relatives, reduced relatives, +object complements ("made the mind affordable"). +""" + +from __future__ import annotations + +import stage5m13e2_construction_kernel_k2 as k2 +from stage5m13e2_construction_kernel import CLOSED_CLASS, Item, _get, _sem +from stage5m13e2_construction_kernel_k2 import ConstructionKernelK2 + +SCHEMA = "oracle-stage5m13e2-construction-kernel-k3-v1" + +# modal verbs join the modal inventory (K2's inversion and lexicon read this dict) +k2.MODALS.update({"can": "can", "could": "could"}) +CLOSED_CLASS |= {"of", "can", "could"} + + +class ConstructionKernelK3(ConstructionKernelK2): + def _lexical(self, token: str, position: int): + low = token.casefold() + span = (position, position + 1) + items = super()._lexical(token, position) + # closed-class and wh tokens must not carry open-class readings: 'not' is not + # a verb, 'What' is not a bare noun, 'Three' is not a name (fold pass-1/3 laws) + if low in k2.WH_WORDS: + items = [item for item in items if item.category not in {"N", "ADJ", "VBASE", "VF"}] + elif low in CLOSED_CLASS: + items = [item for item in items if item.category not in {"N", "ADJ", "VBASE", "VF", "NAME"}] + if low == "of": + items.append(Item("OF", _sem(), span)) + if low.endswith("ly") and low.isalpha() and len(low) > 4: + items.append(Item("ADVLY", _sem(lemma=low), span)) + # Greek/Latin singulars in -is/-us are not plurals (diagnosis, basis, bus) + if low.endswith(("is", "us")) and low.isalpha(): + items = [Item("N", _sem(lemma=low), item.span) if item.category == "N" else item for item in items] + return items + + def _parse_tokens(self, tokens, question: bool): + # copular inversion with an of-PP subject: "Is the king of Norwind a sailor?" + from stage5m13e2_construction_kernel import ARTICLES, COPULAS, QUANTIFIERS + if (question and tokens and tokens[0].casefold() in COPULAS and len(tokens) >= 6 + and tokens[1].casefold() in (ARTICLES | set(QUANTIFIERS)) and tokens[3].casefold() == "of"): + aux, rest = tokens[0], tokens[1:] + # subject NP spans 4 tokens (of + name) or 5 (of + article + noun) + np_length = 5 if len(rest) >= 5 and rest[3].casefold() in ARTICLES else 4 + tokens = [*rest[:np_length], aux, *rest[np_length:]] + return ConstructionKernelK2._parse_tokens(self, tokens, False) + return super()._parse_tokens(tokens, question) + + def _combine(self, left: Item, right: Item): + out = super()._combine(left, right) + span = (left.span[0], right.span[1]) + # 3. adjective stacking: ADJ N -> N with joined lemma (recursive, feeds DET/Q rules) + if left.category == "ADJ" and right.category == "N": + out.append(Item("N", _sem(lemma=f"{_get(left.semantics, 'lemma')} {_get(right.semantics, 'lemma')}"), span)) + # 4. adverb-modified adjective: ADVLY ADJ -> ADJ with joined lemma + if left.category == "ADVLY" and right.category == "ADJ": + out.append(Item("ADJ", _sem(lemma=f"{_get(left.semantics, 'lemma')} {_get(right.semantics, 'lemma')}"), span)) + # 5. of-PP nominal complement: (OF, NAME|N) -> PPOF ; (N, PPOF) -> N joined + if left.category == "OF" and right.category in {"NAME", "N"}: + tail = _get(right.semantics, "name") or _get(right.semantics, "lemma") + out.append(Item("PPOF", _sem(tail=str(tail).casefold()), span)) + if left.category == "N" and right.category == "PPOF": + out.append(Item("N", _sem(lemma=f"{_get(left.semantics, 'lemma')} of {_get(right.semantics, 'tail')}"), span)) + # 2. bare-noun object: VF N -> VP (mass/abstract nouns as arguments) + if left.category == "VF" and right.category == "N": + out.append(Item("VP", _sem(kind="verb", lemma=_get(left.semantics, "lemma"), + obj=("definite", _get(right.semantics, "lemma")), + polarity="+", tense=_get(left.semantics, "tense")), span)) + if left.category == "VBASE" and right.category == "N": + out.append(Item("VPBASE", _sem(lemma=_get(left.semantics, "lemma"), + obj=("definite", _get(right.semantics, "lemma"))), span)) + # 1. intransitive clause: (NAME|DNP|QNP) VF -> CL with no object + if left.category in {"NAME", "DNP", "QNP"} and right.category == "VF": + from stage5m13e2_construction_kernel import _subject_of + out.append(Item("CL", _sem(subject=_subject_of(left), + vp=_sem(kind="verb", lemma=_get(right.semantics, "lemma"), + obj=None, polarity="+", tense=_get(right.semantics, "tense"))), span)) + # 6a. modal + bare verb: MODAL VBASE -> VP (intransitive, modality carried) + if left.category == "MODAL" and right.category == "VBASE": + out.append(Item("VP", _sem(kind="verb", lemma=_get(right.semantics, "lemma"), obj=None, + polarity="+", tense="present", + modality=_get(left.semantics, "modality")), span)) + # 6b. modal + transitive base: MODAL VPBASE -> VP + if left.category == "MODAL" and right.category == "VPBASE": + out.append(Item("VP", _sem(kind="verb", lemma=_get(right.semantics, "lemma"), + obj=_get(right.semantics, "obj"), polarity="+", tense="present", + modality=_get(left.semantics, "modality")), span)) + # 6c. aux intransitives: AUX VBASE -> VP ; AUXNEG VBASE -> VP (negated) + if left.category == "AUX" and right.category == "VBASE": + out.append(Item("VP", _sem(kind="verb", lemma=_get(right.semantics, "lemma"), obj=None, + polarity="+", tense=_get(left.semantics, "tense")), span)) + if left.category == "AUXNEG" and right.category == "VBASE": + out.append(Item("VP", _sem(kind="verb", lemma=_get(right.semantics, "lemma"), obj=None, + polarity="-", tense=_get(left.semantics, "tense")), span)) + return out + + +__all__ = ["ConstructionKernelK3", "SCHEMA"] diff --git a/root/wander-train/train_stage2a_role_ladder.py b/root/wander-train/train_stage2a_role_ladder.py new file mode 100644 index 0000000000000000000000000000000000000000..dd41b479c88d50b20f99b8f3ceb2cd1a7487d2e1 --- /dev/null +++ b/root/wander-train/train_stage2a_role_ladder.py @@ -0,0 +1,592 @@ +#!/usr/bin/env python3 +"""Oracle Phase 2A: compose role-bound specialists and fit bounded routing heads. + +The language/knowledge object is the recursive HRR ladder. Training the +specialist means composing its symbolic, role, Tree-path, Tree-node, literal, +continuation, and protected-root states into that ladder; it does not require +backpropagation. A small ridge head is fitted on frozen carrier features only +for operator/modality/path/node routing. If a carrier feature archive is not +supplied, a deterministic lexical feature map provides a local smoke mode. + +This script deliberately reports two different evaluations: + * construction recovery: can every composed record be recovered at Malkuth? + * held-out routing: can a head fitted on train topics route unseen topics? +Construction recovery is not presented as generalization. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import re +import time +from collections import Counter +from functools import lru_cache +from pathlib import Path +from typing import Any, Iterable + +import numpy as np + + +HRR_DIM = 1024 +SEPHIROTH = ( + "keter", "chokmah", "binah", "chesed", "geburah", + "tiferet", "netzach", "hod", "yesod", "malkuth", +) +PATHS = ( + ("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", "hod"), ("tiferet", "yesod"), + ("netzach", "hod"), ("netzach", "yesod"), ("netzach", "malkuth"), + ("hod", "yesod"), ("hod", "malkuth"), ("yesod", "malkuth"), +) +OPERATIONS = ( + "analogy", "mechanism", "contrast", "synthesis", "return_to_root", + "conversational_continuation", "clarification_repair", +) +MODALITIES = ("equation", "sequence", "poem", "ascii") +ROLE_NAMES = ("root", "source", "field", "transition", "result", "thesis", "counterthesis") +PRIMARY_NODE = { + "analogy": "chokmah", + "mechanism": "hod", + "contrast": "geburah", + "synthesis": "tiferet", + "return_to_root": "yesod", + "conversational_continuation": "netzach", + "clarification_repair": "binah", +} +OP_TO_IDX = {name: index for index, name in enumerate(OPERATIONS)} +MOD_TO_IDX = {name: index for index, name in enumerate(MODALITIES)} +NODE_TO_IDX = {name: index for index, name in enumerate(SEPHIROTH)} +PATH_TO_IDX: dict[tuple[str, str], int] = {} +for _index, (_a, _b) in enumerate(PATHS): + PATH_TO_IDX[(_a, _b)] = _index + PATH_TO_IDX[(_b, _a)] = _index + +TOKENS = re.compile(r"[a-z0-9']+|[^\w\s]", re.I) + + +def _seed_int(label: str) -> int: + return int.from_bytes(hashlib.blake2b(label.encode("utf-8"), digest_size=8).digest(), "little") + + +@lru_cache(maxsize=100_000) +def unitary(label: str) -> np.ndarray: + rng = np.random.default_rng(_seed_int(label)) + raw = rng.normal(0.0, 1.0 / math.sqrt(HRR_DIM), HRR_DIM) + freq = np.fft.fft(raw.astype(np.complex128)) + freq /= np.maximum(np.abs(freq), 1e-12) + return np.fft.ifft(freq).astype(np.complex64) + + +def bind(a: np.ndarray, b: np.ndarray) -> np.ndarray: + return np.fft.ifft(np.fft.fft(a) * np.fft.fft(b)).astype(np.complex64) + + +def unbind(c: np.ndarray, key: np.ndarray) -> np.ndarray: + return np.fft.ifft(np.fft.fft(c) * np.conj(np.fft.fft(key))).astype(np.complex64) + + +def normalize(v: np.ndarray) -> np.ndarray: + n = float(np.linalg.norm(v)) + return (v / max(n, 1e-12)).astype(np.complex64) + + +def cosine(a: np.ndarray, b: np.ndarray) -> float: + den = float(np.linalg.norm(a) * np.linalg.norm(b)) + return float(abs(np.vdot(a, b)) / max(den, 1e-12)) + + +@lru_cache(maxsize=50_000) +def text_hrr(text: str) -> np.ndarray: + """Compositional text state: token, position-role, and adjacent relation.""" + toks = TOKENS.findall(text.lower()) or [""] + state = np.zeros(HRR_DIM, dtype=np.complex64) + previous: np.ndarray | None = None + for index, token in enumerate(toks[:256]): + token_vec = unitary(f"token:{token}") + placed = bind(unitary(f"text-position:{index % 16}"), token_vec) + state += placed + if previous is not None: + relation = bind(unitary("text-relation:next"), bind(previous, token_vec)) + state += np.complex64(0.45) * relation + previous = token_vec + return normalize(state) + + +def as_real(v: np.ndarray) -> np.ndarray: + return np.concatenate((v.real, v.imag)).astype(np.float32) + + +def from_real(v: np.ndarray) -> np.ndarray: + return (v[:HRR_DIM] + 1j * v[HRR_DIM:]).astype(np.complex64) + + +@lru_cache(maxsize=20_000) +def address_key(order: int, address: tuple[int, int, int, int, int]) -> np.ndarray: + key = unitary(f"ladder-role:{order}:0") + key = bind(key, unitary(f"ladder-coord:0:{address[0]}")) + for primitive, coordinate in enumerate(address[1:], start=1): + component = bind( + unitary(f"ladder-role:{order}:{primitive}"), + unitary(f"ladder-coord:{primitive}:{coordinate}"), + ) + key = bind(key, component) + return normalize(key) + + +def grammar_key(order: int) -> np.ndarray: + return unitary(f"ladder-meta-transform:{order}") + + +def compose_order(order: int, children: list[tuple[tuple[int, int, int, int, int], np.ndarray]]) -> np.ndarray: + state = np.zeros(HRR_DIM, dtype=np.complex64) + for address, child in children: + state += bind(child, address_key(order, address)) + return bind(normalize(state), grammar_key(order)) + + +def cleanup(candidate: np.ndarray, siblings: list[np.ndarray]) -> tuple[np.ndarray, int, float]: + scores = [cosine(candidate, sibling) for sibling in siblings] + winner = int(np.argmax(scores)) + return siblings[winner], winner, scores[winner] + + +def semantic_address(record: dict[str, Any], branch: int) -> tuple[int, int, int, int, int]: + operation = record["operation"] + return ( + NODE_TO_IDX[PRIMARY_NODE[operation]], # 4D semantic Tree route + OP_TO_IDX[operation], # 6D callable/operator + branch % 10, # 7D router-set member + MOD_TO_IDX[record["symbolic_modality"]], # 8D grammar/register + (branch + len(record["conversation_state"])) % 10,# 9D discourse position + ) + + +def build_nested_record(record: dict[str, Any]) -> dict[str, Any]: + roles = record["role_binding_map"] + level1_values = [text_hrr(record["symbolic_emission"])] + [text_hrr(roles[name]) for name in ROLE_NAMES] + level1_children = [(semantic_address(record, i), value) for i, value in enumerate(level1_values)] + order1 = compose_order(1, level1_children) + + tree = build_tree_state(record) + level2_values = [order1, text_hrr(record["literal_decode"]), tree["transport"]] + level2_children = [(semantic_address(record, i), value) for i, value in enumerate(level2_values)] + order2 = compose_order(2, level2_children) + + level3_values = [order2, text_hrr(record["next_conversational_move"]), text_hrr(record["root_question"])] + level3_children = [(semantic_address(record, i), value) for i, value in enumerate(level3_values)] + order3 = compose_order(3, level3_children) + return { + "top": order3, + "levels": (level1_values, level2_values, level3_values), + "children": (level1_children, level2_children, level3_children), + "tree": tree, + } + + +def recover_nested(nested: dict[str, Any], target: str) -> tuple[np.ndarray, np.ndarray, list[float]]: + """The universal unbinder is exposed only through this Malkuth resolution.""" + levels = nested["levels"] + children = nested["children"] + current = nested["top"] + cleanup_scores: list[float] = [] + + if target in ("symbolic", "role"): + branch_path = (0, 0, 0 if target == "symbolic" else 1) + orders = (3, 2, 1) + elif target == "literal_decode": + branch_path = (0, 1) + orders = (3, 2) + elif target == "continuation": + branch_path = (1,) + orders = (3,) + elif target == "root": + branch_path = (2,) + orders = (3,) + else: + raise ValueError(target) + + expected = None + for order, branch in zip(orders, branch_path): + current = unbind(current, grammar_key(order)) + current = unbind(current, address_key(order, children[order - 1][branch][0])) + sibling_values = levels[order - 1] + expected = sibling_values[branch] + current, winner, score = cleanup(current, sibling_values) + cleanup_scores.append(score) + if winner != branch: + break + assert expected is not None + return current, expected, cleanup_scores + + +def lane_key(kind: str, name: str) -> np.ndarray: + return unitary(f"tree-lane:{kind}:{name}") + + +def build_tree_state(record: dict[str, Any]) -> dict[str, Any]: + root_value = text_hrr(record["root_question"]) + content_value = text_hrr(record["prompt"]) + root_role = unitary("tree:protected-root") + content_role = unitary("tree:content") + protected_root = bind(root_role, root_value) + lanes: list[tuple[str, np.ndarray, np.ndarray]] = [] + for item in record["path_outputs"]: + name = item["path"] + artifact = text_hrr(item["delta"]) + folded = normalize(bind(unitary(f"tree-fold:path:{name}"), artifact)) + lanes.append((f"path:{name}", lane_key("path", name), folded)) + for item in record["node_outputs"]: + name = item["node"] + artifact = text_hrr(item["artifact"]) + folded = normalize(bind(unitary(f"tree-fold:node:{name}"), artifact)) + lanes.append((f"node:{name}", lane_key("node", name), folded)) + transport = bind(root_role, root_value) + bind(content_role, content_value) + for _, key, value in lanes: + transport += np.complex64(0.72) * bind(key, value) + return { + "transport": normalize(transport), + "protected_root": protected_root, + "root_role": root_role, + "root_value": root_value, + "lanes": lanes, + } + + +def resolve_tree_at_malkuth(record: dict[str, Any], tree: dict[str, Any]) -> dict[str, Any]: + if record["tree_route"]["end"] != "malkuth": + raise ValueError("semantic unbinding is restricted to Malkuth") + recovered_root = unbind(tree["protected_root"], tree["root_role"]) + expected_values = [value for _, _, value in tree["lanes"]] + lane_cosines: list[float] = [] + correct = 0 + for lane_index, (_, key, value) in enumerate(tree["lanes"]): + recovered = unbind(tree["transport"], key) + lane_cosines.append(cosine(recovered, value)) + _, winner, _ = cleanup(recovered, expected_values) + correct += int(winner == lane_index) + return { + "root_cosine": cosine(recovered_root, tree["root_value"]), + "mean_lane_cosine": float(np.mean(lane_cosines)), + "minimum_lane_cosine": float(np.min(lane_cosines)), + "cleanup_accuracy": correct / max(len(expected_values), 1), + "active_lanes": len(tree["lanes"]), + "intermediate_unbinds": 0, + } + + +def stable_bucket(feature: str, size: int) -> tuple[int, float]: + raw = hashlib.blake2b(feature.encode("utf-8"), digest_size=9).digest() + index = int.from_bytes(raw[:8], "little") % size + sign = 1.0 if raw[8] & 1 else -1.0 + return index, sign + + +def lexical_features(text: str, size: int) -> np.ndarray: + tokens = TOKENS.findall(text.lower()) + vector = np.zeros(size, dtype=np.float32) + features: list[str] = [f"u:{token}" for token in tokens] + features += [f"b:{a}|{b}" for a, b in zip(tokens, tokens[1:])] + compact = " ".join(tokens) + features += [f"c:{compact[i:i+3]}" for i in range(max(0, len(compact) - 2))] + for feature in features: + index, sign = stable_bucket(feature, size) + vector[index] += sign + norm = float(np.linalg.norm(vector)) + if norm > 0: + vector /= norm + return vector + + +def macro_f1(truth: np.ndarray, predicted: np.ndarray, n_classes: int) -> float: + scores = [] + for label in range(n_classes): + tp = int(np.sum((truth == label) & (predicted == label))) + fp = int(np.sum((truth != label) & (predicted == label))) + fn = int(np.sum((truth == label) & (predicted != label))) + precision = tp / max(tp + fp, 1) + recall = tp / max(tp + fn, 1) + scores.append(2 * precision * recall / max(precision + recall, 1e-12)) + return float(np.mean(scores)) + + +def micro_f1(truth: np.ndarray, predicted: np.ndarray) -> float: + truth_b = truth.astype(bool) + pred_b = predicted.astype(bool) + tp = int(np.sum(truth_b & pred_b)) + fp = int(np.sum(~truth_b & pred_b)) + fn = int(np.sum(truth_b & ~pred_b)) + return 2 * tp / max(2 * tp + fp + fn, 1) + + +def binomial_tail(n: int, k: int, probability: float) -> float: + """Exact one-sided binomial tail, accumulated stably in log space.""" + if k <= 0: + return 1.0 + if k > n: + return 0.0 + if probability <= 0.0: + return 0.0 + if probability >= 1.0: + return 1.0 + log_p = math.log(probability) + log_q = math.log1p(-probability) + log_n_factorial = math.lgamma(n + 1) + terms = [ + log_n_factorial + - math.lgamma(successes + 1) + - math.lgamma(n - successes + 1) + + successes * log_p + + (n - successes) * log_q + for successes in range(k, n + 1) + ] + peak = max(terms) + return min(1.0, float(math.exp(peak) * sum(math.exp(term - peak) for term in terms))) + + +def wilson_interval(n: int, k: int, z: float = 1.959963984540054) -> list[float]: + proportion = k / max(n, 1) + denominator = 1 + z * z / max(n, 1) + center = (proportion + z * z / (2 * max(n, 1))) / denominator + radius = z * math.sqrt( + proportion * (1 - proportion) / max(n, 1) + z * z / (4 * max(n, 1) ** 2) + ) / denominator + return [max(0.0, center - radius), min(1.0, center + radius)] + + +def load_records(path: Path) -> list[dict[str, Any]]: + with path.open("r", encoding="utf-8") as handle: + return [json.loads(line) for line in handle if line.strip()] + + +def build_targets(records: list[dict[str, Any]]) -> tuple[np.ndarray, dict[str, slice]]: + widths = {"operator": 7, "modality": 4, "nodes": 10, "paths": 22} + slices: dict[str, slice] = {} + offset = 0 + for name, width in widths.items(): + slices[name] = slice(offset, offset + width) + offset += width + targets = np.zeros((len(records), offset), dtype=np.float32) + for row, record in enumerate(records): + targets[row, slices["operator"].start + OP_TO_IDX[record["operation"]]] = 1.0 + targets[row, slices["modality"].start + MOD_TO_IDX[record["symbolic_modality"]]] = 1.0 + for node in record["tree_route"]["nodes"]: + targets[row, slices["nodes"].start + NODE_TO_IDX[node]] = 1.0 + nodes = record["tree_route"]["nodes"] + for a, b in zip(nodes, nodes[1:]): + targets[row, slices["paths"].start + PATH_TO_IDX[(a, b)]] = 1.0 + return targets, slices + + +def load_features( + records: list[dict[str, Any]], feature_path: Path | None, hash_dim: int, + carrier_mode: str, +) -> tuple[np.ndarray, str]: + lexical = np.stack([lexical_features(record["prompt"], hash_dim) for record in records]) + if feature_path is None: + return lexical, "deterministic_lexical_smoke" + archive = np.load(feature_path, allow_pickle=False) + ids = [str(value) for value in archive["ids"]] + by_id = {value: index for index, value in enumerate(ids)} + if set(by_id) != {record["id"] for record in records}: + missing = sorted({record["id"] for record in records} - set(by_id)) + raise ValueError(f"carrier feature archive does not match corpus; missing={missing[:5]}") + order = [by_id[record["id"]] for record in records] + carrier_parts = [] + for name in ("pooled", "comp_emb", "sephirah_logits"): + if name in archive: + carrier_parts.append(np.asarray(archive[name][order], dtype=np.float32)) + if not carrier_parts: + raise ValueError("carrier feature archive has no pooled/comp_emb/sephirah_logits arrays") + carrier = np.concatenate(carrier_parts, axis=1) + norms = np.linalg.norm(carrier, axis=1, keepdims=True) + carrier = carrier / np.maximum(norms, 1e-8) + if carrier_mode == "carrier-only": + return carrier, "frozen_carrier_only" + return np.concatenate((carrier, lexical), axis=1), "frozen_carrier_plus_lexical_roles" + + +def fit_ridge_head(x: np.ndarray, y: np.ndarray, train_mask: np.ndarray, ridge: float) -> np.ndarray: + xt = x[train_mask].astype(np.float64) + yt = y[train_mask].astype(np.float64) + gram = xt @ xt.T + gram.flat[:: gram.shape[0] + 1] += ridge + alpha = np.linalg.solve(gram, yt) + return (xt.T @ alpha).astype(np.float32) + + +def evaluate_routing( + records: list[dict[str, Any]], x: np.ndarray, y: np.ndarray, + weights: np.ndarray, slices: dict[str, slice], split: str, +) -> dict[str, Any]: + mask = np.array([record["split"] == split for record in records]) + scores = x[mask] @ weights + truth = y[mask] + op_true = truth[:, slices["operator"]].argmax(axis=1) + op_pred = scores[:, slices["operator"]].argmax(axis=1) + mod_true = truth[:, slices["modality"]].argmax(axis=1) + mod_pred = scores[:, slices["modality"]].argmax(axis=1) + confusion = np.zeros((len(OPERATIONS), len(OPERATIONS)), dtype=int) + for actual, predicted in zip(op_true, op_pred): + confusion[actual, predicted] += 1 + node_true = truth[:, slices["nodes"]] + path_true = truth[:, slices["paths"]] + node_pred = scores[:, slices["nodes"]] >= 0.5 + path_pred = scores[:, slices["paths"]] >= 0.5 + n_records = int(mask.sum()) + op_correct = int(np.sum(op_true == op_pred)) + modality_correct = int(np.sum(mod_true == mod_pred)) + return { + "records": n_records, + "operator_correct": op_correct, + "operator_accuracy": op_correct / n_records, + "operator_macro_f1": macro_f1(op_true, op_pred, len(OPERATIONS)), + "operator_chance": 1 / len(OPERATIONS), + "operator_binomial_p_one_sided": binomial_tail(n_records, op_correct, 1 / len(OPERATIONS)), + "operator_accuracy_wilson_95": wilson_interval(n_records, op_correct), + "operator_confusion": confusion.tolist(), + "modality_correct": modality_correct, + "modality_accuracy": modality_correct / n_records, + "modality_chance": 1 / len(MODALITIES), + "modality_binomial_p_one_sided": binomial_tail(n_records, modality_correct, 1 / len(MODALITIES)), + "node_micro_f1": micro_f1(node_true, node_pred), + "path_micro_f1": micro_f1(path_true, path_pred), + } + + +def percentile(values: Iterable[float], q: float) -> float: + return float(np.quantile(np.asarray(list(values), dtype=float), q)) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--corpus", type=Path, required=True) + parser.add_argument("--carrier-features", type=Path) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--metrics", type=Path, required=True) + parser.add_argument("--hash-dim", type=int, default=768) + parser.add_argument("--ridge", type=float, default=0.20) + parser.add_argument("--carrier-mode", choices=("carrier-only", "carrier-plus-lexical"), + default="carrier-plus-lexical") + args = parser.parse_args() + if args.hash_dim < 64: + raise ValueError("hash dimension must be at least 64") + + started = time.perf_counter() + records = load_records(args.corpus) + features, feature_mode = load_features(records, args.carrier_features, args.hash_dim, args.carrier_mode) + targets, target_slices = build_targets(records) + train_mask = np.array([record["split"] == "train" for record in records]) + weights = fit_ridge_head(features, targets, train_mask, args.ridge) + + nested_tops = np.empty((len(records), HRR_DIM), dtype=np.complex64) + tree_states = np.empty((len(records), HRR_DIM), dtype=np.complex64) + nested_success = Counter() + nested_scores: list[float] = [] + lane_cosines: list[float] = [] + lane_cleanup: list[float] = [] + root_cosines: list[float] = [] + max_lanes = 0 + for index, record in enumerate(records): + nested = build_nested_record(record) + nested_tops[index] = nested["top"] + tree_states[index] = nested["tree"]["transport"] + for target in ("symbolic", "literal_decode", "continuation", "root"): + recovered, expected, scores = recover_nested(nested, target) + ok = cosine(recovered, expected) > 0.999 + nested_success[target] += int(ok) + nested_scores.extend(scores) + resolved = resolve_tree_at_malkuth(record, nested["tree"]) + lane_cosines.append(resolved["mean_lane_cosine"]) + lane_cleanup.append(resolved["cleanup_accuracy"]) + root_cosines.append(resolved["root_cosine"]) + max_lanes = max(max_lanes, resolved["active_lanes"]) + + train_specialist_centroids = {} + for operation in OPERATIONS: + selected = [nested_tops[i] for i, record in enumerate(records) + if record["split"] == "train" and record["operation"] == operation] + train_specialist_centroids[operation] = normalize(np.sum(selected, axis=0)) + + args.out.parent.mkdir(parents=True, exist_ok=True) + np.savez_compressed( + args.out, + schema_version=np.array("oracle-phase2a-role-ladder-v1"), + ids=np.asarray([record["id"] for record in records]), + splits=np.asarray([record["split"] for record in records]), + operations=np.asarray([record["operation"] for record in records]), + nested_top_real=nested_tops.real.astype(np.float32), + nested_top_imag=nested_tops.imag.astype(np.float32), + tree_state_real=tree_states.real.astype(np.float32), + tree_state_imag=tree_states.imag.astype(np.float32), + specialist_names=np.asarray(OPERATIONS), + specialist_real=np.stack([train_specialist_centroids[name].real for name in OPERATIONS]).astype(np.float32), + specialist_imag=np.stack([train_specialist_centroids[name].imag for name in OPERATIONS]).astype(np.float32), + routing_weights=weights, + feature_mode=np.array(feature_mode), + hash_dim=np.array(args.hash_dim), + ridge=np.array(args.ridge), + ) + + construction = { + "record_count": len(records), + "nested_recovery_accuracy": { + target: nested_success[target] / len(records) + for target in ("symbolic", "literal_decode", "continuation", "root") + }, + "nested_cleanup_score_mean": float(np.mean(nested_scores)), + "nested_cleanup_score_p05": percentile(nested_scores, 0.05), + "tree_root_cosine_minimum": float(np.min(root_cosines)), + "tree_lane_cosine_mean": float(np.mean(lane_cosines)), + "tree_lane_cosine_p05": percentile(lane_cosines, 0.05), + "tree_cleanup_accuracy_mean": float(np.mean(lane_cleanup)), + "tree_cleanup_accuracy_minimum": float(np.min(lane_cleanup)), + "maximum_active_lanes_per_record": max_lanes, + "fixed_lane_capacity": len(SEPHIROTH) + len(PATHS), + "intermediate_semantic_unbinds": 0, + "malkuth_only_resolution": True, + } + held_out = { + split: evaluate_routing(records, features, targets, weights, target_slices, split) + for split in ("dev", "test") + } + metrics = { + "schema_version": "oracle-phase2a-metrics-v1", + "feature_mode": feature_mode, + "carrier_features": str(args.carrier_features.resolve()) if args.carrier_features else None, + "train_records": int(train_mask.sum()), + "trainable_head_values": int(weights.size), + "compose_and_fit_seconds": time.perf_counter() - started, + "construction_recovery": construction, + "held_out_routing": held_out, + "gates": { + "construction_pass": all(value == 1.0 for value in construction["nested_recovery_accuracy"].values()) + and construction["tree_cleanup_accuracy_minimum"] >= 0.95 + and construction["intermediate_semantic_unbinds"] == 0, + "routing_schema_pass": held_out["test"]["operator_accuracy"] > 1 / len(OPERATIONS) + and held_out["test"]["operator_macro_f1"] > 1 / len(OPERATIONS) + and held_out["test"]["node_micro_f1"] >= 0.80 + and held_out["test"]["path_micro_f1"] >= 0.75, + "natural_paraphrase_gate_evaluated": False, + "trained_open_ended_decoder": False, + }, + "routing_probe_difficulty": "operator and modality are explicitly stated in bootstrap prompts", + "claim_boundary": ( + "Construction recovery tests stored compositional structure. Held-out routing tests unseen topics. " + "No open-ended decoder is trained by this stage, so conversational reasoning is not yet established." + ), + } + args.metrics.parent.mkdir(parents=True, exist_ok=True) + args.metrics.write_text(json.dumps(metrics, indent=2) + "\n", encoding="utf-8") + print(json.dumps(metrics, indent=2)) + return 0 if metrics["gates"]["construction_pass"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/root/wander-train/verified_retrieval_v1.py b/root/wander-train/verified_retrieval_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..0382d329ea1859df1f9967a3eaa1a634d74107ed --- /dev/null +++ b/root/wander-train/verified_retrieval_v1.py @@ -0,0 +1,80 @@ +"""verified_retrieval_v1 - a retrieved sentence is not an answer until something independent checks it. + +The four weak retrieval routes (full-text search, page reading, corpus lookup, the bridge/compose readers) answer from a +sentence that is near the question; on four sealed tests they were right about half the time, while every checked route +(maths, specialists, network, the typed relation reader, the reasoning cube) was right ~95%. LAW (09-09): a proposal must +be checked by something independent of what generated it. The independent checker already exists: the reasoning cube's +CHECK (the candidate's OWN page must say it is the asked type; agent/patient role; every other name and year of the +question attested; a value unique in its sentence). This layer routes every weak-route answer through it: + 1. the cube's own full chain answers the question (frame -> link -> bind -> check -> verify): its answer stands; + 2. else the weak route's own sentence yields exactly one candidate of the asked type, and that candidate passes the + cube's CHECK with the question's linked subject: the weak answer stands, restated with the checked value first; + 3. else the reply is WITHHELD; the passage is still shown, marked unverified. +verify(q, out, cube) -> new out (or None when the turn is not a weak-route answer).""" +import re + +WEAK = ("factoid:fts", "factoid:page", "corpus_query", "compose:bridge", "compose:both", "compose:comparison", + "arb:definitional", "arb:timeline", "arb:list_n", "arb:compare", "definitional_encyclopedic") +TAGS = re.compile(r"\[ev:[a-z_]+\]|\[[a-z]+_[0-9a-f]{6,}\]|\[\d+\]") + + +def _sentence(resp): + s = TAGS.sub(" ", str(resp)) + s = " ".join(s.split()) + first = re.split(r"(?<=[.!?])\s+(?=[A-Z])", s, 1)[0] + return first.strip() + + +def _norm(s): + return " ".join(re.findall(r"[a-z0-9]+", str(s).lower())) + + +def verify(q, out, cube): + if not isinstance(out, dict) or out.get("status") != "answered": + return None + path = str(out.get("path", "")) + if not path.startswith(WEAK): + return None + new = dict(out) + # 1. the cube's own checked chain + try: + a = cube.answer(q) + except Exception: # noqa: BLE001 + a = None + if a: + new.update({"status": "answered", "path": "verified:cube>%s|%s" % (a["type"], path), + "response": "%s. %s [%s]" % (a["answer"], a["sentence"], a.get("claim")), + "references": [a.get("claim")], "provenance": {"kind": "verified_retrieval", "by": "cube", "check": a.get("check"), + "weak_path": path}}) + return new + # 2. the weak route's own sentence, checked independently + try: + fr = cube.frame(q) + subs = cube.link(fr) if fr else None + except Exception: # noqa: BLE001 + fr, subs = None, None + sent = _sentence(out.get("response", "")) + if fr and subs and sent: + try: + vals = list(dict.fromkeys(cube._candidates(fr, sent, _norm(fr["q"])))) + except Exception: # noqa: BLE001 + vals = [] + if len(vals) == 1: + for subj in subs[:2]: + c = {"value": vals[0], "sentence": sent, "subject": subj, "claim": None, "score": 0.0} + try: + ok, ev = cube.check(fr, c) + except Exception: # noqa: BLE001 + ok, ev = False, {} + if ok: + new.update({"path": "verified:weak>%s|%s" % (fr["atype"], path), + "response": "%s. %s" % (vals[0], str(out.get("response", ""))), + "provenance": {"kind": "verified_retrieval", "by": "cube_check_on_weak", "check": ev, "weak_path": path}}) + return new + # 3. unverified: shown, not asserted + new.update({"status": "withheld", "path": "unverified:%s" % path, + "response": "I found a passage that may be related, but I can't verify it answers your question: \"%s\"" % sent[:300], + "references": out.get("references", []), + "provenance": {"kind": "verified_retrieval", "by": None, "weak_path": path, + "weak_response": str(out.get("response", ""))[:400]}}) + return new diff --git a/workbench/data/cards/acoustics.md b/workbench/data/cards/acoustics.md new file mode 100644 index 0000000000000000000000000000000000000000..6a1916a9cb6ed336f095e80dece7384cacd50c18 --- /dev/null +++ b/workbench/data/cards/acoustics.md @@ -0,0 +1,25 @@ +# Oracle7 Acoustics & Sound (#49, tier A) + +**id** `acoustics` - organ `organ_acoustics_v1.AcousticsOrgan` composed in front of the frozen head `oracle_release_runtime_w363`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 69/69 (false yes 0) vs head 3/69 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Speed of sound in dry air v = 331.3 sqrt(1 + T/273.15) m/s; fresh water 1481 m/s at 20 C (stated in every answer) (facts / physics) https://en.wikipedia.org/wiki/Speed_of_sound +- Decibel, Doppler, pipe and string harmonic formulas (OpenStax University Physics vol. 1, ch. 17) (CC-BY 4.0) https://openstax.org/details/books/university-physics-volume-1 + +## What it takes + +- answers: beat, doppler, db_sum, db_distance, db_ratio, intensity_ratio, string, pipe_closed, pipe_open, wavelength, frequency, speed +- declines (in-domain): underspecified, impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +Formulas shown in every answer; air at 20 C stated whenever no temperature is given. Panel formulas written independently in acoustics_panel_v1.py. Dev fixes before held-out: one reply wording aligned to 'The X is N' (scorer unchanged), 'honk/whistle/hear' added as sound cues. diff --git a/workbench/data/cards/agriculture-v2.md b/workbench/data/cards/agriculture-v2.md new file mode 100644 index 0000000000000000000000000000000000000000..95d07f67e9c9f019bda9c3c9d572f782fe5bdc01 --- /dev/null +++ b/workbench/data/cards/agriculture-v2.md @@ -0,0 +1,26 @@ +# Oracle7 Agriculture & Crop Science v2 (#99, tier B) + +**id** `agriculture-v2` - organ `organ_agriculture_v2.AgricultureOrganV2` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 17/17 (false yes 0) vs head 1/17 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- USDA / land-grant extension: fertilizer grade arithmetic, seeding rate from spacing, standard bushel test weights (USDA AMS), acre-inch (public domain (US government)) https://www.ams.usda.gov/ + +## What it takes + +- answers: fert_product, nutrient_lb, seeds_per_acre, seeds_needed, yield_kgha, yield_tha, acre_inch +- declines (in-domain): impossible, underspecified +- everything else falls through to the head unchanged + +Supersedes: agriculture (v1 NEGATIVE under gate v3: 2 wrong from head fallthrough) + +## Notes and known gaps + +v2 = v1 + hyphenated bag sizes ('40-pound bag'), 'lb/acre of N', and RECOGNISE-THEN-DECLINE for fertilizer-grade questions it cannot read. v1 NEGATIVE under gate v3: held-out 14/17 vs 1/17 but 2 WRONG - the head's 0 and -15 on '40-pound bag of 20-10-10' turns the organ fell silent on. Fresh panel v2 (seeds 999999/99999999). Same author - disclosed. diff --git a/workbench/data/cards/airquality.md b/workbench/data/cards/airquality.md new file mode 100644 index 0000000000000000000000000000000000000000..0f499434f107d430d440538a754dc12e328dee08 --- /dev/null +++ b/workbench/data/cards/airquality.md @@ -0,0 +1,25 @@ +# Oracle7 Air Quality & Atmosphere (#7, tier B) + +**id** `airquality` - organ `organ_airquality_v1.AirQualityOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 30/38 (false yes 0) vs head 2/38 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- EPA AQI breakpoint table (AQS code table; 2024 PM2.5 revision), verified 2026-09-29 (public domain (US government)) https://aqs.epa.gov/aqsweb/documents/codetables/aqi_breakpoints.html +- EPA Technical Assistance Document for the Reporting of Daily Air Quality - the AQI (truncation rules, interpolation) (public domain (US government)) https://document.airnow.gov/technical-assistance-document-for-the-reporting-of-daily-air-quailty.pdf + +## What it takes + +- answers: aqi, overall, category +- declines (in-domain): impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +Standard averaging periods assumed and stated (PM 24-hour, O3/CO 8-hour, SO2/NO2 1-hour); ozone in ppb converted to ppm. Beyond-the-AQI, 8-hour ozone above 0.200 ppm and 1-hour SO2 above 304 ppb declined (other tables apply); hourly PM (NowCast) not computed. No personal health advice (should I / is it safe for me turns fall through). Panel computes its own expectations from the verified table. Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/algorithms.md b/workbench/data/cards/algorithms.md new file mode 100644 index 0000000000000000000000000000000000000000..f49ec305e06bf0efd0f74acdf0772e544a53416d --- /dev/null +++ b/workbench/data/cards/algorithms.md @@ -0,0 +1,24 @@ +# Oracle7 Algorithms & Data Structures (#57, tier A) + +**id** `algorithms` - organ `organ_algorithms_v1.AlgorithmsOrgan` composed in front of the frozen head `oracle_release_runtime_w363`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 42/42 (false yes 0) vs head 1/42 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Standard algorithms (Dijkstra, Kruskal, binary search, comparison sort) executed on the user's own input; textbook complexity bounds (Cormen et al. / Wikibooks Algorithms, CC-BY-SA) in a small stated table (execution / CC-BY-SA (table facts)) https://en.wikibooks.org/wiki/Algorithms + +## What it takes + +- answers: shortest_path, unreachable, mst, disconnected, bsearch, not_found, sorted, complexity +- declines (in-domain): underspecified, no_node, negative, unsorted +- everything else falls through to the head unchanged + +## Notes and known gaps + +Answers by EXECUTION on the stated graph or list; the panel's expectations come from DIFFERENT algorithms (Floyd-Warshall, Prim, bisect). Binary search refuses an unsorted list; Dijkstra refuses negative weights. Requests to WRITE code are left to the head (full-core sweep caught one). diff --git a/workbench/data/cards/architecture.md b/workbench/data/cards/architecture.md new file mode 100644 index 0000000000000000000000000000000000000000..4f4ced6e2331bd566a678f64f06dcaeff3465a94 --- /dev/null +++ b/workbench/data/cards/architecture.md @@ -0,0 +1,25 @@ +# Oracle7 Architecture (zoning and code arithmetic) (#88, tier B) + +**id** `architecture` - organ `organ_architecture_v1.ArchitectureOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 10/10 (false yes 0) vs head 1/10 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- International Building Code 2021 - occupant load factors (Table 1004.5) and egress width (1005.3); zoning FAR and lot coverage definitions (facts (code values)) https://codes.iccsafe.org/content/IBC2021P2 +- 2010 ADA Standards for Accessible Design 405.2 (ramp running slope 1:12) (public domain (US government)) https://www.ada.gov/law-and-regs/design-standards/2010-stds/ + +## What it takes + +- answers: far, max_floor, coverage, occupant_load, egress_width, ramp_run +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Model-code values (IBC 2021, ADA 2010) named in every answer; local codes and amendments govern real projects. Aesthetic questions are not taken. Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/arthistory.md b/workbench/data/cards/arthistory.md new file mode 100644 index 0000000000000000000000000000000000000000..cea7c7c04600db0cc094e181098a2fdc7a089694 --- /dev/null +++ b/workbench/data/cards/arthistory.md @@ -0,0 +1,24 @@ +# Oracle7 Art History (attribution) (#87, tier B) + +**id** `arthistory` - organ `organ_facts_v1.FactsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 11/11 (false yes 0) vs head 6/11 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- The Metropolitan Museum of Art Open Access (CC0) and museum collection records (attribution facts) (CC0 / facts) https://www.metmuseum.org/about-the-met/policies-and-documents/open-access + +## What it takes + +- answers: artist +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Typed-fact organ: attributions of famous works; opinions, prices and interpretations are blocked. Narrowed (narrow_v1). diff --git a/workbench/data/cards/astronomy-v3.md b/workbench/data/cards/astronomy-v3.md new file mode 100644 index 0000000000000000000000000000000000000000..1de25adedbf3ea3d85ff2995a4bb2efe99a639c6 --- /dev/null +++ b/workbench/data/cards/astronomy-v3.md @@ -0,0 +1,27 @@ +# Oracle7 Astronomy v3 (#16, tier A) + +**id** `astronomy-v3` - organ `organ_astronomy_v3.AstronomyOrganV3` composed in front of the frozen head `oracle_release_runtime_w363`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 137/138 (false yes 0) vs head 9/138 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- NASA NSSDCA Planetary Fact Sheet (8 planets, the Moon, Pluto; 20 properties) (public domain (NASA)) https://nssdc.gsfc.nasa.gov/planetary/factsheet/ +- OpenStax Astronomy 2e (already in the core's world stores) (CC-BY 4.0) https://openstax.org/details/books/astronomy-2e + +## What it takes + +- answers: mass, diameter, density, gravity, escape_velocity, length_of_day, rotation_period, distance_from_the_sun, orbital_period, orbital_velocity, orbital_eccentricity, axial_tilt, mean_temperature, surface_pressure, number_of_moons, ring_system, magnetic_field, light_time, weight, ratio, year_years, distance_from_earth +- declines (in-domain): unknown, no_value +- everything else falls through to the head unchanged + +Supersedes: astronomy-v2 (ADMIT 2026-09-29 01:41 UTC, held-out 130/138; 8 misses = ratio direction) + +## Notes and known gaps + +v3 = v2 + comparison DIRECTION read from grammar (the body after relative to / than / exceed / compared to|with / versus / divided by / 'ratio of X to Y' is the reference). v2's held-out found 8 inverted ratios ('Relative to Mars, how many times as massive is Mercury?' answered Mars/Mercury). Judged under spec_gate_v2 on a FRESH panel v3 (seed 161616, new phrasings both splits, reference-first comparisons, fictional worlds mostly NOT on the organ's list). Same author - disclosed. diff --git a/workbench/data/cards/biology.md b/workbench/data/cards/biology.md new file mode 100644 index 0000000000000000000000000000000000000000..8682a03d30bff5c4ecb3d728be98eda313636b29 --- /dev/null +++ b/workbench/data/cards/biology.md @@ -0,0 +1,25 @@ +# Oracle7 Biology (molecular sequences) (#26, tier A) + +**id** `biology` - organ `organ_biology_v1.BiologyOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 15/15 (false yes 0) vs head 1/15 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- OpenStax Biology 2e ch. 14-15 (DNA structure, transcription, translation, the genetic code) (CC-BY 4.0) https://openstax.org/details/books/biology-2e +- NCBI Genetic Codes - translation table 1 (the standard code) (public domain (US government)) https://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi + +## What it takes + +- answers: codon, gc, revcomp, complement, transcribe, translate, protein_len +- declines (in-domain): impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +Standard genetic code (NCBI table 1); translation from the first base, stops at the first stop codon (said so); never guesses a reading frame for a length not divisible by 3. The broader biology curriculum (MMLU biology) is not covered by this organ - v1 is the sequence core. Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/carbonmat.md b/workbench/data/cards/carbonmat.md new file mode 100644 index 0000000000000000000000000000000000000000..5624399d05a51b8fef69762b99a97f5a2dfef4e9 --- /dev/null +++ b/workbench/data/cards/carbonmat.md @@ -0,0 +1,24 @@ +# Oracle7 Carbon Materials (Nanotubes & Graphene) (#92, tier B) + +**id** `carbonmat` - organ `organ_carbonmat_v1.CarbonMatOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 17/17 (false yes 0) vs head 1/17 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Graphene lattice constant 0.246 nm, graphite interlayer 0.335 nm, CNT chirality rules (diameter, chiral angle, metallic when n - m divisible by 3) - NIST nanomaterials / standard solid-state texts (facts) https://www.nist.gov/topics/nanotechnology + +## What it takes + +- answers: cnt_diameter, cnt_angle, cnt_type, cnt_kind, graphene_layers, graphene_mass +- declines (in-domain): impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +Ideal (unrelaxed) geometry from the graphene lattice; the metallic rule is the zone-folding rule (small-diameter curvature gaps not modelled - a property of the rule). Aerogel porosity lives in #40 materials. Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/childdev.md b/workbench/data/cards/childdev.md new file mode 100644 index 0000000000000000000000000000000000000000..4596db29b72fbc1bfb121ebde0ea4376656a071e --- /dev/null +++ b/workbench/data/cards/childdev.md @@ -0,0 +1,25 @@ +# Oracle7 Child Development (#70, tier C) + +**id** `childdev` - organ `organ_facts_v1.FactsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 9/9 (false yes 0) vs head 1/9 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- OpenStax Lifespan Development / Psychology 2e (CC BY 4.0) https://openstax.org/details/books/psychology-2e +- AAP safe sleep (via CDC / NIH Safe to Sleep) (public domain (US government)) https://safetosleep.nichd.nih.gov/ + +## What it takes + +- answers: childdev +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Typed-fact organ (tier C): developmental-psychology textbook facts. A particular child, delays, diagnosis and 'is it normal' are blocked (the head answers). Narrowed (narrow_v1). diff --git a/workbench/data/cards/climate.md b/workbench/data/cards/climate.md new file mode 100644 index 0000000000000000000000000000000000000000..7392829432848daf8b6a00340535271df33ec919 --- /dev/null +++ b/workbench/data/cards/climate.md @@ -0,0 +1,25 @@ +# Oracle7 Climate Science (#22, tier B) + +**id** `climate` - organ `organ_climate_v1.ClimateOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 24/24 (false yes 0) vs head 3/24 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- NOAA Global Monitoring Laboratory / NASA climate basics; CO2 forcing 5.35 ln(C/C0) (Myhre et al. 1998, adopted by IPCC TAR); Stefan-Boltzmann effective temperature (public domain (US government) / facts) https://gml.noaa.gov/aggi/aggi.html +- Global Carbon Project conversion 1 ppm CO2 = 2.124 GtC (facts) https://www.globalcarbonproject.org/carbonbudget/ + +## What it takes + +- answers: forcing, warming_ecs, warming_lambda, ppm_to_gtc, ppm_to_gtco2, mass_to_ppm, effective_temp, co2e +- declines (in-domain): underspecified, impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +Warming ONLY with a sensitivity or lambda given (the sensitivity is uncertain - never assumed); CO2e ONLY with a GWP given (values differ by IPCC report). Never projects future climate (will / by-a-year / project turns fall through). Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/cooking-v3.md b/workbench/data/cards/cooking-v3.md new file mode 100644 index 0000000000000000000000000000000000000000..3470f9a59680866db433f6c4bc9437a84b3d8751 --- /dev/null +++ b/workbench/data/cards/cooking-v3.md @@ -0,0 +1,27 @@ +# Oracle7 Cooking & Nutrition v3 (#61, tier A) + +**id** `cooking-v3` - organ `organ_nutrition_v3.NutritionOrganV3` composed in front of the frozen head `oracle_release_runtime_w363`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 224/228 (false yes 0) vs head 10/228 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- USDA FoodData Central SR Legacy 2018-04 (public domain (US government work)) https://fdc.nal.usda.gov/ +- Project Gutenberg cookbooks (2,533 recipes, already in the core via the conversation organ) (public domain) https://www.gutenberg.org/ + +## What it takes + +- answers: nutrient +- declines (in-domain): unknown_food, no_value, no_portion, clarify +- everything else falls through to the head unchanged + +Supersedes: cooking-v2 (ADMIT gate v2, 155/210; misses = 'Can you give me the X content of ...' lost its question word) + +## Notes and known gaps + +v3 = v2 + 'What is' restored when frame stripping leaves no question word. Judged under spec_gate_v2 on a FRESH panel (new seeds, new phrasings both splits including the class). Same author - disclosed. Earlier notes: v2 = v1 + one defect-class fix found by v1's held-out verdict: the question frame (contractions, content/amount/level/value, polite frames) leaked into the food name and v1 declined (59 held-out misses, all safe declines). Judged on a FRESH panel v2: seed 6161, a different food partition, new frame-heavy phrasings for both splits, new invented foods. v1's held-out stays sealed. Same author wrote the organ and the fresh phrasings - disclosed. diff --git a/workbench/data/cards/crafts.md b/workbench/data/cards/crafts.md new file mode 100644 index 0000000000000000000000000000000000000000..6a2e612d5bc3d4547194e61d513ae4ac0dfa3f6b --- /dev/null +++ b/workbench/data/cards/crafts.md @@ -0,0 +1,25 @@ +# Oracle7 Arts & Crafts (#75, tier B) + +**id** `crafts` - organ `organ_crafts_v1.CraftsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 14/14 (false yes 0) vs head 1/14 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Craft Yarn Council gauge conventions; quilting 1/4 in seam allowance convention; traditional RYB and additive RGB colour models (standard art / physics references) (facts) https://www.craftyarncouncil.com/standards +- Project Gutenberg craft manuals (public domain) - background (public domain) https://www.gutenberg.org/ + +## What it takes + +- answers: mix_ryb, mix_rgb, complement, cast_on, quilt_blocks, cut_size, yards, mat_outer, clay_fired +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Conventions named (gauge rounding, 1/4 in seams, RYB vs RGB). Taste questions are not taken. Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/cyber.md b/workbench/data/cards/cyber.md new file mode 100644 index 0000000000000000000000000000000000000000..8f70b935688492f916b77fd34c59d55f96a4c235 --- /dev/null +++ b/workbench/data/cards/cyber.md @@ -0,0 +1,25 @@ +# Oracle7 Cybersecurity (Defensive) (#56, tier A) + +**id** `cyber` - organ `organ_cyber_v1.CyberOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 16/20 (false yes 1) vs head 1/20 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- NIST SP 800-63B (memorized secrets), NIST CSRC glossary (entropy, hash functions, FIPS 180-4 digest sizes) (public domain (US government)) https://pages.nist.gov/800-63-3/sp800-63b.html +- RFC 4648 (Base64 encoding) (IETF Trust (BCP 78)) https://www.rfc-editor.org/rfc/rfc4648 + +## What it takes + +- answers: keyspace, entropy, brute_worst, brute_avg, base64_len, digest_hex, birthday +- declines (in-domain): underspecified +- everything else falls through to the head unchanged + +## Notes and known gaps + +Defensive arithmetic only: entropy assumes a RANDOM password over the named set (human-chosen passwords are weaker - NIST 800-63B). Brute-force time only at a STATED guess rate. 'How do I crack / bypass / break into' turns fall through, never answered. Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/economics.md b/workbench/data/cards/economics.md new file mode 100644 index 0000000000000000000000000000000000000000..fd8f73370f426a7cc557966dfd58930bc11eb8a2 --- /dev/null +++ b/workbench/data/cards/economics.md @@ -0,0 +1,24 @@ +# Oracle7 Economics (#83, tier A) + +**id** `economics` - organ `organ_economics_v1.EconomicsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 26/39 (false yes 0) vs head 3/39 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- OpenStax Principles of Economics 3e (elasticity midpoint method, CPI and inflation, real vs nominal, Fisher relation, multipliers, labour-market rates, GDP deflator, rule of 70) (CC-BY 4.0) https://openstax.org/details/books/principles-economics-3e + +## What it takes + +- answers: elasticity, inflation, real_value, real_rate, growth, multiplier, tax_multiplier, unemployment, participation, deflator, rule70 +- declines (in-domain): underspecified, impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +Introductory economics arithmetic, formula named in every answer; Fisher approximation primary with the exact value stated; rule of 70 labelled an approximation. Roles from grammar and years (earlier year = base), never order of mention. Never forecasts, never advises (will-X-rise / should-I / invest turns fall through). Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/electrical.md b/workbench/data/cards/electrical.md new file mode 100644 index 0000000000000000000000000000000000000000..6329c3bd5b45d2e4174dd360f46fa561bea18682 --- /dev/null +++ b/workbench/data/cards/electrical.md @@ -0,0 +1,24 @@ +# Oracle7 Electrical Engineering (Power) (#50, tier A) + +**id** `electrical` - organ `organ_electrical_v1.ElectricalOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 22/24 (false yes 0) vs head 2/24 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- US Navy Electrical Engineering Training Series (NEETS) Module 2 (AC), Module 5 (generators/transformers), three-phase power relations (public domain (US government)) https://www.navy.mil/ + +## What it takes + +- answers: three_phase_kw, three_phase_kva, three_phase_current, wye_vline, delta_iline, pf, reactive, pf_correction, xfmr_v, xfmr_i, hp_kw, kw_hp +- declines (in-domain): underspecified, impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +Ideal transformer; balanced three-phase; mechanical horsepower 745.7 W. Real power needs a stated power factor (never assumed). A ratio 'N:1' is primary:secondary. Narrowed from the start (narrow_v1); no numbers rule. diff --git a/workbench/data/cards/embedded.md b/workbench/data/cards/embedded.md new file mode 100644 index 0000000000000000000000000000000000000000..5c2c1f58170479031c211bd5b04747e3bb4f1992 --- /dev/null +++ b/workbench/data/cards/embedded.md @@ -0,0 +1,25 @@ +# Oracle7 Embedded Systems & Microcontrollers (#59, tier B) + +**id** `embedded` - organ `organ_embedded_v1.EmbeddedOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 25/25 (false yes 0) vs head 1/25 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Arduino documentation (timers, Serial / UART framing) (CC-BY-SA 3.0 (store ships share-alike)) https://docs.arduino.cc/ +- AVR timer CTC relation f = f_clk / (N (1 + OCR)) and UBRR = f_clk / (16 baud) - 1 (Microchip ATmega328P datasheet formulas) (facts) https://www.microchip.com/en-us/product/ATmega328P + +## What it takes + +- answers: tick, tick_freq, overflow, overflow_freq, ctc, uart_time, uart_throughput, ubrr, address_space, address_bytes +- declines (in-domain): impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +AVR conventions named (CTC, UBRR normal asynchronous mode); UART 8N1 unless stated. A CTC value that does not fit the timer is declined with the reason (use a larger prescaler). Narrowed from the start (narrow_v1); NO numbers rule (LAW 2026-09-29). diff --git a/workbench/data/cards/energy-v3.md b/workbench/data/cards/energy-v3.md new file mode 100644 index 0000000000000000000000000000000000000000..f064e25a515aafa8c6f03e3b69df90b2193deeef --- /dev/null +++ b/workbench/data/cards/energy-v3.md @@ -0,0 +1,26 @@ +# Oracle7 Home Energy & Solar v3 (#5, tier B) + +**id** `energy-v3` - organ `organ_energy_v3.EnergyOrganV3` composed in front of the frozen head `oracle_release_runtime_w502`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 69/70 (false yes 1) vs head 3/70 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Energy arithmetic (kWh = W x h / 1000; Wh = V x Ah; PV yield = kW x peak sun hours x derate) as in DOE Energy Saver and NREL PVWatts documentation (public domain (US government)) https://www.energy.gov/energysaver/estimating-appliance-and-home-electronic-energy-use + +## What it takes + +- answers: payback, never, runtime, solar_yield, swap_saving, cost, energy +- declines (in-domain): underspecified, need_tariff, impossible +- everything else falls through to the head unchanged + +Supersedes: energy-v2 (ADMIT gate v2, 66/74, but 8 misses CONFIDENT WRONG: passive swap answered with energy used) + +## Notes and known gaps + +v3 = v2 + passive swap ('X W bulb is replaced by a Y W LED') + asked-quantity rule (a SAVING question is never answered with what is used). Judged under spec_gate_v3 (wrong-answer cap) on a FRESH panel v3. Same author - disclosed. v2 = v1 + payback roles from grammar (saving = the amount attached to save; cost = a DIFFERENT amount; no cost -> decline) - v1's held-out answered 'A heat pump saves $900 a year. How long is the payback?' with 1 year ($900/$900) and was NEGATIVE; + 'costs' read as 'cost'. Judged under spec_gate_v2 on a FRESH panel v2 (saving stated before cost in half the payback items). Same author - disclosed. Never assumes a tariff, price or sun-hours it was not given (a cost with no tariff gives the kWh and asks for the price). Losses stated: solar 'before losses' unless given; battery runtime before inverter and depth-of-discharge losses. Full-core pre-check: 0 of 3107 items taken. Dev fixes before hel diff --git a/workbench/data/cards/finance-v2.md b/workbench/data/cards/finance-v2.md new file mode 100644 index 0000000000000000000000000000000000000000..731a9e31f3dffe5e5780f00a040e52416f6afac2 --- /dev/null +++ b/workbench/data/cards/finance-v2.md @@ -0,0 +1,26 @@ +# Oracle7 Personal Finance Arithmetic v2 (#65, tier B) + +**id** `finance-v2` - organ `organ_finance_v2.FinanceOrganV2` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 64/64 (false yes 0) vs head 3/64 (false yes 1) +- core capability panel: head 160 -> composed 162 (1 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Standard time-value-of-money formulas (compound interest, amortization, APY, sinking fund) as published by the CFPB and Investor.gov calculators (public domain (US government)) https://www.investor.gov/financial-tools-calculators/calculators/compound-interest-calculator + +## What it takes + +- answers: apy, doubling, loan_interest, loan_payment, savings_goal, simple_interest, compound +- declines (in-domain): underspecified, advice +- everything else falls through to the head unchanged + +Supersedes: finance (ADMIT gate v2, held-out 51/64; 13 misses safe declines) + +## Notes and known gaps + +v2 = v1 + a term written as an adjective ('a 15-year, $250,000 mortgage') and doubles/doubled/doubling as doubling - v1's held-out misses (safe declines) - and the family numbers rule. Arithmetic only; advice, prices and predictions still declined. Judged under spec_gate_v3.1 on a FRESH panel v2 (seeds 656565/65656565). Same author - disclosed. diff --git a/workbench/data/cards/firesafety-v2.md b/workbench/data/cards/firesafety-v2.md new file mode 100644 index 0000000000000000000000000000000000000000..bc7f4e01b6d675a806e31a9a11c4e1fbffdc0b13 --- /dev/null +++ b/workbench/data/cards/firesafety-v2.md @@ -0,0 +1,25 @@ +# Oracle7 Fire Safety & Preparedness v2 (#11, tier C) + +**id** `firesafety-v2` - organ `organ_facts_v1.FactsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 10/10 (false yes 0) vs head 1/10 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- US Fire Administration (USFA) home fire safety (public domain (US government)) https://www.usfa.fema.gov/prevention/home-fires/ +- FEMA Ready.gov build a kit (public domain (US government)) https://www.ready.gov/kit + +## What it takes + +- answers: firesafety +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +v2 of firesafety (v1 NEGATIVE 2026-09-29: two CORRECT facts scored wrong because the sentences did not carry the value phrase - lint_facts_v1 now enforces it). General phrasing coverage added. Fresh panel v2. Tier C unchanged. Narrowed (narrow_v1). diff --git a/workbench/data/cards/firstaid.md b/workbench/data/cards/firstaid.md new file mode 100644 index 0000000000000000000000000000000000000000..4f3b10f875c827a4ef82dd4f7ff9efc8129c9acc --- /dev/null +++ b/workbench/data/cards/firstaid.md @@ -0,0 +1,25 @@ +# Oracle7 First Aid (reference) (#66, tier C) + +**id** `firstaid` - organ `organ_facts_v1.FactsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 9/9 (false yes 0) vs head 1/9 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- US Army FM 4-25.11 First Aid (public domain (US government)) https://armypubs.army.mil/ +- 2020 AHA / Red Cross First Aid & CPR guidelines (figures cited) (facts cited) https://cpr.heart.org/ + +## What it takes + +- answers: firstaid +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Typed-fact organ (tier C): textbook first-aid procedure facts only. A person's own injury, medication, dosing and diagnosis are blocked (the head answers). Narrowed (narrow_v1). diff --git a/workbench/data/cards/forestry.md b/workbench/data/cards/forestry.md new file mode 100644 index 0000000000000000000000000000000000000000..0ac62ef47c0bd2739b7f72991a4e07efaa229bee --- /dev/null +++ b/workbench/data/cards/forestry.md @@ -0,0 +1,24 @@ +# Oracle7 Forestry (#37, tier B) + +**id** `forestry` - organ `organ_forestry_v1.ForestryOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 14/16 (false yes 0) vs head 1/16 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- USDA Forest Service - forest mensuration: basal area factor 0.005454, trees per acre, clinometer heights, Smalian's formula, Doyle log rule (public domain (US government)) https://www.fs.usda.gov/ + +## What it takes + +- answers: basal_area, ba_per_acre, basal_area_m2, tpa, height, smalian, doyle +- declines (in-domain): impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +Rules named in every answer (Doyle underestimates small logs - a property of the rule, not corrected). Clinometer height is above eye level unless an eye height is given. Panel two-role items in both orders (end diameters). Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/games-v3.md b/workbench/data/cards/games-v3.md new file mode 100644 index 0000000000000000000000000000000000000000..9567e5a498b3df0c2028bc15e11147cbb03e328f --- /dev/null +++ b/workbench/data/cards/games-v3.md @@ -0,0 +1,24 @@ +# Oracle7 Games & Puzzles (#73, tier A) + +**id** `games-v3` - organ `organ_games_v3.GamesOrganV3` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 18/18 (false yes 0) vs head 1/18 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Hoyle's Games (Project Gutenberg, public domain) - rules; probability computed exactly (combinatorics, dice convolution) (public domain) https://www.gutenberg.org/ + +## What it takes + +- answers: poker_prob, poker_count, dice_sum, at_least_one, card_one, card_k, card_k_repl, anagrams +- declines (in-domain): impossible, underspecified +- everything else falls through to the head unchanged + +## Notes and known gaps + +v3 of games (v2 NEGATIVE 2026-09-29: every probability cue was singular, so 'What are the chances...' fell silent and the head answered 3 at-least-one items wrongly). Inflected cue words normalised (chances, probabilities, likelihood, a pair of dice). Fresh panel v3. diff --git a/workbench/data/cards/gardening.md b/workbench/data/cards/gardening.md new file mode 100644 index 0000000000000000000000000000000000000000..2a6714769544bd3da6f1b118d71b42af75b6ed92 --- /dev/null +++ b/workbench/data/cards/gardening.md @@ -0,0 +1,24 @@ +# Oracle7 Gardening (#63, tier B) + +**id** `gardening` - organ `organ_gardening_v1.GardeningOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 14/15 (false yes 1) vs head 1/15 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- USDA / land-grant extension home-garden guides (raised beds, mulch depth, fertilizer per 1,000 sq ft, 1 inch of water = 0.623 gal/sq ft) (public domain (US government)) https://www.usda.gov/ + +## What it takes + +- answers: cubic_feet, cubic_yards, bags, plants_grid, fert_area, water_gal +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Volumes with no settling allowance; plants on a square grid (floor per side), said so. Advice questions (when to plant, why leaves yellow) fall through. Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/geography.md b/workbench/data/cards/geography.md new file mode 100644 index 0000000000000000000000000000000000000000..72223925d608eff0a704ca08e12fb825bfd03133 --- /dev/null +++ b/workbench/data/cards/geography.md @@ -0,0 +1,25 @@ +# Oracle7 World Geography (#67, tier A) + +**id** `geography` - organ `organ_geography_v1.GeographyOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 9/9 (false yes 0) vs head 1/9 (false yes 0) +- core capability panel: head 161 -> composed 161 (1 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- CIA World Factbook - capitals (including split capitals) (public domain (US government)) https://www.cia.gov/the-world-factbook/ +- Haversine great-circle distance on the mean Earth sphere (R = 6,371 km); 15 degrees of longitude per hour of solar time (facts) https://www.movable-type.co.uk/scripts/latlong.html + +## What it takes + +- answers: capital, capital_split, gc_km, gc_miles, antipode, solar_time, lat_km +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Split or relocating capitals answered with the split stated, never a single guessed city. Spherical Earth for distances (said so). Civil time zones differ from solar time (said so). Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/geology.md b/workbench/data/cards/geology.md new file mode 100644 index 0000000000000000000000000000000000000000..a510f057180171898dfc9ace9fabfc256659594c --- /dev/null +++ b/workbench/data/cards/geology.md @@ -0,0 +1,25 @@ +# Oracle7 Earth Science & Geology (#19, tier A) + +**id** `geology` - organ `organ_geology_v1.GeologyOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 18/18 (false yes 0) vs head 2/18 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- USGS - radiometric dating, half-lives, plate tectonics rates, geothermal gradient (public domain (US government)) https://pubs.usgs.gov/gip/geotime/radiometric.html +- NNDC / NIST half-life values (C-14 5,730 y; K-40 1.248 Gy; U-238 4.468 Gy; U-235 704 My) (public domain (US government)) https://www.nndc.bnl.gov/ + +## What it takes + +- answers: fraction_left, age_fraction, age_ratio, plate_distance, plate_rate, depth_temp +- declines (in-domain): underspecified, impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +Ideal decay, no initial daughter (said so via the formula); C-14 uses the 5,730-year (Cambridge) half-life, not the 5,568-year Libby value of conventional radiocarbon ages. Panel two-role items in both orders in DEV (panel rule). Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/geometry-v4.md b/workbench/data/cards/geometry-v4.md new file mode 100644 index 0000000000000000000000000000000000000000..c2f69efaf804b51ccd01c76fb21ca40a866b6773 --- /dev/null +++ b/workbench/data/cards/geometry-v4.md @@ -0,0 +1,26 @@ +# Oracle7 Geometry v4 (#46, tier A) + +**id** `geometry-v4` - organ `organ_geometry_v4.GeometryOrganV4` composed in front of the frozen head `oracle_release_runtime_w363`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 93/93 (false yes 0) vs head 4/93 (false yes 0) +- core capability panel: head 160 -> composed 163 (3 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Euclidean measurement formulas (area, perimeter, volume, surface area, Pythagoras, Heron, polygon angle sum) (public domain (mathematics)) https://en.wikipedia.org/wiki/Area#Area_formulas + +## What it takes + +- answers: circle_area, circumference, sphere_volume, sphere_surface, cylinder_volume, cylinder_surface, cone_volume, cube_volume, cube_surface, box_volume, rect_area, rect_perimeter, square_area, square_perimeter, tri_area, heron, hypotenuse, leg, angle_sum +- declines (in-domain): underspecified, impossible +- everything else falls through to the head unchanged + +Supersedes: geometry-v3 (ADMIT gate v2, 93/100; 7 misses = imperative 'Compute the hypotenuse') + +## Notes and known gaps + +v4 = v3 + imperative verbs (compute / calculate / determine / give / work out) read as 'find' for the hypotenuse. Judged under spec_gate_v2 on a FRESH panel (new seeds, new phrasings both splits including the class). Same author - disclosed. Earlier notes: v3 = v1 + narrowing (v2: word problems to the head; no false 'I need X' when numbers are present - the full-core sweep found v1 taking 17 core word problems incl. a confident wrong 10.95 for 5) + two reading classes v1 missed (sides stated with a verb, 'sides are a, b and c' - all 8 v1 held-out misses; a hypotenuse value stated after the verb). Judged under spec_gate_v2 on a FRESH panel v2 (new seeds, new phrasings both splits, new declines). Same author - disclosed. Deliberately does NOT read '10 feet across' as a diameter: those core textbook problems use pi = 3.14. diff --git a/workbench/data/cards/government.md b/workbench/data/cards/government.md new file mode 100644 index 0000000000000000000000000000000000000000..c372e8ef7e0c1c5c1d9be53d6004968266d3a0d0 --- /dev/null +++ b/workbench/data/cards/government.md @@ -0,0 +1,25 @@ +# Oracle7 Government & Political Science (US Constitution) (#86, tier A) + +**id** `government` - organ `organ_government_v1.GovernmentOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 10/14 (false yes 0) vs head 1/14 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- The Constitution of the United States and its 27 amendments - National Archives transcription (public domain (US government)) https://www.archives.gov/founding-docs/constitution-transcript +- OpenStax American Government 3e (structure of Congress, Electoral College) (CC-BY 4.0) https://openstax.org/details/books/american-government-3e + +## What it takes + +- answers: amend_for_topic, amend_subject, article_subject, fact_number +- declines (in-domain): impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +Constitutional text as the store; statutory numbers (435 House seats, 9 justices) labelled as statutory. No partisan opinion, candidates or current events (fall through). Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/grammar.md b/workbench/data/cards/grammar.md new file mode 100644 index 0000000000000000000000000000000000000000..6c377251be9e11a9430698f69c70a9a59935ba62 --- /dev/null +++ b/workbench/data/cards/grammar.md @@ -0,0 +1,24 @@ +# Oracle7 English Language & Grammar (irregular forms) (#68, tier B) + +**id** `grammar` - organ `organ_grammar_v1.GrammarOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 15/15 (false yes 0) vs head 1/15 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Irregular English verbs and plurals - Wiktionary appendices (cross-checked against standard reference grammars) (CC-BY-SA 4.0 (store ships share-alike)) https://en.wiktionary.org/wiki/Appendix:English_irregular_verbs + +## What it takes + +- answers: past_tense, past_participle, plural, comparative, superlative +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +A closed table of irregular forms with accepted variants (dreamed/dreamt, got/gotten); regular words fall through (no rule-guessing in v1). Style / usage opinion questions are not taken. Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/greenhouse.md b/workbench/data/cards/greenhouse.md new file mode 100644 index 0000000000000000000000000000000000000000..2d7136e02f708a907414525b1e2e2a55018cc932 --- /dev/null +++ b/workbench/data/cards/greenhouse.md @@ -0,0 +1,25 @@ +# Oracle7 Greenhouse & Controlled Agriculture (#4, tier B) + +**id** `greenhouse` - organ `organ_greenhouse_v1.GreenhouseOrgan` composed in front of the frozen head `oracle_release_runtime_w363`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 45/45 (false yes 0) vs head 3/45 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- FAO Irrigation and Drainage Paper 56 (Tetens saturation vapour pressure, eq. 11) (FAO (free to reproduce with attribution)) https://www.fao.org/3/x0490e/x0490e00.htm +- Daily light integral and growing degree days as defined by USDA / land-grant extension services (public domain (US government)) https://www.usda.gov/ + +## What it takes + +- answers: vpd, vpd_leaf, dli, ppfd_needed, gdd, plant_count +- declines (in-domain): underspecified, impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +Formulas stated in every answer. The GDD base temperature is never assumed (it depends on the crop). Leaf vs air temperature read from grammar, never order of mention (the panel states the leaf first in half the leaf-VPD items). Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/iot.md b/workbench/data/cards/iot.md new file mode 100644 index 0000000000000000000000000000000000000000..ae0147c800506af3338adf97c74ec9595f373b17 --- /dev/null +++ b/workbench/data/cards/iot.md @@ -0,0 +1,24 @@ +# Oracle7 Sensor Networks & IoT (#94, tier B) + +**id** `iot` - organ `organ_iot_v1.IotOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 27/27 (false yes 0) vs head 2/27 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- NIST IoT and measurement publications; ideal ADC transfer (LSB = Vref / 2^n), Nyquist-Shannon sampling, duty-cycle average current (public domain (US government) / facts) https://www.nist.gov/programs-projects/nist-cybersecurity-iot-program + +## What it takes + +- answers: adc_voltage, adc_code, adc_lsb, avg_current, battery_life, nyquist, data_rate, storage_day +- declines (in-domain): underspecified, impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +Ideal ADC convention LSB = Vref / 2^n (named; some datasheets use 2^n - 1). Battery life is ideal (no self-discharge / derating), said so. Radio link budgets are left to spacecomms (#95). Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/javascript.md b/workbench/data/cards/javascript.md new file mode 100644 index 0000000000000000000000000000000000000000..71072e1cb2e521ddd8fffa334e3133bf73955f15 --- /dev/null +++ b/workbench/data/cards/javascript.md @@ -0,0 +1,24 @@ +# Oracle7 JavaScript (#52, tier A) + +**id** `javascript` - organ `organ_facts_v1.FactsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 10/10 (false yes 0) vs head 2/10 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- MDN Web Docs (CC BY-SA 2.5) https://developer.mozilla.org/ + +## What it takes + +- answers: javascript +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Typed-fact organ: JavaScript semantics facts; every value executed under node v22 (js_verify_v1.js). Debugging / writing the asker's code is blocked. Narrowed (narrow_v1). diff --git a/workbench/data/cards/law.md b/workbench/data/cards/law.md new file mode 100644 index 0000000000000000000000000000000000000000..25f4850cebbf4f25e0c4a774deca9ea86c818092 --- /dev/null +++ b/workbench/data/cards/law.md @@ -0,0 +1,24 @@ +# Oracle7 Law: General Concepts (#89, tier C) + +**id** `law` - organ `organ_facts_v1.FactsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 9/9 (false yes 0) vs head 1/9 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- US Supreme Court opinions / US Code (public domain (US government)) https://www.supremecourt.gov/ + +## What it takes + +- answers: law +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Typed-fact organ (tier C): NO LEGAL ADVICE - definitions and landmark cases only. The asker's own situation, suing, liability and arrests are blocked (the head answers). Narrowed (narrow_v1). diff --git a/workbench/data/cards/library.md b/workbench/data/cards/library.md new file mode 100644 index 0000000000000000000000000000000000000000..97e1de2b999757119ad24bce2f463400e966752c --- /dev/null +++ b/workbench/data/cards/library.md @@ -0,0 +1,25 @@ +# Oracle7 Library & Archive Management (#14, tier B) + +**id** `library` - organ `organ_library_v1.LibraryOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 14/15 (false yes 0) vs head 1/15 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Library of Congress Classification Outline (public domain (US government)) https://www.loc.gov/catdir/cpso/lcco/ +- ISBN (ISO 2108) and ISSN (ISO 3297) check-digit algorithms (facts (algorithms)) https://www.isbn-international.org/ + +## What it takes + +- answers: lcc_class, lcc_sub, lcc_for_subject, isbn13_check, isbn10_check, isbn_valid, isbn_convert, issn_check, issn_valid +- declines (in-domain): impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +LCC main classes and a set of common subclasses from the LoC outline (Dewey Decimal is OCLC-copyrighted and not used). ISBN / ISSN arithmetic exact. Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/linguistics.md b/workbench/data/cards/linguistics.md new file mode 100644 index 0000000000000000000000000000000000000000..6497e0ec91ce713b8ac7e8319074459b3dd7f22b --- /dev/null +++ b/workbench/data/cards/linguistics.md @@ -0,0 +1,24 @@ +# Oracle7 Linguistics (language families) (#82, tier B) + +**id** `linguistics` - organ `organ_facts_v1.FactsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 11/11 (false yes 0) vs head 1/11 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Glottolog language classification (CC-BY 4.0) cross-checked with Wikibooks linguistics (CC-BY 4.0) https://glottolog.org/ + +## What it takes + +- answers: language_family +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Typed-fact organ: family and branch per language; difficulty / preference questions are blocked. Narrowed (narrow_v1). diff --git a/workbench/data/cards/linux-v2.md b/workbench/data/cards/linux-v2.md new file mode 100644 index 0000000000000000000000000000000000000000..3b1be3608fa81251a10a5898d9290ce0412eb6dd --- /dev/null +++ b/workbench/data/cards/linux-v2.md @@ -0,0 +1,27 @@ +# Oracle7 Linux & the Command Line v2 (#54, tier B) + +**id** `linux-v2` - organ `organ_linux_v2.LinuxOrganV2` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 42/42 (false yes 0) vs head 3/42 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Linux man-pages: chmod(1), umask(2), crontab(5), signal(7) (x86/ARM numbering) (man-pages licences (verbatim / GPL; facts used, text not shipped)) https://man7.org/linux/man-pages/man7/signal.7.html +- POSIX shell: exit status of a command terminated by a signal is greater than 128 (bash: 128 + n) (facts) https://www.gnu.org/software/bash/manual/html_node/Exit-Status.html + +## What it takes + +- answers: chmod_symbolic, chmod_octal, umask, umask_file, umask_dir, cron_per_hour, cron_per_day, signal_number, signal_name, exit_status +- declines (in-domain): impossible, underspecified +- everything else falls through to the head unchanged + +Supersedes: linux (v1 NEGATIVE under gate v3: held-out 37/42, 2 wrong from head fallthrough) + +## Notes and known gaps + +v2 = v1 + 'in one day / in 24 hours / every day' read as per day, 'signal has the number N' read as signal N, and a RECOGNISED cron run-count question with no readable period DECLINES in-domain instead of falling silent. v1 NEGATIVE under gate v3: held-out 37/42 vs 2/42 but 2 WRONG - the wrong answers were the HEAD's (-3.83, -10) on 'In one day, how many runs...' turns the organ fell silent on. Corollary of the numbers-rule law: recognise-then-decline, never silence into a weak head. Judged under spec_gate_v3.1 on a FRESH panel v2 (seeds 545454/54545454). Same author - disclosed. diff --git a/workbench/data/cards/literature-v2.md b/workbench/data/cards/literature-v2.md new file mode 100644 index 0000000000000000000000000000000000000000..a3b4edc8a527bc45a13f1bc3a687aff495fd450f --- /dev/null +++ b/workbench/data/cards/literature-v2.md @@ -0,0 +1,24 @@ +# Oracle7 Literature & Classics (authorship) (#80, tier B) + +**id** `literature-v2` - organ `organ_facts_v1.FactsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 11/12 (false yes 0) vs head 3/12 (false yes 0) +- core capability panel: head 162 -> composed 162 (2 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Project Gutenberg catalogue (authors of public-domain works) (public domain) https://www.gutenberg.org/ + +## What it takes + +- answers: literature +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +v2 of literature (v1 NEGATIVE 2026-09-29 for NO GAIN: 11/11, 0 wrong, but the head already knew 9 of 11 famous authorships). Keeps authorship and adds depth from the public-domain texts: narrators, characters -> work, settings, opening lines, first-publication years. Fresh panel v2. diff --git a/workbench/data/cards/logic-v3.md b/workbench/data/cards/logic-v3.md new file mode 100644 index 0000000000000000000000000000000000000000..cf03ecccf2810b652b7733d1cf0b69a76e1ebaa6 --- /dev/null +++ b/workbench/data/cards/logic-v3.md @@ -0,0 +1,24 @@ +# Oracle7 Philosophy: Formal Logic (#78, tier A) + +**id** `logic-v3` - organ `organ_logic_v3.LogicOrganV3` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 12/12 (false yes 0) vs head 1/12 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- forall x: Calgary - An Introduction to Formal Logic (truth tables, validity, argument forms) (CC-BY 4.0) https://forallx.openlogicproject.org/ + +## What it takes + +- answers: formula, argument, form +- declines (in-domain): underspecified +- everything else falls through to the head unchanged + +## Notes and known gaps + +v3 of logic (v2 NEGATIVE 2026-09-29: 'Identify the form of this argument: ...' was rejected by v1's entry cue list -> head wrongs). Named forms answered from the argument SHAPE whatever the lead-in; unquoted formulas found as the longest formula span. Fresh panel v3. diff --git a/workbench/data/cards/marinebio.md b/workbench/data/cards/marinebio.md new file mode 100644 index 0000000000000000000000000000000000000000..279934b46979ee28c33a833502a38c585b749284 --- /dev/null +++ b/workbench/data/cards/marinebio.md @@ -0,0 +1,24 @@ +# Oracle7 Marine Biology (#32, tier B) + +**id** `marinebio` - organ `organ_facts_v1.FactsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 7/9 (false yes 0) vs head 1/9 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- NOAA Ocean Service / NOAA Fisheries facts (public domain (US government)) https://oceanservice.noaa.gov/facts/ + +## What it takes + +- answers: marine +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Typed-fact organ: ocean zones and marine-life facts; swimming / eating safety and aquarium advice is blocked. Narrowed (narrow_v1). diff --git a/workbench/data/cards/materials-v2.md b/workbench/data/cards/materials-v2.md new file mode 100644 index 0000000000000000000000000000000000000000..68b018ea49dc8a745007c583416dde25514552b3 --- /dev/null +++ b/workbench/data/cards/materials-v2.md @@ -0,0 +1,25 @@ +# Oracle7 Materials Science & Aerogels (#40, tier B) + +**id** `materials-v2` - organ `organ_materials_v2.MaterialsOrganV2` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 24/24 (false yes 0) vs head 3/24 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- NASA aerogel technical reports (bulk vs skeletal density, porosity); NIST materials data (public domain (US government)) https://www.nasa.gov/general/aerogels-insulating-materials/ +- OpenStax University Physics / Chemistry: stress, strain, Young's modulus, thermal expansion, cubic unit cells (n M / N_A a^3), packing factors (CC-BY 4.0) https://openstax.org/details/books/chemistry-2e + +## What it takes + +- answers: apf, crystal_density, porosity, stress, strain, modulus, expansion +- declines (in-domain): impossible, underspecified +- everything else falls through to the head unchanged + +## Notes and known gaps + +v2 of materials (v1 NEGATIVE 2026-09-29: 3 head-fallthrough wrongs on 'BCC, a = X pm' + 1 false yes from a dropped decline). Reads 'a = X pm', 'an N mm specimen', 'heated N °C'; keeps recognised declines on numeric turns; recognise-then-decline. Fresh panel v2. diff --git a/workbench/data/cards/mechanisms-v2.md b/workbench/data/cards/mechanisms-v2.md new file mode 100644 index 0000000000000000000000000000000000000000..b8b98a6e58871eb69c5dd400099260abaa0aa74b --- /dev/null +++ b/workbench/data/cards/mechanisms-v2.md @@ -0,0 +1,26 @@ +# Oracle7 Mechanical Engineering & Mechanisms v2 (#42, tier B) + +**id** `mechanisms-v2` - organ `organ_mechanisms_v2.MechanismsOrganV2` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 55/55 (false yes 0) vs head 3/55 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Ideal simple-machine relations (gears, belts, levers, pulleys, inclined planes, torque, shaft power) - OpenStax University Physics vol. 1 ch. 10-12 (CC-BY 4.0) https://openstax.org/details/books/university-physics-volume-1 + +## What it takes + +- answers: gear_speed, gear_torque, gear_ratio, belt_speed, pulley_ma, pulley_effort, lever_effort, lever_ma, incline_ma, shaft_power, torque +- declines (in-domain): underspecified, impossible +- everything else falls through to the head unchanged + +Supersedes: mechanisms (ADMIT gate v2, held-out 57/64; 7 misses safe declines) + +## Notes and known gaps + +v2 = v1 + (a) torque asked about a force on a lever with no effort/load arm named reads the lever as the lever arm - v1's held-out misses ('Find the torque when a force of 120 N is applied to a 0.25 m lever', declined for want of arms); (b) found on panel v2 DEV, a latent v1 defect: 'what effort lifts 600 N' - v1 read 'lift N' not 'lifts N' and with no load fell through to the mechanical advantage (confident answer to a different question); v2 reads lifts/lifted/lifting and NEVER answers an effort question with a mechanical advantage; (c) the family numbers rule (an underspecified decline on a turn with numbers becomes silence - the head answers). Judged under spec_gate_v3.1 on a FRESH panel v2 (seeds 424242/42424242; new phrasings incl. torque on a lever). Same author - disclosed. diff --git a/workbench/data/cards/medicine.md b/workbench/data/cards/medicine.md new file mode 100644 index 0000000000000000000000000000000000000000..f0a44f8183cdd12258366fe8d5b8305d7df82573 --- /dev/null +++ b/workbench/data/cards/medicine.md @@ -0,0 +1,25 @@ +# Oracle7 Medicine (reference only) (#90, tier C) + +**id** `medicine` - organ `organ_facts_v1.FactsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 9/9 (false yes 0) vs head 2/9 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- MedlinePlus (NIH NLM) (public domain (US government)) https://medlineplus.gov/ +- CDC antibiotic use / vaccine history (public domain (US government)) https://www.cdc.gov/ + +## What it takes + +- answers: medicine +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Typed-fact organ (tier C): general reference values and history of medicine. Symptoms, diagnosis, a person's readings, treatment, medication and dosing are blocked (the head answers). Narrowed (narrow_v1). diff --git a/workbench/data/cards/meteorology.md b/workbench/data/cards/meteorology.md new file mode 100644 index 0000000000000000000000000000000000000000..8f1fce3c64a2588ea977db49d94e80f2e5ed6fd4 --- /dev/null +++ b/workbench/data/cards/meteorology.md @@ -0,0 +1,26 @@ +# Oracle7 Meteorology & Weather (#20, tier A) + +**id** `meteorology` - organ `organ_weather_v1.WeatherOrgan` composed in front of the frozen head `oracle_release_runtime_w363`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 46/46 (false yes 0) vs head 2/46 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- NWS heat index equation (Rothfusz regression + NWS adjustments) and NWS 2001 wind chill formula (public domain (US government)) https://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml +- NHC Saffir-Simpson Hurricane Wind Scale (public domain (US government)) https://www.nhc.noaa.gov/aboutsshws.php +- WMO Beaufort scale (knots); Magnus dew-point coefficients 17.62 / 243.12 C; ICAO standard atmosphere troposphere (facts / published constants) https://library.wmo.int/ + +## What it takes + +- answers: heat_index, wind_chill, wc_undefined, dew_point, air_temperature, relative_humidity, saffir_simpson, beaufort, isa_pressure, isa_temperature +- declines (in-domain): underspecified, impossible, out_of_range +- everything else falls through to the head unchanged + +## Notes and known gaps + +Published formulas and tables only; never a forecast (tomorrow/forecast/will it rain are not taken). Dev caught two CONFIDENT-WRONG classes before held-out: (1) a nearest-word heuristic tied and swapped air temperature and dew point (answered a must-decline) - replaced by the value attached to 'dew point'; (2) a given dew point was recomputed instead of solving for the asked air temperature - now routed by what is given, with Magnus inverted (round trip 30 C -> 18.44 C -> 30 C). diff --git a/workbench/data/cards/microbiology-v2.md b/workbench/data/cards/microbiology-v2.md new file mode 100644 index 0000000000000000000000000000000000000000..3f931ee842c89f903c1c38dd616f900db1fb9cd0 --- /dev/null +++ b/workbench/data/cards/microbiology-v2.md @@ -0,0 +1,24 @@ +# Oracle7 Microbiology (#33, tier A) + +**id** `microbiology-v2` - organ `organ_micro_v2.MicroOrganV2` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 13/13 (false yes 0) vs head 1/13 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- OpenStax Microbiology ch. 9 (microbial growth: binary fission, generation time, viable plate counts, serial dilution) (CC-BY 4.0) https://openstax.org/details/books/microbiology + +## What it takes + +- answers: growth_n, generations, gen_time, cfu, serial +- declines (in-domain): impossible, underspecified +- everything else falls through to the head unchanged + +## Notes and known gaps + +v2 of microbiology (v1 NEGATIVE 2026-09-29: a computed growth answer silenced by the narrative filter; 'from N cells to M cells' unread -> head wrongs). Narrative filter skipped for asking turns; reads from-to counts, 'population of N cells', successive / tenfold dilutions; recognise-then-decline. Fresh panel v2. diff --git a/workbench/data/cards/music-v2.md b/workbench/data/cards/music-v2.md new file mode 100644 index 0000000000000000000000000000000000000000..3ec708c6c9cabbd83adbc517f225f4fd881dbfcf --- /dev/null +++ b/workbench/data/cards/music-v2.md @@ -0,0 +1,27 @@ +# Oracle7 Music Theory v2 (#74, tier B) + +**id** `music-v2` - organ `organ_music_v2.MusicOrganV2` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 64/64 (false yes 0) vs head 5/64 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Music theory (intervals, scales, key signatures, circle of fifths) - Wikibooks Music Theory (CC-BY-SA 4.0 (store ships share-alike)) https://en.wikibooks.org/wiki/Music_Theory +- 12-tone equal temperament f = 440 x 2^((m-69)/12) (ISO 16:1975 standard pitch A4 = 440 Hz); MIDI 1.0 note numbering (middle C = 60) (facts) https://www.iso.org/standard/3601.html + +## What it takes + +- answers: frequency, midi_number, midi_note, semitones, semitones_between, interval, key_sig, relative, scale, duration, cents +- declines (in-domain): underspecified, impossible +- everything else falls through to the head unchanged + +Supersedes: music (v1 NEGATIVE under gate v3: held-out 56/64 vs 2/64, 3 wrong > cap 1) + +## Notes and known gaps + +v2 = v1 + the tuning REFERENCE is never the target (v1 NEGATIVE under gate v3: 'Tuning to A4 = 432 Hz, what frequency is C5?' answered A4 = 432 Hz, 3 confident wrong - roles from grammar, never order of mention) + 'which minor key is relative to X' (5 safe misses) + 'frequency' in the decline context (v1 dev: the correct decline on 'frequency of C' was dropped). Judged under spec_gate_v3.1 on a FRESH panel v2 (seeds 747474/74747474; reference first AND last on both splits). Same author - disclosed. diff --git a/workbench/data/cards/mycelial.md b/workbench/data/cards/mycelial.md new file mode 100644 index 0000000000000000000000000000000000000000..05e0caae2905378d028d309767a674d2d577c059 --- /dev/null +++ b/workbench/data/cards/mycelial.md @@ -0,0 +1,24 @@ +# Oracle7 Mycelial Networks & Soil Ecology (#91, tier B) + +**id** `mycelial` - organ `organ_facts_v1.FactsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 7/7 (false yes 0) vs head 2/7 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- USDA NRCS Soil Biology Primer / USDA Forest Service mycorrhizae (public domain (US government)) https://www.nrcs.usda.gov/resources/guides-and-instructions/soil-biology-primer + +## What it takes + +- answers: mycelial +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Typed-fact organ: mycorrhizae and soil-fungus ecology. Product / personal garden advice and edibility are blocked. Narrowed (narrow_v1). diff --git a/workbench/data/cards/mycology.md b/workbench/data/cards/mycology.md new file mode 100644 index 0000000000000000000000000000000000000000..515d03d6617f80ba58dc2026ef2bd7f170f2855b --- /dev/null +++ b/workbench/data/cards/mycology.md @@ -0,0 +1,25 @@ +# Oracle7 Mycology (#28, tier B) + +**id** `mycology` - organ `organ_facts_v1.FactsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 9/9 (false yes 0) vs head 2/9 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- OpenStax Biology 2e ch. 24 (Fungi) (CC BY 4.0) https://openstax.org/details/books/biology-2e +- USDA Forest Service fungi facts (public domain (US government)) https://www.fs.usda.gov/wildflowers/interesting/fungi/ + +## What it takes + +- answers: mycology +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Typed-fact organ: fungal biology facts. EDIBILITY, IDENTIFICATION AND TOXICITY ARE NEVER ANSWERED (blocked - a wrong answer can kill). Narrowed (narrow_v1). diff --git a/workbench/data/cards/mythology.md b/workbench/data/cards/mythology.md new file mode 100644 index 0000000000000000000000000000000000000000..3a4126cb581b2de48d638dd76178757d0eb99ae1 --- /dev/null +++ b/workbench/data/cards/mythology.md @@ -0,0 +1,24 @@ +# Oracle7 Mythology (#79, tier A) + +**id** `mythology` - organ `organ_mythology_v1.MythologyOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 13/13 (false yes 0) vs head 1/13 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Thomas Bulfinch, The Age of Fable (Bulfinch's Mythology) - Project Gutenberg (public domain) https://www.gutenberg.org/ebooks/4928 + +## What it takes + +- answers: g2r, r2g, domain_god, role +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Closed table of classical and Norse figures; world religions (belief, practice) are not taken. Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/ocean.md b/workbench/data/cards/ocean.md new file mode 100644 index 0000000000000000000000000000000000000000..121ad8f206f32e22aa481e8d8d42f03ee3360bec --- /dev/null +++ b/workbench/data/cards/ocean.md @@ -0,0 +1,24 @@ +# Oracle7 Oceanography (#21, tier B) + +**id** `ocean` - organ `organ_ocean_v1.OceanOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 23/23 (false yes 0) vs head 2/23 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- NOAA Ocean Service / NOAA Tsunami program - shallow-water wave speed sqrt(g d), deep-water dispersion, pressure with depth, echo sounding (public domain (US government)) https://oceanservice.noaa.gov/facts/ + +## What it takes + +- answers: shallow_speed, tsunami_time, deep_speed, deep_wavelength, pressure, pressure_abs, sonar_depth +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +g = 9.81; seawater 1,025 kg/m3 and sound 1,500 m/s unless given (said so). No in-domain declines in v1: the organ answers what it can compute and is silent otherwise; the panel's invalid items are off-domain ocean questions it must NOT take. Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/optics-v5.md b/workbench/data/cards/optics-v5.md new file mode 100644 index 0000000000000000000000000000000000000000..21ea187d48ad8bd80e8d11f598975cec5d83a36d --- /dev/null +++ b/workbench/data/cards/optics-v5.md @@ -0,0 +1,27 @@ +# Oracle7 Optics & Light v5 (#48, tier A) + +**id** `optics-v5` - organ `organ_optics_v5.OpticsOrganV5` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 51/65 (false yes 0) vs head 2/65 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- SI defining constants h, c, e (exact since 2019, BIPM SI Brochure 9th ed.) (public (BIPM)) https://www.bipm.org/en/publications/si-brochure +- Refractive indices at 589 nm for water, diamond, air (stated in every answer) (facts) https://refractiveindex.info/ + +## What it takes + +- answers: photon_energy, frequency, wavelength, lens_power, image_distance, magnification, at_focus, critical_angle, no_critical, medium_speed, tir, refraction_angle, index +- declines (in-domain): underspecified, impossible +- everything else falls through to the head unchanged + +Supersedes: optics-v3 (standing; ADMIT gate v2, held-out 53/67). optics-v4 NEGATIVE (gate v3, 4 wrong) - DO NOT SHIP. + +## Notes and known gaps + +v5 = v3 + v4's object-distance phrasing + 'how fast light travels inside/through' read as speed in the medium, WITHOUT the family numbers rule. optics-v4 was NEGATIVE under gate v3 (held-out 61/65, 4 WRONG > cap 1): the numbers rule turned v3's safe declines into silence and the head (2/65 in optics) answered 'how fast light travels' with a dictionary definition of 'fast'. LAW: the numbers rule is only safe where the head answers the domain's numeric turns. Judged under spec_gate_v3.1 on a FRESH panel v5 (seeds 5050505/505050505). Same author - disclosed. diff --git a/workbench/data/cards/ornithology.md b/workbench/data/cards/ornithology.md new file mode 100644 index 0000000000000000000000000000000000000000..8193507e4d1d6c53a36cd60c5119eb102a23d89c --- /dev/null +++ b/workbench/data/cards/ornithology.md @@ -0,0 +1,24 @@ +# Oracle7 Ornithology (#31, tier B) + +**id** `ornithology` - organ `organ_facts_v1.FactsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 7/9 (false yes 0) vs head 1/9 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- US Fish and Wildlife Service bird facts; Cornell Lab public facts (public domain / facts) https://www.fws.gov/ + +## What it takes + +- answers: ornithology +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Typed-fact organ: record birds and bird biology; pet-bird care and injured-bird advice is blocked. Narrowed (narrow_v1). diff --git a/workbench/data/cards/pets.md b/workbench/data/cards/pets.md new file mode 100644 index 0000000000000000000000000000000000000000..1fd790c79f86d421d8285c3b94401115268735a2 --- /dev/null +++ b/workbench/data/cards/pets.md @@ -0,0 +1,25 @@ +# Oracle7 Pets & Animal Care (#71, tier C) + +**id** `pets` - organ `organ_facts_v1.FactsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 9/9 (false yes 0) vs head 1/9 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- ASPCA Animal Poison Control toxic plants / people foods lists (facts cited) https://www.aspca.org/pet-care/animal-poison-control +- AVMA / AKC public reference values (facts cited) https://www.avma.org/resources-tools/pet-owners + +## What it takes + +- answers: pets +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Typed-fact organ (tier C): pet reference facts. A particular animal's illness, what to do after it ate something, medication and dosing are blocked (the head answers). Narrowed (narrow_v1). diff --git a/workbench/data/cards/physics-r2.md b/workbench/data/cards/physics-r2.md new file mode 100644 index 0000000000000000000000000000000000000000..eb87a17e7fbf6688c9e4b65916f8caaf860fff46 --- /dev/null +++ b/workbench/data/cards/physics-r2.md @@ -0,0 +1,27 @@ +# Oracle7 Physics (Mechanics) (r2, narrowed) (#39, tier A) + +**id** `physics-r2` - organ `organ_mechanics_v2.MechanicsOrganV2` composed in front of the frozen head `oracle_release_runtime_w363`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 123/123 (false yes 0) vs head 2/123 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Classical mechanics (constant-acceleration kinematics, Newton's second law, work-energy, momentum) with standard gravity 9.80665 m/s^2 (CGPM 1901) (public domain (physical law; value from NIST)) https://physics.nist.gov/cuu/Constants/ +- OpenStax University Physics (already in the core's world stores) (CC-BY 4.0) https://openstax.org/details/books/university-physics-volume-1 + +## What it takes + +- answers: range, impact_speed, fall_time, ke, pe, momentum, weight, force, work, power, final_velocity, distance +- declines (in-domain): underspecified +- everything else falls through to the head unchanged + +Supersedes: physics (v1 admitted 2026-09-29 under spec_gate_v1) + +## Notes and known gaps + +Computation with the formula shown; no air resistance stated. Panel answers from formulas written separately; dev/held-out differ in seed and phrasing (same author). || r2 (2026-09-29): the full-core sweep found this organ taking core items outside its domain (reading passages, word problems, idioms). r2 = runtime v2 (reading turns -> head) + a NARROWING-ONLY organ patch (narrow_v1). INVARIANCE: r2's reply is byte-identical to v1's on 123/123 (counts only, no items or scores viewed), so the SAME held-out panel is re-run under spec_gate_v2 - its domain result is v1's by construction; what is newly measured is the full-core sweep with the per-item no-worse rule. diff --git a/workbench/data/cards/planetary.md b/workbench/data/cards/planetary.md new file mode 100644 index 0000000000000000000000000000000000000000..8d647d22f1c690bd72ad83ff7a774383eabe105f --- /dev/null +++ b/workbench/data/cards/planetary.md @@ -0,0 +1,24 @@ +# Oracle7 Planetary Science (#17, tier A) + +**id** `planetary` - organ `organ_planetary_v1.PlanetaryOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 16/18 (false yes 2) vs head 0/18 (false yes 2) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- NASA Goddard Planetary Fact Sheet relations (surface gravity, escape velocity, mean density) (public domain (US government)) https://nssdc.gsfc.nasa.gov/planetary/factsheet/ + +## What it takes + +- answers: gravity, escape, orbital_v, density, weight +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Computes ONLY from mass and radius given in the turn (SI or Earth units); no stored planet table - 'surface gravity of Jupiter' falls through (convention-dependent for gas giants). Earth units: g 9.81, M 5.972e24 kg, R 6371 km, said so. No in-domain declines. Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/printing-v2.md b/workbench/data/cards/printing-v2.md new file mode 100644 index 0000000000000000000000000000000000000000..0208926f2a292f2958767a92618ac26621d85019 --- /dev/null +++ b/workbench/data/cards/printing-v2.md @@ -0,0 +1,26 @@ +# Oracle7 Workshop & 3D Printing v2 (#8, tier B) + +**id** `printing-v2` - organ `organ_printing_v2.PrintingOrganV2` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 36/37 (false yes 1) vs head 2/37 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Cylinder volume and mass (geometry), typical polymer densities (PLA 1.24, PETG 1.27, ABS 1.04, ASA 1.07, TPU 1.21, nylon 1.14 g/cm^3) as published on manufacturer technical data sheets - stated as typical in every answer (facts) https://reprap.org/wiki/Filament + +## What it takes + +- answers: shrink_scale, layers, flow, cost, length, mass +- declines (in-domain): underspecified, impossible +- everything else falls through to the head unchanged + +Supersedes: printing (ADMIT gate v2, held-out 30/36; 6 misses safe) + +## Notes and known gaps + +v2 = v1 + 'printed' as a print cue and 'mm high' read as 'mm tall' - v1's held-out misses ('A part 180 mm high is printed with 0.2 mm layers', not taken) - and the family numbers rule. Judged under spec_gate_v3.1 on a FRESH panel v2 (seeds 808080/80808080). Same author - disclosed. diff --git a/workbench/data/cards/robotics-v2.md b/workbench/data/cards/robotics-v2.md new file mode 100644 index 0000000000000000000000000000000000000000..d69d6334520360b4c03834ec636f272ebe52bd3c --- /dev/null +++ b/workbench/data/cards/robotics-v2.md @@ -0,0 +1,25 @@ +# Oracle7 Robotics Basics (#97, tier B) + +**id** `robotics-v2` - organ `organ_robotics_v2.RoboticsOrganV2` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 20/23 (false yes 0) vs head 2/23 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Differential-drive kinematics, encoder odometry, planar forward kinematics - Wikibooks Robotics (CC-BY-SA 4.0 (store ships share-alike)) https://en.wikibooks.org/wiki/Robotics_Kinematics_and_Dynamics +- NASA robotics education (wheel speed from rpm, PWM average voltage) (public domain (US government)) https://www.nasa.gov/stem + +## What it takes + +- answers: wheel_speed, diff_linear, diff_angular, turn_radius, encoder, fk, pwm +- declines (in-domain): impossible, straight, underspecified +- everything else falls through to the head unchanged + +## Notes and known gaps + +v2 of robotics (v1 NEGATIVE 2026-09-29: 3 head-fallthrough wrongs on 'X m/s (left)' phrasing). Parses differential drive itself (side labels in any position; track width only from a track phrase), recognise-then-decline, v1 declines kept for numeric turns. Fresh panel v2. diff --git a/workbench/data/cards/safety.md b/workbench/data/cards/safety.md new file mode 100644 index 0000000000000000000000000000000000000000..bf4800da81057d7e94006026712830991389975b --- /dev/null +++ b/workbench/data/cards/safety.md @@ -0,0 +1,26 @@ +# Oracle7 Occupational Safety Arithmetic (#10, tier B) + +**id** `safety` - organ `organ_safety_v1.SafetyOrgan` composed in front of the frozen head `oracle_release_runtime_w363`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 45/45 (false yes 0) vs head 4/45 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- OSHA 29 CFR 1910.95 (occupational noise: Table G-16, Appendix A dose and TWA formulas) (public domain (US government)) https://www.osha.gov/laws-regs/regulations/standardnumber/1910/1910.95 +- OSHA 29 CFR 1926.1053(b)(5)(i) (ladder 4-to-1 rule) (public domain (US government)) https://www.osha.gov/laws-regs/regulations/standardnumber/1926/1926.1053 +- NIOSH Applications Manual for the Revised NIOSH Lifting Equation (1994, metric) (public domain (US government)) https://www.cdc.gov/niosh/docs/94-110/ + +## What it takes + +- answers: noise_time, noise_dose, twa, ladder, rwl, lifting_index +- declines (in-domain): underspecified, judgement +- everything else falls through to the head unchanged + +## Notes and known gaps + +Regulation arithmetic only, cited. Never judges whether a specific workplace situation is safe (declined: needs a qualified person on site) - only workplace-context 'is it safe' questions are taken at all. NIOSH frequency and coupling multipliers are table values that must be stated, never assumed. Dev fix before held-out: each NIOSH input read by its own label ('horizontal distance' was readable as the travel distance). Full-core pre-check: 0 of 3107. diff --git a/workbench/data/cards/seismology.md b/workbench/data/cards/seismology.md new file mode 100644 index 0000000000000000000000000000000000000000..492d7ef719c28901f84b1bb2a76701db2bd3ec7f --- /dev/null +++ b/workbench/data/cards/seismology.md @@ -0,0 +1,25 @@ +# Oracle7 Seismology & Earthquakes (#23, tier B) + +**id** `seismology` - organ `organ_seismology_v1.SeismologyOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 29/34 (false yes 0) vs head 3/34 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- USGS Earthquake Hazards Program - magnitude, energy (10^1.5 per unit), amplitude (10x per unit), S-P travel-time location (public domain (US government)) https://www.usgs.gov/programs/earthquake-hazards/earthquake-magnitude-energy-release-and-shaking-intensity +- IASPEI standard moment magnitude Mw = (log10 M0 - 9.1)/1.5 (Hanks & Kanamori 1979) (facts) http://www.iaspei.org/commissions/commission-on-seismological-observation-and-interpretation/Summary_WG_recommendations_20130327.pdf + +## What it takes + +- answers: energy_ratio, amplitude_ratio, mw, m0, sp_distance, gr_count +- declines (in-domain): underspecified, impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +Relations named in each answer. 'How many times stronger' is ASKED BACK (energy 10^(1.5 dM) vs amplitude 10^dM differ) - never picked. S-P distance only with both wave speeds given (no rule of thumb); Gutenberg-Richter only with a and b. Never predicts or forecasts earthquakes (falls through). Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/spacecomms.md b/workbench/data/cards/spacecomms.md new file mode 100644 index 0000000000000000000000000000000000000000..c0c827570385cc61e638620d7dfb9be33691283f --- /dev/null +++ b/workbench/data/cards/spacecomms.md @@ -0,0 +1,26 @@ +# Oracle7 Delay-Tolerant Networking & Space Communications (#95, tier B) + +**id** `spacecomms` - organ `organ_spacecomms_v1.SpaceCommsOrgan` composed in front of the frozen head `oracle_release_runtime_w363`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 36/36 (false yes 0) vs head 0/36 (false yes 2) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- Exact constants: c = 299,792,458 m/s (SI), 1 AU = 149,597,870,700 m (IAU 2012 Resolution B2) (public (BIPM / IAU)) https://www.iau.org/static/resolutions/IAU2012_English.pdf +- Free-space path loss (Friis) as used in NASA DSN link design (DSN Telecommunications Link Design Handbook 810-005) (public domain (NASA/JPL)) https://deepspace.jpl.nasa.gov/dsndocs/810-005/ +- Delay-tolerant networking bundle protocol context: IETF RFC 9171 (IETF Trust) https://www.rfc-editor.org/rfc/rfc9171 + +## What it takes + +- answers: fspl, transfer_time, bits_in_flight, round_trip, light_time +- declines (in-domain): underspecified +- everything else falls through to the head unchanged + +## Notes and known gaps + +Distances between bodies are never assumed (they change as the planets move); a question naming only two bodies is declined. MB/GB are bytes and Mb/Gb bits, read from the original case. Transfer times exclude protocol overhead, said so. diff --git a/workbench/data/cards/spacecraft.md b/workbench/data/cards/spacecraft.md new file mode 100644 index 0000000000000000000000000000000000000000..74f9eeeaaaf143cbd56ddf31eb5e227a52cff1fb --- /dev/null +++ b/workbench/data/cards/spacecraft.md @@ -0,0 +1,24 @@ +# Oracle7 Spacecraft Operations (#18, tier B) + +**id** `spacecraft` - organ `organ_spacecraft_v1.SpacecraftOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 14/21 (false yes 0) vs head 0/21 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- NASA Glenn Research Center Beginner's Guide to Rockets: ideal rocket equation, specific impulse, thrust, mass flow (public domain (US government)) https://www.grc.nasa.gov/www/k-12/rocket/rktpow.html + +## What it takes + +- answers: delta_v, propellant, exhaust_velocity, twr, mass_flow, burn_time +- declines (in-domain): impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +Ideal (Tsiolkovsky) relations, g0 = 9.80665 m/s2, stated. Mass roles from grammar (initial/wet/fueled vs final/dry/empty/burnout), never order. Narrowed from the start (narrow_v1); no numbers rule. diff --git a/workbench/data/cards/sports.md b/workbench/data/cards/sports.md new file mode 100644 index 0000000000000000000000000000000000000000..6a47eb826b817a5307efa5925aa9a44c4e0e2e99 --- /dev/null +++ b/workbench/data/cards/sports.md @@ -0,0 +1,25 @@ +# Oracle7 Sports & Rules (statistics) (#72, tier B) + +**id** `sports` - organ `organ_sports_v1.SportsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 19/19 (false yes 0) vs head 0/19 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- MLB official statistics glossary (AVG, OBP, SLG, ERA, WHIP), NFL passer rating formula, basketball true shooting (published formulas) (facts (formulas)) https://www.mlb.com/glossary +- Wikipedia sports-statistics articles (formula cross-check) (CC-BY-SA 4.0 (store ships share-alike)) https://en.wikipedia.org/wiki/Passer_rating + +## What it takes + +- answers: avg, obp, slg, era, whip, passer_rating, ts_pct, win_pct, games_behind +- declines (in-domain): impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +Formulas named in every answer; innings in box-score thirds (6.2 = 6 2/3); no betting odds or predictions. Games-behind order-free (absolute value) and the panel puts the leader first and last (panel rule). Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/sql.md b/workbench/data/cards/sql.md new file mode 100644 index 0000000000000000000000000000000000000000..91456795f62188080b8ec80fac9d27c626f05d46 --- /dev/null +++ b/workbench/data/cards/sql.md @@ -0,0 +1,24 @@ +# Oracle7 SQL & Databases (#53, tier A) + +**id** `sql` - organ `organ_sql_v1.SqlOrgan` composed in front of the frozen head `oracle_release_runtime_w363`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 61/61 (false yes 0) vs head 2/61 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- SQLite (public domain) - the answer is SQLite's own execution of the user's statements (public domain) https://sqlite.org/copyright.html + +## What it takes + +- answers: valid, invalid, scalar, rows, error +- declines (in-domain): needs_data, runaway, setup_error +- everything else falls through to the head unchanged + +## Notes and known gaps + +Answers by execution in a sandboxed in-memory SQLite (authorizer denies ATTACH/extensions/PRAGMA writes; step budget; 1 MB value and 20k SQL limits). Panel results computed in Python over the generated rows, including SQL semantics (SUM of no rows is NULL, COUNT(col) skips NULLs). Dev fixes before held-out: concept questions ('What does SELECT mean?') are not executed; query errors classified as query errors. diff --git a/workbench/data/cards/units-v3.md b/workbench/data/cards/units-v3.md new file mode 100644 index 0000000000000000000000000000000000000000..00582c867035a77f6774981c2fcc33f71298f93a --- /dev/null +++ b/workbench/data/cards/units-v3.md @@ -0,0 +1,26 @@ +# Oracle7 Units & Metrology v3 (#47, tier A) + +**id** `units-v3` - organ `organ_units_v3.UnitsOrganV3` composed in front of the frozen head `oracle_release_runtime_w363`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 75/75 (false yes 0) vs head 4/75 (false yes 0) +- core capability panel: head 164 -> composed 164 (4 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- NIST SP 811 and the SI Brochure: exact definitions of the inch, foot, mile, pound, US gallon, atmosphere, calorie and others (public domain (NIST)) https://www.nist.gov/pml/special-publication-811 + +## What it takes + +- answers: convert, temperature +- declines (in-domain): mismatch, impossible +- everything else falls through to the head unchanged + +Supersedes: units-v2 (ADMIT gate v2, 43/74; misses = two-sentence 'I have N X. How many Y is that?') + +## Notes and known gaps + +v3 = v2 + the two-sentence quantity question joined into v1's canonical order. Judged under spec_gate_v2 on a FRESH panel (new seeds, new phrasings both splits including the class). Same author - disclosed. Earlier notes: v2 = v1 + (1) EXACT rational factors (all definitions are exact): whole results printed whole, fractional results as decimal + exact value - the full-core sweep found v1 answering 12 core conversions in decimals/exponent form where the family's exact form is expected ('470/127', '4384800'); (2) narrowing (narrow_v1): rate word problems not taken; (3) quantity-first phrasing read as a class ('250 g equals how many pounds?'). Judged under spec_gate_v2 on a FRESH panel v2 (new seeds, new phrasings both splits, time units, new mismatch declines). Same author - disclosed. DISCLOSED MEASUREMENT DEFE diff --git a/workbench/data/cards/ushistory.md b/workbench/data/cards/ushistory.md new file mode 100644 index 0000000000000000000000000000000000000000..e164d3c1bed5373f10ab9155398468e5f0459491 --- /dev/null +++ b/workbench/data/cards/ushistory.md @@ -0,0 +1,25 @@ +# Oracle7 US History & Civics (reference) (#77, tier A) + +**id** `ushistory` - organ `organ_ushistory_v1.UsHistoryOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 11/12 (false yes 1) vs head 0/12 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- National Archives milestone documents; Library of Congress presidents list (public domain (US government)) https://www.archives.gov/milestone-documents +- OpenStax U.S. History (CC-BY 4.0) https://openstax.org/details/books/us-history + +## What it takes + +- answers: nth_president, president_number, event_year +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Facts only: the presidential sequence (non-consecutive terms counted twice, as the official numbering does) and landmark years. Ranking / opinion questions are not taken. Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/warehouse-r2.md b/workbench/data/cards/warehouse-r2.md new file mode 100644 index 0000000000000000000000000000000000000000..cef77c49a6526588f74ea7ee5101b24ef325fb24 --- /dev/null +++ b/workbench/data/cards/warehouse-r2.md @@ -0,0 +1,26 @@ +# Oracle7 Warehouse & Inventory (r2, narrowed) (#1, tier A) + +**id** `warehouse-r2` - organ `organ_site_v3.SiteOrganV3` composed in front of the frozen head `oracle_release_runtime_w363`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 193/193 (false yes 0) vs head 7/193 (false yes 1) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- site store (operator's own data; here a seeded synthetic site) (operator-owned) + +## What it takes + +- answers: stock, where, runout, low, sensor, range, zone_status, neighbour, confirm, ordered, cancelled +- declines (in-domain): unknown_item, missing_sensor, stale +- everything else falls through to the head unchanged + +Supersedes: warehouse (v1 admitted 2026-09-29 under spec_gate_v1) + +## Notes and known gaps + +Fresh site (build seed 20261001, panel seed 8), never seen while the organ was developed; same zone names and item vocabulary as the development site, so this tests generalisation to new stock, bins and readings, not to new kinds of place. off_site items test DEVICE mode (world stores detached) and are excluded from the composed verdict. || r2 (2026-09-29): the full-core sweep found this organ taking core items outside its domain (reading passages, word problems, idioms). r2 = runtime v2 (reading turns -> head) + a NARROWING-ONLY organ patch (narrow_v1). INVARIANCE: r2's reply is byte-identical to v1's on 199/199 held-out inputs (counts only, no items or scores viewed), so the SAME held-out panel is re-run under spec_gate_v2 - its domain result is v1's by construction; what is newly measured is the full-core sweep with the per-item no-worse rule. diff --git a/workbench/data/cards/wildlife.md b/workbench/data/cards/wildlife.md new file mode 100644 index 0000000000000000000000000000000000000000..61e4068aab116155a8775459c55d01bfb079e6f3 --- /dev/null +++ b/workbench/data/cards/wildlife.md @@ -0,0 +1,24 @@ +# Oracle7 Wildlife & Conservation (#36, tier B) + +**id** `wildlife` - organ `organ_wildlife_v1.WildlifeOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 7/9 (false yes 0) vs head 2/9 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- USFWS / NPS wildlife survey methods: mark-recapture (Lincoln-Petersen, Chapman), density, survival (public domain (US government)) https://www.fws.gov/ + +## What it takes + +- answers: lincoln, chapman, density, survival, mortality +- declines (in-domain): underspecified, impossible +- everything else falls through to the head unchanged + +## Notes and known gaps + +M / C / R from grammar (marked / second sample / recaptured), never order; the panel varies the order (panel rule). A recognised mark-recapture question missing a count DECLINES (recognise-then-decline law). Narrowed from the start (narrow_v1). diff --git a/workbench/data/cards/wiring.md b/workbench/data/cards/wiring.md new file mode 100644 index 0000000000000000000000000000000000000000..9b211e50c51e6dec82ba91c63fb8f75fe482e869 --- /dev/null +++ b/workbench/data/cards/wiring.md @@ -0,0 +1,25 @@ +# Oracle7 Electrical Systems & Wiring (#12, tier B) + +**id** `wiring` - organ `organ_wiring_v1.WiringOrgan` composed in front of the frozen head `oracle_release_runtime_w363`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 45/45 (false yes 0) vs head 3/45 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- AWG definition (ASTM B258): d = 0.127 mm x 92^((36-n)/39); IACS annealed copper resistivity 1/58 uohm m (facts / standards definitions) https://www.nist.gov/ +- NEC 210.19(A)(1) / 210.20(A) continuous-load 80% rule, as summarised in OSHA and US Navy NEETS training material (public domain (US government summaries)) https://www.osha.gov/electrical + +## What it takes + +- answers: continuous, vdrop, resistance, area, diameter, current3, current +- declines (in-domain): underspecified, judgement +- everything else falls through to the head unchanged + +## Notes and known gaps + +Arithmetic only; never says an installation is safe or to code (declined: licensed electrician + local code). Resistances at 20 C. Three-phase power factor taken as 1 only when not given, and said so. Check: 12 AWG = 2.053 mm. diff --git a/workbench/data/cards/worldhistory.md b/workbench/data/cards/worldhistory.md new file mode 100644 index 0000000000000000000000000000000000000000..dc44034ca0fbf11287de27a7c2e5f09f7bd74a8c --- /dev/null +++ b/workbench/data/cards/worldhistory.md @@ -0,0 +1,24 @@ +# Oracle7 World History (reference) (#76, tier A) + +**id** `worldhistory` - organ `organ_facts_v1.FactsOrgan` composed in front of the frozen head `oracle_release_runtime_w503`. + +## Verdict + +- decision: **ADMIT** (gate v2) +- held-out domain: specialist 11/11 (false yes 0) vs head 4/11 (false yes 0) +- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep) +- reasons: none + +## Sources and licences + +- OpenStax World History, Volumes 1 and 2 (CC-BY 4.0) https://openstax.org/details/books/world-history-volume-2 + +## What it takes + +- answers: world_history +- declines (in-domain): none +- everything else falls through to the head unchanged + +## Notes and known gaps + +Typed-fact organ (shared organ_facts_v1): landmark years and figures only; US history lives in #77; opinion / moral judgement turns are blocked. Narrowed (narrow_v1). diff --git a/workbench/static/index.html b/workbench/static/index.html new file mode 100644 index 0000000000000000000000000000000000000000..4396d02053c9fe6a0e78cf38a6cddea97da0bdd3 --- /dev/null +++ b/workbench/static/index.html @@ -0,0 +1,187 @@ + + + + + +Oracle7 Workbench + + + +

+
ORACLE7WORKBENCH
+
+ core … + 267 specialists + 0 of yours + gap journal off + 127.0.0.1 · nothing leaves this machine +
+
+ +
+ + + +
+
Ask
+
this answer's path your specialists declined at a check
+
+
+

Ask anything. Each answer lights the path it took through the diagram above. When Oracle7 cannot verify an answer it says so and says why, and the Gaps tab can turn those declines into the specialists your model is missing.

+
+
+
+
+
+ + +
+ +
+

Point Oracle7 at something of yours and it becomes a reader you can ask about it. Each answer names where it read the value. Everything stays on this computer. Type /help in the chat for every feature and command.

+
+

1Scan this computer

+

System, CPU, memory, disks, uptime and what is using the most memory. Figures and process names only, never your files.

+
+
+
+
+

2Connect a server

+

Read a server over SSH with your own key: hostname, uptime, load, memory, disks, top processes, failed services. Read-only; no password is ever asked for.

+
+ +
+
+
+

3Add files

+

Drop tables (.csv, .tsv) or text (.txt, .md) here, or . Ask "what is the price of item 4?" or "what do my notes say about the boiler?".

+
+
+
+

4Connect an MCP server

+

Give the command that starts it or its URL. Pick its tools and the Workbench builds a specialist that routes each question to the right tool, shows the exact call it made, and learns from your right / wrong marks. Questions routed to a server are sent to it.

+
+ +
+
+
+

5Connect a sensor

+

A device or hub that serves JSON or metrics over HTTP (ESP32, Shelly, Tasmota, Home Assistant, a weather station), an MQTT topic, a USB/serial device, or a log file. No hardware yet? Try the simulated garden node. Readings are kept for 24 hours on this computer; answers give the value, its age and its source.

+
+
+

Or write a specialist by hand on the Build tab.

+
+
+
+ +
+
+ +
+
+

No sensors yet.

+
+

+Connect a sensor

+
+ + + + + + +
+ +
+
+
+

+
+

A specialist is a small program that answers one kind of question and declines the rest. It joins your model only by passing its held-out exam; it can only add answers where the core declined.

+
+
+
+ +
+
+

With the journal on, each question you ask and whether it was answered is kept in workbench/local/journal.jsonl on this machine only. Nothing is sent or packaged. Declines are grouped into the specialists your model is missing.

+
+
+
+
+

Ask for a function. The code organ hands over only programs it has run, so it writes what it can prove and declines the rest. It can write and prove: a small working website, palindrome check, factorial, vowel count, word count and word frequencies, HTTP routes, regular-expression extraction, memoised recursion, a bank-account class, matrix multiply, fizzbuzz, fibonacci, reverse a string, JSON round-trip, concurrent work, binary search, tower of hanoi, quicksort, sum a list, prime test, a number-guessing game, tic tac toe. The bench runs any code against tests of your own in a separate Python process with a time limit.

+
+
+ + +
+ +
+
+

Record answers as a film: the diagram tracing each path, the question, the answer and its receipt. Made in your browser as a .webm file; nothing is uploaded.

+

Ask something first; each answer can be filmed.

+
+

+Narration, sound and images optional · ElevenLabs

+

Connect your own ElevenLabs account to narrate each answer, lay a sound you describe underneath and open each answer with an illustration (images need their Pro plan). This is the only feature that sends anything off this computer: the narration text, sound description and image prompts go to ElevenLabs with your key. Generated images are labelled as generated in the film.

+
+ +
+
+ + +
+
+

Package a specialist for the community registry: its folder, its exam verdict and the SHA-256 of every file. Your questions and journal are never included. Uploading is your choice, with your own Hugging Face account.

+
+ +

Use a shared specialist

+
+

An imported specialist takes its held-out exam on your machine before it joins your model.

+
+
+ + +
+
Log
+
    +
    +
    + + + + + + + diff --git a/workbench/static/o7-explorer.js b/workbench/static/o7-explorer.js new file mode 100644 index 0000000000000000000000000000000000000000..a3c039506fd6a4e44e3eaab7d7443597d1362797 --- /dev/null +++ b/workbench/static/o7-explorer.js @@ -0,0 +1,264 @@ +/* Oracle7 architecture explorer (Workbench copy: preserveDrawingBuffer for films, addModule for your specialists) — themeable. Requires THREE (r128) + OrbitControls. + Usage: const ex = O7Explorer(hostEl, { palette: {...}, onSelect(id) {} }); + Data: the release head w540 (chain of 317 folds) and the specialist ledger on Box C, 2026-10-14. + trace(steps) lights the exact path one answer took: steps = [[stageId, moduleName|null], ...]. */ +(function () { + const STAGES = [ + { id: "L5", name: "Self-model", y: 8.0, r: 2.4, blurb: "The model reading and explaining its own record.", mods: [ + ["Self record & atlas", "w33 · w110 · w117"], ["Self-explanation", "w412: explains itself from its records"], + ["Self-improvement voice", "30 epoch folds, w10 → w342"], ["Charter & milestones", "open capability milestones"]] }, + { id: "L4", name: "Speak & verify", y: 6.4, r: 3.0, blurb: "Turning a bound answer into cited text, and refusing what fails a check.", mods: [ + ["Receipts", "w536: a relation answer names the record it read, both ends with ids"], + ["Final-answer checks", "w532–w534: sign kept, private questions, false date premise, thousands, units, word sense"], + ["Same-name check", "w538: stays with the thing the conversation is about"], + ["Supporting sentence", "w538: a quoted sentence that lost its numbers is dropped"], + ["Answer checks", "w539 · w540: a name is not arithmetic; a count names what it counts; a question's direction; a zero read back; a definition is not a private answer"], + ["Precision guard", "declines what it cannot verify, and says why"], ["Speaker", "evidence-bound"]] }, + { id: "L3", name: "Conversation state", y: 4.8, r: 3.5, blurb: "What the conversation is about, and what was already said.", mods: [ + ["Conversation engine", "subject, topic, last answer and last result, per session"], + ["Follow-up resolver", "\"When was he born?\" is read against the last answer"], + ["Two-part turns", "w533 · w537: each part goes through the whole pipeline"], + ["Hand-offs", "w533: a follow-up goes back to the specialist that answered"], + ["Conversation acts", "greetings, thanks, clarification"], ["Dialogue organ", "w480: what did I ask, you didn't answer me"]] }, + { id: "L2", name: "Route", y: 3.2, r: 3.9, blurb: "Choosing what answers: a specialist, an organ, or the stored text.", mods: [ + ["Exact router", "w524: typed question shapes to one relation"], + ["General reader", "w539 · w540: one Wikidata fact away, on reading declines; held-out 81 of 82"], + ["Family precedence", "w536: relation specialists answer relation questions first (34 more right, 0 lost)"], + ["Specialist call", "picks the admitted specialist for the domain"], ["Organ dispatch", "w480: math, relation, dialogue, code"], + ["Factoid & reading", "w420 · w432 · w434 · w442"], ["Deliberation", "where / when / who over stored text"], + ["Capability routes", "summarize, compare, timeline, explain…"], ["Compose", "w426: inference over two sentences"], + ["Path memory", "research: learned route credit; off until it wins a sealed test"], + ["Front parser", "about half of open trivia phrasings are not parsed (census 10-13); declined, never guessed", "hazard"]] }, + { id: "L1", name: "Parse", y: 1.6, r: 3.5, blurb: "From words to a typed request.", mods: [ + ["Construction grammar", "K8 grammar, runtime N"], ["Typed request / λ-IR", "M13E4 runtime, frozen"], ["Obligations IR", "program_ir_v1"], + ["Splitting", "runtimes AJ · AK · and-parts w533"], ["Frame", "w34"]] }, + { id: "L0", name: "Intake", y: 0.0, r: 3.0, blurb: "Where a request arrives and leaves.", mods: [ + ["Front door", "chat(text, session): sessions, provenance"], ["Harness v21", "response contract"], ["Salience arbitrator", "harness v20"], + ["Live demo", "a public talk page · nothing typed is stored"]] }, + { id: "S", name: "Specialists", y: -1.8, r: 4.3, blurb: "267 small verified programs. Each was admitted by a held-out exam it saw once; 23 failed and stayed out. On their exams: 15,478 right, 14 wrong.", spec: true, mods: [ + ["Relation readers", "161: moons, directors, novels, painters, composers…"], ["Physical science", "densities, units, energy, thermo, optics, decay…"], + ["Earth & life", "geology, ecology, botany, medicine, genetics…"], ["Computing", "python, sql, git, linux, networking…"], + ["Space", "orbits, spacecraft, space comms, planetary"], ["Everyday", "cooking, gardening, first aid, finance…"], + ["Humanities", "literature, law, music, world history…"], ["Exam ledger", "every admission and failure, published"]] }, + { id: "E", name: "Engines", y: -3.6, r: 3.7, blurb: "Computing what should never be memorised.", engine: true, mods: [ + ["Calculator", "w29 · w458: calculator or refuse"], ["Algebra", "w55"], ["Deduction", "w54 · closure runtime AD"], ["Dates", "runtimes Y · AB"], + ["TeX reader", "w428"], ["Math organ", "exact moves, independently checked"], ["Code organ", "w482 · w486: run on your examples, graded"], + ["Word problems", "w488: single-step schemas"], ["Weight from mass", "w538: W = m·g from a stated mass"], ["Operator host", "w59 · w61 · w65"]] }, + { id: "V", name: "Knowledge vault", y: -5.4, r: 5.2, blurb: "Everything it knows, each sentence addressable and cited.", store: true, mods: [ + ["Deep store", "6,339,707 pages · 20,529,863 sentences"], ["Relation edges", "edges.sqlite, 2.2 GB"], ["ConceptNet", "3,422,938 edges"], + ["Wiktionary", "1,486,439 entries"], ["WordNet", "kinds, hypernyms"], ["Textbook store", "20 books · 143,355 typed items"], ["Relation store", "Wikidata · 10.35M entities"]] }, + ]; + const LOOP = [["Failure inbox", "structured failure records", 270], ["Fold worker", "repairs drafted from the inbox", 215], ["Candidate", "one in flight at a time", 150], + ["GATE", "4,114 held-out checks; nothing may get worse", 90, "gate"], ["HEAD_MANIFEST", "every consumer resolves the tip here", 35], + ["Sealed tests", "written before the build, run once (12–19)", 5], ["Served head", "w540", 342], ["Benchmark organ", "rotating unseen windows", 318], ["Stimuli organ", "random conversation pressure", 294]]; + const FAMILY = [["oracle7-deepspace", "98.9% on fresh spacecraft faults"], ["oracle7-vision", "MNIST 98.58% · cites its examples"], ["oracle7-trafficcop", "30/32 held-out routes"], + ["oracle7-chameleon", "builds sites · 0 false completions"], ["oracle7-artist", "composes from cited parts"]]; + + function O7Explorer(host, opt) { + opt = opt || {}; + const P = Object.assign({ ink: 0x15100d, line: 0x342820, accent: 0x2f7d73, store: 0x2a3b52, hazard: 0xc49132, fresh: 0xc0602e, bad: 0x9a3b1d, spec: 0x946d1e, lit: 0xc0602e, muted: 0x6a5a47, discOpacity: 0.05, lineOpacity: 0.6 }, opt.palette || {}); + const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches; + const canvas = document.createElement("canvas"); canvas.className = "o7-canvas"; host.appendChild(canvas); + const labelsEl = document.createElement("div"); labelsEl.className = "o7-labels"; host.appendChild(labelsEl); + const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, preserveDrawingBuffer: true }); + renderer.setPixelRatio(Math.min(devicePixelRatio || 1, 2)); + const scene = new THREE.Scene(), camera = new THREE.PerspectiveCamera(38, 1, 0.1, 500); + const controls = new THREE.OrbitControls(camera, canvas); + controls.enableDamping = true; controls.dampingFactor = 0.08; controls.minDistance = 8; controls.maxDistance = 80; controls.enableZoom = opt.zoom !== false; + controls.autoRotate = !reduce; controls.autoRotateSpeed = 0.35; + canvas.addEventListener("pointerdown", () => { controls.autoRotate = false; }); + + function line(points, color, opacity, dashed) { + const g = new THREE.BufferGeometry().setFromPoints(points); + const m = dashed ? new THREE.LineDashedMaterial({ color, transparent: true, opacity, dashSize: 0.25, gapSize: 0.18 }) : new THREE.LineBasicMaterial({ color, transparent: true, opacity }); + const l = new THREE.Line(g, m); if (dashed) l.computeLineDistances(); return l; + } + const circle = (r, seg) => { const p = []; for (let i = 0; i <= seg; i++) { const a = i / seg * Math.PI * 2; p.push(new THREE.Vector3(Math.cos(a) * r, 0, Math.sin(a) * r)); } return p; }; + const labels = []; + function label(text, getPos, cls, show, extra) { const el = document.createElement("div"); el.className = "o7l " + (cls || ""); el.textContent = text; labelsEl.appendChild(el); const L = Object.assign({ el, getPos, show: show || (() => true) }, extra || {}); labels.push(L); return L; } + + const st = { mode: opt.mode || "improve", selected: opt.select === undefined ? "L2" : opt.select, showAll: false, spread: 0, spreadT: 0, cube: false }; + const stageObjs = [], idx = s => STAGES.length - 1 - STAGES.indexOf(s), stageY = s => s.y + st.spread * (idx(s) - 3) * 0.9; + STAGES.forEach(s => { + const g = new THREE.Group(); scene.add(g); + const col = s.store ? P.store : P.line; + const disc = new THREE.Mesh(new THREE.CircleGeometry(s.r, 64).rotateX(-Math.PI / 2), new THREE.MeshBasicMaterial({ color: s.store ? P.store : P.accent, transparent: true, opacity: P.discOpacity, side: THREE.DoubleSide, depthWrite: false })); + disc.userData.stage = s.id; g.add(disc); + g.add(line(circle(s.r, 96), col, P.lineOpacity)); g.add(line(circle(s.r * 0.35, 48), col, 0.2)); + const mods = []; + s.mods.forEach((m, i) => { + const a = i / s.mods.length * Math.PI * 2 + s.y * 0.3, hz = m[2] === "hazard", x = Math.cos(a) * s.r, z = Math.sin(a) * s.r; + const geo = s.engine ? new THREE.BoxGeometry(0.28, 0.28, 0.28) : s.spec ? new THREE.SphereGeometry(0.17, 12, 8) : new THREE.OctahedronGeometry(hz ? 0.26 : 0.17); + const base = hz ? P.hazard : s.store ? P.store : s.spec ? P.spec : P.accent; + const node = new THREE.Mesh(geo, new THREE.MeshBasicMaterial({ color: base })); + node.position.set(x, 0, z); node.userData.stage = s.id; g.add(node); + g.add(line([new THREE.Vector3(0, 0, 0), new THREE.Vector3(x, 0, z)], col, hz ? 0.55 : 0.14)); + let Lr = null; + Lr = label(m[0], () => new THREE.Vector3(x, g.position.y + 0.1, z), hz ? "hazard" : s.store ? "store" : s.spec ? "spec" : "", () => st.showAll || st.selected === s.id || (hz && !st.quiet) || (Lr && Lr.lit)); + mods.push({ x, z, hz, name: m[0], node, base, L: Lr }); + }); + const LL = label(s.name, () => new THREE.Vector3(s.r + 0.4, g.position.y, 0), "layer", null, { stage: s.id }); + LL.el.style.pointerEvents = "auto"; LL.el.style.cursor = "pointer"; + LL.el.addEventListener("click", () => { api.select(s.id); opt.onSelect && opt.onSelect(s.id); }); + stageObjs.push({ s, g, disc, mods }); + }); + const V = stageObjs.find(o => o.s.store); + { const n = 6000, pos = new Float32Array(n * 3); + for (let i = 0; i < n; i++) { const r = Math.sqrt(Math.random()) * 5.1, a = Math.random() * Math.PI * 2; pos[i * 3] = Math.cos(a) * r; pos[i * 3 + 1] = (Math.random() - 0.5) * 0.5 * (1 - r / 6); pos[i * 3 + 2] = Math.sin(a) * r; } + const geo = new THREE.BufferGeometry(); geo.setAttribute("position", new THREE.BufferAttribute(pos, 3)); + V.cloud = new THREE.Points(geo, new THREE.PointsMaterial({ color: P.store, size: 0.035, transparent: true, opacity: 0.6 })); V.g.add(V.cloud); } + label("20,529,863 cited sentences", () => new THREE.Vector3(0, V.g.position.y - 0.7, 5.4), "store"); + const spine = line([new THREE.Vector3(0, -3.8, 0), new THREE.Vector3(0, 8.6, 0)], P.accent, 0.7); scene.add(spine); + + const LC = { y: 2.1, rx: 8.2, ry: 7.4 }; + const loopPt = (deg, out) => { const a = deg * Math.PI / 180; return (out || new THREE.Vector3()).set(Math.cos(a) * LC.rx, LC.y + Math.sin(a) * LC.ry, 0); }; + const loopPts = []; for (let i = 0; i <= 160; i++) loopPts.push(loopPt(i / 160 * 360)); + const loopLine = line(loopPts, P.accent, 0.5, true); scene.add(loopLine); + const gateMesh = new THREE.Mesh(new THREE.TorusGeometry(0.75, 0.05, 8, 48), new THREE.MeshBasicMaterial({ color: P.accent })); gateMesh.position.copy(loopPt(90)); scene.add(gateMesh); + LOOP.forEach(L => { const p = loopPt(L[2]); + if (L[3] !== "gate") { const b = new THREE.Mesh(new THREE.BoxGeometry(0.34, 0.34, 0.34), new THREE.MeshBasicMaterial({ color: P.accent })); b.position.copy(p); scene.add(b); } + label(L[0], () => p.clone().add(new THREE.Vector3(0, L[3] === "gate" ? 1.0 : 0.25, 0)), L[3] === "gate" ? "gate" : "loop", () => st.mode === "improve" || st.showAll || L[3] === "gate"); }); + label("Self-improvement loop", () => loopPt(160).add(new THREE.Vector3(-0.4, 0, 0)), "big loop", () => st.mode === "improve"); + const lp = new THREE.Mesh(new THREE.SphereGeometry(0.18, 16, 12), new THREE.MeshBasicMaterial({ color: P.accent })); scene.add(lp); + const rejects = []; + + const famObjs = FAMILY.map((f, i) => { + const m = new THREE.Mesh(new THREE.IcosahedronGeometry(0.42, 1), new THREE.MeshBasicMaterial({ color: P.accent, wireframe: true })); + m.add(new THREE.Mesh(new THREE.SphereGeometry(0.16, 12, 8), new THREE.MeshBasicMaterial({ color: P.ink }))); scene.add(m); + const tether = line([new THREE.Vector3(), new THREE.Vector3(0, 1, 0)], P.accent, 0.25, true); scene.add(tether); + label(f[0], () => m.position.clone().add(new THREE.Vector3(0, 0.55, 0)), "fam", () => st.mode === "family" || st.showAll); + label(f[1], () => m.position.clone().add(new THREE.Vector3(0, -0.25, 0)), "famsub", () => st.mode === "family"); + return { m, tether, a0: i / FAMILY.length * Math.PI * 2 }; + }); + const famOrbit = line(circle(11.5, 128), P.muted, 0.25, true); famOrbit.position.y = 3.2; scene.add(famOrbit); + + const SEPH = { keter: [0, 6.6], chokmah: [1.7, 5.6], binah: [-1.7, 5.6], chesed: [1.7, 4.4], geburah: [-1.7, 4.4], tiferet: [0, 3.3], netzach: [1.7, 2.2], hod: [-1.7, 2.2], yesod: [0, 1.2], malkuth: [0, 0] }; + const PATHS = [["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"]]; + const MID = new Set(["keter", "tiferet", "yesod", "malkuth"]); + const cube = new THREE.Group(); cube.visible = false; scene.add(cube); + [0, 60, 120].forEach((deg, ti) => { + const a = deg * Math.PI / 180, tp = s => { const [x0, y] = SEPH[s]; const x = MID.has(s) ? 0 : x0 * 0.6; return new THREE.Vector3(x * Math.cos(a), y * (8 / 6.6), -x * Math.sin(a)); }; + const pts = []; PATHS.forEach(([p, q]) => { if (!(MID.has(p) && MID.has(q)) || ti === 0) pts.push(tp(p), tp(q)); }); + cube.add(new THREE.LineSegments(new THREE.BufferGeometry().setFromPoints(pts), new THREE.LineBasicMaterial({ color: P.fresh, transparent: true, opacity: 0.85 }))); + }); + label("Reasoning cube (proposed)", () => new THREE.Vector3(0, 10.1, 0), "new big", () => st.cube); + + const rq = new THREE.Mesh(new THREE.SphereGeometry(0.2, 16, 12), new THREE.MeshBasicMaterial({ color: P.ink })); scene.add(rq); + let rqT = 0, rqStop = false; + const Y = id => stageObjs.find(o => o.s.id === id).g.position.y; + const modPt = (sid, name) => { const o = stageObjs.find(o => o.s.id === sid); const d = o.mods.find(m => m.name === name) || o.mods[0]; return new THREE.Vector3(d.x, o.g.position.y, d.z); }; + function rqPath() { + const up = id => new THREE.Vector3(0, Y(id), 0); + if (st.cube) return [up("L0"), up("L1"), up("L2"), new THREE.Vector3(0, Y("E"), 0), new THREE.Vector3(2.5, Y("V"), 1.5), up("L3"), up("L4"), up("L0")]; + // a typical answer: parse, read the conversation, route to a specialist, read its record, check, speak. Some are declined at the guard. + return rqStop ? [up("L0"), up("L1"), up("L3"), modPt("L2", "Specialist call"), modPt("S", "Relation readers"), modPt("V", "Relation store"), modPt("L4", "Precision guard"), modPt("L4", "Precision guard"), up("L0")] + : [up("L0"), up("L1"), up("L3"), modPt("L2", "Specialist call"), modPt("S", "Relation readers"), modPt("V", "Relation store"), modPt("L4", "Receipts"), up("L4"), up("L0")]; + } + + const traceLine = new THREE.Line(new THREE.BufferGeometry(), new THREE.LineBasicMaterial({ color: P.lit, transparent: true, opacity: 0.95 })); + traceLine.visible = false; scene.add(traceLine); + function clearTrace() { + stageObjs.forEach(o => o.mods.forEach(m => { if (m.L.lit) { m.L.lit = false; m.L.el.classList.remove("lit"); m.node.material.color.setHex(m.base); m.node.scale.setScalar(1); } })); + st.trace = null; + } + const api = { + data: { STAGES, LOOP, FAMILY }, + trace(steps, declined) { + clearTrace(); + const refs = []; + (steps || []).forEach(([sid, name]) => { const o = stageObjs.find(x => x.s.id === sid); if (!o) return; + const m = name ? o.mods.find(x => x.name === name) || null : null; + const last = refs[refs.length - 1]; if (last && last.o === o && last.m === m) return; refs.push({ o, m }); }); + if (!refs.length) return []; + st.trace = refs; st.traceT = 0; st.traceDeclined = !!declined; st.mode = "trace"; controls.autoRotate = false; + return refs.filter(r => r.m).map(r => [r.o.s.name, r.m.name]); + }, + clearTrace() { clearTrace(); if (st.mode === "trace") st.mode = opt.mode || "improve"; }, + setQuiet(on) { st.quiet = !!on; }, + setMode(m) { st.mode = m; }, + get mode() { return st.mode; }, + select(id) { st.selected = id; stageObjs.forEach(o => { o.disc.material.opacity = o.s.id === id ? P.discOpacity * 3.5 : P.discOpacity; }); labels.forEach(L => { if (L.stage) L.el.classList.toggle("sel", L.stage === id); }); }, + setSpread(on) { st.spreadT = on ? 1 : 0; if (reduce) st.spread = st.spreadT; }, + setCube(on) { st.cube = !!on; cube.visible = st.cube; }, + setShowAll(on) { st.showAll = !!on; }, + canvas, + // a specialist you admitted joins the Specialists ring, outside the release's own groups + addModule(sid, name) { + const o = stageObjs.find(x => x.s.id === sid); if (!o || o.mods.some(m => m.name === name)) return; + const k = o.mods.filter(m => m.mine).length, a = -Math.PI / 2 + k * 0.42, R = o.s.r + 1.3, x = Math.cos(a) * R, z = Math.sin(a) * R; + const node = new THREE.Mesh(new THREE.OctahedronGeometry(0.24), new THREE.MeshBasicMaterial({ color: P.fresh })); + node.position.set(x, 0, z); node.userData.stage = sid; o.g.add(node); + o.g.add(line([new THREE.Vector3(Math.cos(a) * o.s.r, 0, Math.sin(a) * o.s.r), new THREE.Vector3(x, 0, z)], P.fresh, 0.7, true)); + const m = { x, z, hz: false, name, node, base: P.fresh, mine: true }; let Lr = null; + Lr = label(name, () => new THREE.Vector3(x, o.g.position.y + 0.1, z), "mine", () => true); m.L = Lr; o.mods.push(m); + }, + // what is on screen, for drawing a film frame: every visible label with its pixel position and class + labelsOnScreen() { return labels.filter(L => L.el.style.display !== "none").map(L => ({ text: L.el.textContent, x: parseFloat(L.el.style.left) || 0, y: parseFloat(L.el.style.top) || 0, cls: L.el.className })); }, + setView(v) { const VIEWS = { iso: [20, 11, 24], side: [0.01, 2.6, 34], top: [0.01, 44, 0.02] }; camera.position.set(...VIEWS[v]); controls.target.set(0, 1.6, 0); controls.update(); }, + }; + const ray = new THREE.Raycaster(), mouse = new THREE.Vector2(); let downAt = null; + canvas.addEventListener("pointerdown", e => { downAt = [e.clientX, e.clientY]; }); + canvas.addEventListener("pointerup", e => { + if (!downAt || Math.hypot(e.clientX - downAt[0], e.clientY - downAt[1]) > 5) return; + const r = canvas.getBoundingClientRect(); mouse.set((e.clientX - r.left) / r.width * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1); + ray.setFromCamera(mouse, camera); const hit = ray.intersectObjects(stageObjs.map(o => o.g), true).find(h => h.object.userData.stage); + if (hit) { api.select(hit.object.userData.stage); opt.onSelect && opt.onSelect(hit.object.userData.stage); } + }); + function resize() { const w = host.clientWidth, h = host.clientHeight; if (!w || !h) return; renderer.setSize(w, h, false); camera.aspect = w / h; camera.updateProjectionMatrix(); } + new ResizeObserver(resize).observe(host); + + const v = new THREE.Vector3(); let last = performance.now(), loopDeg = 270, cycle = 0; + function frame(now) { + const dt = Math.max(0, Math.min(0.05, (now - last) / 1000)), s = now / 1000; last = now; + st.spread += (st.spreadT - st.spread) * Math.min(1, dt * 4); + stageObjs.forEach(o => { o.g.position.y = stageY(o.s); }); + if (!reduce) V.cloud.rotation.y += dt * 0.05; + spine.geometry.setFromPoints([new THREE.Vector3(0, Y("V"), 0), new THREE.Vector3(0, Y("L5") + 0.6, 0)]); + if (!reduce) loopDeg -= dt * 40; if (loopDeg < -90) loopDeg += 360; + const d = ((loopDeg % 360) + 360) % 360; loopPt(d, lp.position); + lp.visible = st.mode === "improve"; loopLine.material.opacity = st.mode === "improve" ? 0.7 : 0.25; + gateMesh.rotation.y = s * 0.8; gateMesh.scale.setScalar(1 + 0.08 * Math.sin(s * 3)); + if (st.mode === "improve" && Math.abs(d - 90) < dt * 40 + 0.01) { + cycle++; + if (cycle % 3 === 0) { lp.material.color.setHex(P.bad); const rj = new THREE.Mesh(new THREE.SphereGeometry(0.16, 10, 8), new THREE.MeshBasicMaterial({ color: P.bad, transparent: true })); rj.position.copy(lp.position); rj.userData.v = new THREE.Vector3(1.8, 2.4, 1.2); scene.add(rj); rejects.push(rj); opt.onGate && opt.onGate(false); } + else { lp.material.color.setHex(P.accent); opt.onGate && opt.onGate(true); } + } + if (d < 60 || d > 280) lp.material.color.setHex(P.accent); + for (let i = rejects.length - 1; i >= 0; i--) { const r = rejects[i]; r.position.addScaledVector(r.userData.v, dt); r.userData.v.y -= dt * 3; r.material.opacity -= dt * 0.6; if (r.material.opacity <= 0) { scene.remove(r); rejects.splice(i, 1); } } + famObjs.forEach((f, i) => { const a = f.a0 + (reduce ? 0 : s * 0.08); f.m.position.set(Math.cos(a) * 11.5, 3.2 + Math.sin(s * 0.7 + i) * 0.3, Math.sin(a) * 11.5); f.m.rotation.y = s * 0.5; + f.tether.geometry.setFromPoints([f.m.position, new THREE.Vector3(0, Y("L2"), 0)]); f.tether.computeLineDistances(); f.tether.material.opacity = st.mode === "family" ? 0.6 : 0.12; }); + famOrbit.material.opacity = st.mode === "family" ? 0.45 : 0.15; + rq.visible = st.mode === "answer" || st.mode === "trace"; + traceLine.visible = st.mode === "trace"; + if (st.mode === "trace" && st.trace) { + const pts = st.trace.map(r => r.m ? new THREE.Vector3(r.m.x, r.o.g.position.y, r.m.z) : new THREE.Vector3(0, r.o.g.position.y, 0)); + const n = pts.length - 1; + if (n <= 0) { rq.position.copy(pts[0]); } else { + st.traceT = reduce ? n : Math.min(n, st.traceT + dt * 1.5); + const i = Math.min(n - 1, Math.floor(st.traceT)), k = st.traceT - i; + rq.position.copy(pts[i]).lerp(pts[i + 1], Math.min(1, k)); + const drawn = pts.slice(0, i + 1).concat([rq.position.clone()]); + traceLine.geometry.setFromPoints(drawn); + st.trace.forEach((r, j) => { if (r.m && j <= st.traceT + 0.01 && !r.m.L.lit) { r.m.L.lit = true; r.m.L.el.classList.add("lit"); r.m.node.material.color.setHex(P.lit); r.m.node.scale.setScalar(1.9); } }); + } + rq.material.color.setHex(st.traceDeclined ? P.hazard : P.lit); + } + if (st.mode === "answer") { + const path = rqPath(); if (!reduce) rqT += dt * 0.9; + if (rqT >= path.length - 1) { rqT = 0; rqStop = Math.random() < 0.3; } + const i = Math.max(0, Math.min(path.length - 2, Math.floor(rqT))), k = Math.min(1, Math.max(0, rqT - i)); rq.position.copy(path[i]).lerp(path[Math.min(path.length - 1, i + 1)], k); + rq.material.color.setHex(!st.cube && rqStop && i >= 6 ? P.hazard : st.cube ? P.fresh : P.ink); + } + controls.update(); renderer.render(scene, camera); + const w = host.clientWidth, h = host.clientHeight; + labels.forEach(L => { if (!L.show()) { L.el.style.display = "none"; return; } v.copy(L.getPos()).project(camera); + if (v.z > 1) { L.el.style.display = "none"; return; } L.el.style.display = ""; L.el.style.left = ((v.x + 1) / 2 * w) + "px"; L.el.style.top = ((1 - v.y) / 2 * h) + "px"; }); + requestAnimationFrame(frame); + } + resize(); api.setView(opt.view || "iso"); if (st.selected) api.select(st.selected); + requestAnimationFrame(frame); + return api; + } + O7Explorer.data = { STAGES, LOOP, FAMILY }; + window.O7Explorer = O7Explorer; +})();