Release 12.0 (full): one browser harness that converses, writes from held sources and builds what you describe, keeping each request through corrections and restarts. No language model. (part 5)
Browse filesHead oracle_release_runtime_w575. Root 507d4c9ed8427d70c9a5cf209fe3f5928a2a52e2429c7eeae6d5c4e4f8bfb237. Supersedes 11.0.1 (ebda97495a9d). Judged by the revised candidate's own outcome checks, run on this code through the shipped page on fresh fixtures: browser outcomes 23 of 23, restart outcomes 16 of 16 (records/12/codex_browser_outcomes_c63.json, codex_restart_outcomes_c63.json). Gate: reference 600 through the door against the head: 0 lost, 0 new wrong; every earlier frozen set unchanged. Writing is built from held source sentences and checked against the requested size; open-ended conversation, writing and building beyond these checks are the next version's work. Records: records/12 and records/115. Changelog: CHANGELOG_12.md.
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- workbench/judge/project_sources_judge.pyAdded+154
- workbench/kernel/kernel_cli.pyAdded+55
- workbench/kernel/kernel_v0.pyAdded+128
- workbench/kernel/kernel_v1.pyAdded+92
- workbench/kernel/kernel_v2.pyAdded+187
- workbench/kernel/kernel_v3.pyAdded+27
- workbench/kernel/kernel_v4.pyAdded+176
- workbench/kernel/kernel_v5.pyAdded+73
- workbench/kernel/kernel_v6.pyAdded+56
- workbench/kernel/kernel_v7.pyAdded+106
- workbench/kernel/kernel_v8.pyAdded+58
- workbench/kernel/kernel_v9.pyAdded+58
- workbench/kernel/network_glue_v1.pyAdded+321
- workbench/kernel/network_glue_v2.pyAdded+431
- workbench/kernel/network_glue_v3.pyAdded+181
- workbench/kernel/network_v2.pyAdded+733
- workbench/kernel/path_hrr_v1.pyAdded+80
- workbench/language_bridge.pyAdded+363
- workbench/learn.pyAdded+240
- workbench/machine_probe.pyAdded+146
- workbench/machines.pyAdded+271
- workbench/make.pyAdded+657
- workbench/o7_browser.pyAdded+119
- workbench/planner.pyAdded+216
- workbench/program_examples.pyAdded+81
- workbench/program_prose.pyAdded+407
- workbench/program_steps.pyAdded+236
- workbench/project.pyAdded
- workbench/project_answer.pyAdded+92
- workbench/project_context.pyAdded+49
- workbench/project_discussion.pyAdded+241
- workbench/project_intent.pyAdded+385
- workbench/project_interactive.pyAdded+541
- workbench/project_sources.pyAdded+377
- workbench/prosefold/core.py+4-1
- workbench/prosefold/options.py+4-1
- workbench/question_obligation.pyAdded+364
- workbench/reflect.pyAdded+763
- workbench/registry.py+28-8
- workbench/relay.pyAdded+91
- workbench/repair.pyAdded+519
- workbench/resolve.pyAdded+278
- workbench/runjail.pyAdded+63
- workbench/seal.pyAdded+155
- workbench/selfdev.pyAdded+374
- workbench/server.py
- workbench/service_parts.pyAdded+288
- workbench/shadow.pyAdded+142
- workbench/static/chat.htmlAdded+380
- workbench/static/machines.htmlAdded+572
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""Read the rows a project's named sources ask for, independently of its writer.
This judge does not import project_sources or run generated source code. Joins
are read by comparing row pairs, rather than by the writer's indexed join.
The source graph is the received contract; a separate request check must still
establish that it represents the user's words.
"""
import csv
import json
import math
from pathlib import Path
class SourceJudgeError(ValueError):
"""The source contract cannot be checked against the current input files."""
def _read(root, filename):
base = Path(root).resolve()
if not isinstance(filename, str) or not filename:
raise SourceJudgeError("a source must name a file")
import os
path = Path(os.path.normpath(str(base / filename))) # C15b: inside the folder as written; a kept link is a source
try:
path.relative_to(base)
except ValueError as exc:
raise SourceJudgeError("source leaves the project folder: %s" % filename) from exc
if not path.is_file():
raise SourceJudgeError("source file is missing: %s" % filename)
try:
if path.suffix.lower() == ".csv":
with path.open(encoding="utf-8-sig", newline="") as stream:
reader = csv.DictReader(stream)
columns = list(reader.fieldnames or [])
rows = list(reader)
if len(columns) != len(set(columns)):
raise SourceJudgeError("source has repeated column names: %s" % filename)
if any(None in row for row in rows):
raise SourceJudgeError("source has rows wider than its header: %s" % filename)
elif path.suffix.lower() in (".json", ".jsonl"):
contents = path.read_text(encoding="utf-8-sig")
if path.suffix.lower() == ".jsonl":
rows = [json.loads(line) for line in contents.splitlines() if line.strip()]
else:
rows = json.loads(contents)
if isinstance(rows, dict):
rows = next((value for value in rows.values() if isinstance(value, list)), [rows])
if not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows):
raise SourceJudgeError("source must contain record objects: %s" % filename)
columns = list(rows[0]) if rows else []
if any(set(row) != set(columns) for row in rows):
raise SourceJudgeError("source records have different columns: %s" % filename)
else:
raise SourceJudgeError("source is not CSV, JSON or JSONL: %s" % filename)
except (OSError, UnicodeError, json.JSONDecodeError, csv.Error) as exc:
raise SourceJudgeError("source could not be read: %s (%s)" % (filename, exc)) from exc
return columns, [dict(row) for row in rows]
def _key_value(value):
if value is None:
return None
if not isinstance(value, (str, int, float, bool)) or isinstance(value, float) and not math.isfinite(value):
raise SourceJudgeError("join keys must be finite scalar values")
return str(value).strip() or None
def _matches(left, right, keys):
for left_name, right_name in keys:
a, b = _key_value(left.get(left_name)), _key_value(right.get(right_name))
if a is None or b is None or a != b:
return False
return True
def _evaluate(root, graph):
if not isinstance(graph, dict):
raise SourceJudgeError("source shape must be an object")
operation = graph.get("op")
if operation == "read":
return _read(root, graph.get("file"))
if operation == "union":
inputs = graph.get("inputs")
if not isinstance(inputs, list) or not inputs:
raise SourceJudgeError("stacking must name at least one input")
columns, rows = _evaluate(root, inputs[0])
for child in inputs[1:]:
other_columns, other_rows = _evaluate(root, child)
if not other_columns and not other_rows:
continue
if not columns and not rows:
columns = other_columns
if set(columns) != set(other_columns):
raise SourceJudgeError("stacked sources have different columns")
rows.extend({column: row.get(column) for column in columns} for row in other_rows)
return columns, rows
if operation not in ("join", "lookup"):
raise SourceJudgeError("unknown source operation: %s" % operation)
left_columns, left_rows = _evaluate(root, graph.get("left"))
right_columns, right_rows = _evaluate(root, graph.get("right"))
keys = graph.get("keys")
if not isinstance(keys, list) or not keys or any(
not isinstance(pair, (list, tuple)) or len(pair) != 2 or
not all(isinstance(name, str) for name in pair) for pair in keys
):
raise SourceJudgeError("a join must bind named columns on both sources")
if any(a not in left_columns or b not in right_columns for a, b in keys):
raise SourceJudgeError("a join key is missing from its source")
for row in left_rows:
for name, _other in keys:
_key_value(row.get(name))
for row in right_rows:
for _other, name in keys:
_key_value(row.get(name))
how = graph.get("how", "inner")
if how not in ("inner", "left"):
raise SourceJudgeError("unknown join shape: %s" % how)
right_key_names = {pair[1] for pair in keys}
appended = [column for column in right_columns if column not in right_key_names]
collisions = set(left_columns).intersection(appended)
if collisions:
raise SourceJudgeError("joined non-key columns collide: %s" % ", ".join(sorted(collisions)))
if operation == "lookup":
right_pairs = [[name, name] for name in right_key_names]
for index, row in enumerate(right_rows):
if any(_matches(row, prior, right_pairs) for prior in right_rows[:index]):
raise SourceJudgeError("lookup reference keys are not unique")
out = []
for left in left_rows:
matches = [right for right in right_rows if _matches(left, right, keys)]
if not matches:
if operation == "lookup":
raise SourceJudgeError("lookup has no reference row for a source row")
if how == "left":
out.append(dict(left, **{column: None for column in appended}))
continue
for right in matches:
joined = dict(left)
joined.update({column: right.get(column) for column in appended})
out.append(joined)
return left_columns + appended, out
def expected_source_rows(root, graph):
"""Expected input rows in source order, before project filters or totals."""
return _evaluate(root, graph)[1]
def expected_source_columns(root, graph):
"""The independently checked output columns, including empty CSV schemas."""
return _evaluate(root, graph)[0]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455#!/usr/bin/env python3"""`python oracle7.py kernel ...` - the 11.5 kernel at its newest admitted version (v9). kernel "question" quantities through the kernel's parts (formula parts + learned specialist faces) kernel --head "question" the head as one of the kernel's parts too: any question the head answers, under both laws kernel faces what the kernel can read and give kernel --json ... the full reply with its receipts"""from __future__ import annotations
import jsonimport sysfrom pathlib import Path
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))
def _head(): import importlib.util root = HERE.parents[1] spec = importlib.util.spec_from_file_location("o7", str(root / "oracle7.py")) o7 = importlib.util.module_from_spec(spec) argv, sys.argv = sys.argv, ["oracle7.py"] spec.loader.exec_module(o7) sys.argv = argv eng = o7.Engine() return lambda q, s: eng.chat(q, s)
def cli(rest): as_json, use_head = "--json" in rest, "--head" in rest rest = [x for x in rest if x not in ("--json", "--head")] if not rest: print(__doc__) return 0 from kernel_v9 import Kernel9 k = Kernel9(head_chat=_head() if use_head else (lambda q, s: {"status": "declined"})) if rest[:1] == ["faces"]: print("declared faces (formula parts): %d over %d (quantity, dimension) keys" % (len(k.declared.parts), len(k.declared.keys))) print("induced faces (specialists, learned from their own worked examples): %d" % len(k.induced.faces)) return 0 r = k.solve(" ".join(rest)) if as_json: print(json.dumps(r, indent=1, default=str)) return 0 if r.get("status") == "answered": print(r["answer"]) path = r.get("path") or [t.get("node") for t in r.get("trace", []) if t.get("node")] print(" [answered, %s reading] path: %s" % (r.get("reading", "induced"), " -> ".join(map(str, path)) or "core arithmetic")) else: print("I can't answer that with a checked path: %s" % (r.get("reason") or "no path")) return 0
if __name__ == "__main__": sys.exit(cli(sys.argv[1:]))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128#!/usr/bin/env python3"""The Oracle7 kernel, v0 (KERNEL_SPEC.md steps K0-K1). Built on the head's own pieces, not beside them: - declared faces = the physics organ's admitted formula parts, loaded by the head's own loader (grow60.load_parts): inputs and output keyed (quantity noun, SI dimension in 7 base units incl. mol), each part's own program; - the schedule = the head's Planner (grow60): backward chains up to depth 3 over keys that share BOTH noun and dimension; an answer only when every plan agrees; - receipts = one record per hop (part id, inputs in the part's own units, output), replayable.K0: count faces and keys; list what does not parse. K1: every part's own recorded example, asked as a question, must comeback as its expected value through the kernel, and the kernel's answer must be identical to grow60.ask on the same question.usage: kernel_v0.py <pack tree> <out.json>"""from __future__ import annotations
import collectionsimport jsonimport mathimport osimport sysimport timefrom pathlib import Path
TREE = Path(os.environ.get("O7_KERNEL_TREE", Path(__file__).resolve().parents[2])) # the released pack the kernel readssys.path.insert(0, str(TREE / "workbench" / "swarm"))os.environ.setdefault("O7_TREE", str(TREE))import grow60 as G # noqa: E402
ORGAN = TREE / "root" / "organs10" / "physics"
class Kernel: def __init__(self, organ=ORGAN): t0 = time.time() self.parts = G.load_parts(organ) # declared faces, the head's own loader self.planner = G.Planner(self.parts) # the head's own schedule self.keys = collections.Counter(k for p in self.parts.values() for k in p["in_keys"] + [p["out_key"]]) self.load_seconds = round(time.time() - t0, 2)
def ask_keys(self, want_noun, given, depth=3): """want noun + {(noun, dims): SI value} -> answer with receipts, or a hole""" wkeys = [k for k in self.planner.by_out if k[0] == want_noun] plans = [] for wk in wkeys: plans += self.planner.plans(wk, set(given), depth) if not plans: return {"status": "declined", "hole": {"want": want_noun, "given": sorted(str(k) for k in given)}, "why": "no admitted part or chain gives the %s from those givens" % want_noun} runs = [] for pl in plans: have, receipts = dict(given), [] try: for p in pl: args = [have[k] / s for k, s in zip(p["in_keys"], p["scale_in"])] y = float(p["fn"](*args)) v = y * p["scale_out"] if not math.isfinite(v): raise ValueError("not finite") have[p["out_key"]] = v receipts.append({"part": p["id"], "inputs": dict(zip(p["inputs"], args)), "output": {p["output"]: y}}) runs.append((have[pl[-1]["out_key"]], receipts)) except (ValueError, ZeroDivisionError, OverflowError, TypeError): continue if not runs: return {"status": "declined", "why": "no plan could be run on those values"} v0 = runs[0][0] if any(abs(v - v0) > 1e-6 * max(abs(v0), 1e-300) for v, _ in runs): return {"status": "declined", "why": "%d plans disagree" % len(runs), "check": "every plan agrees"} return {"status": "answered", "value": v0, "plans": len(runs), "receipts": runs[0][1]}
def ask(self, q): r, why = G.read(q) if r is None: return {"status": "declined", "why": why} want, gs = r return self.ask_keys(want, {(n, d): v for n, v, d in gs})
def example_questions(organ=ORGAN): """each admitted part's own first recorded point, written as the head reader's question form""" qs = [] for pid in sorted(os.listdir(organ / "specialists")): spec_p = organ / "specialists" / pid / "spec.json" if not spec_p.exists(): continue spec = json.loads(spec_p.read_text(encoding="utf-8")) pts = spec.get("points") or [] if not pts or not spec.get("inputs"): continue pt = pts[0] parts = [] for lab, v in zip(spec["inputs"], pt.get("in", [])): unit = lab[lab.rfind("(") + 1:-1] if lab.endswith(")") else "" parts.append("the %s is %r %s" % (G.noun(lab), float(v), "" if unit == "1" else unit)) if not parts or not isinstance(pt.get("out"), (int, float)): continue q = "What is the %s when %s?" % (G.noun(spec["output"]), ", ".join(x.strip() for x in parts[:-1]) + (" and " if len(parts) > 1 else "") + parts[-1].strip()) qs.append({"part": pid, "q": q, "expect": float(pt["out"]), "out_unit": spec["output"]}) return qs
if __name__ == "__main__": out = sys.argv[2] if len(sys.argv) > 2 else "kernel_v0.json" k = Kernel() rep = {"K0": {"faces_declared": len(k.parts), "keys": len(k.keys), "load_seconds": k.load_seconds, "part_folders": len(os.listdir(ORGAN / "specialists"))}} print("K0", rep["K0"], flush=True) qs = example_questions() st = collections.Counter() diffs, wrong = [], [] for x in qs: a = k.ask(x["q"]) b = G.ask(k.planner, x["q"]) same = (a["status"] == b["status"]) and (a["status"] != "answered" or abs(a["value"] - b["value"]) <= 1e-12 * max(1, abs(b["value"]))) if not same: diffs.append({"q": x["q"], "kernel": a.get("value", a.get("why")), "grow60": b.get("value", b.get("why"))}) if a["status"] == "answered": # the example's expected value is in the output label's own unit; the kernel's value is SI dims = G.ldims(x["out_unit"]) v = a["value"] / dims[1] if dims else a["value"] ok = abs(v - x["expect"]) <= 1e-6 * max(abs(x["expect"]), 1e-12) st["right" if ok else "wrong"] += 1 if not ok and len(wrong) < 10: wrong.append({"q": x["q"][:160], "got": v, "expect": x["expect"]}) else: st["declined:" + a.get("why", "")[:40]] += 1 rep["K1"] = {"questions": len(qs), "tally": dict(st), "identical_to_grow60": len(qs) - len(diffs), "differences": diffs[:10], "wrong_examples": wrong} print("K1", json.dumps(rep["K1"], indent=1)[:2500], flush=True) json.dump(rep, open(out, "w"), indent=1, default=str)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192#!/usr/bin/env python3"""The Oracle7 kernel, v1: v0 plus SYSTEM-AWARE LINKING (found by K1: 9 of the head's own part examples had plans thatdisagree, because a noun like "height", "radius" or "volume" is shared by different shapes - a cone formula's height waschained into a cylinder formula's; the every-plan-agrees law caught all 9, but a question with ONE such plan would havenothing to disagree with).Each part belongs to a system: its defining formula's Wikidata item (from its title), else its own equation set. A link(one part's output feeding another's input through a key) is allowed across systems only when that key is produced byparts of exactly ONE system; a key produced by several systems links only within one system.K1 again: every part's own example; the kernel must still answer it (a part alone is always in its own system), with 0wrong; every answer that changes against grow60 is listed with the reason.usage: kernel_v1.py <pack tree> <out.json>"""from __future__ import annotations
import collectionsimport hashlibimport jsonimport reimport sys
from kernel_v0 import ORGAN, G, Kernel, example_questions
def system_of(pid, organ=ORGAN): try: spec = json.loads((organ / "specialists" / pid / "spec.json").read_text(encoding="utf-8")) except Exception: # noqa: BLE001 return "part:" + pid q = re.findall(r"Wikidata (Q\d+)", spec.get("title", "")) if q: return q[-1] eqs = (spec.get("system") or {}).get("equations") if eqs: return "eq:" + hashlib.sha256(json.dumps(sorted(eqs)).encode()).hexdigest()[:12] return "part:" + pid
class Kernel1(Kernel): def __init__(self, organ=ORGAN): super().__init__(organ) self.sys = {pid: system_of(pid, organ) for pid in self.parts} prod = collections.defaultdict(set) for p in self.parts.values(): prod[p["out_key"]].add(self.sys[p["id"]]) self.multi = {k for k, s in prod.items() if len(s) > 1} # keys several systems produce
def linked_ok(self, plan, given): """every internal link either crosses through a single-system key or stays inside one system""" producer = {} for p in plan: producer[p["out_key"]] = p for c in plan: for k in c["in_keys"]: if k in given or k not in producer: continue p = producer[k] if k in self.multi and self.sys[p["id"]] != self.sys[c["id"]]: return False return True
def ask_keys(self, want_noun, given, depth=3): orig = self.planner.plans self.planner.plans = lambda wk, gk, d=depth: [pl for pl in orig(wk, gk, d) if self.linked_ok(pl, gk)] try: return super().ask_keys(want_noun, given, depth) finally: self.planner.plans = orig
if __name__ == "__main__": out = sys.argv[2] if len(sys.argv) > 2 else "kernel_v1.json" k = Kernel1() print("systems", len(set(k.sys.values())), "| keys produced by several systems", len(k.multi), flush=True) st, changed, wrong = collections.Counter(), [], [] for x in example_questions(): a = k.ask(x["q"]) b = G.ask(k.planner, x["q"]) if a["status"] == "answered": dims = G.ldims(x["out_unit"]) v = a["value"] / dims[1] if dims else a["value"] ok = abs(v - x["expect"]) <= 1e-6 * max(abs(x["expect"]), 1e-12) st["right" if ok else "wrong"] += 1 if not ok: wrong.append({"part": x["part"], "got": v, "expect": x["expect"]}) else: st["declined"] += 1 if (a["status"], round(a.get("value", 0) or 0, 9)) != (b["status"], round(b.get("value", 0) or 0, 9)): changed.append({"part": x["part"], "kernel": a.get("value", a.get("why")), "grow60": b.get("value", b.get("why"))}) rep = {"tally": dict(st), "changed_vs_grow60": changed, "wrong": wrong, "multi_system_keys": sorted(map(str, k.multi))[:40]} print(json.dumps({"tally": rep["tally"], "changed": len(changed), "wrong": len(wrong)}), flush=True) for c in changed[:15]: print(" CHANGED", c, flush=True) json.dump(rep, open(out, "w"), indent=1, default=str)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187#!/usr/bin/env python3"""The Oracle7 kernel, v2 (KERNEL_SPEC.md step K2): ONE kernel over declared and induced faces.
READER glue v3's reader gives every given's SI value, dimension and surface span. The kernel adds each given's QUANTITY NOUN from the words just before it, matched only against nouns the admitted formula parts use (the longest known noun ending there: "a density of 7850 kg per cubic metre" -> density), and the WANTED noun as the longest known noun in the question's asking clause ("what is its mass" -> mass). DECLARED the formula parts (830), planned by kernel v1: keys = noun + dimension, system-aware links, every plan agrees. Used only when every given and the wanted quantity are named. INDUCED the specialists, through glue v3's learned faces, typed medium and law (conditions, coverage, named ratios). LAW both readings answer -> they must agree (relative 1%), else the kernel declines ("two readings disagree"). One answers -> that answer, with its receipts. Neither -> a hole: what was wanted, what was given, why.usage: kernel_v2.py (module; see run_kernel_dev.py)"""from __future__ import annotations
import collectionsimport jsonimport osimport reimport sysfrom pathlib import Path
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))sys.path.insert(0, str(HERE))from kernel_v1 import Kernel1 # noqa: E402from kernel_v0 import ORGAN # noqa: E402
ORGAN_DIR = ORGAN / "specialists"from network_glue_v3 import GlueNetwork3, reader # noqa: E402
STOP_TAIL = {"of", "is", "was", "at", "a", "an", "the", "its", "with", "has", "=", "to", "by", "about", "and", "in", "for"}
def to7(d6): """glue (m, kg, s, A, K, $) -> formula side (m, kg, s, A, K, mol, cd); money has no formula-side dimension""" if d6[5]: return None return (d6[0], d6[1], d6[2], d6[3], d6[4], 0, 0)
WORD = re.compile(r"[a-z][a-z\-]+")TITLE_STOP = {"from", "the", "a", "an", "of", "and", "in", "on", "by", "for", "to", "with", "wikidata", "per", "unit", "system"}
class Declared(Kernel1): """kernel v1's declared side, with SYSTEM CONDITIONS replacing v1's link rule. A key several systems produce (a cone's height and a cylinder's height are both 'height') is produced, for a given question, only by systems the question names: a system's distinguishing words are its titles' words that no other system producing that key uses. A key one system produces needs no naming. (v1's rule blocked valid chains such as sphere volume -> mass through density.)"""
def __init__(self, *a, **k): super().__init__(*a, **k) self.sys_words = collections.defaultdict(set) for pid, p in self.parts.items(): try: t = json.loads((ORGAN_DIR / pid / "spec.json").read_text(encoding="utf-8")).get("title", "") except Exception: # noqa: BLE001 t = "" self.sys_words[self.sys[pid]] |= {w for w in WORD.findall(t.lower()) if w not in TITLE_STOP} # rivals: systems giving the SAME output from the SAME inputs (alternative models, e.g. cone vs cylinder volume # from radius and height). Systems that reach an output from different inputs are told apart by the givens. self.key_systems = collections.defaultdict(set) for p in self.parts.values(): self.key_systems[(p["out_key"], tuple(sorted(p["in_keys"])))].add(self.sys[p["id"]]) self.qwords = set()
def allowed(self, p): systems = self.key_systems[(p["out_key"], tuple(sorted(p["in_keys"])))] if len(systems) <= 1: return True mine = self.sys_words[self.sys[p["id"]]] others = set().union(*(self.sys_words[s] for s in systems if s != self.sys[p["id"]])) return bool((mine - others) & self.qwords)
def linked_ok(self, plan, given): return all(self.allowed(p) for p in plan)
class Kernel2: def __init__(self, standing, spec_root="/opt/o7spec", combo="/opt/o7spec/_fam"): self.declared = Declared() self.induced = GlueNetwork3(standing, spec_root, combo, log=lambda s: None) self.nouns = sorted({k[0] for k in self.declared.keys}, key=lambda n: -len(n)) self.noun_dims = {} for (n, d) in self.declared.keys: self.noun_dims.setdefault(n, set()).add(d)
def _noun_before(self, text, span): i = text.find(span) if i < 0: return None words = re.findall(r"[a-z][a-z\-]*", text[:i].lower()) while words and words[-1] in STOP_TAIL: words.pop() for n in self.nouns: # longest first nw = n.split() if len(nw) <= len(words) and words[-len(nw):] == nw: return n return None
def _wanted(self, text): sents = [s for s in re.split(r"(?<=[.?!])\s+", text.strip()) if s] ask = (sents[-1] if sents else text).lower() best = None for n in self.nouns: if re.search(r"\b%s\b" % re.escape(n), ask): best = n break return best
def _leaves(self, want, d7, depth=3): """every input key that appears in some chain (depth <= 3) toward the wanted key, among parts this question allows""" seen, frontier, leaves = set(), [(want, d7)], set() for _ in range(depth): nxt = [] for key in frontier: for p in self.declared.planner.by_out.get(key, []): if p["id"] in seen or not self.declared.allowed(p): continue seen.add(p["id"]) for ik in p["in_keys"]: leaves.add(ik) nxt.append(ik) frontier = nxt return leaves
def declared_answer(self, text): t = reader.normalise(text) givens, flags = reader.read_givens(t) goal = reader.read_goal(t) if not givens or flags.get("unread_numbers") or goal is None or goal[0] != "dim": return None, "declared: question not fully read" want = self._wanted(t) gd7 = to7(goal[1]) if want is None or gd7 is None or gd7 not in self.noun_dims.get(want, set()): return None, "declared: no wanted quantity a part produces" self.declared.qwords = {w for w in WORD.findall(t.lower())} leaves = self._leaves(want, gd7) given, unnamed = {}, [] for q in givens: n = self._noun_before(t, q.text) d7 = to7(q.dim) if d7 is None: return None, "declared: money has no formula-side quantity" if n is None or d7 not in self.noun_dims.get(n, set()): unnamed.append((q, d7)) # named by its dimension below, if that is unambiguous continue if (n, d7) in given: return None, "declared: two givens of the same quantity" given[(n, d7)] = q.v for q, d7 in unnamed: cands = [key for key in leaves if key[1] == d7 and key not in given] if len(cands) != 1: return None, "declared: %s names no quantity, and its dimension fits %d inputs" % (q.text, len(cands)) given[cands[0]] = q.v r = self.declared.ask_keys(want, given) if r["status"] != "answered": return None, "declared: " + r.get("why", "") val = r["value"] / goal[3] unit = goal[2] return {"status": "answered", "answer": ("$%.2f" % val) if unit == "$" else "%s %s" % (reader.g(round(val, 6)), unit), "value_si": r["value"], "path": [x["part"] for x in r["receipts"]], "receipts": r["receipts"], "reading": "declared"}, None
def solve(self, text): a, why_a = self.declared_answer(text) b = self.induced.solve(text) b_ok = b.get("status") == "answered" if a and b_ok: vb = _num(b.get("answer")) va = _num(a["answer"]) if va is not None and vb is not None and abs(va - vb) > 0.01 * max(abs(va), abs(vb), 1e-12): return {"status": "declined", "reason": "two readings disagree: declared %s, induced %s" % (a["answer"], b["answer"]), "check": "readings agree"} return dict(a, also_induced=b.get("answer"), trace=b.get("trace", [])) if a: return dict(a, trace=[{"node": p} for p in a["path"]]) if b_ok: return dict(b, reading="induced") return {"status": "declined", "reason": b.get("reason") or why_a, "declared_reason": why_a, "hole": {"question": text, "declared": why_a, "induced": b.get("reason")}}
def _num(ans): m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?", str(ans or "").replace("$", "")) return float(m.group(0).replace(",", "")) if m else None123456789101112131415161718192021222324252627#!/usr/bin/env python3"""The Oracle7 kernel, v3: kernel v2 plus the class fix from KERNEL SEALED 1's verdict (k26: the declared reading answered"a sphere with a radius of 0 m" with 0 litres, because only the induced path checked validity).THE LAW ON EVERY PATH: the declared reading runs the same validity check as the induced one (every given a physical amount,every number read) before planning, and refuses a non-finite or negative physical result. Nothing else changes.usage: module"""from __future__ import annotations
import math
from kernel_v2 import Kernel2, reader
class Kernel3(Kernel2): def declared_answer(self, text): t = reader.normalise(text) givens, flags = reader.read_givens(t) if flags.get("unread_numbers"): return None, "declared: numbers I could not read" for q in givens: bad = reader.valid_given(q) if bad: return None, "declared: " + bad # the same law the induced path applies a, why = super().declared_answer(text) if a is not None and (not math.isfinite(a["value_si"]) or a["value_si"] <= 0): return None, "declared: the result %s is not a physical amount" % a["value_si"] return a, why123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176#!/usr/bin/env python3"""The Oracle7 kernel, v4: the goal reader. Found by the OpenStax held-out run (126 of 136 independent textbook exercisesdeclined because the question's GOAL was unread: the reader only knew goals with a unit spelled out, "in kWh").A goal is now also read from: 1. the wanted quantity NOUN the kernel's parts declare ("What is its acceleration?" -> acceleration, its dimension from the parts; answered in SI), when that noun has exactly one dimension among the parts; 2. the closed class of English wh-idioms that ask for a quantity: how far / how high / how tall / how deep / how long (a distance) -> length; how long (with a time verb) / how much time -> time; how fast / how quickly -> speed; how heavy -> mass; how much energy / heat / work -> energy. (A closed list, like the unit table: English grammar, not data about any question.)The answer is given in the SI unit of that dimension. Everything else is kernel v3 (validity on every path).usage: module"""from __future__ import annotations
import re
from kernel_v3 import Kernel3, reader
L, M, T = (1, 0, 0, 0, 0, 0), (0, 1, 0, 0, 0, 0), (0, 0, 1, 0, 0, 0)V, E = (1, 0, -1, 0, 0, 0), (2, 1, -2, 0, 0, 0)SI_NAME = {L: "m", M: "kg", T: "s", V: "m/s", E: "J", (1, 0, -2, 0, 0, 0): "m/s^2", (1, 1, -2, 0, 0, 0): "N", (2, 1, -3, 0, 0, 0): "W", (-1, 1, -2, 0, 0, 0): "Pa", (3, 0, 0, 0, 0, 0): "m^3", (2, 0, 0, 0, 0, 0): "m^2", (0, 0, -1, 0, 0, 0): "Hz", (-3, 1, 0, 0, 0, 0): "kg/m^3", (1, 1, -1, 0, 0, 0): "kg m/s", (0, 0, 0, 0, 1, 0): "K", (0, 0, 0, 1, 0, 0): "A"}TIME_VERB = re.compile(r"\bhow long\b[^?]*\b(take|last|wait|stay|remain|run|burn|fall|travel|until|before)\b", re.I)IDIOMS = [(re.compile(r"\bhow (far|high|tall|deep)\b", re.I), L), (re.compile(r"\bhow (fast|quickly)\b", re.I), V), (re.compile(r"\bhow heavy\b", re.I), M), (re.compile(r"\bhow much (time)\b", re.I), T), (re.compile(r"\bhow much (energy|heat|work)\b", re.I), E)]
def _from7(d7): return (d7[0], d7[1], d7[2], d7[3], d7[4], 0) if not (d7[5] or d7[6]) else None
class Kernel4(Kernel3): def __init__(self, *a, **k): super().__init__(*a, **k) self._glue_solve = self.induced.solve # glue v3 as frozen, kept for comparison self.induced.solve = self._induced_solve # the kernel's induced path: slot cues + no self-cancellation
def goal_of(self, text): t = reader.normalise(text) g = reader.read_goal(t) if g is not None: return g g = self._implicit_goal(t) if g is None: return None # an implicit goal answers in the unit the question itself uses for that dimension, else SI givens, _ = reader.read_givens(t) for q in givens: if q.dim == g[1]: m = re.match(r"\s*-?[\d.,]+\s*(.+?)\s*$", q.text) u = reader.unit_lookup(m.group(1)) if m else None if u and u[1] == g[1]: return ("dim", g[1], m.group(1), u[0]) return g
def _implicit_goal(self, t): ask = self._asking(t) if TIME_VERB.search(ask): return ("dim", T, "s", 1) for rx, d in IDIOMS: if rx.search(ask): return ("dim", d, SI_NAME[d], 1) want = self._wanted(t) if want: dims = {_from7(d) for d in self.noun_dims.get(want, set())} - {None} if len(dims) == 1: d = dims.pop() if d in SI_NAME: return ("dim", d, SI_NAME[d], 1) return None
@staticmethod def _asking(t): """the sentence that asks: the last one ending in '?', else the last one with a wh-word or an imperative ask""" sents = [s for s in re.split(r"(?<=[.?!])\s+", t.strip()) if s] or [t] asks = [s for s in sents if s.endswith("?")] if asks: return asks[-1] asks = [s for s in sents if re.search(r"\b(what|how|which|calculate|find|determine|compute)\b", s, re.I)] return asks[-1] if asks else sents[-1]
def _wanted(self, text): # v2 read the wanted noun from the LAST sentence; a stated fact after the question ("The nail puller has a mass # of 2.10 kg.", "Assume coffee has the same density as water.") then became the goal. The asking sentence only. ask = self._asking(text).lower() for n in self.nouns: if re.search(r"\b%s\b" % re.escape(n), ask): return n return None
def declared_answer(self, text): a, why = super().declared_answer(text) if a is not None: t = reader.normalise(text) givens, _ = reader.read_givens(t) for q in givens: if abs(q.v - a["value_si"]) <= 1e-9 * max(1.0, abs(q.v)): return None, "declared: the answer would be a given handed back (%s)" % q.text # never an echo return a, why
# ---- slot cues for induced faces (the OpenStax run: a geometry 'hypotenuse/leg' face read two POWERS as lengths, and # a 'box lifted' potential-energy face was applied to a trampoline). A face's slot cue words are the content words its # own template puts right beside each slot; a face is used only when the question says at least one of them. def _cues(self, f): if not hasattr(f, "_cue_stems"): stems = __import__("glue2_v3").stems stopw = __import__("glue1_v3").STOP cues = set() for m in re.finditer(r"\{\d+\}", f.template): left = [w for w in re.findall(r"[a-z][a-z\-']+", f.template[:m.start()].lower()) if w not in stopw][-1:] right = [w for w in re.findall(r"[a-z][a-z\-']+", f.template[m.end():].lower()) if w not in stopw][:1] cues |= set(left) | set(right) # the face's output name ("energy" in "the potential energy of a {0} box") names what it gives, not a slot f._cue_stems = stems(cues) - stems(self.induced._wh_words(f.template)) return f._cue_stems
def _induced_solve(self, text): stems = __import__("glue2_v3").stems words = __import__("glue1_v3").words qw = stems(words(reader.normalise(text))) allf = self.induced.faces goal = reader.read_goal(reader.normalise(text)) gdim = goal[1] if goal and goal[0] == "dim" else None
def needs_cue(f): # where the risk was measured: bare-number slots read any dimension, and an intermediate step hands its output # on without the question naming it. A final step already answers under the conditions law. free = any(s.get("dim") == "free" for s in f.slots) final = f.out_kind == "bool" or (f.power is None and f.out_dim == gdim) return free or not final self.induced.faces = [f for f in allf if not needs_cue(f) or self._cues(f) & qw] try: r = self._glue_solve(text) finally: self.induced.faces = allf if r.get("status") == "answered": for tr in r.get("trace", []): terms = [x.strip() for x in str(tr.get("formula", "")).split("×")] if any("1/(%s)" % x in terms for x in terms if not x.startswith("1/(")): return {"status": "declined", "reason": "a given cancelled against itself in the arithmetic", "check": "every given used for what it says"} return r
@staticmethod def _merge_restated(givens): """one fact stated twice ("4.0 km/h (1.1 m/s)", "a 12.0-V system ... a 12.0-V battery") is one quantity: same dimension and role, values within 2% -> keep one, preferring the one written in SI units""" out = [] for q in givens: twin = next((o for o in out if o.dim == q.dim and o.role == q.role and not q.temp_point and abs(o.v - q.v) <= 0.02 * max(abs(o.v), abs(q.v), 1e-300)), None) if twin is None: out.append(q) continue m = re.match(r"\s*-?[\d.,]+\s*-?\s*(.+?)\s*$", q.text) u = reader.unit_lookup(m.group(1)) if m else None if u and u[0] == 1: # the restatement is in SI: keep it instead out[out.index(twin)] = q return out
def solve(self, text): orig_goal, orig_givens = reader.read_goal, reader.read_givens goal = self.goal_of(text) reader.read_goal = (lambda t, _g=goal: _g) if goal is not None else orig_goal # the same goal for both readings
def read_givens(t): g, f = orig_givens(t) return self._merge_restated(g), f reader.read_givens = read_givens try: return super().solve(text) finally: reader.read_goal, reader.read_givens = orig_goal, orig_givens12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273#!/usr/bin/env python3"""The Oracle7 kernel, v5: kernel v4 plus the class fix from KERNEL SEALED 2 (m13: "What power, in kilowatts, must themotor supply? (Neglect friction.)" was answered in watts: the goal reader read the LAST sentence, the parenthetical, so theasked-for unit was never seen). The goal, like the wanted quantity since v4, is read from the ASKING sentence.Also the pack front door: Kernel5() with no arguments reads the specialists the released head stands (the union of itsstanding lists) from this install, and `python oracle7.py kernel "question"` asks it.usage: python oracle7.py kernel "question" [--json] | python oracle7.py kernel faces"""from __future__ import annotations
import jsonimport osimport sysfrom pathlib import Path
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))from kernel_v4 import Kernel4, reader # noqa: E402
INSTALL = Path(os.environ.get("O7_KERNEL_TREE", HERE.parents[1]))SPEC = INSTALL / "root" / "specialists"GATE = SPEC / "_gate"LISTS = ("standing_v2.txt", "standing_new_v1.txt", "standing_new_v2.txt", "standing_new_v3.txt", "standing_new_v4.txt", "standing_new_v5.txt", "standing_owner_v1.txt", "standing_stars_v1.txt", "standing_net_v6.txt")
def pack_standing(): ids = set() for n in LISTS: p = GATE / n if p.exists(): ids |= set(p.read_text(encoding="utf-8").split()) return sorted(ids)
class Kernel5(Kernel4): def __init__(self, standing=None, spec_root=None, combo=None): super().__init__(standing or pack_standing(), str(spec_root or SPEC), str(combo or GATE))
def goal_of(self, text): t = reader.normalise(text) g = reader.read_goal(self._asking(t)) # the asked-for unit is in the asking sentence if g is not None: return g return super().goal_of(text)
def cli(rest): as_json = "--json" in rest rest = [x for x in rest if x != "--json"] k = Kernel5() if rest[:1] == ["faces"]: print("declared faces (formula parts): %d over %d (quantity, dimension) keys" % (len(k.declared.parts), len(k.declared.keys))) print("induced faces (specialists, learned from their own examples): %d" % len(k.induced.faces)) return 0 if not rest: print(__doc__) return 0 r = k.solve(" ".join(rest)) if as_json: print(json.dumps(r, indent=1, default=str)) return 0 if r.get("status") == "answered": print(r["answer"]) path = r.get("path") or [t.get("node") for t in r.get("trace", []) if t.get("node")] print(" [answered, %s reading] path: %s" % (r.get("reading", "induced"), " -> ".join(map(str, path)) or "core arithmetic")) else: print("I can't answer that with a checked path: %s" % (r.get("reason") or "no path")) print(" [declined] this goes to the holes as: %s" % json.dumps(r.get("hole") or {"question": " ".join(rest)})[:300]) return 0
if __name__ == "__main__": sys.exit(cli(sys.argv[1:]))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556#!/usr/bin/env python3"""The Oracle7 kernel, v6: META SWARM round 1 (the census: 84.5% of 5,518 holes were goals the kernel could not carry,because it only carried QUANTITIES). The head's own front door becomes a part of the kernel: - a question whose goal is a quantity: the kernel's declared and induced readings, as v5. If the head also answers it with a number, the two must agree (else the kernel declines: "kernel and head disagree"); - any other question (who, which, where, yes/no, define, compare...): the head's whole `ask` path - the 9.0 reader, the specialists, the relation store, the ego layer - under the head's own law, and its answer joins the kernel's medium as a TERM with the head's receipt (status, path, provenance); - a question the kernel can't answer as a quantity but the head can: the head's answer.Nothing about the head changes; the kernel reads it the way it reads any part.usage: module (Kernel6(head_chat=callable)); the gate: kernel6_gate.py"""from __future__ import annotations
import re
from kernel_v5 import Kernel5, reader
NUM = re.compile(r"-?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?")
class Kernel6(Kernel5): def __init__(self, head_chat, *a, **k): super().__init__(*a, **k) self.head_chat = head_chat # the head's front door: text, session -> reply dict
def solve(self, text, session="kernel"): quantity_goal = self.goal_of(text) is not None r = super().solve(text) if quantity_goal else {"status": "declined", "reason": "not a quantity goal"} h = self.head_chat(text, session) h_ok = h.get("status") == "answered" if r.get("status") == "answered": if h_ok and quantity_goal: hv = _first_number(h.get("response")) kv = _first_number(r.get("answer")) if hv is not None and kv is not None and abs(hv - kv) > 0.02 * max(abs(hv), abs(kv), 1e-12) and \ not _same_up_to_unit(hv, kv): return {"status": "declined", "reason": "kernel and head disagree: kernel %s, head %s" % (r["answer"], h.get("response", "")[:60]), "check": "readings agree", "head": h} return dict(r, head_status=h.get("status")) if h_ok: return {"status": "answered", "answer": h.get("response"), "response": h.get("response"), "reading": "head", "path": [str(h.get("path"))], "head": h} return dict(r, head=h, hole={"question": text, "kernel": r.get("reason"), "head": h.get("status")})
def _first_number(s): m = NUM.search(str(s or "").replace("$", "")) return float(m.group(0).replace(",", "")) if m else None
def _same_up_to_unit(a, b): """1000x / 1e6x apart: the same quantity in a prefixed unit (kW vs W), not a disagreement""" for f in (1e3, 1e6, 1e-3, 1e-6, 3600, 1 / 3600, 3.6e6, 1 / 3.6e6): if abs(a * f - b) <= 0.02 * max(abs(b), 1e-12): return True return False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106#!/usr/bin/env python3"""The Oracle7 kernel, v7: META SWARM round 2, the second-largest hole class (numbers_unread, 7.5% of the census).Sampled from the pools, the unread numbers were three classes, each fixed in the READER (so the kernel AND the faces itlearns from the specialists' own examples both read them): 1. number formatting: "2.5 * (10)^(4)", "5 . 0*( 10 )^(5)", "34 . 0º C", "45º" -> ordinary numbers and units; 2. a number after a quantity noun the formula parts declare DIMENSIONLESS ("refractive index of 1.52", "f-number of 16", "efficiency of 0.35") -> that quantity, dimensionless, named by its noun (role); 3. a count: a number before a plural noun or "-tooth"/"-turn" style compound ("2 supporting strands", "18-tooth", "500 bacteria") -> a dimensionless count named by its noun (role "count:<noun>").A named dimensionless quantity or count is never a FREE factor of core arithmetic (the 09-30 law: hidden dimensionlessfactors make dimensional analysis a weak filter); only a part whose slot reads it may use it.usage: module (Kernel7, a drop-in for Kernel6)"""from __future__ import annotations
import reimport sys
from kernel_v6 import Kernel6import kernel_v5
reader = kernel_v5.readerG1 = sys.modules["glue1_v3"]G2 = sys.modules["glue2_v3"]_orig_norm, _orig_givens = reader.normalise, reader.read_givens
SCI = [(re.compile(r"(\d)\s*\.\s*(\d)"), r"\1.\2"), # "5 . 0" -> "5.0" (re.compile(r"(-?\d[\d.]*)\s*[*x×]\s*\(?\s*10\s*\)?\s*\^\s*\(?\s*(-?\d+)\s*\)?"), r"\1e\2"), # 2.5 * (10)^(4) (re.compile(r"º"), "°"), (re.compile(r"(\d)\s*°\s*([CF])\b"), r"\1 \2")]COUNT = re.compile(r"(?<![\w.])(\d+)(?:\s*-\s*|\s+)((?:[a-z]+-)?[a-z]+(?:s|tooth|turn|blade|pole|stage))\b", re.I)
def normalise(t): t = _orig_norm(t) for rx, rep in SCI: t = rx.sub(rep, t) return t
class Kernel7(Kernel6): def __init__(self, *a, **k): # the reader is extended BEFORE the faces are learned, so specialists whose own examples use these forms gain faces; # the dimensionless nouns come from the formula parts' own declared keys from kernel_v1 import Kernel1 self._dimless_nouns = sorted({n for (n, d) in Kernel1().keys if not any(d)}, key=lambda n: -len(n)) self._install_reader() super().__init__(*a, **k) fin = self.induced._finish2 named = set(self._dimless_nouns)
def finish2(base, givens, pool, used, goal, trace, hops, path, *rest): left = [q for i, q in enumerate(pool) if i not in used and not isinstance(q, tuple)] if any(q.dim == reader.DIMLESS and (q.role.startswith("count:") or q.role in named) for q in left): return None # a count or named ratio is read by a part's slot, never a free factor return fin(base, givens, pool, used, goal, trace, hops, path, *rest) self.induced._finish2 = finish2
def declared_answer(self, text): t = reader.normalise(text) g, _f = reader.read_givens(t) for q in g: if q.role.startswith("count:") and q.role[6:] not in self.noun_dims: return None, "declared: a count no formula part names (%s)" % q.text # never bound by dimension alone return super().declared_answer(text)
def _install_reader(self): kern = self
def read_givens(t): g, flags = _orig_givens(t) unread = list(flags.get("unread_numbers") or []) if not unread: return g, flags still = [] for u in unread: q = kern._bind_number(t, str(u)) if q is None: still.append(u) else: g.append(q) flags = dict(flags, unread_numbers=still) return g, flags for mod in (reader, G1, G2): if hasattr(mod, "read_givens"): mod.read_givens = read_givens if hasattr(mod, "normalise"): mod.normalise = normalise
def _bind_number(self, t, u): i = t.find(u) if i < 0: return None try: v = float(u.replace(",", "")) except ValueError: return None before = re.findall(r"[a-z][a-z\-]*", t[:i].lower())[-6:] while before and before[-1] in ("of", "is", "a", "an", "the", "with", "at", "to", "has", "=", "and", "by"): before.pop() for n in (self._dimless_nouns or []): nw = n.split() if before[-len(nw):] == nw: return reader.Q(v, reader.DIMLESS, u, n) # a named dimensionless quantity m = COUNT.match(t, i) if m and m.group(1) == u: return reader.Q(v, reader.DIMLESS, m.group(0), "count:" + m.group(2).lower()) return None12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758#!/usr/bin/env python3"""The Oracle7 kernel, v8: three classes found by v7's OpenStax run (3 wrong answers), each fixed at one place. 1. A UNIT READ SHORT. "1250 N/m" was read as "1250 N" (the reader had no "N/m"), so every "springs" face learned its spring constant as a FORCE, and a cart's 10 N push and a nail puller's 1250 N were then taken as spring constants. Fix: units with "/" composed from units already defined (N/m, J/kg, W/m^2, kg/m^3 ...), and a quantity whose unit continues past what was read ("N" then "/m") is never read short. Faces are learned again under this reader. 2. AN ARTICLE READ AS A UNIT. "in series to a 12.0-V battery" gave the goal unit "a" (amperes). One-letter unit words that are English words ("a", "in") are never a goal unit. 3. A COMMON WORD AS A SLOT CUE. "one headlight" matched the cue "one" of "one leg is {1}". Cue words must be distinctive: IDF above the median of the face vocabulary.usage: module (Kernel8, a drop-in for Kernel7)"""from __future__ import annotations
import reimport statistics
import kernel_v5import kernel_v7from kernel_v7 import Kernel7
reader = kernel_v5.readerDENS = ("m", "s", "kg", "h", "m^2", "m2", "m^3", "m3", "s^2", "s2", "kwh", "mol", "l", "min", "day", "km", "cm")
def _extend_units(): U = reader.UNITS if U.get("n/m"): return for num in [k for k in list(U) if " " not in k and "/" not in k and "^" not in k]: for den in DENS: if den in U and num != den: (f1, d1), (f2, d2) = U[num], U[den] if isinstance(d1, tuple) and isinstance(d2, tuple): U.setdefault("%s/%s" % (num, den), (f1 / f2, reader.dmul(d1, d2, -1))) reader.UNIT_ALT = "|".join(sorted((re.escape(k) for k in U), key=len, reverse=True)) NUM, ALT = reader.NUM, reader.UNIT_ALT reader.RX_QTY = re.compile(r"(?<![\w.])(%s)\s*[- ]?\s*(%s)(?![a-z/^])" % (NUM, ALT), re.I) # never read short reader.RX_RANGE = re.compile(r"\bfrom\s+(%s)\s*(%s)?\s+(?:up\s+)?to\s+(%s)\s*(%s)(?![a-z/^])" % (NUM, ALT, NUM, ALT), re.I) # "to a 12.0-V battery": the word after "to/in" is an article, not the unit ampere reader.RX_GOAL_UNIT = re.compile(r"\b(?:how many|in|into|as|to)\s+(?:us\s+)?(?!(?:a|an|in|at|as)\s)(%s)(?![a-z/^])" % ALT, re.I)
class Kernel8(Kernel7): def __init__(self, *a, **k): _extend_units() # before any face is learned super().__init__(*a, **k) vals = sorted(self.induced.idf.values()) self._cue_floor = statistics.median(vals) if vals else 0.0
def goal_of(self, text): g = super().goal_of(text) if g is not None and len(g) > 2 and str(g[2]).strip().lower() in ("a", "an", "in", "at", "as"): return None # an article or preposition, never a unit return g
def _cues(self, f): c = super()._cues(f) return {w for w in c if self.induced.idf.get(w, 0) > self._cue_floor}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758#!/usr/bin/env python3"""The Oracle7 kernel, v9: v8's reader fixes (units with "/" read whole, never short; articles never goal units), WITHOUTv8's IDF cue filter (it cost right answers on every sealed set), and three structural laws found by v8's OpenStax run.Reading more questions surfaced more weak paths, the 09-30 law in action (dimensional analysis can't see hiddenfactors: 1/2, 2, pi, geometry). So the law changes in structure, not by item: 1. AN IMPLICIT GOAL COMES FROM A PART THAT GIVES IT. When the question doesn't state the unit it wants ("What minimum force...", "What is the coefficient of performance..."), the answer must be produced directly by a formula part or a specialist face whose output is that quantity; core arithmetic may not finish the chain by combining leftover givens. An explicit unit goal ("in kWh") keeps the arithmetic finish: the everyday unit-chain family where it has held (every sealed set). 2. ONE QUESTION PER TURN. A turn that asks two things (two sentences ending in "?") is declined, not half-answered. 3. THE WANTED QUANTITY IS THE HEAD OF THE ASKING PHRASE: the first part-declared noun after "what is the / what / how much", up to "of / for / when / if / that / ,", not any quantity noun elsewhere in the sentence.usage: module (Kernel9, a drop-in for Kernel8)"""from __future__ import annotations
import re
import kernel_v4import kernel_v5from kernel_v8 import Kernel8
reader = kernel_v5.readerHEAD = re.compile(r"\b(?:what is the|what are the|what was the|what's the|find the|calculate the|determine the|what|how much)\s+" r"(.+?)(?:\s+(?:of|for|when|if|that|which|in|at|on|to|does|do|is|was|must|would|will|can)\b|[,?.]|$)", re.I)
class Kernel9(Kernel8): def _cues(self, f): return kernel_v4.Kernel4._cues(self, f) # v8's IDF filter removed
def _wanted(self, text): ask = self._asking(text) m = HEAD.search(ask) span = (m.group(1) if m else ask).lower() for n in self.nouns: # longest first, inside the asking phrase's head only if re.search(r"\b%s\b" % re.escape(n), span): return n return None
def solve(self, text, session="kernel"): t = reader.normalise(text) if len([s for s in re.split(r"(?<=[.?!])\s+", t.strip()) if s.strip().endswith("?")]) > 1: h = self.head_chat(text, session) if h.get("status") == "answered": return {"status": "answered", "answer": h.get("response"), "reading": "head", "head": h, "path": [str(h.get("path"))]} return {"status": "declined", "reason": "two questions in one turn: ask them one at a time", "check": "one question per turn"} explicit = reader.read_goal(self._asking(t)) is not None r = super().solve(text, session) if r.get("status") == "answered" and r.get("reading") not in ("declared", "head") and not explicit: tr = r.get("trace", []) last = tr[-1] if tr else {} if last.get("node") == "core_math" and len([x for x in str(last.get("formula", "")).split("×") if x.strip()]) > 1: return {"status": "declined", "reason": "an implicit goal must come from a part that gives it, not from " "arithmetic over leftover givens", "check": "implicit goal from a part"} return r123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321#!/usr/bin/env python3"""network_glue_v1 - the specialist network with GLUE instead of hand adapters (11.5 test, 2026-11-05).
network_v2 reaches each specialist through a hand-written typed adapter (ops_for: phrasing template, typed slots, replyunit pattern; 11 of them) and plans at most 2 specialist hops. This version removes every hand adapter:
FACES ARE LEARNED from each specialist's own dev panel. For a dev item (q, expect): the givens reader types the numbers inq (dimension, role, surface span); the specialist is asked q, and the number in its reply that equals `expect` gives theoutput's unit, hence its dimension. The face = template (q with each given's span replaced by a typed slot that remembersits surface unit) + output dimension. EXAMINED: a face is kept only if, rendered with the givens of ANOTHER dev item of thesame specialist and slot signature, the specialist returns that item's expected value. Nothing is written per specialist.
THE MEDIUM is a pool of typed quantities (SI value, dimension, role, source). Specialists never address each other: a facereads quantities of its slot types from the pool and writes its output back (the residual-stream analogue). Normalisationis the SI pool itself (every value in base units, so any face can read any write).
THE SELECTOR (the attention step) decides which faces may read the question at all: fit = IDF-weighted share of the face'stemplate words present in the question (IDF over all learned faces), eligible at fit >= FIT_MIN. The schedule: rounds offace applications (depth <= MAX_HOPS, derived inputs from core math allowed as in v2), and after any round the remainingquantities must reach the goal by CORE_MATH using every one of them (v2's rule). Checks unchanged: validity of givens, allnumbers read, multi-step only, no echo. No checked path -> decline.usage: network_glue_v1.py <standing.txt> <spec_root> <combo_code> [question ...]"""from __future__ import annotations
import collectionsimport itertoolsimport jsonimport mathimport osimport reimport sys
HERE = os.path.dirname(os.path.abspath(__file__))sys.path.insert(0, HERE)from network_v2 import (DIMLESS, TEMP, Q, Registry, core_math, g, normalise, read_givens, read_goal, # noqa: E402 unit_lookup, valid_given)
FIT_MIN = 0.5MAX_HOPS = 2STOP = set("a an the of to in on at for and or is are was were be by with from what how much many does do it its this that " "you your we our their there if then than per each into as which who whom whose".split())WORD = re.compile(r"[a-z][a-z\-']+")NUMU = re.compile(r"(-?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?)\s*([A-Za-z°/%$²³^0-9\-\.]*(?:\s(?:per|a|an)\s\w+)?)")
def words(text): return {w for w in WORD.findall(str(text).lower()) if w not in STOP and not unit_lookup(w)}
class Face: def __init__(self, sid, kind, template, slots, out_dim, out_factor, out_unit, src_q): self.sid, self.kind, self.template, self.slots = sid, kind, template, slots self.out_dim, self.out_factor, self.out_unit, self.src_q = out_dim, out_factor, out_unit, src_q self.words = words(re.sub(r"\{\d+\}", " ", template))
def signature(self): return tuple((s["dim"], s["role"]) for s in self.slots)
def render(self, qs): text = self.template for i, (s, q) in enumerate(zip(self.slots, qs)): if s["dim"] == TEMP: raw = q.v - s["offset"] if s["scale"] == 1 else (q.v - 273.15) * 9 / 5 + 32 else: raw = q.v / s["factor"] text = text.replace("{%d}" % i, s["prefix"] + g(raw) + s["suffix"], 1) return text
def public(self): return {"sid": self.sid, "kind": self.kind, "template": self.template, "out_unit": self.out_unit, "slots": [[str(s["dim"]), s["role"]] for s in self.slots], "from": self.src_q}
def _slot(q): """a slot remembers how its surface span writes a number: prefix, raw number, suffix; factor raw -> SI""" m = re.search(r"-?\d[\d,]*(?:\.\d+)?", q.text) if not m: return None raw = float(m.group(0).replace(",", "")) s = {"dim": q.dim, "role": q.role, "prefix": q.text[:m.start()], "suffix": q.text[m.end():]} if q.dim == TEMP: unit = q.text[m.end():].strip().lower() if unit.startswith("f"): s.update(scale=9 / 5, offset=0.0) else: s.update(scale=1, offset=q.v - raw) return s if raw == 0: return None s["factor"] = q.v / raw return s
def reply_value(resp, expect): """the number in the reply equal to the expected value, with the unit written after it""" for m in NUMU.finditer(resp or ""): try: v = float(m.group(1).replace(",", "")) except ValueError: continue if abs(v - expect) <= 0.01 * max(abs(expect), 1e-12): unit = m.group(2).strip().rstrip(".,;") for cut in (unit, unit.split(" ")[0]): u = unit_lookup(cut) if cut else None if u: return v, u, cut return v, None, unit return None
def parse_out(resp, face): for m in NUMU.finditer(resp or ""): unit = m.group(2).strip().rstrip(".,;") for cut in (unit, unit.split(" ")[0]): if cut and cut == face.out_unit: try: return float(m.group(1).replace(",", "")) except ValueError: return None return None
class GlueNetwork: def __init__(self, standing, spec_root, combo_code, log=print): self.reg = Registry(standing, spec_root, combo_code) self.root = spec_root self.log = log self.faces, self.report = self._learn() df = collections.Counter(w for f in self.faces for w in f.words) n = max(1, len(self.faces)) self.idf = {w: math.log(1 + n / c) for w, c in df.items()}
# ------------------------------------------------------------ learning faces from each specialist's own dev panel def _panel(self, sid): try: man = json.load(open(os.path.join(self.root, sid, "manifest.json"))) p = man.get("panel", {}).get("path", "") local = os.path.join(self.root, sid, os.path.basename(p)) items = json.load(open(local if os.path.exists(local) else p)) except Exception: # noqa: BLE001 return [] return [it for it in items if isinstance(it, dict) and it.get("split") == "dev" and it.get("valid", True) and isinstance(it.get("expect"), (int, float)) and not isinstance(it.get("expect"), bool)]
def _ask(self, sid, text): try: r = self.reg.ask(sid, text) except Exception: # noqa: BLE001 return None if not r or r.get("declined"): return None return r.get("response", "")
def _learn(self): faces, rep = [], {"specialists": 0, "with_panel": 0, "candidates": 0, "examined_ok": 0, "unexamined": 0, "failed": 0, "by_specialist": {}} for sid in self.reg.ids: rep["specialists"] += 1 items = self._panel(sid) if not items: continue rep["with_panel"] += 1 cands = [] for it in items[:60]: q = normalise(it["q"]) givens, flags = read_givens(q) if not givens or flags.get("unread_numbers") or len(givens) > 4: continue if any(q.find(x.text) < 0 for x in givens): continue resp = self._ask(sid, it["q"]) hit = reply_value(resp, float(it["expect"])) if resp else None if not hit or not hit[1]: continue v, (factor, dim), unit = hit template, slots, ok = q, [], True for i, x in enumerate(givens): s = _slot(x) if s is None: ok = False break template = template.replace(x.text, "{%d}" % i, 1) slots.append(s) if ok and all("{%d}" % i in template for i in range(len(slots))): cands.append((Face(sid, it.get("kind", ""), template, slots, dim, factor, unit, it["q"]), givens, it)) rep["candidates"] += len(cands) kept = 0 by_sig = collections.defaultdict(list) for c in cands: by_sig[(c[0].kind, c[0].signature())].append(c) for sig, group in by_sig.items(): seen_templates = set() for f, _g, _it in group: if f.template in seen_templates: continue others = [(gv, it) for ff, gv, it in group if ff is not f and ff.src_q != f.src_q] if not others: rep["unexamined"] += 1 continue passed = False for gv, it in others[:3]: resp = self._ask(sid, f.render(gv)) out = parse_out(resp, f) if resp else None if out is not None and abs(out - float(it["expect"])) <= 0.01 * max(abs(float(it["expect"])), 1e-12): passed = True break if passed: faces.append(f) seen_templates.add(f.template) kept += 1 rep["examined_ok"] += 1 else: rep["failed"] += 1 rep["by_specialist"][sid] = kept if kept: self.log("faces %-22s %d" % (sid, kept)) return faces, rep
# ------------------------------------------------------------ the selector and the medium def fit(self, face, qwords): tot = sum(self.idf.get(w, 0) for w in face.words) if tot <= 0: return 0.0 return sum(self.idf.get(w, 0) for w in face.words & qwords) / tot
def _fillers(self, pool, used, slot): out = [i for i, q in enumerate(pool) if i not in used and q.dim == slot["dim"] and q.role == slot["role"]] if slot["dim"] != TEMP: for i, j in itertools.combinations([k for k in range(len(pool)) if k not in used and not pool[k].temp_point], 2): cm = core_math([pool[i], pool[j]], slot["dim"]) if cm and slot["role"] == "": out.append(("d", (i, j))) return out
def _apply(self, face, pool, used, trace): """every way this face can read the pool; yields (new pool, new used, new trace)""" fills = [self._fillers(pool, used, s) for s in face.slots] for combo in itertools.product(*fills): idx = set() for sp in combo: ix = set(sp[1]) if isinstance(sp, tuple) else {sp} if idx & ix: break idx |= ix else: args, tr = [], list(trace) for sp, s in zip(combo, face.slots): if isinstance(sp, tuple): cm = core_math([pool[i] for i in sp[1]], s["dim"]) tr.append({"node": "core_math", "op": "derive", "formula": cm[1], "value": cm[0]}) args.append(Q(cm[0], s["dim"], "(%s)" % cm[1], "")) else: args.append(pool[sp]) text = face.render(args) resp = self._ask(face.sid, text) val = parse_out(resp, face) if resp else None tr.append({"node": face.sid, "kind": face.kind, "asked": text, "reply": resp, "value": val}) if val is None or not math.isfinite(val): continue out = Q(val * face.out_factor, face.out_dim, "%s(%s)" % (face.kind or face.sid, ", ".join(a.text for a in args)), "", src=face.sid) yield pool + [out], used | idx, tr
def solve(self, text): text = normalise(text) givens, flags = read_givens(text) goal = read_goal(text) base = {"question": text, "givens": [repr(q) for q in givens], "goal": str(goal)} if goal is None or goal[0] != "dim": return dict(base, status="declined", reason="no numeric goal I can reach") if not givens: return dict(base, status="declined", reason="no quantities to work from") for q in givens: bad = valid_given(q) if bad: return dict(base, status="declined", reason=bad, check="validity") if flags.get("unread_numbers"): return dict(base, status="declined", reason="numbers I could not read", check="all numbers read") qw = words(text) eligible = [f for f in self.faces if self.fit(f, qw) >= FIT_MIN] eligible.sort(key=lambda f: -self.fit(f, qw)) frontier = [(list(givens), set(), [], 0)] for depth in range(MAX_HOPS + 1): nxt = [] for pool, used, trace, hops in frontier: rest = [q for i, q in enumerate(pool) if i not in used] done = self._finish(base, givens, rest, goal, trace, hops) if done: return done if hops < MAX_HOPS: for f in eligible: for p2, u2, t2 in self._apply(f, pool, used, trace): nxt.append((p2, u2, t2, hops + 1)) frontier = nxt[:200] return dict(base, status="declined", reason="no checked path from the givens to what is asked", eligible=[f.sid + ":" + f.kind for f in eligible[:6]])
def _finish(self, base, givens, rest, goal, trace, hops): cm = core_math(rest, goal[1]) if not cm: return None val = cm[0] / goal[3] if not math.isfinite(val) or val < 0: return None if hops == 0 and len(givens) == 1: return dict(base, status="declined", reason="single conversion (the core's own operator)", check="multi-step only") if hops == 0 and any(abs(cm[0] - q.v) <= 1e-9 * max(1.0, abs(q.v)) and q.dim == goal[1] for q in givens): return None unit = goal[2] say = ("$%.2f" % val) if unit == "$" else "%s %s" % (g(round(val, 6)), unit) trace = trace + [{"node": "core_math", "op": "dimensional", "formula": cm[1], "value": val, "unit": unit}] nodes = [t["node"] for t in trace] return dict(base, status="answered", answer=say, response="The answer is %s. (path: %s)" % (say, " → ".join(nodes)), trace=trace, hops=hops)
if __name__ == "__main__": net = GlueNetwork(open(sys.argv[1]).read().split(), sys.argv[2], sys.argv[3]) print(json.dumps({k: v for k, v in net.report.items() if k != "by_specialist"})) for q in sys.argv[4:]: print(json.dumps(net.solve(q), indent=1, ensure_ascii=False)[:1500])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431#!/usr/bin/env python3"""network_glue_v2 - glue v1 plus the three classes its first run found (2026-11-05). Still 0 hand-written adapters.
1. CONDITIONS, learned by ablation from the specialist itself. Every content word of a face's template is removed in turn and the specialist re-asked with the face's own dev givens; a word whose removal changes the answer or makes the specialist decline is a CONDITION of the face. A face is eligible only when all its conditions are in the question. COVERAGE (second reading of the question): every question word that is a condition of SOME face, and every name (capitalised word after the first), must be covered by a face on the path, else the network declines. And a dimensionless quantity carrying a role (e.g. "twice Earth's mass") is a condition, never a free factor: core math may not absorb it. (v1's 2 wrong + 2 false yes: an Earth-gravity fall face applied to the Moon / another planet.)2. OUTPUT KINDS. Yes/no faces (dev expect "Yes"/"No") answer bool goals; counting goals use v2's per-unit rule; faces whose dev questions carry bare numbers (geometry: "radius 2") get their dimensional law from a SCALING PROBE: the input is doubled and the exponent read from the answer's ratio (area 4x -> output = input^2), so a bare-number slot reads any quantity of one dimension and writes that dimension to the learned power.3. SELECTOR: types gate (a face can only read quantities of its slot types), conditions gate, words rank (v1 gated on word fit at 0.5 and missed "a motor lifts a load" against "a box lifted").usage: network_glue_v2.py <standing.txt> <spec_root> <combo_code> [question ...]"""from __future__ import annotations
import collectionsimport itertoolsimport jsonimport mathimport reimport sys
from network_glue_v1 import (GlueNetwork, Face, _slot, parse_out, reply_value, words) # noqa: F401from network_v2 import DIMLESS, TEMP, Q, core_math, dmul, g, normalise, read_givens, read_goal, unit_lookup, valid_given
FREE = "free"BARE = re.compile(r"(?<![\w.])(-?\d+(?:\.\d+)?)(?![\w.]*\s*(?:%|°))")YESNO = re.compile(r"^\W*(yes|no)\b", re.I)
def _stem(w): for suf in ("ing", "ed", "es", "s"): if len(w) > len(suf) + 3 and w.endswith(suf): return w[:-len(suf)] return w
def stems(ws): return {_stem(w) for w in ws}
class Face2(Face): def __init__(self, *a, out_kind="dim", power=None, **k): super().__init__(*a, **k) self.out_kind, self.power, self.conditions = out_kind, power, set()
def render(self, qs): if self.power is None: return super().render(qs) text = self.template for i, q in enumerate(qs): text = text.replace("{%d}" % i, g(q.v), 1) return text
def public(self): d = super().public() d.update(out_kind=self.out_kind, power=self.power, conditions=sorted(self.conditions)) return d
class GlueNetwork2(GlueNetwork): # ------------------------------------------------------------ learning def _learn(self): faces, rep = [], {"specialists": 0, "with_panel": 0, "candidates": 0, "examined_ok": 0, "unexamined": 0, "failed": 0, "bool_faces": 0, "scaling_faces": 0, "conditions_total": 0, "by_specialist": {}} for sid in self.reg.ids: rep["specialists"] += 1 items = self._panel_any(sid) if not items: continue rep["with_panel"] += 1 self._vocab = getattr(self, "_vocab", {}) self._vocab[sid] = set().union(*(words(re.sub(r"-?\d[\d,.]*", " ", it["q"])) for it in items[:60])) self._kind_vocab = getattr(self, "_kind_vocab", {}) for it in items[:60]: self._kind_vocab.setdefault((sid, it.get("kind", "")), set()).update(words(re.sub(r"-?\d[\d,.]*", " ", it["q"]))) cands = [c for it in items[:60] for c in [self._candidate(sid, it)] if c] rep["candidates"] += len(cands) kept = 0 groups = collections.defaultdict(list) for c in cands: groups[(c[0].kind, c[0].out_kind, c[0].signature(), c[0].power is not None)].append(c) for _key, group in groups.items(): done = set() for f, gv, it in group: if f.template in done: continue others = [(g2, i2) for f2, g2, i2 in group if f2.src_q != f.src_q] if not others: rep["unexamined"] += 1 continue if not any(self._check(f, g2, i2) for g2, i2 in others[:3]): rep["failed"] += 1 continue f.conditions = self._conditions(f, gv, it) f.out_name = stems(self._wh_words(f.template)) & stems(f.conditions) f.ctx = stems(f.conditions) - f.out_name rep["conditions_total"] += len(f.conditions) faces.append(f) done.add(f.template) kept += 1 rep["examined_ok"] += 1 rep["bool_faces"] += f.out_kind == "bool" rep["scaling_faces"] += f.power is not None rep["by_specialist"][sid] = kept if kept: self.log("faces %-22s %d" % (sid, kept)) return faces, rep
def _panel_any(self, sid): try: man = json.load(open("%s/%s/manifest.json" % (self.root, sid))) p = man.get("panel", {}).get("path", "") import os local = os.path.join(self.root, sid, os.path.basename(p)) items = json.load(open(local if os.path.exists(local) else p)) except Exception: # noqa: BLE001 return [] out = [] for it in items: if not isinstance(it, dict) or it.get("split") != "dev" or not it.get("valid", True): continue e = it.get("expect") if isinstance(e, bool): continue if isinstance(e, (int, float)) or (isinstance(e, str) and e.strip().lower() in ("yes", "no")): out.append(it) return out
def _candidate(self, sid, it): q = normalise(it["q"]) expect = it["expect"] boolish = isinstance(expect, str) givens, flags = read_givens(q) if givens and not flags.get("unread_numbers") and len(givens) <= 4 and all(q.find(x.text) >= 0 for x in givens): resp = self._ask(sid, it["q"]) if not resp: return None if boolish: m = YESNO.match(resp) if not m or m.group(1).lower() != expect.strip().lower(): return None out_dim, factor, unit, kind = None, 1, "", "bool" else: hit = reply_value(resp, float(expect)) if not hit or not hit[1]: return None _v, (factor, out_dim), unit = hit kind = "dim" template, slots = q, [] for i, x in enumerate(givens): s = _slot(x) if s is None: return None template = template.replace(x.text, "{%d}" % i, 1) slots.append(s) if not all("{%d}" % i in template for i in range(len(slots))): return None return (Face2(sid, it.get("kind", ""), template, slots, out_dim, factor, unit, it["q"], out_kind=kind), givens, it) if boolish or givens: return None # bare numbers: a scaling probe gives the dimensional law nums = list(BARE.finditer(q)) if not nums or len(nums) > 2: return None resp = self._ask(sid, it["q"]) if not resp or not reply_value(resp, float(expect)): return None vals = [float(m.group(1)) for m in nums] template = q for i, m in enumerate(reversed(nums)): j = len(nums) - 1 - i template = template[:m.start()] + "{%d}" % j + template[m.end():] f = Face2(sid, it.get("kind", ""), template, [{"dim": FREE, "role": ""} for _ in nums], None, 1, "", it["q"], power=0) base = float(expect) r2 = self._ask(sid, f.render([Q(v * 2, DIMLESS, "") for v in vals])) out = self._first_number(r2) if out is None or base == 0 or out / base <= 0: return None p = math.log(out / base, 2) if abs(p - round(p)) > 0.02 or round(p) == 0: return None f.power = int(round(p)) return (f, [Q(v, DIMLESS, "") for v in vals], it)
@staticmethod def _wh_words(template): """the words naming what a dev question asks for: its wh-phrase, up to the first preposition or verb join""" last = [s for s in re.split(r"(?<=[.?!])\s+", template) if s][-1:] or [template] m = re.search(r"\b(?:what|how|which)\b(.*?)(?:\bof\b|\bdoes\b|\bdo\b|\bat\b|\bwill\b|\bfor\b|\bwith\b|\?|$)", last[0], re.I) return words(m.group(1)) if m else set()
@staticmethod def _first_number(resp): m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?", resp or "") return float(m.group(0).replace(",", "")) if m else None
def _value(self, f, resp): if not resp: return None if f.out_kind == "bool": m = YESNO.match(resp) return m.group(1).lower() if m else None if f.power is not None: return self._first_number(resp) return parse_out(resp, f)
def _check(self, f, givens, it): v = self._value(f, self._ask(f.sid, f.render(givens))) e = it["expect"] if f.out_kind == "bool": return v is not None and v == str(e).strip().lower() return v is not None and abs(v - float(e)) <= 0.01 * max(abs(float(e)), 1e-12)
def _conditions(self, f, givens, it): """words of the template that change what the specialist computes. Each word is swapped for words the SAME specialist uses in its other dev questions (its own vocabulary, so the sentence stays one it reads); if any swap gives a different answer, the word is a condition ("lead" -> "water" changes the heat; "okay" -> "compliant" changes nothing). A swap the specialist declines says nothing either way.""" base = self._value(f, self._ask(f.sid, f.render(givens))) # first the words that vary across the same KIND of dev question (where materials, bodies, objects change), # then the rest of the specialist's vocabulary same_kind = sorted(self._kind_vocab.get((f.sid, f.kind), set()) - f.words) vocab = same_kind + sorted(self._vocab.get(f.sid, set()) - f.words - set(same_kind)) conds = set() for w in sorted(f.words): for alt in vocab[:12]: t = re.sub(r"\b%s\b" % re.escape(w), alt, f.template, count=1, flags=re.I) probe = Face2(f.sid, f.kind, t, f.slots, f.out_dim, f.out_factor, f.out_unit, f.src_q, out_kind=f.out_kind, power=f.power) v = self._value(probe, self._ask(f.sid, probe.render(givens))) if v is None: continue same = (v == base) if f.out_kind == "bool" else (base is not None and abs(v - base) <= 1e-6 * max(abs(base), 1e-12)) if not same: conds.add(w) break return conds
# ------------------------------------------------------------ solving def _fillers(self, pool, used, slot): if slot["dim"] == FREE: # a bare-number slot reads a quantity with no role, or one whose role word the face's own template uses fw = getattr(self, "_face_words", set()) return [i for i, q in enumerate(pool) if i not in used and q.dim != DIMLESS and not q.temp_point and (not q.role or q.role in fw)] named = {i for i, q in enumerate(pool) if q.dim == DIMLESS and q.role and re.search(r"\b[A-Z][a-z]+", q.text)} # a ratio to a named body never enters a derived input either (the side door v2's first run found) return [sp for sp in super()._fillers(pool, used, slot) if not (isinstance(sp, tuple) and set(sp[1]) & named)]
def _apply(self, face, pool, used, trace): self._face_words = face.words fills = [self._fillers(pool, used, s) for s in face.slots] for combo in itertools.product(*fills): flat = [] for sp in combo: flat += list(sp[1]) if isinstance(sp, tuple) else [sp] if len(flat) != len(set(flat)): continue if face.power is not None: dims = {pool[i].dim for i in combo} if len(dims) != 1: continue args, tr = [], list(trace) for sp, s in zip(combo, face.slots): if isinstance(sp, tuple): cm = core_math([pool[i] for i in sp[1]], s["dim"]) tr.append({"node": "core_math", "op": "derive", "formula": cm[1], "value": cm[0]}) args.append(Q(cm[0], s["dim"], "(%s)" % cm[1], "")) else: args.append(pool[sp]) text = face.render(args) val = self._value(face, self._ask(face.sid, text)) tr.append({"node": face.sid, "kind": face.kind, "asked": text, "value": val, "face": face.template}) if val is None: continue if face.out_kind == "bool": yield pool + [("bool", val)], used | set(flat), tr continue if not isinstance(val, float) or not math.isfinite(val): continue if face.power is not None: d = args[0].dim out_dim = DIMLESS for _ in range(abs(face.power)): out_dim = dmul(out_dim, d, 1 if face.power > 0 else -1) out = Q(val, out_dim, "%s(%s)" % (face.kind, ", ".join(a.text for a in args)), "", src=face.sid) else: out = Q(val * face.out_factor, face.out_dim, "%s(%s)" % (face.kind or face.sid, ", ".join(a.text for a in args)), "", src=face.sid) yield pool + [out], used | set(flat), tr
def solve(self, text): text = normalise(text) givens, flags = read_givens(text) goal = read_goal(text) base = {"question": text, "givens": [repr(q) for q in givens], "goal": str(goal)} if goal is None: return dict(base, status="declined", reason="no goal I can reach") if not givens: return dict(base, status="declined", reason="no quantities to work from") for q in givens: bad = valid_given(q) if bad: return dict(base, status="declined", reason=bad, check="validity") if flags.get("unread_numbers"): return dict(base, status="declined", reason="numbers I could not read", check="all numbers read") qw = stems(words(text)) in_givens = " ".join(q.text for q in givens).lower() names = {_stem(w.lower()) for w in re.findall(r"(?<=[^.?!:]\s)([A-Z][a-z]+)\b", text) if not unit_lookup(w) and w.lower() not in in_givens} all_conds = set().union(*(stems(f.conditions) for f in self.faces)) if self.faces else set() goal_dim = goal[1] if goal[0] == "dim" else None
def ok(f): final = f.out_kind == "bool" or (f.power is None and f.out_dim == goal_dim) or f.power is not None if final: # its output is the answer: every condition named, and the words fit if not stems(f.conditions) <= qw: return False return bool(f.conditions) or self.fit(f, qw) >= 0.5 # word fit only when no condition was learned # an intermediate step: the question names its situation, not the quantity it hands on return f.ctx <= qw and bool(stems(f.words - f.conditions) & qw or f.ctx & qw) eligible = [f for f in self.faces if ok(f)] # siblings (same specialist, same slot types, same output kind) compete on the words that tell them apart sib = collections.defaultdict(list) for f in self.faces: sib[(f.sid, f.signature(), f.out_kind)].append(f) keep = [] for f in eligible: group = sib[(f.sid, f.signature(), f.out_kind)] if len(group) == 1: keep.append(f) continue def score(x): others = set().union(*(stems(y.words) for y in group if y is not x)) return len((stems(x.words) - others) & qw) mine = score(f) rival = max(score(y) for y in group if y is not f) if mine >= 1 and mine > rival: keep.append(f) eligible = keep # coverage reads only conditions of faces that could have read these quantities (a competing reading) fillable = [f for f in self.faces if all(self._fillers(list(givens), set(), s) for s in f.slots)] all_conds = set().union(*(stems(f.conditions) for f in fillable)) if fillable else set() if goal[0] == "bool": eligible = [f for f in eligible if f.out_kind == "bool"] else: eligible = [f for f in eligible if f.out_kind != "bool"] eligible.sort(key=lambda f: -self.fit(f, qw)) frontier = [(list(givens), set(), [], 0, [])] for _depth in range(3): nxt = [] for pool, used, trace, hops, path in frontier: done = self._finish2(base, givens, pool, used, goal, trace, hops, path, qw, names, all_conds) if done: return done if hops < 2: for f in eligible: for p2, u2, t2 in self._apply(f, pool, used, trace): nxt.append((p2, u2, t2, hops + 1, path + [f])) frontier = nxt[:200] return dict(base, status="declined", reason="no checked path from the givens to what is asked", eligible=[f.sid + ":" + f.kind for f in eligible[:6]])
def _covered(self, path, qw, names, all_conds): cover = set() for f in path: cover |= stems(f.words) | stems(f.conditions) # a condition word of another face that only names an output quantity is not a situation the path ignored all_conds = all_conds - set().union(*(getattr(f, "out_name", set()) for f in self.faces)) return sorted(((qw & all_conds) | names) - cover)
def _finish2(self, base, givens, pool, used, goal, trace, hops, path, qw, names, all_conds): rest = [q for i, q in enumerate(pool) if i not in used] bools = [x for x in rest if isinstance(x, tuple)] rest = [x for x in rest if not isinstance(x, tuple)] if goal[0] == "bool": if len(bools) != 1 or rest: return None ans = bools[0][1] sentence = "%s." % ans.capitalize() else: if bools: return None if any(q.dim == DIMLESS and q.role and re.search(r"\b[A-Z][a-z]+", q.text) for q in rest): return None # a ratio to a named body is a condition, never a free factor if goal[0] == "count": per = [q for q in rest if q.role.startswith("per_unit_")] if len(per) != 1: return None cm = core_math([q for q in rest if q is not per[0]], (0, 0, 1, 0, 0, 0)) if not cm: return None n = cm[0] / per[0].v ans = "%s" % g(n) sentence = "That is %s %s." % (g(round(n, 4)), goal[1]) else: cm = core_math(rest, goal[1]) if not cm: return None val = cm[0] / goal[3] if not math.isfinite(val) or val < 0: return None if hops == 0 and len(givens) == 1: return dict(base, status="declined", reason="single conversion (the core's own operator)", check="multi-step only") if hops == 0 and any(abs(cm[0] - q.v) <= 1e-9 * max(1.0, abs(q.v)) and q.dim == goal[1] for q in givens): return None unit = goal[2] ans = ("$%.2f" % val) if unit == "$" else "%s %s" % (g(round(val, 6)), unit) sentence = "The answer is %s." % ans trace = trace + [{"node": "core_math", "op": "dimensional", "formula": cm[1], "value": val, "unit": unit}] missing = self._covered(path, qw, names, all_conds) if missing: return dict(base, status="declined", reason="part of the question no path read: %s" % ", ".join(missing[:5]), check="coverage") nodes = [t["node"] for t in trace] return dict(base, status="answered", answer=ans, response="%s (path: %s)" % (sentence, " → ".join(nodes) or "core_math"), trace=trace, hops=hops)
if __name__ == "__main__": net = GlueNetwork2(open(sys.argv[1]).read().split(), sys.argv[2], sys.argv[3]) print(json.dumps({k: v for k, v in net.report.items() if k != "by_specialist"})) for q in sys.argv[4:]: print(json.dumps(net.solve(q), indent=1, ensure_ascii=False)[:1200])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181#!/usr/bin/env python3"""network_glue_v3 - glue v2 plus the class fixes from GLUE SEALED 1's verdict (GLUE_SEALED1_VERDICT.md). 0 hand adapters.
1. THE READER (shared with network_v2, which stays unchanged): glue v3 loads its OWN copy of the reader with standard units added - definitions, not fitted values: pascal/kPa, electronvolt, food Calorie (kcal), rpm, newton-metre, nanometre, km/s, kilonewton, GHz, MHz. Case-ambiguous prefixes in a lowercase table are left out (mW/MW, mPa/MPa): the reader would have to guess. network_v2 and glue v1/v2 in the same process keep the original reader.2. SCALING FACES (geometry) follow the same final/intermediate rule as every face: a volume handed on to mass or cost needs its situation words, not its output name. The output name of an imperative dev question ("Calculate the area of ...", "Work out the volume of ...") is read like a wh-question's.3. FINAL STEPS: a final step's own output name may be met by the goal's dimension, when the question names the face's situation through at least one of its distinctive words (IDF above the median of the face vocabulary) - "how many seconds until it lands" reaches the fall face through "dropped/falls", not through its word "long".4. COVERAGE: a condition word blocks only when it belongs to a fillable face whose output is the goal's kind (a competing reading of this question), plus names - not to any face that could read the quantities.usage: network_glue_v3.py <standing.txt> <spec_root> <combo_code> [question ...]"""from __future__ import annotations
import collectionsimport jsonimport osimport reimport statisticsimport sysimport types
HERE = os.path.dirname(os.path.abspath(__file__))sys.path.insert(0, HERE)
EXTRA_UNITS = '''_u("pa|pascal|pascals", 1, D(kg=1, m=-1, s=-2))_u("kpa|kilopascal|kilopascals", 1e3, D(kg=1, m=-1, s=-2))_u("ev|electronvolt|electronvolts|electron volt|electron volts", 1.602176634e-19, ENERGY)_u("kcal|kilocalorie|kilocalories|food calorie|food calories", 4184, ENERGY)# rpm left out: as torque x rpm it hides 2*pi (rev -> rad); dimensional analysis cannot see it (the 09-30 law)_u("n·m|n m|n-m|newton-metre|newton-metres|newton metre|newton metres", 1, ENERGY)_u("nm|nanometre|nanometres|nanometer|nanometers", 1e-9, LEN)_u("km/s", 1000, VEL)_u("kn|kilonewton|kilonewtons", 1e3, D(kg=1, m=1, s=-2))_u("ghz|gigahertz", 1e9, FREQ)_u("mhz|megahertz", 1e6, FREQ)# compound units "a per b" composed from units already defined (a density must never be read as a mass): every# numerator unit over the common denominators of volume, area, time, mass and lengthfor _num in [k for k in list(UNITS) if " " not in k and "/" not in k and len(k) > 1]: for _den in ("cubic metre", "cubic metres", "m3", "litre", "litres", "liter", "liters", "square metre", "square metres", "m2", "second", "hour", "kg", "kilogram", "metre", "meter"): _f1, _d1 = UNITS[_num] _f2, _d2 = UNITS[_den] _key = _num + " per " + _den if _key not in UNITS and not isinstance(_d1, str): UNITS[_key] = (_f1 / _f2, dmul(_d1, _d2, -1))'''
def _load(name, path, subs): src = open(path, encoding="utf-8").read() for a, b in subs: assert a in src, (name, a[:40]) src = src.replace(a, b, 1) if a == "NUMW = {" else src.replace(a, b) mod = types.ModuleType(name) mod.__file__ = path sys.modules[name] = mod exec(compile(src, path, "exec"), mod.__dict__) return mod
reader = _load("reader_v3", os.path.join(HERE, "network_v2.py"), [("NUMW = {", EXTRA_UNITS + "\nNUMW = {")])g1 = _load("glue1_v3", os.path.join(HERE, "network_glue_v1.py"), [("from network_v2 import", "from reader_v3 import")])g2 = _load("glue2_v3", os.path.join(HERE, "network_glue_v2.py"), [("from network_v2 import", "from reader_v3 import"), ("from network_glue_v1 import", "from glue1_v3 import")])stems, words, Face2 = g2.stems, g2.words, g2.Face2WH = re.compile(r"\b(?:what|how|which|calculate|determine|find|give|compute|work out)\b(.*?)" r"(?:\bof\b|\bdoes\b|\bdo\b|\bat\b|\bwill\b|\bfor\b|\bwith\b|\?|\.|$)", re.I)
class GlueNetwork3(g2.GlueNetwork2): def __init__(self, *a, **k): super().__init__(*a, **k) vals = sorted(self.idf.values()) self.idf_median = statistics.median(vals) if vals else 0.0
@staticmethod def _wh_words(template): last = [s for s in re.split(r"(?<=[.?!])\s+", template) if s][-1:] or [template] m = WH.search(last[0]) return words(m.group(1)) if m else set()
def _distinct(self, f): return {w for w in stems(f.words - f.conditions) if self.idf.get(w, 0) > self.idf_median}
def _final(self, f, goal_dim): if f.out_kind == "bool": return True if f.power is not None: d = reader.DIMLESS for _ in range(abs(f.power)): d = reader.dmul(d, reader.LEN, 1 if f.power > 0 else -1) return d == goal_dim return f.out_dim == goal_dim
def solve(self, text): text = reader.normalise(text) givens, flags = reader.read_givens(text) goal = reader.read_goal(text) base = {"question": text, "givens": [repr(q) for q in givens], "goal": str(goal)} if goal is None: return dict(base, status="declined", reason="no goal I can reach") if not givens: return dict(base, status="declined", reason="no quantities to work from") for q in givens: bad = reader.valid_given(q) if bad: return dict(base, status="declined", reason=bad, check="validity") if flags.get("unread_numbers"): return dict(base, status="declined", reason="numbers I could not read", check="all numbers read") qw = stems(words(text)) in_givens = " ".join(q.text for q in givens).lower() names = {g2._stem(w.lower()) for w in re.findall(r"(?<=[^.?!:]\s)([A-Z][a-z]+)\b", text) if not reader.unit_lookup(w) and w.lower() not in in_givens} goal_dim = goal[1] if goal[0] == "dim" else None
def ok(f): ctx = getattr(f, "ctx", set()) if not ctx <= qw: return False if self._final(f, goal_dim): if stems(f.conditions) <= qw: return bool(f.conditions) or self.fit(f, qw) >= 0.5 or bool(self._distinct(f) & qw) # its output name is met by the goal's kind; its situation must still be named distinctively return bool(self._distinct(f) & qw) or bool(ctx & qw) return bool(stems(f.words - f.conditions) & qw or ctx & qw)
eligible = [f for f in self.faces if ok(f)] sib = collections.defaultdict(list) for f in self.faces: sib[(f.sid, f.signature(), f.out_kind)].append(f) keep = [] for f in eligible: group = sib[(f.sid, f.signature(), f.out_kind)] if len(group) == 1: keep.append(f) continue
def score(x): others = set().union(*(stems(y.words) for y in group if y is not x)) return len((stems(x.words) - others) & qw) mine, rival = score(f), max(score(y) for y in group if y is not f) if mine >= 1 and mine > rival: keep.append(f) eligible = keep competing = [f for f in self.faces if self._final(f, goal_dim) and all(self._fillers(list(givens), set(), s) for s in f.slots)] all_conds = set().union(*(getattr(f, "ctx", set()) for f in competing)) if competing else set() eligible = [f for f in eligible if (f.out_kind == "bool") == (goal[0] == "bool")] eligible.sort(key=lambda f: -self.fit(f, qw)) frontier = [(list(givens), set(), [], 0, [])] for _depth in range(3): nxt = [] for pool, used, trace, hops, path in frontier: done = self._finish2(base, givens, pool, used, goal, trace, hops, path, qw, names, all_conds) if done: return done if hops < 2: for f in eligible: for p2, u2, t2 in self._apply(f, pool, used, trace): nxt.append((p2, u2, t2, hops + 1, path + [f])) frontier = nxt[:200] return dict(base, status="declined", reason="no checked path from the givens to what is asked", eligible=[f.sid + ":" + f.kind for f in eligible[:6]])
def _covered(self, path, qw, names, all_conds): cover = set() for f in path: cover |= stems(f.words) | stems(f.conditions) return sorted(((qw & all_conds) | names) - cover)
if __name__ == "__main__": net = GlueNetwork3(open(sys.argv[1]).read().split(), sys.argv[2], sys.argv[3]) print(json.dumps({k: v for k, v in net.report.items() if k != "by_specialist"})) for q in sys.argv[4:]: print(json.dumps(net.solve(q), indent=1, ensure_ascii=False)[:1200])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733#!/usr/bin/env python3
"""network_v2 - v2 = v1.2 + BREADTH (phase 7a, 2026-09-30): more typed operations from existing nodes (geometry cylinder
volume, thermo heating a named material / melting ice, carboncapture gasoline CO2, planetary weight) and DERIVED inputs:
an operation's input may be computed by CORE_MATH from 2-3 givens first (miles / mpg -> gallons -> CO2), so paths run
core -> specialist -> core. The v1 description follows.
network_v1 - the Oracle7 SPECIALIST NETWORK (phases 1-4 of the 2026-09-30 plan).
NODES (one byte each): the standing specialists (IDs 0..N-1 in registry order) + CORE_MATH (0xFE, the frozen core's
exact dimensional arithmetic) . A node is called through a TYPED ADAPTER: typed inputs are rendered into a phrasing the
specialist already answers (taken from its own dev panel), its reply is parsed back into a typed, unit-checked value. The
specialists stay frozen and gated; nothing inside a node changes.
PLAN: read the question into typed GIVENS (numbers with units, rates such as "8 hours a day", ratios such as "twice
Earth's mass", temperatures, directions) and a typed GOAL (the dimension/unit asked for, or a yes/no compliance); search
paths = up to 2 domain-node applications followed by one CORE_MATH combination that uses EVERY remaining given exactly
once (exponent +1/-1) to reach the goal dimension. Every hop is CHECKED: physical validity of inputs (durations > 0, at
most 24 hours in a day, non-negative magnitudes, ...), the node's reply parses to the expected unit, the final dimension
matches the goal. No checked path -> the network declines (never guesses).
PATH MEMORY (phase 4): a path that ran clean is stored under its question SHAPE (goal signature + given signatures) as a
byte string; the next question of the same shape tries that path first.
"""
from __future__ import annotations
import itertools
import json
import math
import os
import re
import sys
from fractions import Fraction
HERE = os.path.dirname(os.path.abspath(__file__))
# ---------------------------------------------------------------- dimensions & units (SI base: m kg s A K $)
BASE = ("m", "kg", "s", "A", "K", "$")
def D(**e):
return tuple(e.get(b, 0) for b in BASE)
def dmul(a, b, k=1):
return tuple(x + k * y for x, y in zip(a, b))
DIMLESS = D()
LEN, MASS, TIME, AREA, VOL = D(m=1), D(kg=1), D(s=1), D(m=2), D(m=3)
VEL, ACC, FREQ = D(m=1, s=-1), D(m=1, s=-2), D(s=-1)
ENERGY, POWER = D(kg=1, m=2, s=-2), D(kg=1, m=2, s=-3)
VOLT, CURR, CHARGE, MONEY = D(kg=1, m=2, s=-3, A=-1), D(A=1), D(A=1, s=1), D(**{"$": 1})
TEMP, INV_TEMP, FLOW = D(K=1), D(K=-1), D(m=3, s=-1)
# name -> (factor to SI, dimension)
UNITS = {}
def _u(names, factor, dim):
for n in names.split("|"):
UNITS[n] = (factor, dim)
_u("w|watt|watts", 1, POWER)
_u("kw|kilowatt|kilowatts", 1000, POWER)
_u("hp|horsepower", 745.69987, POWER)
_u("v|volt|volts", 1, VOLT)
_u("a|amp|amps|ampere|amperes", 1, CURR)
_u("ah|amp-hour|amp-hours", 3600, CHARGE)
_u("s|sec|secs|second|seconds", 1, TIME)
_u("min|mins|minute|minutes", 60, TIME)
_u("h|hr|hrs|hour|hours", 3600, TIME)
_u("day|days", 86400, TIME)
_u("week|weeks", 7 * 86400, TIME)
_u("year|years", 365 * 86400, TIME)
_u("kwh|kilowatt-hour|kilowatt-hours", 3.6e6, ENERGY)
_u("wh|watt-hour|watt-hours", 3600, ENERGY)
_u("j|joule|joules", 1, ENERGY)
_u("kj|kilojoule|kilojoules", 1000, ENERGY)
_u("mph", 0.44704, VEL)
_u("m/s", 1, VEL)
_u("km/h|kph", 1 / 3.6, VEL)
_u("m/s^2|m/s2|m/s²|metres per second squared|meters per second squared", 1, ACC)
_u("m|metre|metres|meter|meters", 1, LEN)
_u("km|kilometre|kilometres|kilometer|kilometers", 1000, LEN)
_u("cm|centimetre|centimetres|centimeter|centimeters", 0.01, LEN)
_u("mm|millimetre|millimetres|millimeter|millimeters", 0.001, LEN)
_u("in|inch|inches", 0.0254, LEN)
_u("ft|foot|feet", 0.3048, LEN)
_u("mile|miles", 1609.344, LEN)
_u("m2|m^2|m²|square metre|square metres|square meter|square meters", 1, AREA)
_u("sq ft|square foot|square feet|ft2", 0.09290304, AREA)
_u("m3|m^3|m³|cubic metre|cubic metres", 1, VOL)
_u("l|litre|litres|liter|liters", 1e-3, VOL)
_u("ml|millilitre|millilitres|milliliter|milliliters", 1e-6, VOL)
_u("gallon|gallons|us gallon|us gallons|gal", 3.785411784e-3, VOL)
_u("cfm", 0.3048 ** 3 / 60, FLOW)
_u("kg|kilogram|kilograms", 1, MASS)
_u("n|newton|newtons", 1, D(kg=1, m=1, s=-2))
_u("mpg|miles per gallon", 1609.344 / 3.785411784e-3, D(m=-2))
_u("g|gram|grams", 1e-3, MASS)
_u("lb|lbs|pound|pounds", 0.45359237, MASS)
_u("tonne|tonnes", 1000, MASS)
_u("hz|hertz", 1, FREQ)
_u("khz", 1e3, FREQ)
_u("thz", 1e12, FREQ)
_u("dollar|dollars", 1, MONEY)
_u("cent|cents", 0.01, MONEY)
NUMW = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10,
"twice": 2, "double": 2, "triple": 3, "half": 0.5}
class Q:
"""a typed quantity: SI value, dimension, the text it came from, a role hint, and whether it is a temperature point"""
def __init__(self, v, dim, text="", role="", temp_point=False, src="given"):
self.v, self.dim, self.text, self.role, self.temp_point, self.src = float(v), dim, text, role, temp_point, src
def __repr__(self):
return "Q(%.6g %s %s %s)" % (self.v, self.dim, self.role, self.text[:30])
def unit_lookup(u):
u = u.lower().strip().rstrip(".")
u = re.sub(r"\s+", " ", u)
return UNITS.get(u)
# ---------------------------------------------------------------- reading the question: givens
NUM = r"-?\d[\d,]*(?:\.\d+)?(?:\s*(?:x|×)\s*10\^?\s*-?\d+)?"
def fnum(s):
s = s.replace(",", "").replace("×", "x")
m = re.match(r"(-?[\d.]+)\s*x\s*10\^?\s*(-?\d+)", s)
return float(m.group(1)) * 10 ** int(m.group(2)) if m else float(s)
UNIT_ALT = "|".join(sorted((re.escape(k) for k in UNITS), key=len, reverse=True))
RX_QTY = re.compile(r"(?<![\w.])(%s)\s*[- ]?\s*(%s)(?![a-z])" % (NUM, UNIT_ALT), re.I)
RX_MONEY = re.compile(r"\$\s*(%s)" % NUM)
RX_RANGE = re.compile(r"\bfrom\s+(%s)\s*(%s)?\s+(?:up\s+)?to\s+(%s)\s*(%s)(?![a-z])" % (NUM, UNIT_ALT, NUM, UNIT_ALT), re.I)
RX_PRICE = re.compile(r"(?:\$\s*(%s)|(%s)\s*cents?)\s*(?:per|a|/)\s*(kwh|kilowatt-hour|wh)" % (NUM, NUM), re.I)
RX_TEMP = re.compile(r"(-?\d+(?:\.\d+)?)\s*(?:°\s*|degrees?\s+)?(c|f|celsius|fahrenheit)\b", re.I)
RX_PER_DAY = re.compile(r"(%s)\s*(hours?|minutes?|hrs?|mins?)\s+(?:a|per|each|every)\s+(day|week)" % NUM, re.I)
RX_EVERY_DAY = re.compile(r"(%s)\s*(hours?|minutes?|hrs?|mins?)\s+(?:every|each)\s+day" % NUM, re.I)
RX_DAYS_PER_WEEK = re.compile(r"(%s)\s*days?\s+(?:a|per|each)\s+week" % NUM, re.I)
RX_DAYS_SPAN = re.compile(r"(?:for\s+|a\s+|over\s+)?(%s)[- ]days?(?:\s+month)?" % NUM, re.I)
RX_YEAR = re.compile(r"\b(?:for|over)\s+a\s+year\b", re.I)
RX_RATIO = re.compile(r"\b(twice|double|triple|half|\d+(?:\.\d+)?\s*times)\s+(?:the\s+)?earth'?s\s+(mass|radius)", re.I)
RX_RATIO_UNITS = re.compile(r"\b(\d+(?:\.\d+)?)\s+earth\s+(mass|masses|radius|radii)\b", re.I)
RX_RATIO_ITS = re.compile(r"\b(twice|double|triple|half|\d+(?:\.\d+)?\s*times)\s+(?:the\s+|its\s+)(mass|radius)", re.I)
RX_EMIT = re.compile(r"(?:each|every|per)\s+kwh\s+(?:releases|emits|produces)\s+(%s)\s*(kg|g|grams?|kilograms?)" % NUM, re.I)
RX_EMIT2 = re.compile(r"(%s)\s*(kg|g)\s+(?:of\s+)?co2\s+per\s+kwh" % NUM, re.I)
RX_COEF = re.compile(r"(?:coefficient|expansion)[^.?]*?(%s)\s*(?:per|/)\s*(?:degree|°)\s*c" % NUM, re.I)
RX_SPECHEAT = re.compile(r"specific heat\s*(?:of\s*)?(%s)\s*j\s*/\s*kg" % NUM, re.I)
RX_ACROSS = re.compile(r"(%s)\s*(m|metres?|meters?|ft|feet)\s+(?:across|in diameter|wide)\b" % NUM, re.I)
RX_ROOM = re.compile(r"(%s)\s*(m|ft)?\s*(?:by|x)\s*(%s)\s*(m|ft)?\b(?:[^.?]*?(%s)\s*(m|ft)\s+(?:ceiling|high|tall))?" % (NUM, NUM, NUM), re.I)
RX_ACH = re.compile(r"(%s)\s*(?:air changes per hour|ach)\b" % NUM, re.I)
RX_TALL = re.compile(r"(%s)\s*(m|metres?|meters?|ft|feet|cm)\s+(?:tall|high|deep|long)\b" % NUM, re.I)
MATERIALS = r"water|ice|aluminium|aluminum|copper|iron|steel|glass|lead|gold|silver|concrete|oil|brass|granite"
RX_MATERIAL = re.compile(r"\bkg\s+of\s+(%s)\b" % MATERIALS, re.I)
RX_NIGHTS = re.compile(r"how many\s+(%s)[- ](hours?|minutes?)\s+(\w+)" % NUM, re.I)
TOWARD = re.compile(r"\b(?:toward|towards|approach\w*|coming (?:at|toward)|comes? toward)\b", re.I)
AWAY = re.compile(r"\b(?:away|reced\w*|leaving)\b", re.I)
def read_givens(text):
"""-> list of Q. Consumed spans are masked so one number is read once."""
t = str(text)
used = [False] * len(t)
out = []
def take(m, grp=0):
a, b = m.span(grp)
if any(used[a:b]):
return False
for i in range(a, b):
used[i] = True
return True
# a CHANGE given as a range: "from 0 to 20 mph" -> 20 mph of change (|B - A|, unit of B); temperatures excluded
for m in RX_RANGE.finditer(t):
u = unit_lookup(m.group(4))
if not u or u[1] == TEMP or (m.group(2) and unit_lookup(m.group(2)) != u):
continue
if take(m):
out.append(Q(abs(fnum(m.group(3)) - fnum(m.group(1))) * u[0], u[1], m.group(0), "delta"))
for m in RX_PRICE.finditer(t):
if take(m):
v = fnum(m.group(1)) if m.group(1) else fnum(m.group(2)) / 100
per = UNITS[m.group(3).lower()][0]
out.append(Q(v / per, dmul(MONEY, ENERGY, -1), m.group(0), "price"))
for rx in (RX_EMIT, RX_EMIT2):
for m in rx.finditer(t):
if take(m):
f = UNITS[m.group(2).lower().rstrip("s") if m.group(2).lower() not in UNITS else m.group(2).lower()][0]
out.append(Q(fnum(m.group(1)) * f / 3.6e6, dmul(MASS, ENERGY, -1), m.group(0), "emission"))
for m in RX_COEF.finditer(t):
if take(m, 1):
out.append(Q(fnum(m.group(1)), INV_TEMP, m.group(0), "coefficient"))
for m in RX_SPECHEAT.finditer(t):
if take(m, 1):
out.append(Q(fnum(m.group(1)), D(m=2, s=-2, K=-1), m.group(0), "specific_heat"))
for m in RX_PER_DAY.finditer(t):
if take(m):
dur = fnum(m.group(1)) * UNITS[m.group(2).lower()][0]
span = UNITS[m.group(3).lower()][0]
out.append(Q(dur / span, DIMLESS, m.group(0), "duty"))
for m in RX_DAYS_PER_WEEK.finditer(t):
if take(m):
out.append(Q(fnum(m.group(1)) / 7, DIMLESS, m.group(0), "duty"))
for m in RX_RATIO.finditer(t):
if take(m):
w = m.group(1).lower()
v = NUMW.get(w, None) or fnum(w.split()[0])
out.append(Q(v, DIMLESS, m.group(0), "earth_" + m.group(2).lower()))
for m in RX_RATIO_UNITS.finditer(t):
if take(m):
kind = "mass" if m.group(2).lower().startswith("mass") else "radius"
out.append(Q(fnum(m.group(1)), DIMLESS, m.group(0), "earth_" + kind))
for m in RX_RATIO_ITS.finditer(t):
if take(m):
w = m.group(1).lower()
v = NUMW.get(w, None) or fnum(w.split()[0])
out.append(Q(v, DIMLESS, m.group(0), "earth_" + m.group(2).lower()))
for m in RX_ACH.finditer(t):
if take(m):
out.append(Q(fnum(m.group(1)) / 3600, FREQ, m.group(0), "ach"))
for m in RX_TALL.finditer(t):
if take(m):
f = unit_lookup(m.group(2))[0]
out.append(Q(fnum(m.group(1)) * f, LEN, m.group(0), "height"))
for m in RX_ACROSS.finditer(t):
if take(m):
f = unit_lookup(m.group(2))[0]
out.append(Q(fnum(m.group(1)) * f, LEN, m.group(0), "diameter"))
for m in RX_NIGHTS.finditer(t):
if take(m, 1) and take(m, 2):
out.append(Q(fnum(m.group(1)) * UNITS[m.group(2).lower()][0], TIME, m.group(0), "per_unit_" + m.group(3).lower()))
for m in RX_YEAR.finditer(t):
if take(m):
out.append(Q(365 * 86400, TIME, m.group(0), "span"))
temps = []
for m in RX_TEMP.finditer(t):
a, b = m.span()
if any(used[a:b]):
continue
u = m.group(2).lower()[0]
v = fnum(m.group(1))
k = (v + 273.15) if u == "c" else ((v - 32) * 5 / 9 + 273.15)
for i in range(a, b):
used[i] = True
temps.append(Q(k, TEMP, m.group(0), "temp", temp_point=True))
out.extend(temps)
for m in RX_MONEY.finditer(t):
if take(m):
out.append(Q(fnum(m.group(1)), MONEY, m.group(0), "money"))
for m in RX_QTY.finditer(t):
a, b = m.span()
if any(used[a:b]):
continue
u = unit_lookup(m.group(2))
if not u:
continue
for i in range(a, b):
used[i] = True
out.append(Q(fnum(m.group(1)) * u[0], u[1], m.group(0), ""))
for m in RX_DAYS_SPAN.finditer(t):
a, b = m.span(1)
if any(used[a:b]):
continue
for i in range(m.start(), m.end()):
used[i] = True
out.append(Q(fnum(m.group(1)) * 86400, TIME, m.group(0), "span"))
# direction of motion (a flag, not a number)
flags = {"toward": bool(TOWARD.search(t)), "away": bool(AWAY.search(t))}
mm = RX_MATERIAL.search(t)
flags["material"] = mm.group(1).lower().replace("aluminum", "aluminium") if mm else ""
flags["gasoline"] = bool(re.search(r"\b(?:gasoline|petrol|gas)\b|\bmpg\b|miles per gallon", t, re.I))
flags["melt"] = bool(re.search(r"\bmelt\w*\b", t, re.I)) and bool(re.search(r"\bice\b", t, re.I))
# v1.1: every number in the question must have been read into a given. A digit left over (a percentage, a count
# the reader has no unit for) means the network did not understand the question - it must not answer it.
# digits glued to a letter or caret belong to a unit or formula name ("m/s^2", "m2", "CO2", "MgSO4", "PM2.5"), not a quantity
unread = [m.group(0) for m in re.finditer(r"(?<![A-Za-z^\d.,])\d+(?:[.,]\d+)*", t) if not all(used[m.start():m.end()])]
flags["unread_numbers"] = unread
return out, flags
# ---------------------------------------------------------------- reading the question: goal
GOALS = [
(r"\bis (?:that|it|this) (?:compliant|safe|okay|ok)\b.*\bcold[- ]holding\b|\bcold[- ]holding\b.*\bis (?:that|it)\b", ("bool", "cold_hold")),
(r"\bhow many\s+(?:kilowatt-hours|kwh)\b|\bin kwh\b|\bkilowatt-hours of\b", ("dim", ENERGY, "kWh", 3.6e6)),
(r"\bhow many\s+kilojoules\b|\bin kilojoules\b|\bin kj\b", ("dim", ENERGY, "kJ", 1000)),
(r"\bin horsepower\b|\bhow many horsepower\b", ("dim", POWER, "hp", 745.69987)),
(r"\bwhat (?:does|do|would|will)\b.*\bcost\b|\bcost (?:in dollars|how much)\b|\bhow much does .* cost\b", ("dim", MONEY, "$", 1)),
(r"\bwhat frequency\b|\bwhat pitch\b", ("dim", FREQ, "Hz", 1)),
(r"\bhow many seconds\b|\bhow long\b.*\bfall\b", ("dim", TIME, "s", 1)),
(r"\bacceleration\b", ("dim", ACC, "m/s²", 1)),
(r"\bhow much (?:does|would|will) .* weigh\b|\bwhat (?:does|would|will) .* weigh\b", ("dim", D(kg=1, m=1, s=-2), "N", 1)),
(r"\bhow many litres\b|\bhow many liters\b|\bin litres\b", ("dim", VOL, "L", 1e-3)),
(r"\bhow many (?:us )?gallons\b", ("dim", VOL, "US gallons", 3.785411784e-3)),
(r"\bhow many kilograms\b|\bhow many kg\b|\bin kilograms\b", ("dim", MASS, "kg", 1)),
(r"\bhow many millimetres\b|\bhow many millimeters\b|\bin mm\b", ("dim", LEN, "mm", 1e-3)),
(r"\bhow many cfm\b|\bcfm of airflow\b", ("dim", FLOW, "CFM", 0.3048 ** 3 / 60)),
]
RX_GOAL_UNIT = re.compile(r"\b(?:how many|in|into|as|to)\s+(?:us\s+)?(%s)(?![a-z])" % UNIT_ALT, re.I)
RX_COLD_BOOL = re.compile(r"\bcold[- ]holding\b", re.I)
RX_BOOL_ASK = re.compile(r"\b(?:is|are)\b[^?]*\b(?:compliant|safe|okay|ok|acceptable|allowed|within)\b|\b(?:compliant|safe|okay|acceptable)\b[^?]*\?", re.I)
RX_MONEY_ASK = re.compile(r"\b(?:cost|costs|bill|spend|pay)\b", re.I)
def read_goal(text):
t = str(text).lower()
q = [s for s in re.split(r"(?<=[.?!])\s+", t.strip()) if s]
ask = q[-1] if q else t
m = RX_NIGHTS.search(text)
if m:
return ("count", m.group(3).lower())
if RX_COLD_BOOL.search(t) and RX_BOOL_ASK.search(t):
return ("bool", "cold_hold")
# an explicit unit asked for: "how many kWh", "in horsepower", "into kWh", "in m/s^2", "how many hours"
m = RX_GOAL_UNIT.search(ask)
if m:
u = unit_lookup(m.group(1))
if u:
return ("dim", u[1], m.group(1), u[0])
for rx, g in GOALS:
if g[0] != "bool" and re.search(rx, ask):
return g
if RX_MONEY_ASK.search(ask) and re.search(r"\b(?:what|how much|what's)\b", ask):
return ("dim", MONEY, "$", 1)
return None
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, "fifteen": 15, "twenty": 20, "thirty": 30}
RX_WORDNUM = re.compile(r"\b(%s)\b(?=\s+(?:hours?|hrs?|minutes?|mins?|days?|weeks?|years?|seconds?|nights?)\b)" % "|".join(WORDNUM), re.I)
def normalise(text):
"""number words before a unit of time become digits ("for two weeks" -> "for 2 weeks")"""
return RX_WORDNUM.sub(lambda m: str(WORDNUM[m.group(1).lower()]), str(text))
# ---------------------------------------------------------------- nodes
class Registry:
"""byte IDs: specialists 0..N-1 in the standing order; CORE_MATH 0xFE"""
CORE_MATH = 0xFE
def __init__(self, standing, spec_root, combo_code):
sys.path.insert(0, combo_code)
from combo_runtime_v1 import _Organ # noqa: E402
self.ids = []
for s in standing:
for m in s.split("+"):
self.ids.append(m)
self.byte = {sid: i for i, sid in enumerate(self.ids)}
self._organ_cls, self.root, self._organs = _Organ, spec_root, {}
def organ(self, sid):
if sid not in self._organs:
d = os.path.join(self.root, sid)
self._organs[sid] = self._organ_cls(os.path.join(d, "manifest.json"), d)
return self._organs[sid]
def ask(self, sid, text):
r = self.organ(sid).reply(text, "network")
return r
def g(v):
"""format a number for a node's phrasing"""
return ("%.6g" % v) if abs(v) >= 1e-4 else ("%.4e" % v)
RX_ANS = re.compile(r"(-?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?)\s*(?:×\s*10\^?(-?\d+))?", re.I)
def parse_value(resp, unit_rx):
"""first number in the reply directly followed by the expected unit"""
for m in re.finditer(r"(-?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?)\s*(%s)" % unit_rx, resp or "", re.I):
try:
return float(m.group(1).replace(",", ""))
except ValueError:
continue
return None
class Op:
"""a typed domain operation executed by a specialist node through its own proven phrasing"""
def __init__(self, name, sid, slots, out_dim, render, out_unit_rx, out_factor, check=None, role_out=""):
self.name, self.sid, self.slots, self.out_dim = name, sid, slots, out_dim
self.render, self.out_unit_rx, self.out_factor, self.check, self.role_out = render, out_unit_rx, out_factor, check, role_out
def _k_to_f(k):
return (k - 273.15) * 9 / 5 + 32
def ops_for(reg):
"""the typed adapters. slots: list of (dim, role-predicate). render(args, flags) -> question text or None."""
has = reg.byte.__contains__
O = []
if has("acoustics"):
O.append(Op("doppler", "acoustics", [(FREQ, lambda q: q.role == ""), (VEL, lambda q: True)], FREQ,
lambda a, f: ("A siren of %s Hz is moving %s you at %s m/s. What frequency do you hear?" %
(g(a[0].v), "toward" if f["toward"] and not f["away"] else "away from" if f["away"] and not f["toward"] else None, g(a[1].v)))
if (f["toward"] != f["away"]) else None,
r"Hz", 1))
phys = "physics-r3" if has("physics-r3") else "physics-r2"
if has(phys):
O.append(Op("kinetic_energy", phys, [(MASS, lambda q: True), (VEL, lambda q: True)], ENERGY,
lambda a, f: "What is the kinetic energy of a %s kg ball moving at %s m/s?" % (g(a[0].v), g(a[1].v)),
r"J\b|joules?", 1, role_out="kinetic"))
O.append(Op("potential_energy", phys, [(MASS, lambda q: True), (LEN, lambda q: q.role == "")], ENERGY,
lambda a, f: "What is the potential energy of a %s kg box lifted %s m?" % (g(a[0].v), g(a[1].v)),
r"J\b|joules?", 1, role_out="potential"))
if has("planetary"):
def _grav(a, f):
m = [q for q in a if q.role == "earth_mass"]
r = [q for q in a if q.role == "earth_radius"]
return ("What is the surface gravity on a planet with %s times Earth's mass and %s times Earth's radius?" % (g(m[0].v), g(r[0].v))) if m and r else None
O.append(Op("surface_gravity", "planetary", [(DIMLESS, lambda q: q.role == "earth_mass"), (DIMLESS, lambda q: q.role == "earth_radius")],
ACC, _grav, r"m/s²|m/s\^?2", 1, role_out="gravity"))
if has("coldchain-v2"):
O.append(Op("cold_hold", "coldchain-v2", [(TEMP, lambda q: q.temp_point)], "bool",
lambda a, f: "Our walk-in cooler holds %s F. Is that okay for cold holding?" % g(round(_k_to_f(a[0].v), 1)),
None, None))
if has("geometry-v4"):
O.append(Op("circle_area", "geometry-v4", [(LEN, lambda q: q.role == "diameter")], AREA,
lambda a, f: "Calculate the area of a circle of radius %s." % g(a[0].v / 2),
r"", 1, role_out="area"))
O.append(Op("cylinder_volume", "geometry-v4", [(LEN, lambda q: q.role == "diameter"), (LEN, lambda q: q.role == "height")], VOL,
lambda a, f: "Determine the volume of a cylinder with radius %s and height %s." % (g(a[0].v / 2), g(a[1].v)),
r"", 1, role_out="volume"))
if has("thermo"):
def _heat(a, f):
if not f.get("material") or f["material"] == "ice" or a[2].v <= a[1].v:
return None
return "How much heat is needed to raise %s kg of %s from %s C to %s C?" % (
g(a[0].v), f["material"], g(round(a[1].v - 273.15, 4)), g(round(a[2].v - 273.15, 4)))
O.append(Op("sensible_heat", "thermo", [(MASS, lambda q: True), (TEMP, lambda q: q.temp_point), (TEMP, lambda q: q.temp_point)],
ENERGY, _heat, r"J\b", 1, role_out="heat"))
O.append(Op("melt_ice", "thermo", [(MASS, lambda q: True)], ENERGY,
lambda a, f: ("How much energy does it take to melt %s kg of ice?" % g(a[0].v)) if f.get("melt") else None,
r"J\b", 1, role_out="heat"))
if has("carboncapture"):
O.append(Op("fuel_co2", "carboncapture", [(VOL, lambda q: True)], MASS,
lambda a, f: ("How much CO2 is emitted by burning %s gallons of gasoline?" % g(a[0].v / 3.785411784e-3)) if f.get("gasoline") else None,
r"kg\b", 1, role_out="co2"))
if has("planetary"):
O.append(Op("planet_weight", "planetary", [(MASS, lambda q: True), (DIMLESS, lambda q: q.role == "earth_mass"),
(DIMLESS, lambda q: q.role == "earth_radius")], D(kg=1, m=1, s=-2),
lambda a, f: "How much would an %s kg astronaut weigh on a planet with %s Earth masses and %s Earth radii?" % (
g(a[0].v), g(a[1].v), g(a[2].v)),
r"N\b", 1, role_out="weight"))
return O
# ---------------------------------------------------------------- checks (generic physical validity - not item-specific)
def valid_given(q):
if q.role == "duty" and not (0 < q.v <= 1):
return "a duty of %s is more than the whole day" % q.text
if q.dim in (TIME, MASS, LEN, AREA, VOL, CURR, CHARGE, FREQ, FLOW) and q.v <= 0 and not q.temp_point:
return "%s is not a physical amount" % q.text
if q.dim == POWER and q.v <= 0:
return "%s is not a physical power" % q.text
if q.v <= 0 and q.dim not in (DIMLESS, TEMP, MONEY) and not q.temp_point and q.role != "delta":
return "%s is not a physical amount" % q.text
if q.role in ("earth_mass", "earth_radius") and q.v <= 0:
return "%s is not a physical body" % q.text
return None
# ---------------------------------------------------------------- core math: exponents over the remaining quantities
def core_math(qs, goal_dim):
"""find exponents e_i in {+1,-1} (every quantity used exactly once) with prod q_i^e_i of dimension goal_dim.
Temperature points are first reduced to their difference (two points -> one delta). Returns (value, formula) or None."""
qs = list(qs)
pts = [q for q in qs if q.temp_point]
if len(pts) == 2:
qs = [q for q in qs if not q.temp_point] + [Q(abs(pts[1].v - pts[0].v), TEMP, "Δ(%s→%s)" % (pts[0].text, pts[1].text), "delta")]
elif pts:
return None
n = len(qs)
if n == 0 or n > 7:
return None
sols = []
for signs in itertools.product((1, -1), repeat=n):
dim = DIMLESS
for q, e in zip(qs, signs):
dim = dmul(dim, q.dim, e)
if dim == goal_dim:
sols.append(signs)
if not sols:
return None
# prefer the solution with the most +1 exponents (a product before a ratio); ambiguity with EQUAL counts -> decline
best = max(sum(s) for s in sols)
top = [s for s in sols if sum(s) == best]
if len(top) > 1:
vals = {round(math.prod(q.v ** e for q, e in zip(qs, s)), 9) for s in top}
if len(vals) > 1:
return None
s = top[0]
val = math.prod(q.v ** e for q, e in zip(qs, s))
formula = " × ".join(("%s" if e > 0 else "1/(%s)") % q.text for q, e in zip(qs, s))
return val, formula
# ---------------------------------------------------------------- the network
class Network:
def __init__(self, standing, spec_root, combo_code, memory_path=None):
self.reg = Registry(standing, spec_root, combo_code)
self.ops = ops_for(self.reg)
self.memory_path = memory_path
self.memory = {}
try: # v1.2: the HRR path memory (partial-cue recall) when numpy is available; JSON exact-shape memory always
sys.path.insert(0, HERE)
from path_hrr_v1 import PathHRR # noqa: E402
self.hrr = PathHRR()
except Exception: # noqa: BLE001
self.hrr = None
self.hrr_stats = {"exact": 0, "hrr_recalled": 0, "hrr_recalled_and_used": 0}
if memory_path and os.path.exists(memory_path):
try:
self.memory = json.load(open(memory_path))
except (OSError, ValueError):
self.memory = {}
# a question SHAPE: what is asked + the kinds of givens (not their values)
@staticmethod
def shape(goal, givens, flags):
gs = sorted("%s:%s" % (q.role or "-", q.dim) for q in givens)
return json.dumps([str(goal[:2] if goal else None), gs, sorted(k for k, v in flags.items() if v)])
def _run_op(self, op, args, flags, trace):
text = op.render(args, flags)
if not text:
return None
r = self.reg.ask(op.sid, text)
if not r or r.get("declined"):
trace.append({"node": op.sid, "byte": self.reg.byte[op.sid], "op": op.name, "asked": text, "declined": True,
"reply": (r or {}).get("response")})
return "declined"
if op.out_dim == "bool":
v = r["response"].strip().lower()
ans = True if re.match(r"^\W*yes\b", v) else False if re.match(r"^\W*no\b", v) else None
trace.append({"node": op.sid, "byte": self.reg.byte[op.sid], "op": op.name, "asked": text, "reply": r["response"]})
return ("bool", ans, r["response"]) if ans is not None else None
val = parse_value(r["response"], op.out_unit_rx) if op.out_unit_rx else None
if val is None and op.out_unit_rx == "":
m = RX_ANS.search(r["response"])
val = float(m.group(1).replace(",", "")) if m else None
trace.append({"node": op.sid, "byte": self.reg.byte[op.sid], "op": op.name, "asked": text, "reply": r["response"], "value": val})
if val is None or not math.isfinite(val):
return None
return Q(val * op.out_factor, op.out_dim, "%s(%s)" % (op.name, ", ".join(a.text for a in args)), op.role_out, src=op.sid)
@staticmethod
def _spec_indices(spec):
return set(spec[1]) if isinstance(spec, tuple) else {spec}
def _slot_fillers(self, givens, dim, pred):
"""a slot is filled by ONE given of its dimension, or (v2) DERIVED by core math from TWO givens"""
out = [i for i, q in enumerate(givens) if q.dim == dim and pred(q)]
for i, j in itertools.combinations(range(len(givens)), 2):
if givens[i].temp_point or givens[j].temp_point:
continue
cm = core_math([givens[i], givens[j]], dim)
if cm and pred(Q(cm[0], dim, "derived", "")):
out.append(("d", (i, j)))
return out
def _plans(self, givens, goal):
"""candidate plans: [] (core math only), then 1 op (slots from givens or derived pairs), then 2 ops (givens only).
Each = list of (op, arg-specs); a spec is a given index or ("d", (i, j)) for a core-math-derived input."""
yield []
idx = range(len(givens))
for op in self.ops:
fill = [self._slot_fillers(givens, d, pred) for d, pred in op.slots]
temp_slots = [k for k, (d, _p) in enumerate(op.slots) if d == TEMP]
for combo in itertools.product(*fill):
# two temperatures keep the question's from -> to order (never swapped into a different process)
if len(temp_slots) >= 2 and any(not isinstance(combo[a], int) or not isinstance(combo[b], int) or combo[a] > combo[b]
for a, b in zip(temp_slots, temp_slots[1:])):
continue
seen = set()
ok = True
for sp in combo:
ix = self._spec_indices(sp)
if seen & ix:
ok = False
break
seen |= ix
if ok:
yield [(op, combo)]
for op1 in self.ops:
for c1 in itertools.permutations(idx, len(op1.slots)):
if not all(givens[i].dim == d and pred(givens[i]) for i, (d, pred) in zip(c1, op1.slots)):
continue
for op2 in self.ops:
if op2 is op1:
continue
rest = [i for i in idx if i not in c1]
for c2 in itertools.permutations(rest, len(op2.slots)):
if all(givens[i].dim == d and pred(givens[i]) for i, (d, pred) in zip(c2, op2.slots)):
yield [(op1, c1), (op2, c2)]
def solve(self, text):
text = normalise(text)
givens, flags = read_givens(text)
goal = read_goal(text)
base = {"question": text, "givens": [repr(q) for q in givens], "goal": str(goal)}
if goal is None:
return dict(base, status="declined", reason="no answerable goal in the question")
if not givens:
return dict(base, status="declined", reason="no quantities to work from")
for q in givens:
bad = valid_given(q)
if bad:
return dict(base, status="declined", reason=bad, check="validity")
if flags.get("unread_numbers"):
return dict(base, status="declined", reason="numbers I could not read: %s" % ", ".join(flags["unread_numbers"][:4]),
check="all numbers read")
flags = {k: v for k, v in flags.items() if k != "unread_numbers"}
self._last_tokens = self._shape_tokens(goal, givens, flags)
shape = self.shape(goal, givens, flags)
remembered = self.memory.get(shape)
plans = list(self._plans(givens, goal))
self._hrr_pref = None
if remembered:
self.hrr_stats["exact"] += 1
plans.sort(key=lambda p: [o.name for o, _ in p] != remembered["ops"])
elif self.hrr is not None:
codes, res = self.hrr.recall(self._shape_tokens(goal, givens, flags))
if codes:
names = [self.ops[c].name for c in codes if c < len(self.ops)]
self.hrr_stats["hrr_recalled"] += 1
self._hrr_pref = names
plans.sort(key=lambda p: [o.name for o, _ in p] != names)
for plan in plans:
trace, pool, used, ok = [], list(givens), set(), True
final_bool = None
for op, combo in plan:
args = []
for sp, (d, _pred) in zip(combo, op.slots):
if isinstance(sp, tuple): # v2: core math first, its result feeds the specialist
cm = core_math([givens[i] for i in sp[1]], d)
if not cm:
ok = False
break
trace.append({"node": "core_math", "byte": Registry.CORE_MATH, "op": "derive", "formula": cm[1], "value": cm[0]})
args.append(Q(cm[0], d, "(%s)" % cm[1], "derived"))
else:
args.append(givens[sp])
if not ok:
break
res = self._run_op(op, args, flags, trace)
if res is None or res == "declined":
ok = False
break
for sp in combo:
used |= self._spec_indices(sp)
if isinstance(res, tuple) and res[0] == "bool":
final_bool = res
else:
pool.append(res)
if not ok:
continue
rest = [q for i, q in enumerate(givens) if i not in used] + pool[len(givens):]
if goal[0] == "bool":
if final_bool is None or rest:
continue
return self._done(base, shape, plan, trace, "yes" if final_bool[1] else "no", final_bool[2], goal, remembered)
if goal[0] == "count":
per = [q for q in rest if q.role.startswith("per_unit_")]
if len(per) != 1:
continue
others = [q for q in rest if q is not per[0]]
cm = core_math(others, TIME)
if not cm:
continue
n = cm[0] / per[0].v
trace.append({"node": "core_math", "byte": Registry.CORE_MATH, "op": "count", "formula": "(%s) / %s" % (cm[1], per[0].text), "value": n})
return self._done(base, shape, plan, trace, "%s" % g(n), "That is %s %s." % (g(round(n, 4)), goal[1]), goal, remembered)
cm = core_math(rest, goal[1])
if not cm:
continue
val = cm[0] / goal[3]
if not math.isfinite(val) or val < 0:
continue
if not plan and len(givens) == 1:
# v1.1: a single given converted to another unit is not a multi-step problem - the core answers those
return dict(base, status="declined", reason="single conversion (the core's own operator)", check="multi-step only")
if not plan and any(abs(cm[0] - q.v) <= 1e-9 * max(1.0, abs(q.v)) and q.dim == goal[1] for q in givens):
# v1.1: the 'answer' is a given handed back unchanged - an echo, never an answer
continue
trace.append({"node": "core_math", "byte": Registry.CORE_MATH, "op": "dimensional", "formula": cm[1], "value": val, "unit": goal[2]})
unit = goal[2]
say = ("$%.2f" % val) if unit == "$" else "%s %s" % (g(round(val, 6)), unit)
return self._done(base, shape, plan, trace, say, "The answer is %s." % say, goal, remembered)
return dict(base, status="declined", reason="no checked path from the givens to what is asked")
@staticmethod
def _shape_tokens(goal, givens, flags):
toks = ["goal:%s" % (goal[:2] if goal else None,)]
toks += ["given:%s:%s" % (q.role or "-", q.dim) for q in givens]
toks += ["flag:%s" % k for k, v in flags.items() if v and k != "unread_numbers"]
return toks
def _done(self, base, shape, plan, trace, answer, sentence, goal, remembered):
path = [t["byte"] for t in trace] # every hop in order, core-math derivations included
entry = {"ops": [o.name for o, _ in plan], "path": path, "hits": (remembered or {}).get("hits", 0) + 1}
if getattr(self, "_hrr_pref", None) is not None and entry["ops"] == self._hrr_pref:
self.hrr_stats["hrr_recalled_and_used"] += 1
if self.hrr is not None and not remembered:
codes = [self.ops.index(o) for o, _ in plan] + ([0xFE] if goal[0] != "bool" else [])
self.hrr.store(self._last_tokens, codes)
self.memory[shape] = entry
if self.memory_path:
json.dump(self.memory, open(self.memory_path, "w"), indent=1)
nodes = [t["node"] for t in trace]
return dict(base, status="answered", answer=answer, response="%s (path: %s)" % (sentence, " → ".join(nodes)),
path_bytes=bytes(path).hex(), trace=trace, reused_path=bool(remembered))
if __name__ == "__main__":
net = Network(open(sys.argv[1]).read().split(), sys.argv[2], sys.argv[3])
for q in sys.argv[4:]:
print(json.dumps(net.solve(q), indent=1, ensure_ascii=False)[:1500])1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980#!/usr/bin/env python3"""path_hrr_v1 - the network's PATH MEMORY in the substrate's own algebra (phase 4, HRR form).
Codebook (same construction as the recall index and phase0_baseline_v1): osub_seed = sha256-seeded unit phasors, D=1024. op key K[c] = osub_seed("o7op:%d" % c) - one key per op code c (0..255; 0xFE = core math) role R[p] = osub_seed("o7pos:%d" % p) - one role per path position PATH = sum_p bind(K[c_p], R[p]) - a whole path is ONE vector (validated: 4-hop recovery 100% at D=1024) SHAPE = superpose of osub_seed(token) over the question's shape tokens (goal signature + given signatures)store(shape, path): keeps (SHAPE, PATH, length). recall(shape): the stored entry whose SHAPE resonates most with thequery's (partial cue - a new question whose shape overlaps a stored one retrieves that path), then unbind each positionand clean up against the op codebook. Retrieval only ORDERS the plans the network tries; every answer still has to passevery check, so memory can never make an answer wrong, only find a proven path first."""from __future__ import annotations
import hashlib
import numpy as np
D = 1024
def osub_seed(text: str, dim: int = D) -> np.ndarray: h = int(hashlib.sha256(text.lower().strip().encode()).hexdigest(), 16) rng = np.random.RandomState(h % (2 ** 31)) return np.exp(1j * rng.uniform(0, 2 * np.pi, dim)).astype(np.complex64)
def bind(a, b): return np.fft.ifft(np.fft.fft(a) * np.fft.fft(b)).astype(np.complex64)
def unbind(c, b): return np.fft.ifft(np.fft.fft(c) * np.conj(np.fft.fft(b))).astype(np.complex64)
class PathHRR: def __init__(self, n_codes: int = 256, max_len: int = 8): self.K = np.stack([osub_seed("o7op:%d" % c) for c in range(n_codes)]) self.R = [osub_seed("o7pos:%d" % p) for p in range(max_len)] self.entries: list[tuple[np.ndarray, np.ndarray, int]] = []
def shape_vec(self, tokens): vs = [osub_seed("o7shape:" + t) for t in tokens] if not vs: return None v = np.mean(np.stack(vs), axis=0) return (v / np.maximum(np.abs(v), 1e-8)).astype(np.complex64)
def path_vec(self, codes): return np.sum([bind(self.K[c], self.R[p]) for p, c in enumerate(codes)], axis=0).astype(np.complex64)
def decode(self, vec, length): out = [] for p in range(length): est = unbind(vec, self.R[p]) sims = np.real(self.K.conj() @ est) / D out.append(int(np.argmax(sims))) return out
def store(self, tokens, codes): sv = self.shape_vec(tokens) if sv is None or not codes: return self.entries.append((sv, self.path_vec(codes), len(codes)))
def recall(self, tokens, min_resonance: float = 0.35): """-> (codes, resonance) of the most resonant stored shape, or (None, best) below the threshold""" sv = self.shape_vec(tokens) if sv is None or not self.entries: return None, 0.0 best, arg = -1.0, None for i, (s, _, _) in enumerate(self.entries): r = float(np.real(np.vdot(s, sv)) / D) if r > best: best, arg = r, i if best < min_resonance: return None, best _, pv, n = self.entries[arg] return self.decode(pv, n), best123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363"""Connect the existing turn grammar to work, and word work from its receipts.
The original turn accompanies every changed reading. A request envelope may be
removed; its payload stays exact. Spelling is suggested only for a named hole.
No reply here adds a fact beyond the project's saved shape or execution receipt.
"""
import re
import sys
from pathlib import Path
def _grammar():
# In the installed pack this module is in workbench/converse, whose path is
# set by Converse. The development overlay supplies release115 on sys.path.
try:
from turn_reader import REQUEST, WH, AUX
return REQUEST, WH, AUX
except ImportError:
local = Path(__file__).resolve().parent / "converse"
if (local / "turn_reader.py").is_file() and str(local) not in sys.path:
sys.path.insert(0, str(local))
return _grammar()
return None, (), ()
_ENVELOPE = re.compile(
r"\s*(?:(?:ok(?:ay)?|well|so|now)[,\s]+)*"
r"(?:(?:can|could|would|will)\s+(?:you|we|u)(?:\s+please)?(?:\s+just)?|"
r"please|let'?s|lets|let us|(?:we|i)\s+(?:need|want)(?:\s+to)?|"
r"need\s+to|make\s+sure(?:\s+that)?|go\s+ahead\s+and|"
r"i'?d\s+like(?:\s+you)?(?:\s+to)?)\s+", re.I)
_CORRECTION = re.compile(
r"^\s*(?:(?:sorry|no|oh|wait)[,\s]+)*(?:i\s+meant|i\s+mean)\s+(.+)$", re.I | re.S)
def code_context(text, native, env, turn=None):
"""Read local-code discussion through the same source and receipt boundary."""
local = str(Path(__file__).resolve().parent / "converse")
if local not in sys.path:
sys.path.insert(0, local)
import code_discussion
return code_discussion.handle(text, native, env, turn)
def request_reading(text, active_project=False, active_work=False):
"""A conservative reading using the native request grammar, with evidence.
The native REQUEST searches within a turn; the envelope check requires its
complete prefix to be a request marker, so quoted requests and questions
about a request do not turn into actions.
"""
original = str(text or "")
payload = original
steps = []
request, _wh, _aux = _grammar()
if request is not None:
found = request.match(payload)
if found and _ENVELOPE.fullmatch(payload[:found.start(1)]):
body = payload[found.start(1):found.end(1)]
prefix = payload[:found.start(1)]
# "I need a program that ..." receives a desired object. Removing
# "I need" leaves a noun fragment, not an equivalent imperative.
nominal = bool(re.search(r"\b(?:need|want|like)\b", prefix, re.I) and
re.match(r"\s*(?:a|an|the|some|my|our)\b", body, re.I))
if body and not nominal:
steps.append({"part": "turn_reader.REQUEST", "prefix": payload[:found.start(1)],
"body_start": found.start(1), "body_end": found.end(1)})
payload = body
if active_project or active_work:
correction = _CORRECTION.match(payload)
if correction:
body = payload[correction.start(1):correction.end(1)]
# C15: the revision marker is added only when the correction does not already carry one ("I meant it above
# 10 instead" stays as said; it was read as "instead it above 10 instead")
mark = "" if re.search(r"(?i)\b(?:instead|rather|change|changed|update|revise)\b", body) else "instead "
steps.append({"part": "work.REVISE" if active_work else "project.REVISE", "prefix": payload[:correction.start(1)],
"replacement": mark, "body_start": correction.start(1),
"body_end": correction.end(1)})
payload = mark + body
return {"original": original, "reading": payload, "steps": steps}
def asks_about(text):
"""A question/account is not an instruction to revise the active project."""
reading = request_reading(text)
if reading["steps"]:
return asks_about(reading["reading"])
_request, wh, aux = _grammar()
words = re.findall(r"[A-Za-z]+(?:'[A-Za-z]+)?", str(text or "").lower())
while words and words[0] in {"okay", "ok", "so", "well", "now", "and", "hey"}:
words.pop(0)
if len(words) > 1 and words[0] in {"do", "does", "did"} and words[1] == "not":
return False
if words and words[0] in set(wh) | set(aux):
return True
return bool(re.match(r"^\s*(?:explain|describe|tell me about|tell me why|tell me how)\b", str(text or ""), re.I))
_STATE_QUESTIONS = (
("holes", re.compile(r"(?:what(?:'s| is) (?:still )?(?:missing|left|needed|blocking(?: it| this project)?)|"
r"what (?:else |still )?(?:needs to be done|remains)|"
r"why (?:is|was) (?:it|this project|the project) (?:blocked|stuck|unfinished)|"
r"why (?:can't|cannot|didn't|did not) (?:it|this project|the project) (?:finish|complete))", re.I)),
("inputs", re.compile(r"(?:what (?:are|were) (?:the |its )?(?:inputs|sources)(?: (?:for|of) (?:this |the )?project)?|"
r"(?:what|which) (?:files|tables|sources|inputs) (?:does|did|will) (?:it|this project|the project) (?:read|use)|"
r"(?:show|tell) me (?:the |its )?(?:inputs|sources)(?: (?:for|of) (?:this |the )?project)?)", re.I)),
)
def _files(source):
if not isinstance(source, dict):
return []
if source.get("op") == "read":
return [source["file"]] if source.get("file") else []
children = source.get("inputs", ()) if source.get("op") == "union" else (source.get("left"), source.get("right"))
return list(dict.fromkeys(f for child in children for f in _files(child)))
# C15: a question about the project is read by what it refers to and what it asks about, not by a fixed list of phrasings.
# Each aspect is a part of the saved record; a question naming none of them, or not referring to the project, is not taken.
_ASPECTS = (
("holes", r"missing|left|needs?|needed|blocking|blocked|stuck|unfinished|waiting|holes?|gaps?"),
("inputs", r"sources?|inputs?|tables?|reads?|combines?|combined|joins?|joined|stack(?:s|ed)?|lookups?|look up|merges?|"
r"merged|come from|data"),
("outputs", r"outputs?|writes?|written|produces?|produced|makes?|saves?|saved|result files?|creates?"),
("status", r"done|finished|built|work(?:s|ing|ed)?|pass(?:ed|es)?|status|state|succeed(?:ed)?|complete(?:d)?|ready"),
("requirements", r"requirements?|obligations?|asked for|supposed to do|what (?:does|will) it do"),
("history", r"tried|attempts?|history|changes?|changed|corrections?|revisions?|so far"),
)
_REFERS = r"\b(?:project|it|its|it's|this|that|the build|the program|the job)\b"
def _aspect(q, shape):
# Quoted examples (including JSON keys/values) are data, not the aspect
# being asked about. A key named "state" must not turn an explanation of
# an example into a status report about an unrelated active project.
low = re.sub(r'"(?:\\.|[^"\\\n])*"|(?<!\w)\'(?:\\.|[^\'\\\n])*\'(?!\w)', ' ', q.lower())
if "`" in q or re.match(r"(?:build|make|create|write|set up|add|also|save|export|keep|serve|print|change|drop|use|"
r"actually|instead|no,)\b", low):
return None # a request to do something, however it is phrased, is not a question
names = {str(shape.get("module") or "")} | {str(e) for e in (shape.get("entries") or {})}
names |= {f for src in (shape.get("sources") or {}).values() for f in _files(src)}
refers = re.search(_REFERS, low) or any(n and n.lower() in low for n in names)
if not refers or re.search(r"\b(?:you|yourself|oracle7)\b", low) and not re.search(r"\b(?:project|it|its)\b", low):
return None
return next((kind for kind, words in _ASPECTS if re.search(r"\b(?:%s)\b" % words, low)), None)
def _describe(source):
"""a source graph in words: what is read, and how tables are joined, stacked or looked up"""
if not isinstance(source, dict):
return "nothing resolved yet"
op = source.get("op")
if op == "read":
return "`%s`" % source.get("file")
if op == "union":
return "the rows of %s stacked together" % " and ".join(_describe(x) for x in source.get("inputs") or ())
keys = " and ".join("%s = %s" % tuple(k) if k[0] != k[1] else k[0] for k in source.get("keys") or ())
if op == "lookup":
return "%s, each row looking up %s by %s" % (_describe(source.get("left")), _describe(source.get("right")), keys or "?")
return "%s joined with %s on %s (%s join%s)" % (
_describe(source.get("left")), _describe(source.get("right")), keys or "?", source.get("how") or "inner",
": every row of the first kept" if source.get("how") == "left" else ": only rows that match")
def project_answer(text, shape):
"""Word a project-state question from the kept record only."""
if not shape:
return None
q = request_reading(text)["reading"].strip().rstrip("?.! ")
kind = next((name for name, pattern in _STATE_QUESTIONS if pattern.fullmatch(q)), None)
if kind is None and (asks_about(text) or str(text).strip().endswith("?")):
kind = _aspect(q, shape)
if kind is None:
return None
if kind in ("outputs", "status", "requirements", "history"):
return _record_answer(kind, shape)
module = shape.get("module") or "the unnamed project"
state = shape.get("status") or "not recorded"
lines = ["The last recorded state of `%s` is %s." % (module, state)]
basis = ["project.status", "project.module"]
if kind == "holes":
holes = [h.get("text", "") for h in shape.get("holes_kept", ()) if h.get("text")]
last = (shape.get("last_reply") or {}).get("execution") or {}
if not holes:
holes = [str(h) for h in last.get("holes", ())]
if holes:
lines.append("To continue, I need:\n" + "\n".join("- " + h for h in holes))
basis.append("project.holes_kept/last_reply.execution.holes")
else:
pending = [r["id"] for r in last.get("requirements", ()) if r.get("status") not in ("passed", "superseded", "excluded")]
if pending:
lines.append("The last attempt left these requirements unresolved: %s." % ", ".join(pending))
elif state == "built" and last.get("state") == "changed-checked":
lines.append("The saved receipt says every requirement passed.")
else:
lines.append("The saved record names no remaining hole; that alone does not establish completion.")
basis.append("project.last_reply.execution")
else:
sources = shape.get("sources") or {}
named = [(entry, _files(source)) for entry, source in sources.items()]
named = [(entry, files) for entry, files in named if files]
if named:
lines.append("Its commands read these sources:\n" + "\n".join(
"- `%s`: %s" % (entry, ", ".join("`%s`" % f for f in files)) for entry, files in named))
combined = [(entry, s) for entry, s in sources.items() if isinstance(s, dict) and s.get("op") != "read"]
if combined:
lines.append("How they are combined:\n" + "\n".join("- `%s`: %s" % (e, _describe(s)) for e, s in combined))
else:
lines.append("No input source has been resolved in the saved project yet.")
basis.append("project.sources")
lines.append("This is the saved record; I have not rerun the project for this answer.")
return {"status": "answered", "path": "bench:project:record:" + kind, "response": "\n\n".join(lines),
"execution": {"state": "read", "project": shape.get("pid"), "basis": basis}}
def _record_answer(kind, shape):
"""outputs, status, requirements, history: from the saved receipt and attempts only"""
module = shape.get("module") or "the unnamed project"
state = shape.get("status") or "not recorded"
last = shape.get("last_reply") or {}
ex = last.get("execution") or {}
reqs = ex.get("requirements") or []
lines = ["The last recorded state of `%s` is %s." % (module, state)]
ledger = [ln.strip() for ln in (last.get("response") or "").splitlines() if re.match(r"\s+R\d+ ", ln)]
if kind == "status":
passed = sum(1 for r in reqs if r.get("status") == "passed")
open_ = [r["id"] for r in reqs if r.get("status") not in ("passed", "superseded", "excluded", "dropped")]
lines.append("Its last attempt ended %s: %d of %d recorded requirements passed%s." % (
ex.get("state") or "without a receipt", passed, len(reqs),
("; not yet met: " + ", ".join(open_)) if open_ else ""))
holes = [h.get("text", "") for h in shape.get("holes_kept") or () if h.get("text")]
if holes:
lines.append("To continue, I need:\n" + "\n".join("- " + h for h in holes))
elif kind == "requirements":
lines.append("Its requirements, as last judged:\n" + "\n".join("- " + ln for ln in ledger) if ledger else
"Its requirements: %s." % ", ".join("%s %s (%s)" % (r["id"], r["kind"], r.get("status")) for r in reqs)
if reqs else "No requirement has been recorded yet.")
elif kind == "outputs":
outs = [ln for ln in ledger if re.search(r"\b(?:writes|keeps rows|a page|prints)\b", ln)]
files = ex.get("files") or []
lines.append("What it makes:\n" + "\n".join("- " + ln for ln in outs) if outs else
"No outcome has been recorded yet.")
if files:
lines.append("Files it changed last: %s." % ", ".join("`%s`" % f for f in files))
else:
att = shape.get("attempts") or []
lines.append("What has been tried (%d attempt%s):\n" % (len(att), "" if len(att) == 1 else "s") + "\n".join(
"- %d: \"%s\" -> %s%s" % (a.get("seq"), str(a.get("text"))[:90], a.get("state"),
(", then a different step: " + a["cont"]) if a.get("cont") else "")
for a in att[-8:]) if att else "No attempt is recorded yet.")
lines.append("This is the saved record; I have not rerun the project for this answer.")
return {"status": "answered", "path": "bench:project:record:" + kind, "response": "\n\n".join(lines),
"execution": {"state": "read", "project": shape.get("pid"), "basis": ["project.last_reply", "project.attempts"]}}
def work_answer(text, shape, reading=None):
"""A question about the active general work uses that work's own record."""
if not shape:
return None
q = request_reading(text)["reading"].strip().rstrip("?.! ")
kind = next((name for name, pattern in _STATE_QUESTIONS if pattern.fullmatch(q)), None)
if kind is None and (asks_about(text) or text.strip().endswith("?")):
referring = re.sub(r"\b(?:work|task|goal)\b", "project", q, flags=re.I)
kind = _aspect(referring, {"module": "", "entries": {s["id"]: {} for s in shape.get("steps", ())}})
if kind is None:
import bench
if bench._STATUS.fullmatch(text.strip()):
kind = "status"
elif bench._TASKS.fullmatch(text.strip()):
kind = "holes"
if kind is None:
import project_discussion
return project_discussion.answer(text, shape, reading=reading)
steps = shape.get("steps") or []
done = sum(step.get("state") == "done" for step in steps)
lines = ["The active work is %s: %d of %d steps are complete." % (shape.get("state", "received"), done, len(steps)),
"The goal is: " + str(shape.get("goal") or "not recorded")]
holes = shape.get("holes") or []
if kind in ("holes", "status"):
if holes:
lines.append("What it needs next:\n" + "\n".join("- " + str(h.get("text") or h) for h in holes))
elif done < len(steps):
lines.append("Still open:\n" + "\n".join("- %s: %s" % (s["id"], s.get("request", s["kind"]))
for s in steps if s.get("state") != "done"))
elif shape.get("state") != "done":
lines.append("The saved state does not establish completion yet.")
elif kind == "requirements":
requirements = shape.get("requirements") or []
lines.append("\n".join("- %s: %s (%s)" % (r.get("id", "?"), r.get("text") or r.get("request") or r.get("kind", ""),
r.get("status", "open")) for r in requirements) or "No requirement is recorded yet.")
if shape.get("constraints"):
lines.append("Constraints:\n" + "\n".join("- " + c["text"] for c in shape["constraints"]))
elif kind == "inputs":
lines.append("The saved requests for each part:\n" + "\n".join("- %s: %s" % (s["id"], s.get("request", "")) for s in steps))
elif kind == "outputs":
files = list(dict.fromkeys(f for receipt in shape.get("receipts", ()) for f in (
receipt.get("result", {}).get("files") or receipt.get("result", {}).get("execution", {}).get("files") or [])))
lines.append("Files recorded by completed actions: %s." % ", ".join("`%s`" % f for f in files)
if files else "No changed file has been recorded in this work's receipts.")
else:
lines.append("Recorded attempts:\n" + "\n".join("- %s: %s (%d attempt%s)" % (
s["id"], s.get("state", "pending"), len(s.get("attempts") or []), "" if len(s.get("attempts") or []) == 1 else "s") for s in steps))
lines.append("This is the saved work record; I have not run a step for this answer.")
return {"status": "answered", "path": "bench:work:record:" + kind, "response": "\n\n".join(lines),
"execution": {"state": "read", "work_id": shape.get("id"), "basis": ["work.steps", "work.requirements", "work.receipts", "work.holes"]}}
def word_receipt(reply):
"""A short lead from a project receipt; keep the complete original account."""
if not str(reply.get("path", "")).startswith("bench:project") or reply.get("details") is not None:
return reply
ex = reply.get("execution") or {}
state = ex.get("state")
if state == "changed-checked":
reqs = ex.get("requirements") or []
passed = [r for r in reqs if r.get("status") == "passed"]
if reqs and len(passed) == len(reqs):
lead = "The project is built, and all %d recorded requirements passed their checks." % len(reqs)
else:
lead = "The project change completed with a checked receipt."
if ex.get("files"):
lead += " The changed file%s: %s." % ("s are" if len(ex["files"]) != 1 else " is", ", ".join("`%s`" % f for f in ex["files"]))
elif state in {"missing", "blocked"}:
holes = ex.get("holes") or []
lead = "The project is kept for the next turn, but it is not finished."
if holes:
lead += " %d unresolved requirement%s remain%s." % (len(holes), "s" if len(holes) != 1 else "", "" if len(holes) != 1 else "s")
if ex.get("started") is False:
lead += " This attempt did not start a build."
elif state == "failed":
lead = "This attempt did not pass its checks; the project is not finished."
elif state == "refused":
lead = "The project is waiting for the change permission recorded for this conversation."
else:
return reply
details = str(reply.get("response", ""))
return dict(reply, response=lead + "\n\n" + details, details=details,
wording={"basis": "execution", "state": state})
def spelling_suggestions(shape, reader, owned):
"""Use the existing Speller on unread holes only; never change the request."""
speller = getattr(reader, "sp", None)
if speller is None:
return []
owned = {str(w).lower() for w in owned}
suggestions = []
for hole in (shape or {}).get("holes_kept", ()):
if hole.get("kind") != "unread":
continue
for word in hole.get("words", ()):
if not re.fullmatch(r"[a-zA-Z]+", word) or word.lower() in owned:
continue
try:
candidate = speller.fix_word(word)
except Exception:
continue
if candidate.lower() != word.lower() and candidate.lower() in owned:
suggestion = {"word": word, "reading": candidate, "requirement": hole.get("req"), "part": "turn_reader.Speller"}
if suggestion not in suggestions:
suggestions.append(suggestion)
return suggestions123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240"""learn - the gap loop (12.0). When the door cannot answer a question under the law, it says so and offers to look it up in theverified sources; on your go it searches them, reads what it finds, takes the sentences that answer the question, checks them,and keeps what holds, with its source, for every later turn.
look Wikipedia (English) and Simple English Wikipedia, through their public search and plain-text extract APIs read the extract of the best article from each, split into sentences answer the native clause that binds the question's subject, roles and demanded field check compare the demanded values, retaining disagreements and source provenance; Wikipedia editions are related sources, not independent confirmation keep workbench/local/learned.jsonl: question, sentence, source URL, sha256 of the sentence, corroborated or not; a later question that resonates with a kept one is answered from it, with the same citationNo language model; nothing outside the verified list is fetched."""import hashlibimport jsonimport osimport reimport timeimport urllib.parseimport urllib.requestfrom pathlib import Path
WB = Path(__file__).resolve().parentSTORE = Path(os.environ.get("ORACLE7_LEARNED", WB / "local" / "learned.jsonl"))UA = {"User-Agent": "Oracle7/12.0 (https://huggingface.co/psiloceyeben/oracle7; verified-sources reader, no language model)"}SOURCES = [("Wikipedia", "en.wikipedia.org"), ("Simple English Wikipedia", "simple.wikipedia.org")]STOP = set("the a an of in on at to for with by from as is are was were be been being do does did what which who whom whose " "where when why how many much is it its this that these those and or not no yes tell me about please there their " "they he she his her him you your i we our us can could would should will shall may might must has have had".split())W = re.compile(r"[A-Za-z][A-Za-z'-]+|\d[\d,.]*")
def words(t): return [w.lower().strip(".,") for w in W.findall(t or "")]
def content(t): return [w for w in words(t) if w not in STOP and len(w) > 1]
def stem(w): for s in ("ies", "es", "s", "ing", "ed"): if len(w) > len(s) + 3 and w.endswith(s): return w[: -len(s)] return w
def _get(url, tries=3): """one polite request: identified, and when the source says too many requests, wait as long as it asks (or 5 s) and retry""" import urllib.error for k in range(tries): time.sleep(0.4) # never a burst req = urllib.request.Request(url, headers=UA) try: with urllib.request.urlopen(req, timeout=25) as r: return json.loads(r.read(3_000_000).decode("utf-8", "ignore")) except urllib.error.HTTPError as e: if e.code != 429 or k == tries - 1: raise time.sleep(min(30, int(e.headers.get("Retry-After") or 5))) return {}
def search(host, q, n=2): q = " ".join(content(q)) or q # the question's content words, not its frame u = "https://%s/w/api.php?%s" % (host, urllib.parse.urlencode( {"action": "query", "list": "search", "srsearch": q, "format": "json", "srlimit": n})) return [h["title"] for h in _get(u).get("query", {}).get("search", [])]
def extract(host, title): u = "https://%s/w/api.php?%s" % (host, urllib.parse.urlencode( {"action": "query", "prop": "extracts", "explaintext": 1, "titles": title, "format": "json", "redirects": 1})) pages = _get(u).get("query", {}).get("pages", {}) for p in pages.values(): return p.get("extract") or "" return ""
ABBR = re.compile(r"\b(c|ca|e\.g|i\.e|Mr|Mrs|Ms|Dr|St|No|vs|approx|est|Jr|Sr|Inc|Ltd|Co|Mt|Ft|U\.S|U\.K)\.$")YEAR = re.compile(r"\b(1\d{3}|20\d{2})\b|\b\d{1,2} (January|February|March|April|May|June|July|August|September|October|" r"November|December)\b|\b(January|February|March|April|May|June|July|August|September|October|November|" r"December) \d{1,2}\b")
def sentences(text): text = re.sub(r"(?m)^\s*=+[^=\n]*=+\s*$", "\n", text) # section headings are not sentences text = re.sub(r"\s*\n\s*", " ", text) out, cur = [], "" for piece in re.split(r"(?<=[.!?])\s+(?=[A-Z0-9\"(])", text[:80000]): cur = (cur + " " + piece).strip() if cur else piece.strip() if ABBR.search(cur): # "Cellos made before c." does not end a sentence continue out.append(cur) cur = "" if cur: out.append(cur) return out
def wants(question): """the kind of answer the question asks for, read from its first words""" q = question.strip().lower() if re.match(r"(when|what year|in what year|which year|what date)\b", q): return "time" if re.match(r"(who|whom|whose)\b", q): return "person" if re.match(r"(how many|how much|how long|how tall|how high|how old|how far|how big|how deep|how heavy|what is the population)\b", q): return "number" if re.match(r"where\b", q): return "place" return None
def fits(kind, s, question): if kind == "time": return bool(YEAR.search(s)) if kind == "number": return bool(re.search(r"\d", s)) if kind in ("person", "place"): qw = {w.lower() for w in W.findall(question)} caps = [w for w in re.findall(r"(?<![.!?]\s)(?<!^)\b[A-Z][a-z]+", s) if w.lower() not in qw] return bool(caps) return True
def select_answer(question, text, title="", reader=None): """Keep the exact selected source sentence and its checked question duty.""" from question_obligation import select_records records = [{"sentence": s, "title": title} for s in sentences(text) if 4 <= len(s) <= 1200 and not s.startswith("==")] return select_records(question, records, reader, title)
def best_sentence(question, text, title, reader=None): selected = select_answer(question, text, title, reader) return selected["sentence"] if selected else None
def lookup(question, reader=None): """-> {"status": answered|offered|hole, "response", "path", "evidence": [...]}""" from question_obligation import receive duty = receive(question, reader) if duty["missing"]: return {"status": "hole", "path": "learn:question", "evidence": [], "question_obligation": duty, "response": "Before selecting a source answer I need %s." % "; ".join(duty["missing"])} found = [] qstems = {stem(w) for w in content(question)} for name, host in SOURCES: try: titles = search(host, question, n=4) # the article about the question's subject first: most of the question's words in its title, then search order titles = sorted(titles, key=lambda t: -len({stem(w) for w in content(t)} & qstems)) for title in titles[:2]: selected = select_answer(question, extract(host, title), title, reader) if selected: found.append(dict(selected, source=name, provenance_family="Wikimedia", url="https://%s/wiki/%s" % (host, urllib.parse.quote(title.replace(" ", "_"))))) break except Exception as e: # noqa: BLE001 found.append({"source": name, "error": repr(e)[:120]}) good = [f for f in found if f.get("sentence")] if not good: return {"status": "hole", "path": "learn:none", "evidence": found, "response": "I looked in %s and found nothing that answers it, so I still do not hold it." % ( " and ".join(n for n, _ in SOURCES))} from question_obligation import agreement checked = agreement([f["answer_check"] for f in good]) lead = good[0] for f in good: keep(question, f, False, reader=reader, agreement=checked) if checked["conflict"]: return {"status": "hole", "path": "learn:conflict", "evidence": good, "agreement": checked, "response": "The sources disagree on the requested %s: %s. I have kept both accounts; this answer remains unresolved." % (lead["question_obligation"]["kind"], "; ".join("%s [%s]" % (f["sentence"], f["url"]) for f in good))} if checked["agrees"]: resp = "%s [%s] The two Wikipedia editions agree on this answer, but they are related sources, not independent confirmation. [%s]" % ( lead["sentence"], lead["url"], good[1]["url"]) return {"status": "offered", "path": "learn:source-agreement", "evidence": good, "agreement": checked, "response": resp} resp = "From %s, one source: %s [%s]" % (lead["source"], lead["sentence"], lead["url"]) return {"status": "offered", "path": "learn:one-source", "evidence": good, "agreement": checked, "response": resp}
def keep(question, f, corroborated=False, reader=None, agreement=None): from question_obligation import receive, match duty = receive(question, reader) checked = match(duty, f["sentence"], reader, f.get("title", "")) if not checked: return False STORE.parent.mkdir(parents=True, exist_ok=True) rec = {"t": int(time.time()), "q": question, "sentence": f["sentence"], "source": f["source"], "url": f["url"], "sha256": hashlib.sha256(f["sentence"].encode()).hexdigest(), "corroborated": False, "title": f.get("title", ""), "question_obligation": duty, "answer_check": checked, "agreement": agreement or {}, "provenance_family": f.get("provenance_family", "unverified")} with open(STORE, "a", encoding="utf-8") as fh: fh.write(json.dumps(rec) + "\n") return True
def recall(question, reader=None): """Recheck the same demanded field and source integrity before using a record.""" if not STORE.is_file(): return None from question_obligation import receive, match, agreement duty = receive(question, reader) if duty["missing"]: return None found = [] with open(STORE, encoding="utf-8") as source: for line in source: try: r = json.loads(line) if hashlib.sha256(r["sentence"].encode()).hexdigest() != r["sha256"]: continue original = receive(r["q"], reader) if original.get("key") != duty["key"]: continue checked = match(duty, r["sentence"], reader, r.get("title", "")) if checked and r.get("source") and r.get("url"): found.append(dict(r, answer_check=checked)) except (ValueError, TypeError, KeyError): continue if not found: return None checked = agreement([f["answer_check"] for f in found]) if checked["conflict"]: return {"status": "hole", "path": "learn:kept-conflict", "evidence": found, "agreement": checked, "response": "The kept sources disagree on this requested field: " + "; ".join( "%s [%s]" % (f["sentence"], f["url"]) for f in found) + ". The answer remains unresolved."} best = found[-1] return {"status": "offered", "path": "learn:kept", "evidence": [best], "agreement": checked, "response": "I kept this source account from %s (not independently confirmed): %s [%s]" % ( best["source"], best["sentence"], best["url"])}
GO = re.compile(r"^\s*(?:yes|yeah|yep|go|go ahead|do it|sure|ok|okay|please do|look it up|fetch (?:it|them)|find out)\b[\s.!]*$", re.I)
def offer_text(): return "I don't hold that. I can look it up in %s and compare their answers; those editions are related sources. Say go." % ( " and ".join(n for n, _ in SOURCES))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146# Runs ON each server (piped over ssh stdin), prints one JSON object.
# Read-only: reads /proc, systemctl, ss, nginx -T, cert files, curls its own vhosts via 127.0.0.1.
import json, os, re, shutil, socket, subprocess, time, glob
from concurrent.futures import ThreadPoolExecutor
def sh(cmd, t=15):
try:
return subprocess.run(cmd, shell=False, capture_output=True, text=True, timeout=t).stdout
except Exception:
return ""
def meminfo():
m = {}
for line in open("/proc/meminfo"):
k, v = line.split(":", 1)
m[k] = int(v.split()[0]) * 1024
return m
SYSTEM = re.compile(r"^(systemd-|dbus|ssh|cron|rsyslog|snapd|getty|serial-getty|user@|polkit|udisks|ModemManager|"
r"networkd-dispatcher|unattended-upgrades|multipathd|qemu-guest-agent|irqbalance|packagekit|"
r"fwupd|accounts-daemon|chrony|atd|upower|thermald|cloud-|hv-|open-vm|apport|lvm2|"
r"setvtrgb|keyboard-setup|console-setup|plymouth|rtkit|wpa_supplicant|NetworkManager|"
r"containerd|php.*-fpm|postfix|exim|uuidd|blk-availability|haveged|gpu-manager)")
def unit_of(pid):
try:
for line in open(f"/proc/{pid}/cgroup"):
m = re.search(r"/([^/]+\.service)", line)
if m:
return m.group(1)
except Exception:
pass
return None
out = {"probed_at": int(time.time()), "hostname": socket.gethostname()}
osr = dict(re.findall(r'^(\w+)="?([^"\n]*)"?', open("/etc/os-release").read(), re.M))
out["os"] = osr.get("PRETTY_NAME", "")
out["cpus"] = os.cpu_count()
cpu_model = re.search(r"model name\s*:\s*(.+)", open("/proc/cpuinfo").read())
out["cpu_model"] = cpu_model.group(1).strip() if cpu_model else ""
out["load"] = [float(x) for x in open("/proc/loadavg").read().split()[:3]]
mi = meminfo()
out["mem"] = {"total": mi["MemTotal"], "used": mi["MemTotal"] - mi["MemAvailable"],
"swap_total": mi.get("SwapTotal", 0), "swap_used": mi.get("SwapTotal", 0) - mi.get("SwapFree", 0)}
du = shutil.disk_usage("/")
out["disk"] = {"total": du.total, "used": du.used, "free": du.free}
out["uptime_s"] = int(float(open("/proc/uptime").read().split()[0]))
out["reboot_required"] = os.path.exists("/var/run/reboot-required")
# services
running = sh(['systemctl', 'list-units', '--type=service', '--state=running', '--no-legend', '--plain']).split("\n")
names = [l.split()[0] for l in running if l.strip()]
out["service_count"] = len(names)
failed = sh(['systemctl', 'list-units', '--type=service', '--state=failed', '--no-legend', '--plain']).split("\n")
out["failed"] = [l.split()[0] for l in failed if l.strip() and l.split()[0].endswith(".service")]
# listening ports -> owning unit
ports = {}
for l in sh(['ss', '-ltnpH']).split("\n"):
parts = l.split()
if len(parts) < 5:
continue
addr = parts[3]
host, _, port = addr.rpartition(":")
pid = re.search(r"pid=(\d+)", l)
proc = re.search(r'\(\("([^"]+)"', l)
unit = unit_of(pid.group(1)) if pid else None
key = unit or (proc.group(1) if proc else "?")
ports.setdefault(key, set()).add((int(port), host.strip("[]") in ("0.0.0.0", "*", "::")))
svcs = []
for n in names:
if SYSTEM.match(n):
continue
p = sorted(ports.get(n, []))
svcs.append({"name": n[:-8] if n.endswith(".service") else n,
"ports": [x[0] for x in p], "public": any(x[1] for x in p)})
out["services"] = svcs
# docker
dk = sh(['docker', 'ps', '--format', '{{.Names}}|{{.Image}}|{{.Ports}}|{{.Status}}'])
out["containers"] = [dict(zip(["name", "image", "ports", "status"], l.split("|"))) for l in dk.split("\n") if l.strip()]
# nginx vhosts
sites = {}
conf = sh(['nginx', '-T'], 20)
depth, block = 0, None
for raw in conf.split("\n"):
line = raw.split("#", 1)[0].strip()
if raw.startswith("# configuration file"):
depth, block = 0, None
continue
if re.match(r"^server\s*\{", line) and block is None:
block = {"names": [], "proxy": None, "ssl": False, "root": None, "start": depth}
if block is not None:
m = re.match(r"server_name\s+([^;]+);", line)
if m:
block["names"] += m.group(1).split()
m = re.search(r"proxy_pass\s+https?://[^:/;]+:(\d+)", line)
if m and not block["proxy"]:
block["proxy"] = int(m.group(1))
if re.match(r"listen\s+.*443", line):
block["ssl"] = True
m = re.match(r"root\s+([^;]+);", line)
if m and not block["root"]:
block["root"] = m.group(1)
depth += line.count("{") - line.count("}")
if block is not None and depth <= block["start"]:
for n in block["names"]:
if n in ("_", "localhost") or re.match(r"^[\d.]+$", n) or n.startswith("~"):
continue
s = sites.setdefault(n, {"domain": n, "port": None, "ssl": False, "static": False})
s["port"] = s["port"] or block["proxy"]
s["ssl"] = s["ssl"] or block["ssl"]
s["static"] = s["static"] or (block["root"] is not None and not block["proxy"])
block = None
def check(s):
d = s["domain"]
if len(d) > 253 or not re.fullmatch(
r"(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.?", d
):
s["code"] = None
return s
scheme, port = ("https", 443) if s["ssl"] else ("http", 80)
code = sh(["curl", "-q", "-sk", "--noproxy", "*", "--proto", f"={scheme}", "-o", "/dev/null",
"-w", "%{http_code}", "-m", "5", "--resolve", f"{d}:{port}:127.0.0.1",
f"{scheme}://{d}/"], 8).strip()
s["code"] = int(code) if code.isdigit() else 0
return s
with ThreadPoolExecutor(12) as ex:
out["sites"] = sorted(ex.map(check, list(sites.values())[:120]), key=lambda s: s["domain"])
# certs
certs = []
for c in glob.glob("/etc/letsencrypt/live/*/cert.pem"):
end = sh(["openssl", "x509", "-enddate", "-noout", "-in", c]).strip().split("=", 1)[-1]
try:
days = int((time.mktime(time.strptime(end, "%b %d %H:%M:%S %Y %Z")) - time.time()) // 86400)
except Exception:
days = None
certs.append({"name": c.split("/")[-2], "days_left": days})
out["certs"] = sorted(certs, key=lambda c: (c["days_left"] is None, c["days_left"] or 0))
print(json.dumps(out))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271"""machines - the map of this computer and the machines it reaches (12.0).
One place that shows the computer Oracle7 runs on and every server the user lists, read live and drawn as a map(static/machines.html, the page's Machines tab). The list is the user's own: workbench/local/machines.json (orORACLE7_WORKBENCH_LOCAL/machines.json), which never ships in a pack. A machine is named by what the user's own sshreaches it as: an ssh alias from their ~/.ssh/config ("research") or user@host.
{"machines": [{"id": "web", "name": "Web server", "ssh": "root@203.0.113.7", "role": "sites", "color": "#0969da"}]}
Reading is read-only. Each server is read by machine_probe.py piped over ssh stdin (it reads /proc, systemctl, ss, nginx-T, certificate files and fetches its own sites on 127.0.0.1; it writes nothing). ssh runs with BatchMode (keys only, nopassword prompt), StrictHostKeyChecking=yes (a host it has never seen is not trusted silently) and no forwarding. Thiscomputer is read with the standard library (and psutil when it is installed). Nothing is sent anywhere else.
Would not solve: a machine that ssh cannot reach with a key; Windows servers (the probe reads Linux /proc)."""import jsonimport osimport platformimport reimport shutilimport socketimport subprocessimport sysimport timefrom concurrent.futures import ThreadPoolExecutorfrom pathlib import Path
HERE = Path(__file__).resolve().parentPROBE = HERE / "machine_probe.py"ID = re.compile(r"^[A-Za-z0-9_-]{1,24}$")SSH_TARGET = re.compile(r"^(?:[A-Za-z0-9._-]{1,64}@)?[A-Za-z0-9._-]{1,253}$")COLOR = re.compile(r"^#[0-9a-fA-F]{6}$")PALETTE = ["#0969da", "#1a7f37", "#8250df", "#bf3989", "#e95420", "#9a6700", "#0a7ea4", "#cf222e"]DAY = 86400
def _local(): return Path(os.environ.get("ORACLE7_WORKBENCH_LOCAL") or (HERE / "local"))
def _paths(): base = _local() return base / "machines.json", base / "machines_map.json", base / "machines_history.json"
def config(): """the user's list: [{id, name, ssh, role, color}] (empty when none is kept)""" cfg, _m, _h = _paths() try: items = json.loads(cfg.read_text(encoding="utf-8")).get("machines") or [] except (OSError, ValueError): items = [] return [m for m in (_clean(x, i) for i, x in enumerate(items)) if m]
def _clean(m, i=0): if not isinstance(m, dict): return None mid, ssh = str(m.get("id") or "").strip(), str(m.get("ssh") or "").strip() if not ID.match(mid) or not SSH_TARGET.match(ssh) or ssh.startswith("-"): return None color = str(m.get("color") or "") return {"id": mid, "name": str(m.get("name") or mid)[:40], "ssh": ssh, "role": str(m.get("role") or "")[:120], "color": color if COLOR.match(color) else PALETTE[i % len(PALETTE)]}
def save(items): """keep the user's list (validated; ids unique). -> the list as kept""" kept, seen = [], set() for i, x in enumerate(items or []): m = _clean(x, i) if m and m["id"] not in seen: seen.add(m["id"]) kept.append(m) cfg, _m, _h = _paths() cfg.parent.mkdir(parents=True, exist_ok=True) tmp = cfg.with_suffix(".tmp") tmp.write_text(json.dumps({"machines": kept}, indent=1), encoding="utf-8") os.replace(tmp, cfg) return kept
def probe_server(ssh, timeout=60): """one server's inventory, read by machine_probe.py over ssh (read-only). -> dict, or {"unreachable": True, "why"}""" if not SSH_TARGET.match(ssh) or ssh.startswith("-"): return {"unreachable": True, "why": "not an ssh target", "probed_at": int(time.time())} cmd = ["ssh", "-T", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", "-o", "ClearAllForwardings=yes", "-o", "ForwardAgent=no", "-o", "ForwardX11=no", "-o", "ConnectTimeout=10", ssh, "python3", "-"] try: r = subprocess.run(cmd, input=PROBE.read_text(encoding="utf-8"), capture_output=True, text=True, timeout=timeout) except FileNotFoundError: return {"unreachable": True, "why": "no ssh command on this computer", "probed_at": int(time.time())} except subprocess.TimeoutExpired: return {"unreachable": True, "why": "no answer within %d s" % timeout, "probed_at": int(time.time())} out = r.stdout.strip() try: sample = json.loads(out[out.index("{"):]) if "{" in out else None except ValueError: sample = None if not sample or not sample.get("cpus") or not (sample.get("disk") or {}).get("total"): why = (r.stderr.strip().splitlines() or ["no inventory returned"])[-1][:200] return {"unreachable": True, "why": why, "probed_at": int(time.time())} return sample
def _mem(): try: import psutil # optional v = psutil.virtual_memory() return {"total": int(v.total), "used": int(v.total - v.available)} except Exception: # noqa: BLE001 pass if sys.platform == "win32": try: import ctypes
class MS(ctypes.Structure): _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), ("ullAvailExtendedVirtual", ctypes.c_ulonglong)] m = MS() m.dwLength = ctypes.sizeof(MS) ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m)) return {"total": int(m.ullTotalPhys), "used": int(m.ullTotalPhys - m.ullAvailPhys)} except Exception: # noqa: BLE001 return {"total": 0, "used": 0} try: info = {} for line in open("/proc/meminfo"): k, v = line.split(":", 1) info[k] = int(v.split()[0]) * 1024 return {"total": info["MemTotal"], "used": info["MemTotal"] - info.get("MemAvailable", info.get("MemFree", 0))} except Exception: # noqa: BLE001 return {"total": 0, "used": 0}
def _uptime(): try: import psutil return int(time.time() - psutil.boot_time()) except Exception: # noqa: BLE001 pass if sys.platform == "win32": try: import ctypes return int(ctypes.windll.kernel32.GetTickCount64() // 1000) except Exception: # noqa: BLE001 return 0 try: return int(float(open("/proc/uptime").read().split()[0])) except Exception: # noqa: BLE001 return 0
def _cpu_pct(): try: import psutil return int(psutil.cpu_percent(interval=0.3)) except Exception: # noqa: BLE001 pass try: return int(100 * os.getloadavg()[0] / (os.cpu_count() or 1)) except Exception: # noqa: BLE001 return 0
def _drives(): """the computer's other drives (an external disk shows as one): [{mount, total, used, free}]""" mounts = [] if sys.platform == "win32": mounts = ["%s:\\" % c for c in "DEFGHIJKLMNOPQRSTUVWXYZ" if os.path.exists("%s:\\" % c)] else: for base in ("/media", "/mnt", "/Volumes"): try: mounts += [os.path.join(base, d) for d in os.listdir(base)] except OSError: pass out = [] for m in mounts[:6]: try: du = shutil.disk_usage(m) out.append({"mount": m, "total": du.total, "used": du.used, "free": du.free}) except OSError: pass return out
def probe_local(): """this computer, read with the standard library (psutil when present)""" root = os.path.abspath(os.sep) if sys.platform != "win32" else os.environ.get("SystemDrive", "C:") + "\\" du = shutil.disk_usage(root) return {"hostname": socket.gethostname(), "model": platform.node(), "os": "%s %s" % (platform.system(), platform.release()), "cpu_model": platform.processor() or platform.machine(), "cpus": os.cpu_count() or 1, "cpu_pct": _cpu_pct(), "mem": _mem(), "disk": {"total": du.total, "used": du.used, "free": du.free}, "disk_name": root, "uptime_s": _uptime(), "battery": None, "on_power": True, "drives": _drives()}
def collect(): """read every listed machine (in parallel) and this computer; keep the map and 24 h of history. -> the map""" items = config() with ThreadPoolExecutor(max_workers=max(1, min(8, len(items)))) as ex: found = dict(zip([m["id"] for m in items], ex.map(lambda m: probe_server(m["ssh"]), items))) laptop = probe_local() drives = laptop.get("drives") or [] drive = {"connected": bool(drives)} if drives: d = max(drives, key=lambda x: x["total"]) drive.update(label=d["mount"], fs="", model="", total=d["total"], used=d["used"], free=d["free"], folders=[]) now = int(time.time()) _cfg, map_path, hist_path = _paths() try: hist = json.loads(hist_path.read_text(encoding="utf-8")) except (OSError, ValueError): hist = {} hist = {k: [p for p in v if now - p[0] < DAY] for k, v in hist.items()}
def point(key, disk, mem, load): hist.setdefault(key, []).append([now, round(disk, 1), round(mem, 1), round(load, 2)]) for mid, b in found.items(): if not b.get("unreachable"): point(mid, 100 * b["disk"]["used"] / b["disk"]["total"], 100 * b["mem"]["used"] / max(1, b["mem"]["total"]), 100 * (b.get("load") or [0])[0] / max(1, b.get("cpus") or 1)) point("laptop", 100 * laptop["disk"]["used"] / max(1, laptop["disk"]["total"]), 100 * laptop["mem"]["used"] / max(1, laptop["mem"]["total"]), laptop["cpu_pct"]) data = {"collected_at": now, "boxes": found, "laptop": laptop, "drive": drive, "history": hist} map_path.parent.mkdir(parents=True, exist_ok=True) for path, value in ((hist_path, hist), (map_path, data)): tmp = path.with_suffix(".tmp") tmp.write_text(json.dumps(value), encoding="utf-8") os.replace(tmp, path) return data
def latest(): """the last map kept (None before the first reading) and the list it was drawn for""" _cfg, map_path, _h = _paths() try: data = json.loads(map_path.read_text(encoding="utf-8")) except (OSError, ValueError): data = None return {"meta": {m["id"]: m for m in config()}, "map": data}
def summary(data=None): """the map in words, for a reply in the chat""" data = data or (latest().get("map") or {}) if not data: return "No machines have been read yet." meta = {m["id"]: m for m in config()} lines = [] lap = data.get("laptop") or {} if lap: lines.append("This computer (%s): %d%% CPU, memory %.0f%% used, disk %.0f%% used." % ( lap.get("hostname", ""), lap.get("cpu_pct", 0), 100 * lap["mem"]["used"] / max(1, lap["mem"]["total"]), 100 * lap["disk"]["used"] / max(1, lap["disk"]["total"]))) for mid, b in (data.get("boxes") or {}).items(): name = meta.get(mid, {}).get("name", mid) if b.get("unreachable"): lines.append("%s: not reached (%s)." % (name, b.get("why", "no answer"))) continue failed = b.get("failed") or [] lines.append("%s (%s): load %.2f on %d cores, memory %.0f%% used, disk %.0f%% used, %d services%s%s." % ( name, b.get("hostname", ""), (b.get("load") or [0])[0], b.get("cpus", 0), 100 * b["mem"]["used"] / max(1, b["mem"]["total"]), 100 * b["disk"]["used"] / max(1, b["disk"]["total"]), b.get("service_count", len(b.get("services") or [])), ("; failed: " + ", ".join(failed[:5])) if failed else "", "; reboot required" if b.get("reboot_required") else "")) return "\n".join(lines)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657"""make - build an algorithm as described (12.0, Ben: "we need it to know how to build one as described").
The description is read as steps (sentences, ";", "then", numbered lines). Each step becomes one typed code move: - a move of the language itself (what Python can do): read, fetch, split, parse, keep/remove where, count, sort by, top N, sum, average, max, min, unique, lower/upper, replace, extract numbers/emails/urls/words, hash, field, join, write, print - or, when no language move fits, a function from your workspace found by meaning (the workspace index), copied into the program with its file's importsThe value flows from step to step ("it", "them", "the result" = the previous step's value), with its kind tracked (text,list, number, rows, pairs) so a move applies only where it can. The program is written to the sandbox, run, and checkedagainst "expect <value>" if you give one. A step no move can build is reported as a named gap with the nearest workspacefunctions, never guessed. No language model."""import astimport jsonimport reimport threadingfrom pathlib import Path
NUM = r"(-?\d+(?:\.\d+)?)"Q = r"""['"‘“]?([^'"’”]+?)['"’”]?"""
def steps_of(desc): """steps: lines, numbered items, sentences, ";", "then", and every comma that opens a new clause (a fragment that only qualifies the step before it - "descending", "and so on", a number - stays with that step)""" d = re.sub(r"(?m)^\s*\d+[.)]\s*", "\n", desc.strip()) d = re.sub(r"\bexpect(?:ing)?\b.*$", "", d, flags=re.I | re.S) parts = re.split(r"\n+|;|(?<=[a-z0-9\"')\]])\.\s+|,?\s+then\s+", d, flags=re.I) out = [] # sealed v2 (v19): "reverse them" was merged into the step before as a sort qualifier and had no effect. Order words # qualify only a sort step, and only as a bare qualifier; a clause with its own verb is its own step. QUAL = re.compile(r"^(?:\d|from |to |by |with |as |in |into |on |of )", re.I) ORDERQ = re.compile(r"^(?:descending|ascending|largest first|smallest first|in order|alphabetically|reversed|in reverse)$", re.I) carry = "" for p in parts: for frag in re.split(r",\s+", p): f = re.sub(r"^(?:and|or)\s+", "", frag.strip(" .,"), flags=re.I) if not f: continue if re.fullmatch(r"for\s+(?:each|every)\s+\w+", f, re.I): # "for each line," opens the step that follows carry = f + ", " continue f, carry = carry + f, "" if out and (QUAL.match(f) or (ORDERQ.match(f) and re.match(r"sort\b", out[-1], re.I))): out[-1] = out[-1] + ", " + f else: out.append(f) return out
class Prog: def __init__(self): self.lines, self.imports, self.extra, self.kind, self.gaps, self.trace = [], set(), [], None, [], []
def emit(self, line, kind, imp=()): self.lines.append(line) self.imports.update(imp) self.kind = kind
def source(self): """a program another program can use: run(x) holds the steps; printing goes through _show, which a program that uses this one turns off; main() runs it on its own""" head = "\n".join(sorted("import " + i for i in self.imports)) body = "\n".join(" " + (("_show(" + ln[len("print("):]) if ln.startswith("print(") else ln) for ln in self.lines) return ("%s\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\n%s\n\n\ndef run(x=None):\n%s\n return x\n\n\n" "def main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\n" % (head, "\n\n".join(self.extra), body or " pass")).lstrip()
NUMP = NUM # 12.0 Amendment 13b: inside a function with inputs, a condition may compare with an input by name
def _cond(text): """a keep/remove condition -> a Python test on i""" t = text.strip() m = re.search(r"(?:at least|no less than)\s+" + NUMP + r"|>=\s*" + NUMP, t) if m: return "float(i) >= %s" % (m.group(1) or m.group(2)) m = re.search(r"(?:at most|no more than)\s+" + NUMP + r"|<=\s*" + NUMP, t) if m: return "float(i) <= %s" % (m.group(1) or m.group(2)) m = re.search(r"(?:greater|more|larger|bigger|higher)\s+than\s+" + NUMP + r"|\b(?:over|above)\s+" + NUMP + r"|>\s*" + NUMP, t) if m: return "float(i) > %s" % (m.group(1) or m.group(2) or m.group(3)) m = re.search(r"(?:less|smaller|fewer|lower)\s+than\s+" + NUMP + r"|\b(?:under|below)\s+" + NUMP + r"|<\s*" + NUMP, t) if m: return "float(i) < %s" % (m.group(1) or m.group(2) or m.group(3)) m = re.search(r"longer\s+than\s+" + NUMP, t) if m: return "len(str(i)) > %s" % m.group(1) m = re.search(r"shorter\s+than\s+" + NUMP, t) if m: return "len(str(i)) < %s" % m.group(1) if re.search(r"\b(?:non-?negative)\b", t): return "float(i) >= 0" if re.search(r"\bpositive\b", t): return "float(i) > 0" if re.search(r"\bnegative\b", t): return "float(i) < 0" if re.search(r"\bnon-?empty\b|\bnot empty\b", t): return "bool(str(i).strip())" m = re.search(r"(?:start|begin)s?\s+with\s+" + Q + r"\s*$", t) if m: return "str(i).startswith(%r)" % m.group(1) m = re.search(r"ends?\s+with\s+" + Q + r"\s*$", t) if m: return "str(i).endswith(%r)" % m.group(1) m = re.search(r"(?:contain(?:s|ing)?|with|mention(?:s|ing)?|that have|having)\s+" + Q + r"\s*$", t) if m: return "%r in str(i)" % m.group(1) if re.search(r"\b(empty|blank)\b", t): return "not str(i).strip()" if re.search(r"\beven\b", t): return "float(i) % 2 == 0" if re.search(r"\bodd\b", t): return "float(i) % 2 == 1" return None
def each(step, P): """a move applied to each item: "<step> of each <thing>", "<step> for each <thing>", "for each <thing>, <step>""" s = step.strip() m = re.match(r"^for\s+(?:each|every)\s+\w+\s*,?\s*(.+)$", s, re.I) or \ re.match(r"^(.+?)\s+(?:of|for|in|from)\s+(?:each|every)\s+\w+$", s, re.I) if not m or P.kind not in ("list", "rows", "value", None): # sealed v3 (w04): a used program's value may be a list return False inner = Prog() inner.kind = "text" move(m.group(1), inner, None) if not inner.lines: return False n = len(P.extra) + 1 body = "\n".join(" " + ln for ln in inner.lines) P.extra.append("def each_%d(x):\n%s\n return x" % (n, body)) P.imports.update(inner.imports) P.emit("x = [each_%d(i) for i in x]" % n, "list") return True
KNOWN = set() # programs already made in the sandbox (set by the caller): a later program can use them by name
USE_SRC = '''def _use(name, x): """another program made here, used as a step: its run() on this value, its own printing off""" import importlib, os, sys here = os.path.dirname(os.path.abspath(__file__)) if here not in sys.path: sys.path.insert(0, here) m = importlib.import_module(name) m._SHOW = False return m.run(x)'''
ROWS_SRC = '''def _cell(r, k): """a row's value under the column as named (case, spaces and spelling forgiven)""" if k in r: return r[k] norm = lambda s: "".join(ch for ch in str(s).lower() if ch.isalnum()) for h in r: if norm(h) == norm(k): return r[h] import difflib near = difflib.get_close_matches(k, list(r), n=1, cutoff=0.5) return r[near[0]] if near else None
def _cellnum(r, k): """the cell as a number, as people write numbers ($1,200.50, 45%), or None""" import re as _re v = _cell(r, k) if isinstance(v, (int, float)): return float(v) m = _re.search(r"-?\\d[\\d,]*(?:\\.\\d+)?|-?\\.\\d+", str(v or "")) return float(m.group(0).replace(",", "")) if m else None'''
PAGE_SRC = '''def _page(x, name): """the value as a page: a table for rows (dicts) and pairs, a list for a list, the value itself otherwise""" esc = html.escape if isinstance(x, list) and x and isinstance(x[0], dict): cols = list(x[0]) body = "<table><tr>%s</tr>%s</table>" % ("".join("<th>%s</th>" % esc(str(c)) for c in cols), "".join( "<tr>%s</tr>" % "".join("<td>%s</td>" % esc(str(r.get(c, ""))) for c in cols) for r in x)) elif isinstance(x, list) and x and isinstance(x[0], tuple): body = "<table>%s</table>" % "".join("<tr>%s</tr>" % "".join("<td>%s</td>" % esc(str(v)) for v in p) for p in x) elif isinstance(x, list): body = "<ul>%s</ul>" % "".join("<li>%s</li>" % esc(str(v)) for v in x) else: body = "<p>%s</p>" % esc(str(x)) style = "body{font-family:system-ui,sans-serif;margin:2rem;color:#222}td,th{border-bottom:1px solid #ddd;padding:4px 10px;text-align:left}" open(name, "w", encoding="utf-8").write("<!doctype html><meta charset=utf-8><title>%s</title><style>%s</style><h1>%s</h1>%s" % ( esc(name), style, esc(name.rsplit(".", 1)[0]), body)) _show("page written: " + name)'''
SERVE_SRC = '''def _serve(x, port): """the value at http://127.0.0.1:<port>/ as JSON, and any page made here at /page. Run once, it asks itself for / and stops (so a build can be checked); with --serve on the command line it stays up until stopped""" import glob pages = sorted(glob.glob("*.html"))
class H(http.server.BaseHTTPRequestHandler): def do_GET(self): if self.path.startswith("/page") and pages: body, ctype = open(pages[-1], "rb").read(), "text/html; charset=utf-8" else: body, ctype = json.dumps(x, default=str, indent=1).encode(), "application/json" self.send_response(200) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body)
def log_message(self, *a): pass
srv = http.server.ThreadingHTTPServer(("127.0.0.1", port), H) if "--serve" in sys.argv: print("serving on http://127.0.0.1:%d/ (Ctrl+C stops)" % port) srv.serve_forever() return t = threading.Thread(target=srv.serve_forever, daemon=True) t.start() got = urllib.request.urlopen("http://127.0.0.1:%d/" % port, timeout=10).read().decode() srv.shutdown() _show("served on http://127.0.0.1:%d/ and answered itself: %s" % (port, got[:300])) _show("(run it with --serve to keep it up)")'''
def branch(steps, i, P): """"[for each <thing>,] if <condition>" + the step that follows + an optional "otherwise <step>" = one move that applies the first step where the condition holds and the second (or nothing) where it does not; per item on a list""" m = re.match(r"^(for\s+(?:each|every)\s+\w+\s*,\s*)?if\s+(.+?)$", steps[i].strip(), re.I) if not m or i + 1 >= len(steps): return 0 cond = _cond(re.sub(r"^(?:it|they|the \w+|that|this)\s+(?:is\s+|are\s+)?", "", m.group(2).strip(), flags=re.I)) if not cond: return 0 per_item = bool(m.group(1)) or P.kind in ("list", "rows") then_txt = re.sub(r"^then\s+", "", steps[i + 1].strip(), flags=re.I) m2 = re.match(r"^(?:otherwise|else)[,\s]+(.+)$", steps[i + 2].strip(), re.I) if i + 2 < len(steps) else None
def inner(text): q = Prog() q.kind = "text" if per_item else P.kind move(text, q, None) return q
t = inner(then_txt) if not t.lines: return 0 e = inner(m2.group(1)) if m2 else None if m2 and not e.lines: return 0 n = len(P.extra) + 1 src = "def branch_%d(x):\n i = x\n if %s:\n%s\n" % (n, cond, "\n".join(" " + ln for ln in t.lines)) if e: src += " else:\n%s\n" % "\n".join(" " + ln for ln in e.lines) src += " return x" P.extra.append(src) P.imports.update(t.imports | (e.imports if e else set())) P.emit("x = [branch_%d(i) for i in x]" % n if per_item else "x = branch_%d(x)" % n, "list" if per_item else "value") return 3 if m2 else 2
def move(step, P, prev_names): s = step.strip() lo = s.lower() k = P.kind m = re.match(r"^(?:use|apply|call|run)\s+(?:the\s+)?(?:program\s+)?([A-Za-z0-9_]+)(\s+(?:on|to)\s+(?:it|them|this|that|the result))?$", s, re.I) if m and m.group(1) in KNOWN and m.group(1) not in DEFINED: if USE_SRC not in P.extra: P.extra.append(USE_SRC) return P.emit("x = _use(%r, %s)" % (m.group(1), "x" if m.group(2) else "None"), "value") # rows kept by a condition on a column: compared with a number, with the column's own average / median, or equal to a value m = re.match(r"^(?:keep|select|filter|take)\s+(?:only\s+)?(?:the\s+)?rows\s+(?:whose|where)\s+(?:the\s+)?(.+?)\s+(?:is|are)\s+" r"(greater than|more than|above|over|less than|below|under|at least|at most)\s+(?:the\s+)?(average|mean|median|" + NUM + r")$", s, re.I) if m: col, rel, ref = m.group(1).strip(), m.group(2).lower(), m.group(3).lower() op = ">" if rel in ("greater than", "more than", "above", "over") else "<" if rel in ("less than", "below", "under") else \ ">=" if rel == "at least" else "<=" if ROWS_SRC not in P.extra: P.extra.append(ROWS_SRC) if ref in ("average", "mean", "median"): fn = "statistics.median" if ref == "median" else "statistics.mean" return P.emit("x = (lambda t: [r for r in x if _cellnum(r, %r) is not None and _cellnum(r, %r) %s t])(%s([v for v in (_cellnum(r, %r) for r in x) if v is not None]))" % (col, col, op, fn, col), "rows", ["statistics"]) return P.emit("x = [r for r in x if _cellnum(r, %r) is not None and _cellnum(r, %r) %s %s]" % (col, col, op, ref), "rows") m = re.match(r"^(?:keep|select|filter|take)\s+(?:only\s+)?(?:the\s+)?rows\s+(?:whose|where)\s+(?:the\s+)?(.+?)\s+(?:is|are|=)\s+" + Q + r"$", s, re.I) if m: if ROWS_SRC not in P.extra: P.extra.append(ROWS_SRC) return P.emit("x = [r for r in x if str(_cell(r, %r)).strip().lower() == %r]" % (m.group(1).strip(), m.group(2).strip().lower()), "rows") # a function this program defines, called by name: "total it", "use total", "apply total to them", "total" m = re.match(r"^(?:use|apply|call|run|do)?\s*(?:the\s+)?([A-Za-z_][A-Za-z0-9_]*)(?:\s+(?:on|to|of|for)?\s*(?:it|them|this|that|the result))?$", s, re.I) if m and m.group(1) in DEFINED: return P.emit("x = %s(x)" % m.group(1), "value") # a page: the value as an HTML page in the sandbox (a table for rows and pairs, a list otherwise) m = re.match(r"^(?:make|write|save|build|show)\s+(?:it\s+as\s+|them\s+as\s+)?(?:an?\s+)?(?:html\s+)?page" r"(?:\s+(?:showing|of|for|with)\s+(?:it|them|the result))?(?:\s+(?:called|named|to|as|in)\s+" + Q + r")?$", s, re.I) if m: f = m.group(1) or "page.html" f = f if f.endswith(".html") else f + ".html" if PAGE_SRC not in P.extra: P.extra.append(PAGE_SRC) return P.emit("_page(x, %r)" % f, k, ["html"]) # a server: the value served as JSON at / (and the page at /page if one was made); run once it serves itself a request # and stops; run with --serve it stays up m = re.match(r"^(?:serve|host|publish)\s+(?:it|them|the result|the page)?(?:\s+(?:on|at)\s+port\s+(\d+))?$", s, re.I) if m: if SERVE_SRC not in P.extra: P.extra.append(SERVE_SRC) return P.emit("_serve(x, %s)" % (m.group(1) or "8765"), k, ["json", "http.server", "threading", "urllib.request", "sys"]) m = re.match(r"^(?:take|get|keep|find)\s+(?:the\s+)?(last|first)\s+word$", lo) if m: return P.emit("x = (str(x).split() or [''])[%s]" % ("-1" if m.group(1) == "last" else "0"), "text") m = re.match(r"^(?:take|get|keep)\s+(?:the\s+)?(last|first)\s+" + NUM + r"\s+(?:characters|chars|letters)$", lo) if m: n = int(float(m.group(2))) return P.emit("x = str(x)[-%d:]" % n if m.group(1) == "last" else "x = str(x)[:%d]" % n, "text") if re.match(r"^(?:take|get|find|compute|measure)\s+(?:the\s+)?(?:length|size)$", lo): return P.emit("x = len(x)", "num") if re.match(r"^reverse\b", lo): return P.emit("x = x[::-1]", k) m = re.match(r"^(?:read|open|load)\s+(?:the\s+)?(?:file\s+)?" + Q + r"(?:\s+file)?$", s, re.I) if m: f = m.group(1) if f.lower().endswith(".json"): return P.emit("x = json.load(open(%r))" % f, "rows", ["json"]) return P.emit("x = open(%r, encoding=\"utf-8\", errors=\"ignore\").read()" % f, "text") m = re.match(r"^(?:fetch|download|get)\s+(?:the\s+page\s+)?(https://\S+)", s, re.I) if m: P.extra.append(FETCH_SRC) return P.emit("x = fetch_text(%r)" % m.group(1).rstrip(".,"), "text", ["re", "urllib.request", "urllib.parse"]) if re.match(r"^(?:split|break|turn|cut)\b.*\blines?\b", lo): return P.emit("x = [l for l in str(x).splitlines() if l.strip()]", "list") if re.match(r"^(?:split|break|turn|cut)\b.*\bwords?\b", lo) or re.match(r"^extract\s+(?:the\s+)?words", lo): return P.emit("x = re.findall(r\"[A-Za-z']+\", str(x))", "list", ["re"]) m = re.match(r"^split\b.*\b(?:on|by)\s+" + Q + r"$", s, re.I) if m: sep = {"comma": ",", "commas": ",", "space": " ", "spaces": " ", "tab": "\t", "tabs": "\t"}.get(m.group(1).lower(), m.group(1)) return P.emit("x = [p.strip() for p in str(x).split(%r)]" % sep, "list") if re.match(r"^(?:make|turn|convert|change)\b.*\blower", lo) or lo.startswith("lowercase"): return P.emit("x = [str(i).lower() for i in x]" if k == "list" else "x = str(x).lower()", k) if re.match(r"^(?:make|turn|convert|change)\b.*\bupper", lo) or lo.startswith("uppercase"): return P.emit("x = [str(i).upper() for i in x]" if k == "list" else "x = str(x).upper()", k) if re.match(r"^(?:parse|read)\b.*\bcsv\b", lo): return P.emit("x = list(csv.DictReader(io.StringIO(str(x))))", "rows", ["csv", "io"]) if re.match(r"^(?:parse|read)\b.*\bjson\b", lo): return P.emit("x = json.loads(str(x))", "rows", ["json"]) m = re.match(r"^(?:take|get|keep|pick|select|use)\s+(?:only\s+)?(?:the\s+)?" + Q + r"\s+(?:column|field|key|value)s?$", s, re.I) if m: return P.emit("x = [r[%r] for r in x]" % m.group(1), "list") if re.match(r"^(?:convert|turn|make)\b.*\bnumbers?\b", lo): return P.emit("x = [float(i) for i in x]", "list") m = re.match(r"^extract\s+(?:all\s+)?(?:the\s+)?(numbers|emails?|urls?|links?|dates?|years?)", lo) if m: what = m.group(1) rx = {"numbers": NUM, "email": r"[\w.+-]+@[\w-]+\.[\w.]+", "url": r"https?://[^\s\"'<>]+", "link": r"https?://[^\s\"'<>]+", "date": r"\d{4}-\d{2}-\d{2}", "year": r"\b(1[5-9]\d\d|20\d\d)\b"}[what.rstrip("s") if what != "numbers" else "numbers"] conv = "float(n)" if what == "numbers" else "int(n)" if what.startswith("year") else "n" return P.emit("x = [%s for n in re.findall(%r, str(x))]" % (conv, rx), "list", ["re"]) m = re.match(r"^(keep|filter|select|pick|find|take)\s+(?:only\s+)?(?:the\s+)?(?:\w+\s+)?(?:that|which|where|whose|if|with|" r"containing|longer|shorter|greater|less|more|starting|ending|over|under|above|below)\b(.*)$", s, re.I) if m: c = _cond(s[len(m.group(1)):]) if c: return P.emit("x = [i for i in x if %s]" % c, "list") m = re.match(r"^(?:keep|filter|select|pick|take)\s+(?:only\s+)?(?:the\s+)?((?:non-?)?(?:even|odd|positive|negative|non-?negative|" r"empty|blank|non-?empty))\s+(?:numbers|values|items|ones|entries|lines|words|strings)?\s*(?:in it|from it|of it)?$", s, re.I) if m: # Amendment 13b: "keep the even numbers" - the kind named before the noun c = _cond(m.group(1)) if c: return P.emit("x = [i for i in x if %s]" % c, "list") m = re.match(r"^(?:remove|drop|exclude|delete|skip)\s+(?:the\s+)?((?:non-?)?(?:even|odd|positive|negative))\s+" r"(?:numbers|values|items|ones|entries)?\s*$", s, re.I) if m: c = _cond(m.group(1)) if c: return P.emit("x = [i for i in x if not (%s)]" % c, "list") m = re.match(r"^(?:remove|drop|exclude|delete|skip)\s+(?:the\s+)?(?:\w+\s+)?(?:that|which|where|whose|if|with|containing|" r"longer|shorter|greater|less|empty|blank|starting|ending)\b(.*)$", s, re.I) if m or re.match(r"^(?:remove|drop)\s+(?:the\s+)?(?:empty|blank)", lo): c = _cond(s.split(None, 1)[1] if " " in s else s) if c: return P.emit("x = [i for i in x if not (%s)]" % c, "list") if re.match(r"^(?:remove|drop)\s+(?:the\s+)?duplicates|^(?:dedupe|unique|keep\s+(?:only\s+)?(?:the\s+)?unique|make\s+.*unique)", lo): return P.emit("x = list(dict.fromkeys(x))", "list") if re.match(r"^count\b.*\b(?:each|every|how often|occurrences|frequenc)", lo) or re.match(r"^(?:tally|frequency)", lo): return P.emit("x = collections.Counter(x).most_common()", "pairs", ["collections"]) m = re.match(r"^(?:count|how many)\s+(?:the\s+)?(?:number\s+of\s+)?(words|lines|characters|chars|letters|sentences)\b", lo) if m and k in ("text", None): # the unit the step names is the unit counted expr = {"words": "len(str(x).split())", "lines": "len(str(x).splitlines())", "sentences": "len([p for p in re.split(r'[.!?]+', str(x)) if p.strip()])"}.get(m.group(1), "len(str(x))") return P.emit("x = " + expr, "num", ["re"] if m.group(1) == "sentences" else []) if re.match(r"^(?:count|how many)\b", lo): return P.emit("x = len(x)", "num") if re.match(r"^sort\b", lo): rev = bool(re.search(r"\b(desc|descending|largest|biggest|highest|most|reverse|decreasing)", lo)) if k == "pairs": key = "lambda p: p[1]" if re.search(r"\b(count|frequency|number|times|value)\b", lo) else "lambda p: p[0]" if re.search(r"\b(count|frequency)\b", lo) and not re.search(r"\b(asc|ascending|least|fewest|increasing)", lo): rev = True elif re.search(r"\blength\b", lo): key = "len" elif re.search(r"\b(value|number|numerically|size)\b", lo): key = "float" else: m2 = re.search(r"\bby\s+(?:the\s+)?" + Q + r"(?:\s+(?:column|field))?(?:\s+(?:asc|desc)\w*)?$", s, re.I) key = ("lambda r: r[%r]" % m2.group(1)) if (m2 and k == "rows") else None return P.emit("x = sorted(x%s%s)" % (", key=%s" % key if key else "", ", reverse=True" if rev else ""), k) m = re.match(r"^(?:take|keep|get|show|print|return)\s+(?:only\s+)?(?:the\s+)?(?:top|first|last)\s+" + NUM, lo) if m: n = int(float(m.group(1))) line = "x = x[-%d:]" % n if " last " in " %s " % lo else "x = x[:%d]" % n P.emit(line, k) if re.match(r"^(?:print|show)", lo): P.emit("print(x)", k) return m = re.search(r"\b(median|mode|standard deviation|stdev|std|variance)\b", lo) if m and re.match(r"^(?:compute|calculate|find|take|get|work out)?\s*(?:the\s+)?(?:population\s+)?" r"(median|mode|standard deviation|stdev|std|variance)\b", lo): fn = {"median": "median", "mode": "mode", "standard deviation": "stdev", "stdev": "stdev", "std": "stdev", "variance": "variance"}[m.group(1)] if "population" in lo and fn in ("stdev", "variance"): fn = "p" + fn return P.emit("x = statistics.%s([float(i) for i in x]) if %s else None" % (fn, "len(x) > 1" if fn in ("stdev", "variance") else "x"), "num", ["statistics"]) if re.match(r"^(?:sum|add|total)\b", lo): return P.emit("x = sum(float(i) for i in x)", "num") if re.match(r"^(?:average|mean|find the average|compute the average|calculate the average)", lo) or "average" in lo: return P.emit("x = sum(float(i) for i in x) / len(x) if x else 0.0", "num") if re.match(r"^(?:find\s+the\s+)?(?:max|maximum|largest|biggest|highest)", lo): return P.emit("x = max(x, key=lambda p: p[1]) if x and isinstance(x[0], tuple) else max(x)", "num") if re.match(r"^(?:find\s+the\s+)?(?:min|minimum|smallest|lowest)", lo): return P.emit("x = min(x, key=lambda p: p[1]) if x and isinstance(x[0], tuple) else min(x)", "num") m = re.match(r"^replace\s+" + Q + r"\s+with\s+" + Q + r"$", s, re.I) if m: a, b = m.group(1), m.group(2) return P.emit("x = [str(i).replace(%r, %r) for i in x]" % (a, b) if k == "list" else "x = str(x).replace(%r, %r)" % (a, b), k) if re.match(r"^(?:hash|compute the hash|take the hash)\b", lo) or "sha256" in lo: m = re.search(r"\b(?:hash|of)\s+" + Q + r"\s+with\b", s, re.I) if m and "." in m.group(1): P.emit("x = open(%r, \"rb\").read()" % m.group(1), "bytes") return P.emit("x = hashlib.sha256(x if isinstance(x, bytes) else str(x).encode()).hexdigest()", "text", ["hashlib"]) m = re.match(r"^join\b.*?(?:with|by|using)\s+" + Q + r"$", s, re.I) if m or re.match(r"^join\b", lo): sep = (m.group(1) if m else " ") sep = {"comma": ", ", "commas": ", ", "newline": "\n", "newlines": "\n", "space": " ", "spaces": " "}.get(sep.lower(), sep) return P.emit("x = %r.join(str(i) for i in x)" % sep, "text") m = re.match(r"^(?:write|save|store)\b.*?(?:to|in|into|as)\s+" + Q + r"$", s, re.I) if m: f = m.group(1) if f.endswith(".json"): return P.emit("json.dump(x, open(%r, \"w\"), indent=1)" % f, k, ["json"]) return P.emit("open(%r, \"w\").write(x if isinstance(x, str) else \"\\n\".join(map(str, x)))" % f, k) if re.match(r"^(?:print|show|display|output|return)\b", lo): if k == "pairs": return P.emit("print(\"\\n\".join(\"%s\\t%s\" % p for p in x))", k) if k == "list": return P.emit("print(\"\\n\".join(map(str, x)))", k) return P.emit("print(x)", k) return None
FETCH_SRC = '''def fetch_text(url): """a page from the verified sources, as text""" host = urllib.parse.urlparse(url).netloc.lower() if host not in VERIFIED: raise ValueError(host + " is not on the verified list") req = urllib.request.Request(url, headers={"User-Agent": "Oracle7-make/12.0"}) t = urllib.request.urlopen(req, timeout=30).read(5_000_000).decode("utf-8", "ignore") m = re.search(r'(?s)id="mw-content-text".*', t) t = m.group(0) if m else t t = re.sub(r"(?is)<(script|style).*?</\\1>", " ", t) return re.sub(r"\\s+", " ", re.sub(r"(?s)<[^>]+>", " ", t)).strip()'''
def workspace_move(step, P, find_fn, read_rec): """no language move fits: a workspace function that does this step, copied in with its file's imports""" hits = find_fn(step) if not hits: return False, [] best, score = hits[0] named = getattr(find_fn, "named", None) # the step NAMES a workspace function: exact, no threshold if named: # sealed v3 (w04): "of each line" named the workspace function line(). Only the thing the step acts on counts: the # first word after the verb and its articles (joined with the next word as one name too: standard_deviation). ws = re.findall(r"[a-z_][a-z0-9_]*", step.lower()) while ws and ws[0] in {"compute", "calculate", "find", "take", "get", "work", "out", "apply", "the", "a", "an", "its", "their", "then", "and"}: ws.pop(0) cands = ([ws[0] + "_" + ws[1]] if len(ws) > 1 else []) + ws[:1] # sealed v5 (z10): "train a neural network on it" named an unrelated train(). A named function is taken only when # every other content word of the step is in the function's own name or description. filler = {"it", "them", "this", "that", "on", "of", "to", "for", "in", "with", "a", "an", "the", "result", "each", "every", "and", "by", "from", "into", "all", "its", "their"} rest = [w for w in ws if w not in filler and len(w) > 2] for w in cands: rec = named(w) if len(w) > 2 else None if rec: own = set(re.findall(r"[a-z]+", (rec["name"] + " " + rec.get("doc", "")).lower().replace("_", " "))) if all(x in own or x in w.split("_") for x in rest): best, score = rec, 1.0 break near = ["%s (%s, %.2f)" % (h["name"], h["path"], s) for h, s in hits[:3]] required = getattr(find_fn, "required", None) # inputs without a default, read from the function's definition nreq = required(best) if required else len([a for a in best["args"] if a != "self"]) if score < 0.80 or best["kind"] != "def" or nreq != 1 or "self" in best["args"]: return False, near src, imps = read_rec(best) if not src: return False, near P.extra.append(src) P.imports.update(imps) P.emit("x = %s(x)" % best["name"], "value") P.trace.append("workspace: %s from %s" % (best["name"], best["path"])) return True, near
HEADER = re.compile(r"^\s*(?:function|define|def|to)\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:\([^)]*\))?\s*:\s*(.*)$", re.I | re.S)PARAMS_RX = re.compile(r"^\s*(?:function|define|def|to)\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\)", re.I)FPARAMS = {} # Amendment 13b: a function's inputs as its header names them ("function big_total(xs, limit): ...")MAINH = re.compile(r"^\s*(?:main|then|finally|the program)\s*:\s*(.*)$", re.I | re.S)
def blocks_of(desc): """a program of several functions: "function <name>: <steps>; function <name>: <steps>; main: <steps>". Segments are cut at ";" and new lines; a segment with a header opens a function; the rest belongs to main. -> [(name or None, text)]""" body = re.sub(r"\bexpect(?:ing)?\b.*$", "", desc, flags=re.I | re.S) segs = [s for s in re.split(r";|\n", body) if s.strip()] if not any(HEADER.match(s) for s in segs): return [(None, desc)] out, cur = [], [None, []] for s in segs: h, m = HEADER.match(s), MAINH.match(s) if h: if cur[1]: out.append((cur[0], ", ".join(cur[1]))) cur = [h.group(1), [h.group(2)] if h.group(2).strip() else []] elif m: if cur[1]: out.append((cur[0], ", ".join(cur[1]))) cur = [None, [m.group(1)] if m.group(1).strip() else []] else: cur[1].append(s) if cur[1]: out.append((cur[0], ", ".join(cur[1]))) return out
DEFINED = set()
_COMPOSE_LOCK = threading.RLock()
def compose(desc, find_fn, read_rec): with _COMPOSE_LOCK: return _compose(desc, find_fn, read_rec)
def _compose(desc, find_fn, read_rec): """one program from a description: its functions first (each composed from its own steps, x in, x out), then main, whose steps may call them by name ("total it", "use total")""" global NUMP FPARAMS.clear() for seg in re.split(r";|\n", re.sub(r"\bexpect(?:ing)?\b.*$", "", desc, flags=re.I | re.S)): pm = PARAMS_RX.match(seg) if pm: FPARAMS[pm.group(1)] = [a.strip() for a in pm.group(2).split(",") if re.fullmatch(r"\s*[A-Za-z_]\w*\s*", a)] blocks = blocks_of(desc) DEFINED.clear() DEFINED.update(n for n, _ in blocks if n) fns, gaps, trace, imports = [], [], [], set() for name, text in blocks: if not name: continue params = FPARAMS.get(name) or [] extra_in = [p for p in params[1:] if p != "x"] NUMP = (r"(-?\d+(?:\.\d+)?|" + "|".join(re.escape(p) for p in extra_in) + r")") if extra_in else NUM Q = Prog() try: compile_steps(steps_of(text), Q, find_fn, read_rec) finally: NUMP = NUM gaps += ["in %s: %s" % (name, g) for g in Q.gaps] trace += ["%s: %s" % (name, t) for t in Q.trace] imports |= Q.imports body = "\n".join(" " + (("_show(" + ln[len("print("):]) if ln.startswith("print(") else ln) for ln in Q.lines) or " pass" if params: # the first input is the value the steps start from; the others are named head = "def %s(%s):\n" % (name, ", ".join(params)) + (" x = %s\n" % params[0] if params[0] != "x" else "") else: head = "def %s(x):\n" % name fns.append((Q.extra, "%s%s\n return x" % (head, body))) main_text = ", ".join(t for n, t in blocks if not n) P = Prog() for extra, src in fns: for e in extra: if e not in P.extra: P.extra.append(e) P.extra.append(src) P.imports |= imports P.trace += trace if main_text.strip(): compile_steps(steps_of(main_text), P, find_fn, read_rec) P.gaps = gaps + P.gaps return finish(P)
def compile_steps(steps, P, find_fn, read_rec): j = 0 while j < len(steps): st, i = steps[j], j + 1 n0 = len(P.lines) try: used = branch(steps, j, P) except Exception as e: # noqa: BLE001 used = 0 P.gaps.append("step %d (%s): the branch raised %s" % (i, st, e)) if used: P.trace.append("step %d-%d: %s -> %s" % (i, i + used - 1, " / ".join(steps[j:j + used]), P.lines[-1])) j += used continue j += 1 try: if not each(st, P): move(st, P, None) except Exception as e: # noqa: BLE001 P.gaps.append("step %d (%s): the move raised %s" % (i, st, e)) continue if len(P.lines) > n0: P.trace.append("step %d: %s -> %s" % (i, st, P.lines[-1])) continue ok, near = workspace_move(st, P, find_fn, read_rec) if not ok: P.gaps.append("step %d (%s): no move of the language does this and no workspace function fits it%s" % ( i, st, ("; nearest: " + "; ".join(near)) if near else "")) return P
def finish(P): if P.lines and not any(ln.startswith(("print(", "x = _serve(", "_serve(")) for ln in P.lines): P.emit("print(x)" if P.kind not in ("list", "pairs") else ("print(\"\\n\".join(map(str, x)))" if P.kind == "list" else "print(\"\\n\".join(\"%s\\t%s\" % p for p in x))"), P.kind) if "fetch_text" in "\n".join(P.extra): P.extra.insert(0, "VERIFIED = %r" % VERIFIED_LIST) src = P.source() ast.parse(src) return src, P
VERIFIED_LIST = []
def expected_of(desc): m = re.search(r"\bexpect(?:ing)?\s*:?\s*(.+)$", desc, re.I | re.S) return m.group(1).strip().strip("'\"") if m else None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""o7_browser - open the Oracle7 harness page on this computer while Oracle7 runs on the box.
python o7_browser.py (defaults: host o7research, port 8199 here, 8231 there)
python o7_browser.py --host o7research --local 8199 --remote 8231
It starts one ordinary ssh session to the box that runs relay.py there (the box needs no port forwarding), serves the page
at http://127.0.0.1:8199/ here, and carries each request of the page through that session. Close this window to stop; the
harness server it started on the box stops with it. Python standard library only; needs ssh with your key for the host."""
import argparse
import functools
import base64
import http.server
import json
import subprocess
import sys
import threading
import webbrowser
ap = argparse.ArgumentParser()
ap.add_argument("--host", default="o7research")
ap.add_argument("--local", type=int, default=8199)
ap.add_argument("--remote", type=int, default=8231)
ap.add_argument("--tree", default="/opt/rel12/w")
ap.add_argument("--relay", default=None, help="default: the tree's own workbench/relay.py")
ap.add_argument("--state", default="/opt/o7conv/state_runs/browser")
ap.add_argument("--cmd", default=None, help="run this instead of ssh (testing on the box itself)")
ap.add_argument("--no-open", action="store_true")
a = ap.parse_args()
print = functools.partial(print, flush=True) # noqa: A001 (the lines show at once, also into a log)
a.relay = a.relay or a.tree.rstrip("/") + "/workbench/relay.py"
far = a.cmd or "ssh -o BatchMode=yes -o ServerAliveInterval=30 %s python3 %s %d %s %s" % (a.host, a.relay, a.remote, a.tree, a.state)
print("Connecting to %s (the harness may take a minute or two to load the first time) ..." % (a.host if not a.cmd else "relay"))
P = subprocess.Popen(far, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=0)
hello = json.loads(P.stdout.readline() or b"{}")
if not hello.get("ready"):
print("The harness on %s did not come up: %s" % (a.host, hello))
sys.exit(1)
ID = hello.get("identity") or {}
if ID.get("error") or not ID.get("build"): # 12.0 C11: what runs is named, not assumed from a 200 at /
print("The harness answered but did not say what it runs: %s" % (ID.get("error") or ID))
sys.exit(1)
print("Running build %s: tree %s, state %s, pid %s, version %s; workbench %s (%s files)%s%s" % (
ID["build"], ID["tree"], ID["state"], ID["pid"], ID.get("version"), ID["workbench_at_start"]["sha256"][:16],
ID["workbench_at_start"]["files"], "" if ID.get("running_is_release") else
" - NOT the assembled release's workbench (%s)" % (ID.get("workbench_in_release") or {}).get("sha256", "?")[:16],
"" if ID.get("running_is_on_disk") else " - files changed on disk since it started: %s (restart it to load them)" %
", ".join(ID.get("loaded_but_changed_on_disk") or ["the workbench"])))
WLOCK = threading.Lock() # writing a request line; replies come back by id, in any order
N = [0]
WAIT = {}
def reader():
for line in iter(P.stdout.readline, b""):
try:
r = json.loads(line)
except ValueError:
continue
w = WAIT.get(r.get("id"))
if w:
w[1] = r
w[0].set()
for w in list(WAIT.values()): # the link closed: everyone waiting is told
w[0].set()
threading.Thread(target=reader, daemon=True).start()
def carry(method, path, headers, body):
with WLOCK:
N[0] += 1
n = N[0]
WAIT[n] = [threading.Event(), None]
P.stdin.write((json.dumps({"id": n, "method": method, "path": path, "headers": headers,
"body": base64.b64encode(body).decode() if body else None}) + "\n").encode())
P.stdin.flush()
WAIT[n][0].wait()
r = WAIT.pop(n)[1]
if not r:
return 502, {"Content-Type": "text/plain"}, b"the link to the box closed"
return r["status"], r["headers"], base64.b64decode(r["body"])
class H(http.server.BaseHTTPRequestHandler):
def _go(self, method):
n = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(n) if n else None
code, hdrs, out = carry(method, self.path, dict(self.headers), body)
self.send_response(code)
for k, v in hdrs.items():
self.send_header(k, v)
self.send_header("Content-Length", str(len(out)))
self.end_headers()
self.wfile.write(out)
def do_GET(self): # noqa: N802
self._go("GET")
def do_POST(self): # noqa: N802
self._go("POST")
def log_message(self, *args):
pass
srv = http.server.ThreadingHTTPServer(("127.0.0.1", a.local), H)
url = "http://127.0.0.1:%d/" % a.local
print("Oracle7 harness: %s (Ctrl+C to stop)" % url)
if not a.no_open:
webbrowser.open(url)
try:
srv.serve_forever()
except KeyboardInterrupt:
pass
finally:
P.stdin.close()
P.wait(15)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216"""planner - build what you want, not only what you spell out (12.0; the Pokemon satellite's shape pointed at building: read theworld's real rules, chain backward from the goal, name the blocker).
world the files in the sandbox, read: for a table, its columns, which hold numbers, a few values of each goal what you want, read for its parts: the result's form (a page, served, a count, a total, an average, the largest, a list), the thing it is about (a column, by its name or a word for it), conditions ("whose amount is above average", "where city is leeds", "over 20"), the source ("from sales.csv", or the one table that has those columns) need backward: the form needs a value of some kind; each kind is given by a step that needs another kind; the chain stops at a file in the sandbox. Each link records why it is there. steps the chain, forward, written in make's own words; make builds, runs, repairs and checks it as alwaysA part of the goal no link can give is named (the column that is not in any file, the condition it cannot read), never guessed.No language model."""import csvimport ioimport refrom pathlib import Path
NUMW = r"(-?\d+(?:\.\d+)?)"
def stem(w): w = w.lower() for s in ("ies", "es", "s"): if len(w) > len(s) + 2 and w.endswith(s): return w[: -len(s)] + ("y" if s == "ies" else "") return w
def read_world(sandbox): """the tables in the sandbox: {file: {"cols": [...], "numeric": set, "values": {col: [few]}}}""" world = {} for p in sorted(Path(sandbox).glob("*")): if p.suffix.lower() not in (".csv", ".tsv") or not p.is_file(): continue text = p.read_text(errors="ignore") rows = list(csv.DictReader(io.StringIO(text), delimiter="\t" if p.suffix.lower() == ".tsv" else ",")) if not rows: continue cols = list(rows[0].keys()) numeric = set() for c in cols: vals = [str(r.get(c, "")).strip() for r in rows if str(r.get(c, "")).strip()] if vals and all(re.fullmatch(r"[$£€]?-?[\d,]*\.?\d+%?", v) for v in vals): numeric.add(c) world[p.name] = {"cols": cols, "numeric": numeric, "values": {c: [r.get(c) for r in rows[:50]] for c in cols}} return world
def forms(word): """the word and its singular readings (names -> name, nam; cities -> city; boxes -> box)""" w = word.lower() out = {w, stem(w)} if w.endswith("s") and len(w) > 3: out.add(w[:-1]) return out
def find_col(word, info): """a column the word names: its header, the header's stem, or a header the word is part of (plurals read both ways: sealed want v1 p03/p10 - 'names' was cut to 'nam' and missed the column 'name')""" ws = forms(word) for c in info["cols"]: k = re.sub(r"[^a-z0-9]+", " ", c.lower()).strip() if ws & (forms(k) | {f for x in k.split() for f in forms(x)}): return c return None
def find_value_col(word, info): """a column one of whose values is the word (\"leeds\" -> city)""" for c, vals in info["values"].items(): if any(str(v).strip().lower() == word.lower() for v in vals): return c return None
def plan(goal, sandbox): """-> (steps text for make, [why ...]) or (None, [the blocker])""" g = goal.strip().rstrip(".") # Amendment 13: a written comparison is read, never dropped ("amount > 10" was planned as no filter at all) g = re.sub(r"\s*>=\s*", " at least ", g) g = re.sub(r"\s*<=\s*", " at most ", g) g = re.sub(r"\s*>\s*", " over ", g) g = re.sub(r"\s*<\s*", " under ", g) lo = g.lower() world = read_world(sandbox) if not world: return None, ["there is no table (csv) in the sandbox to build this from; write or fetch one there first"] m = re.search(r"\b(?:from|in|of|using)\s+([\w.-]+\.(?:csv|tsv))\b", g, re.I) words = re.findall(r"[a-z][a-z0-9_]+", lo) if m and m.group(1) in world: src = m.group(1) elif m: return None, ["there is no %s in the sandbox" % m.group(1)] else: # the table the goal is about: its name, its columns and its values, as the goal names them def table_score(f, i): s = sum(2 for w in words if find_col(w, i)) + sum(1 for w in words if find_value_col(w, i)) return s + (2 if any(stem(w) == stem(Path(f).stem) for w in words) else 0) score = {f: table_score(f, i) for f, i in world.items()} src = max(score, key=score.get) if not score[src]: return None, ["none of the tables in the sandbox (%s) has a name, column or value your goal names" % ", ".join(world)] info = world[src] why = ["read the world: %s has columns %s (numbers: %s)" % (src, ", ".join(info["cols"]), ", ".join(sorted(info["numeric"])) or "none")]
# the result's form form = "print" if re.search(r"\b(page|html|report|web ?page)\b", lo): form = "page" if re.search(r"\b(serve|server|host|api|endpoint)\b", lo): form = "serve" if form != "page" else "page+serve" # what is asked of the values, read with the conditions taken out ("whose amount is above average" asks for no average) # and with a word that is a column of the table left as the column ("the average total": total is the column) cond_rx = (r"\b(?:whose|where|with|that have|having)\s+(?:the\s+)?[a-z][a-z ]*?\s+(?:is|are|was|were)?\s*(?:above|below|over|" r"under|more than|less than|greater than|at least|at most)\s+(?:the\s+)?(?:average|mean|median|-?\d+(?:\.\d+)?)") asked = re.sub(cond_rx, " ", lo) colword = lambda w: find_col(w, info) is not None agg = None for pat, a in ((r"\bhow many\b|\bcount of\b|\bnumber of\b", "count"), (r"\baverage\b|\bmean\b", "average"), (r"\bmedian\b", "median"), (r"\b(largest|biggest|highest|max(?:imum)?)\b", "max"), (r"\b(smallest|lowest|min(?:imum)?)\b", "min"), (r"\bsum\b|\badd up\b", "sum"), (r"\btotal\b", "sum")): mm = re.search(pat, asked) if mm and not (mm.group(0) == "total" and colword("total")): # "total" that is a column names the column agg = a break
# conditions, read before the subject so their words are not taken for it conds, used = [], set() for cm in re.finditer(r"\b(?:whose|where|with|that have|having)\s+(?:the\s+)?([a-z][a-z ]*?)\s+(?:is|are|was|were)?\s*" r"(above|below|over|under|more than|less than|greater than|at least|at most)\s+(?:the\s+)?(average|mean|median|" + NUMW + r")", lo): col = find_col(cm.group(1).split()[-1], info) if not col: return None, why + ["the condition names %r, which is not a column of %s (%s)" % (cm.group(1), src, ", ".join(info["cols"]))] if col not in info["numeric"]: return None, why + ["%s is compared as a number, but %s holds text" % (cm.group(1), col)] op = ("at least" if cm.group(2) == "at least" else "at most" if cm.group(2) == "at most" else # Amendment 13: "greater than" if cm.group(2) in ("above", "over", "more than", "greater than") else "less than") # not made strict conds.append("keep rows whose %s is %s %s" % (col, op, cm.group(3))) used |= set(cm.group(0).split()) why.append("the goal wants only rows whose %s is %s %s: a filter on the parsed rows" % (col, op, cm.group(3))) for cm in re.finditer(r"\b(?:where|whose|in|for)\s+(?:the\s+)?([a-z]+)\s+(?:is|=)\s+([a-z0-9]+)\b", lo): if cm.group(0) in " ".join(conds): continue col = find_col(cm.group(1), info) if col and col not in info["numeric"]: conds.append("keep rows whose %s is %s" % (col, cm.group(2))) used |= set(cm.group(0).split()) why.append("the goal wants only rows whose %s is %s" % (col, cm.group(2))) for w in words: # a bare value names its column ("in leeds" -> city is leeds) if w in used: continue c = find_value_col(w, info) if c and not find_col(w, info) and not any(("whose %s is" % c) in x for x in conds): conds.append("keep rows whose %s is %s" % (c, w)) why.append("%r is a value of %s: keep the rows that have it" % (w, c))
# the subject: the column the result is about (the first column the goal names outside its conditions) subject = None for w in words: if w in used: continue c = find_col(w, info) if c: subject = c break if agg in ("sum", "average", "max", "min", "median") and (subject is None or subject not in info["numeric"]): nums = [c for c in info["numeric"] if any(find_col(w, {"cols": [c]}) for w in words)] or sorted(info["numeric"]) if not nums: return None, why + ["the goal asks for a %s, and %s has no column of numbers" % (agg, src)] subject = nums[0]
# every word of the goal must be accounted for: a part it names, a word of form or of what is asked, or a plain function word. # A word no link uses is the blocker, named - never planned around (the satellite's rule: name what blocks, do not guess) known = set(words) & ({"a", "an", "the", "of", "in", "on", "for", "from", "to", "with", "and", "or", "all", "me", "my", "show", "list", "give", "get", "find", "what", "which", "who", "is", "are", "was", "were", "there", "that", "this", "these", "those", "please", "want", "make", "build", "each", "every", "their", "its", "by", "page", "html", "report", "web", "webpage", "serve", "server", "host", "api", "endpoint", "served", "how", "many", "much", "count", "number", "total", "sum", "add", "up", "average", "mean", "median", "largest", "biggest", "highest", "max", "maximum", "smallest", "lowest", "min", "minimum", "whose", "where", "having", "have", "above", "below", "over", "under", "more", "less", "than", "greater", "least", "most", "at", "it", "them", "do", "does", "using", "csv", "tsv", "rows", "row", "values", "value", "ones", "items", "entries", "column", "columns", "table", "file", "field"}) for w in words: if (w in known or w in used or find_col(w, info) or find_value_col(w, info) or stem(w) == stem(Path(src).stem) or re.fullmatch(r"\d+", w) or w in Path(src).name.lower()): continue return None, why + ["I cannot read %r in your goal: it is not a column of %s (%s), not one of its values, and not something I " "know how to do; say it with a column's name (for example: whose %s is more than 2)" % ( w, src, ", ".join(info["cols"]), sorted(info["numeric"])[0] if info["numeric"] else info["cols"][0])]
# need, backward: form <- value <- (aggregate <- numbers <- column) | column | rows <- filters <- rows <- parse <- read chain = [] if form in ("page", "page+serve"): chain.append(("make a page called %s" % re.sub(r"[^a-z0-9]+", "_", (subject or "result").lower()).strip("_"), "a page needs a value to show")) if form in ("serve", "page+serve"): chain.append(("serve it on port 8790", "serving needs a value to answer with")) if form == "print" or agg: chain.append(("print it", "the result is shown")) if agg == "count": chain.append(("count them", "how many = the number of items")) elif agg: chain.append(({"sum": "sum them", "average": "average them", "max": "find the maximum", "min": "find the minimum", "median": "compute the median"}[agg], "a %s needs numbers" % agg)) chain.append(("convert to numbers", "numbers need the column's values read as numbers")) if subject and (agg != "count" or form != "print" or True): if not (agg == "count" and not subject): chain.append(("take the %s column" % subject, "the result is about %s: its column of the rows" % subject)) for c in reversed(conds): chain.append((c, "only some rows are wanted")) chain.append(("parse it as csv", "rows need the table parsed")) chain.append(("read %s" % src, "the table is %s, in the sandbox" % src)) steps = [s for s, _ in reversed(chain)] why += ["%s <- because %s" % (s, w) for s, w in reversed(chain)] return ", ".join(steps), why123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""Read back a received program's behavior in fresh fixture directories."""import contextlibimport importlib.utilimport ioimport jsonimport mathfrom pathlib import Pathimport sysimport tempfile
def same(actual, expected): if isinstance(actual, bool) or isinstance(expected, bool): return type(actual) is type(expected) and actual == expected if isinstance(actual, (int, float)) and isinstance(expected, (int, float)): return math.isfinite(actual) and math.isfinite(expected) and actual == expected if type(actual) is not type(expected): return False if isinstance(actual, dict): return actual.keys() == expected.keys() and all(same(actual[k], expected[k]) for k in actual) if isinstance(actual, list): return len(actual) == len(expected) and all(same(a, b) for a, b in zip(actual, expected)) return actual == expected
def check(request): import os source = Path(request['source']).read_bytes() received = request['examples'] if not received: raise ValueError('receive at least one input and its expected result') old = Path.cwd() active = {'root': None} def guard(event, args): root = active['root'] if root is None: return if event.startswith(('socket.', 'subprocess.', 'os.exec', 'os.spawn')) or event in ('os.system', 'os.fork'): raise PermissionError('behavior examples do not authorize outside effects') if event == 'open' and isinstance(args[0], (str, bytes, os.PathLike)): path = Path(os.fsdecode(args[0])).resolve() mode, flags = args[1], args[2] writing = (isinstance(mode, str) and any(c in mode for c in 'wax+')) or flags & (os.O_WRONLY | os.O_RDWR | os.O_APPEND | os.O_CREAT | os.O_TRUNC) if path != root and root not in path.parents and (writing or path.suffix not in ('.py', '.pyc', '.pyd')): raise PermissionError('behavior examples may access only their received fixture files') if event in ('os.remove', 'os.rename', 'os.mkdir', 'os.rmdir', 'os.link', 'os.symlink'): raise PermissionError('behavior examples do not authorize filesystem structure changes') sys.addaudithook(guard) try: for number, example in enumerate(received): with tempfile.TemporaryDirectory(prefix='oracle7-program-example-') as directory: root = Path(directory) for name, contents in example.get('files', {}).items(): path = (root / name).resolve() if root not in path.parents or not isinstance(contents, str): raise ValueError('example files must be relative text files') path.parent.mkdir(parents=True, exist_ok=True) path.write_text(contents, encoding='utf-8') os.chdir(root) path = root / '_received_program.py' path.write_bytes(source) spec = importlib.util.spec_from_file_location('_received_program_' + str(number), path) module = importlib.util.module_from_spec(spec) with contextlib.redirect_stdout(io.StringIO()): active['root'] = root try: exec(compile(source, str(path), 'exec'), module.__dict__) module._SHOW = False actual = module.run(example.get('input')) finally: active['root'] = None if not same(actual, example['expected']): raise AssertionError('example %d expected %r, received %r' % (number + 1, example['expected'], actual)) os.chdir(old) finally: os.chdir(old) return {'ok': True, 'examples': len(received), 'basis': 'received inputs and expected values; separate execution'}
if __name__ == '__main__': print(json.dumps(check(json.loads(Path(sys.argv[1]).read_text(encoding='utf-8')))))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407"""Connect described state/event relationships to the existing browser program part.
Every accepted clause has an exact source receipt. Unknown behavior remains anowned hole; this part never treats a retained description as a finished build.The named grammar is about executable relationships, not application templates."""import copyimport hashlibimport jsonimport re
NAME = r'[A-Za-z][A-Za-z0-9_]{0,63}'NUM = r'[+-]?(?:\d+(?:\.\d+)?|\.\d+)'PREFIX = r'(?:(?:please|(?:can|could|would) you(?: please)?)\s+)?'INTRO = (PREFIX + r'(?:build|create|make|i (?:need|want)(?: to build)?)\s+(?:a |an |the )?' r'(?:(?:local|small|simple|interactive)\s+)*(?:(?:browser|web)\s+)?(?:app|application|program|counter|checklist|panel)\b')
def _literal(text): text = text.strip().strip('`') if len(text) >= 2 and text[0] == text[-1] and text[0] in '\"\'': return text[1:-1] if re.fullmatch(NUM, text): return float(text) if '.' in text else int(text) if text.lower() in ('true', 'false'): return text.lower() == 'true' if re.fullmatch(NAME, text): return text raise ValueError('name a quoted text value, number, or boolean')
def _type(value): return 'boolean' if isinstance(value, bool) else 'integer' if isinstance(value, int) else 'number' if isinstance(value, float) else 'string'
def _split(text, pattern): """Split outside quoted strings; preserve offsets in the received turn.""" masked = list(text) for quoted in re.finditer(r'"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'|`[^`]*`', text): masked[quoted.start():quoted.end()] = ' ' * (quoted.end() - quoted.start()) start = 0 for match in re.finditer(pattern, ''.join(masked), re.I): if text[start:match.start()].strip(): yield start, text[start:match.start()] start = match.end() if text[start:].strip(): yield start, text[start:]
def _event_id(label): return label.lower()
def _hole(kind, text, needed, event=None): result = {'id': 'P' + hashlib.sha256((kind + ':' + text + ':' + str(event)).encode()).hexdigest()[:10], 'kind': kind, 'text': text, 'needed': needed} if event: result['event'] = event return result
def _guard(text, state): """Resolve explicit conditions; shorthand needs one possible owning field.""" match = re.fullmatch(r'(?:only\s+)?(?:when|if)\s+(' + NAME + r')\s+(?:is\s+)?(?:(not|below|above|less than|greater than|at least|at most)\s+)?(.+)', text, re.I) if match: field, compare, val = match.groups() if field not in state: raise ValueError('condition needs declared field ' + field) value = _literal(val) op = {None: 'eq', 'not': 'ne', 'below': 'lt', 'less than': 'lt', 'above': 'gt', 'greater than': 'gt', 'at least': 'ge', 'at most': 'le'}[compare.lower() if compare else None] return {'field': field, 'compare': op, 'value': value} match = re.fullmatch(r'(?:only\s+)?in\s+(.+)', text, re.I) if match: value = _literal(match[1]) fields = [name for name, schema in state.items() if schema['type'] == _type(value)] if len(fields) != 1: raise ValueError('name the field for condition ' + text) return {'field': fields[0], 'compare': 'eq', 'value': value} raise ValueError('name one explicit state condition for this event')
def _action(text, fields): text = re.sub(r'^(?:it\s+)?(?:should\s+)?', '', text.strip(), flags=re.I) match = re.fullmatch(r'(?:increases?|decreases?)\s+(' + NAME + r')(?:\s+by\s+(' + NUM + r'))?', text, re.I) if match: return {'kind': 'delta', 'field': match[1], 'value': _literal(match[2]) if match[2] else None, 'sign': -1 if text.lower().startswith('decrease') else 1} match = re.fullmatch(r'(?:adds?|subtracts?)\s+(' + NUM + r')\s+(?:to|from)\s+(' + NAME + r')', text, re.I) if match: if text.lower().startswith('add') and fields.get(match[2], {}).get('type') == 'array': return {'kind': 'append', 'field': match[2], 'value': _literal(match[1])} return {'kind': 'delta', 'field': match[2], 'value': _literal(match[1]), 'sign': -1 if text.lower().startswith('subtract') else 1} match = re.fullmatch(r'(?:sets?|changes?)\s+(' + NAME + r')\s+to\s+(.+)', text, re.I) if match: return {'kind': 'set', 'field': match[1], 'value': _literal(match[2])} match = re.fullmatch(r'(?:adds?|appends?|removes?)\s+(.+?)\s+(?:to|from)\s+(' + NAME + r')', text, re.I) if match: return {'kind': 'remove' if text.lower().startswith('remove') else 'append', 'field': match[2], 'value': _literal(match[1])} raise ValueError('name a set, numeric change, list addition, or list removal')
def _test_guard(guard, values): if not guard: return True a, b = values[guard['field']], guard['value'] return {'eq': lambda: type(a) == type(b) and a == b, 'ne': lambda: type(a) != type(b) or a != b, 'lt': lambda: a < b, 'le': lambda: a <= b, 'gt': lambda: a > b, 'ge': lambda: a >= b}[guard['compare']]()
def _expected(event, values): """Interpret received changes, independently of the compiled action graph.""" result = copy.deepcopy(values) for action in event['changes']: field, value = action['field'], action['value'] if action['kind'] == 'delta': result[field] += value * action['sign'] elif action['kind'] == 'set': result[field] = copy.deepcopy(value) elif action['kind'] == 'append': result[field].append(copy.deepcopy(value)) elif action['kind'] == 'remove': result[field] = [item for item in result[field] if item != value] return result
def _checks(fields, events): """Find explicit event paths, bounded at 256 states and 32 events per path.""" initial = {k: copy.deepcopy(v['initial']) for k, v in fields.items()} todo = [(initial, [])]; seen = set(); covered = set(); checks = [] while todo and len(seen) < 256 and len(covered) < len(events): values, path = todo.pop(0) key = json.dumps(values, sort_keys=True) if key in seen or len(path) >= 32: continue seen.add(key) for name, event in events.items(): if not _test_guard(event.get('condition'), values): continue after = _expected(event, values); steps = path + [{'event': name}] if name not in covered: checks.append({'events': steps, 'state': after}); covered.add(name) if _test_guard(event.get('condition'), after): checks.append({'events': steps + [{'event': name}], 'state': _expected(event, after)}) todo.append((after, steps)) return checks, set(events) - covered
def _compile(record): fields, events = copy.deepcopy(record['fields']), copy.deepcopy(record['events']) holes = copy.deepcopy(record['unbound']) if not fields: holes.append(_hole('state', record['original'], 'name state and its initial value')) if not events: holes.append(_hole('event', record['original'], 'name a browser event and its changes')) for event_id, event in events.items(): if not event['changes']: holes.append(_hole('event_action', event['source'], 'name the changes made by ' + event['label'], event_id)) if event.get('condition_text'): try: event['condition'] = _guard(event['condition_text'], fields) except ValueError as error: holes.append(_hole('condition', event['source'], str(error), event_id)) for action in event['changes']: target = fields.get(action['field']) if not target: holes.append(_hole('target', event['source'], 'declare state ' + action['field'], event_id)); continue if action['kind'] == 'delta' and (action['value'] is None or target['type'] not in ('integer', 'number')): holes.append(_hole('amount', event['source'], 'name the numeric amount and numeric field for ' + event['label'], event_id)) elif action['kind'] in ('append', 'remove'): if target['type'] != 'array': holes.append(_hole('target_type', event['source'], 'list changes need an array field', event_id)) else: typ = _type(action['value']) if target.get('items') and target['items']['type'] != typ: holes.append(_hole('item_type', event['source'], 'all list values need the declared item type', event_id)) else: target['items'] = {'type': typ} for name, field in fields.items(): if field['type'] == 'array' and 'items' not in field: holes.append(_hole('item_type', name, 'name the type of items in ' + name)) for field in record['views']: if field not in fields: holes.append(_hole('view', field, 'declare displayed state ' + field)) if not record['views']: holes.append(_hole('view', record['original'], 'name the state to display')) contract = {'version': 1, 'title': record['title'], 'state': fields, 'events': {}, 'parts': {}, 'views': [{'kind': 'list' if fields.get(f, {}).get('type') == 'array' else 'text', 'label': f, 'value': {'state': f}} for f in record['views']], 'controls': [], 'checks': []} for name, event in events.items(): actions = [] for change in event['changes']: value = change['value'] if change['kind'] == 'delta': value = {'op': 'add' if change['sign'] == 1 else 'subtract', 'args': [{'state': change['field']}, value]} actions.append({'op': 'set' if change['kind'] in ('delta', 'set') else change['kind'], 'field': change['field'], 'value': value}) contract['events'][name] = {'actions': actions} if event.get('condition'): guard = event['condition'] contract['events'][name]['guard'] = {'op': guard['compare'], 'args': [{'state': guard['field']}, guard['value']]} contract['controls'].append({'kind': 'button', 'label': event['label'], 'event': name}) if not holes: try: checks, missing = _checks(fields, events); contract['checks'] = checks for name in sorted(missing): holes.append(_hole('event_path', name, 'provide a reachable event sequence for ' + events[name]['label'])) import interactive_program as IP contract = IP.validate(contract) except (ValueError, TypeError, KeyError) as error: holes.append(_hole('program_shape', record['original'], str(error))) record['contract'], record['holes'], record['ready'] = contract, holes, not holes return record
def receive(text, kept=None, reading=None): """Receive reusable program clauses or return None for unrelated turns.
A kept record is copied. The caller owns file destination, authority, durable work history and deciding whether to build, discuss, or ask for a hole fill. """ text = str(text).strip() if re.fullmatch(r'(?:call|name|save)\s+it\s+.+\.py[.!]?', text, re.I): return copy.deepcopy(kept) if kept else None if re.match(r'\s*(?:what|why|how|does|do not|don\'t|explain|describe|before building)\b', text, re.I): return None opening = re.match(INTRO, text, re.I) if opening and not re.search(r'\b(?:browser|web)\b', opening[0], re.I) and not re.search(r'\b(?:button|clicking|when I click)\b', text, re.I): opening = None if not kept and not opening: return None if kept and not opening: labels = '|'.join(re.escape(e['label']) for e in kept.get('events', {}).values()) continued = (r'^(?:actually|instead|no[, ]|change|revise|add|also|start|set|display|show|save|persist|remember|' r'keep|clicking|when I click|it should have|a button|an? (?:integer|number|string|boolean|empty list))\b') if not re.match(continued, text, re.I) and not (labels and re.match(r'^(?:' + labels + r')\s+should\b', text, re.I)): return None if kept and opening: kept = None # a complete new named project does not inherit old handlers record = copy.deepcopy(kept) if kept else {'kind': 'interactive_program_intent', 'original': text, 'turns': [], 'fields': {}, 'events': {}, 'views': [], 'storage': 'local', 'title': 'Browser program', 'unbound': [], 'consumed': []} record['turns'].append({'text': text, 'reading': copy.deepcopy(reading)}) turn = len(record['turns']) - 1 revision = bool(re.match(r'(?:actually|instead|no[, ]|change|revise)\b', text, re.I)) current_event = None
def consume(raw, offset, kind): nodes = ((reading or {}).get('graph') or {}).get('nodes', []) joined = [n.get('id') for n in nodes if isinstance(n.get('span'), list) and len(n['span']) == 2 and n['span'][0] < offset + len(raw) and n['span'][1] > offset] exact = text[offset:offset + len(raw)] receipt = {'turn': turn, 'span': [offset, offset + len(raw)], 'text': exact, 'kind': kind, 'native_nodes': joined} if exact != raw: receipt['binding_text'] = raw record['consumed'].append(receipt)
def fail(raw, offset, needed, kind='clause'): h = _hole(kind, raw.strip(), needed); h.update(turn=turn, span=[offset, offset + len(raw)]) if h['id'] not in {x['id'] for x in record['unbound']}: record['unbound'].append(h)
def event_changes(label, body, raw, offset, append=False): nonlocal current_event event_id = _event_id(label); current_event = event_id old = record['events'].get(event_id) event = copy.deepcopy(old) if old else {'label': label, 'changes': [], 'source': raw.strip()} if re.match(r'(?:is\s+)?allowed\s+', body, re.I): condition = re.sub(r'^(?:is\s+)?allowed\s+', '', body, flags=re.I) event['condition_text'] = condition; event['condition_source'] = raw.strip(); record['events'][event_id] = event consume(raw, offset, 'condition'); return parts = list(_split(body, r'\s+and\s+')) parsed = [] for _, part in parts: condition = re.search(r'\s+(only\s+(?:when|if|in)\s+.+)$', part, re.I) if condition: event['condition_text'] = condition[1]; event['condition_source'] = raw.strip(); part = part[:condition.start()] try: change = _action(part, record['fields']); change['source'] = part.strip(); change['turn'] = turn; parsed.append(change) except ValueError as error: fail(part, offset + raw.find(part), str(error), 'event_action') for change in parsed: matches = [i for i, old_change in enumerate(event['changes']) if old_change['field'] == change['field'] and old_change['kind'] == change['kind']] if not old or append: event['changes'].append(change) # ordered repetition is behavior, not duplicate metadata elif matches and (revision or any(event['changes'][i].get('value') is None for i in matches)): if len(matches) != 1: fail(raw, offset, 'name which ordered change to replace in ' + label, 'event_revision') else: event['changes'][matches[0]] = change elif not any(all(previous.get(k) == change.get(k) for k in ('kind', 'field', 'value', 'sign')) for previous in event['changes']): if matches: fail(raw, offset, 'say whether to replace or add this change to ' + label, 'event_revision') else: event['changes'].append(change) record['events'][event_id] = event if parsed: consume(raw, offset, 'event')
def clause(raw, offset, initial_context=False): nonlocal current_event leading = len(raw) - len(raw.lstrip()); offset += leading; raw = raw.strip() if not raw: return value = raw initial_context = initial_context or bool(re.match(r'^start\s+with\s+', raw, re.I)) start = re.match(INTRO + r'(?:\s+(?:in|as|called)\s+[^\s]+\.py)?', value, re.I) if start: consume(raw[:start.end()], offset, 'program') tail = value[start.end():].strip() if tail: tail = re.sub(r'^with\s+', '', tail, flags=re.I) clause(tail, offset + value.index(tail)) return if re.fullmatch(r'(?:call|name|save)\s+it\s+.+\.py', value, re.I): consume(raw, offset, 'destination'); return value = re.sub(r'^(?:actually|instead|no)[,\s]+', '', value, flags=re.I) value = re.sub(r'^(?:it\s+)?should\s+have\s+|^start\s+with\s+', '', value, flags=re.I) # An event named in a previous clause owns only an immediate explicit it. if current_event and re.match(r'^it\s+(?:adds?|sets?|changes?|increases?|decreases?|removes?)\b', value, re.I): event_changes(record['events'][current_event]['label'], re.sub(r'^it\s+', '', value, flags=re.I), raw, offset, append=True); return event = re.fullmatch(r'(?:a\s+button\s+(?:named|called)\s+|clicking\s+|when I click\s+)(' + NAME + r')\s*,?\s+(.+)', value, re.I) if not event: event = re.fullmatch(r'(?:an?\s+)?(' + NAME + r')\s+button\s+that\s+(.+)', value, re.I) if not event: event = re.fullmatch(r'(' + NAME + r')\s+should\s+(.+)', value, re.I) if event and _event_id(event[1]) not in record['events']: event = None if event: event_changes(event[1], event[2], raw, offset); return # A correction names the target event and field; all other actions stay. correction = re.fullmatch(r'(increase|decrease)\s+(' + NAME + r')\s+by\s+(' + NUM + r')\s+on\s+(' + NAME + r')', value, re.I) if correction and _event_id(correction[4]) in record['events']: event_changes(correction[4], '%s %s by %s' % (correction[1], correction[2], correction[3]), raw, offset); return correction = re.fullmatch(r'make\s+(' + NAME + r')\s+add\s+(' + NUM + r')\s+instead\s+of\s+(' + NUM + r')(.*)', value, re.I) if correction and _event_id(correction[1]) in record['events']: e = record['events'][_event_id(correction[1])] changes = [a for a in e['changes'] if a['kind'] == 'delta' and a['sign'] == 1 and a['value'] == _literal(correction[3])] if len(changes) != 1: fail(raw, offset, 'name the field and old amount to replace', 'event_revision'); return changes[0]['value'] = _literal(correction[2]); changes[0]['source'] = raw[:correction.start(4)]; changes[0]['turn'] = turn consume(raw[:correction.start(4)], offset, 'event_revision') if correction[4].strip(): tail = re.sub(r'^\s*,?\s*and\s+', '', correction[4], flags=re.I); clause(tail, offset + raw.find(tail)) return keep = re.fullmatch(r'keep\s+the\s+starting\s+value\s+at\s+(' + NUM + r')', value, re.I) if keep and len(record['fields']) == 1 and next(iter(record['fields'].values()))['initial'] == _literal(keep[1]): consume(raw, offset, 'preserve_initial'); return # Display fields are references. No undeclared extra words disappear. display = re.match(r'^(?:display|show)\s+', value, re.I) if display: sections = list(_split(value[display.end():], r',?\s+and\s+(?=(?:save|persist|remember)\b)|,\s*(?=(?:save|persist|remember)\b)')) names = re.split(r'\s*(?:,|\band\b)\s*', sections[0][1]) if all(re.fullmatch(NAME, name) for name in names): record['views'] = list(dict.fromkeys(record['views'] + names)); consume(raw[:display.end()+len(sections[0][1])], offset, 'view') for part_offset, part in sections[1:]: clause(part, offset + display.end() + part_offset) return if re.fullmatch(r'(?:save|persist|remember)\s+(?:changes|(?:the\s+)?state|it|them)(?:\s+locally)?\s+(?:across\s+reloads|after\s+(?:reopening|reloads)|across\s+restarts)', value, re.I): record['storage'] = 'local'; consume(raw, offset, 'storage'); return if re.fullmatch(r'(?:save|persist|remember)\s+(?:the\s+)?(' + NAME + r')\s+(?:across\s+reloads|after\s+reopening)', value, re.I): name = re.fullmatch(r'(?:save|persist|remember)\s+(?:the\s+)?(' + NAME + r')\s+.+', value, re.I)[1] if name in record['fields']: record['storage'] = 'local'; consume(raw, offset, 'storage'); return # State declarations can be joined, each with its own complete meaning. pieces = list(_split(value, r'\s+and\s+')) if len(pieces) > 1: for shift, piece in pieces: clause(piece, offset + raw.find(value) + shift, initial_context) return empty = re.fullmatch(r'(?:an?\s+)?empty\s+list\s+(?:named|called)\s+(' + NAME + r')', value, re.I) match = re.fullmatch(r'(?:an?\s+)?(?:(integer|number|string|boolean)\s+)?(' + NAME + r')\s+(?:starting\s+at|initially|starts\s+at|starting\s+with)\s+(.+)', value, re.I) if not match and initial_context: match = re.fullmatch(r'()(' + NAME + r')\s+(.+)', value, re.I) if empty or match: try: name = empty[1] if empty else match[2] initial = [] if empty else _literal(match[3]) schema = {'type': 'array' if empty else (match[1] or _type(initial)).lower(), 'initial': initial} old = record['fields'].get(name) if old and old != schema and not revision: raise ValueError('say whether to revise the existing initial state ' + name) record['fields'][name] = schema; consume(raw, offset, 'state'); return except ValueError as error: fail(raw, offset, str(error), 'state'); return fail(raw, offset, 'connect this exact clause to a state, event, condition, view, or storage part')
binding_text = list(text) owned = set() for delegated in (reading or {}).get('project_delegated', []): if not isinstance(delegated, dict): fail(text, 0, 'delegated reason needs a named native source receipt', 'reason_ownership') continue span = delegated.get('span') if (delegated.get('owner') != 'reason' or not isinstance(span, list) or len(span) != 2 or any(type(n) is not int for n in span) or not 0 <= span[0] < span[1] <= len(text) or text[span[0]:span[1]] != delegated.get('text') or any(i in owned for i in range(*span))): fail(text, 0, 'delegated reason needs an exact, nonoverlapping native source receipt', 'reason_ownership') continue consume(text[span[0]:span[1]], span[0], 'delegated_reason') for i in range(*span): # Preserve sentence boundaries so a reason cannot merge separate actions. if text[i] not in '.;\n': binding_text[i] = ' ' owned.add(i) for offset, segment in _split(''.join(binding_text), r';\s*|\.(?=\s|$)\s*|\n+'): clause(segment, offset) return _compile(record)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236"""Connect the existing step compiler to the selected work environment."""import astimport hashlibimport osfrom pathlib import Pathimport reimport textwrapimport threading
_LOCK = threading.RLock()
def build(root, args, runenv=None): import make import work_tasks as work root = Path(root).resolve() description = args.get('description') destination = args.get('file') check = args.get('check') postcondition = args.get('postcondition') if not isinstance(description, str) or not description.strip() or not isinstance(destination, str): raise work.WorkHole('input', 'receive the complete program description and its destination file') if not isinstance(check, (str, list)) or not check: raise work.WorkHole('postcondition', 'name a behavior check for the described program before calling it complete') target = work._path(root, destination) received_target = target.read_bytes() if target.is_file() else None for name, expected in args.get('source_files', {}).items(): if hashlib.sha256(work._path(root, name).read_bytes()).hexdigest() != expected: raise work.WorkHole('changed-input', 'the received program description changed: ' + name) if target.suffix != '.py': raise work.WorkHole('input', 'the existing step compiler emits a Python file') work.guard_write(target) from work_synthesis import _evidence_files, _changed_evidence evidence_files = _evidence_files(root, check, postcondition) items = work.inventory(root) if items.get('clipped'): raise work.WorkHole('inventory', 'open a smaller repository folder so the function inventory is complete') records, modules, hashes, proposed, unbound = [], {}, {}, {}, []
def index_source(name, raw, prepared=False): try: tree = ast.parse(raw) except (SyntaxError, UnicodeError): return modules[name] = tree if not prepared: hashes[name] = hashlib.sha256(raw).hexdigest() records[:] = [record for record in records if record['path'] != name] for node in tree.body: if not isinstance(node, ast.FunctionDef) or node.name.startswith('_'): continue positional = node.args.posonlyargs + node.args.args required = len(positional) - len(node.args.defaults) if node.args.vararg or node.args.kwarg or any(v is None for v in node.args.kw_defaults): continue records.append({'name': node.name, 'path': name, 'kind': 'def', 'args': [x.arg for x in positional], 'required': required, 'doc': ast.get_docstring(node) or ''})
for name in items['files']: if name.endswith('.py') and work._path(root, name) != target: index_source(name, work._path(root, name).read_bytes())
def matches(step): found = [r for r in records if re.search(r'\b' + re.escape(r['name']) + r'\b', step)] qualified = [r for r in found if r['path'] in step] return qualified or found
filler = {'apply', 'use', 'compute', 'calculate', 'call', 'run', 'take', 'get', 'return', 'it', 'them', 'this', 'that', 'the', 'result', 'on', 'to', 'from', 'in', 'of', 'a', 'an'}
def described(step): wanted = set(re.findall(r'[A-Za-z_]+', step.lower())) - filler if len(wanted) < 2: return [] # A repository part's own documented face supplies vocabulary. Every # requested word must occur there; ties remain holes, not guessed calls. return [record for record in records if record['doc'] and wanted <= set(re.findall(r'[A-Za-z_]+', record['doc'].lower()))]
def find(step): found = matches(step) by_description = not found if by_description: found = described(step) if len(found) > 1: raise work.WorkHole('binding', 'several repository functions match this step: ' + step) if found and not by_description: remaining = step.replace(found[0]['path'], '').replace(found[0]['name'], '') if set(re.findall(r'[A-Za-z_]+', remaining.lower())) - filler: unbound.append(step) return [] # a named function cannot silently consume extra requested behavior if not found: unbound.append(step) return [(record, 1.0) for record in found]
find.required = lambda record: record['required'] used = dict(args.get('source_files') or {})
def read(record): tree = modules[record['path']] top = {} imports = [] for node in tree.body: if isinstance(node, (ast.Import, ast.ImportFrom)): if isinstance(node, ast.ImportFrom) and node.level: raise work.WorkHole('binding', 'relative-import function reuse needs its package context: ' + record['path']) imports.append(node) elif isinstance(node, (ast.FunctionDef, ast.ClassDef)): top[node.name] = node elif isinstance(node, (ast.Assign, ast.AnnAssign)): for child in ast.walk(node): if isinstance(child, ast.Name) and isinstance(child.ctx, ast.Store): top[child.id] = node todo, selected = [record['name']], {} while todo: name = todo.pop() if name not in top or name in selected: continue node = top[name] if any(isinstance(child, (ast.Global, ast.Nonlocal)) for child in ast.walk(node)): raise work.WorkHole('binding', 'this function changes module scope; receive it as an explicit effect part') selected[name] = node todo += [child.id for child in ast.walk(node) if isinstance(child, ast.Name) and child.id in top] nodes = sorted({id(n): n for n in imports + list(selected.values())}.values(), key=lambda n: n.lineno) body = '\n\n'.join(ast.unparse(node) for node in nodes) # A local closure keeps each source module's constants/import aliases # separate when several repository functions are composed together. source = 'def %s(x):\n%s\n return %s(x)' % ( record['name'], textwrap.indent(body, ' '), record['name']) if record['path'] not in proposed: used[record['path']] = hashes[record['path']] return source, set()
# The existing compiler's function/parameter registers are module globals. # Serialize this connection; make.compose itself also owns the shared lock. with _LOCK: source, plan = make.compose(description, find, read) prepared = None if plan.gaps and unbound: import compose_code as composer import work_synthesis as synthesis tests = composer.read_tests(root) targets = [] for name, evidence in tests.items(): filename = evidence['module'].replace('.', '/') + '.py' # Only an explicitly named, otherwise unqualified missing step can # receive these examples. Never fall back to unrelated test targets. relevant = [step for step in unbound if re.search(r'\b' + re.escape(name) + r'\b', step) and not (set(re.findall(r'[A-Za-z_]+', step.replace(filename, '').replace(name, '').lower())) - filler)] if not relevant: continue identities = {composer.read_tests(root, only=[test_file]).get(name, {}).get('module') for test_file in evidence['files']} identities.discard(None) if len(identities) != 1: raise work.WorkHole('binding', 'the missing function name has examples in several modules: ' + name) path = work._path(root, filename) if path == target: raise work.WorkHole('binding', 'the missing helper and parent program need distinct destinations: ' + name) if name in synthesis._definitions(path.read_text(encoding='utf-8') if path.is_file() else ''): continue targets.append({'file': filename, 'function': name, 'mode': 'create', 'examples': evidence['examples'], 'test_files': evidence['files']}) step_of = {} received_examples = [e for e in (args.get('examples') or []) if isinstance(e, dict) and 'input' in e and 'expected' in e] if not targets and received_examples and len(set(unbound)) == 1: # The request's own examples ("100 should give 212") describe its one unconnected step: the composer # constructs that step as a helper from them, checked with its parent under the original check (11-17). # The examples are recorded as supplied assistance; a step they do not determine stays a hole. step = unbound[0] words = [w for w in re.findall(r'[a-z]+', step.lower()) if w not in filler][:5] or ['step'] name = '_'.join(words) helper = Path(destination).stem + '_parts.py' if name not in synthesis._definitions(work._path(root, helper).read_text(encoding='utf-8') if work._path(root, helper).is_file() else ''): targets.append({'file': helper, 'function': name, 'mode': 'create', 'examples': [((e['input'],), e['expected'], None) for e in received_examples], 'test_files': []}) step_of[name] = step if targets: changed = _changed_evidence(root, evidence_files) if changed: raise work.WorkHole('evidence', 'the received behavior evidence changed before helper preparation', changed=changed) try: prepared = synthesis.prepare(root, description, [{k: v for k, v in t.items()} for t in targets], check, postcondition, runenv, require_failing_baseline=False) proposed.update(prepared['sources']) for name, text in proposed.items(): index_source(name, text.encode('utf-8'), prepared=True) # a step constructed from the request's own examples is named by the helper built for it for function, step in step_of.items(): if step in description: description = description.replace(step, function) unbound.clear() with _LOCK: source, plan = make.compose(description, find, read) synthesis.validate_prepared(root, prepared) except work.WorkHole as exc: exc.hole['parent'] = {'request': description, 'file': destination, 'check': check} exc.hole['missing_steps'] = list(dict.fromkeys(unbound)) raise if plan.gaps: raise work.WorkHole('composition', 'Unconnected program steps: ' + '; '.join(plan.gaps), parent={'request': description, 'file': destination, 'check': check}, obligations=[{'step': step, 'receiver': 'work_synthesis', 'needs': 'a named callable with examples, or a connected existing part'} for step in dict.fromkeys(unbound)], prepared_helpers=[item['function'] for item in prepared['received']] if prepared else []) for name, expected in used.items(): path = work._path(root, name) if not path.is_file() or hashlib.sha256(path.read_bytes()).hexdigest() != expected: raise work.WorkHole('changed-input', 'the source function changed while composing: ' + name) before_bytes = target.read_bytes() if target.is_file() else None if before_bytes != received_target: raise work.WorkHole('changed-input', 'the destination changed while its described program was composed') before = target.read_text(encoding='utf-8') if target.is_file() else None edit = {'path': destination, 'content': source} if before is not None: edit['before'] = before edits = (prepared['edits'] if prepared else []) + [edit] originals = dict(prepared['original_bytes'] if prepared else {}, **{destination: before_bytes}) published = dict(proposed, **{destination: source}) result = work.edit_transaction(root, edits, check=check, runenv=runenv, postcondition=postcondition, witness=True) changed = _changed_evidence(root, dict(evidence_files, **used)) if changed: restored = {name: work._rollback_owned(work._path(root, name), {'before': originals[name], 'after': text.replace('\n', os.linesep).encode('utf-8')}) for name, text in published.items()} raise work.WorkHole('evidence', 'the received source or behavior check changed while building; reread it before completion', changed=changed, restored=restored) result['trace'] = list(plan.trace) result['source_files'] = used result['evidence_files'] = evidence_files result['description'] = description if prepared: result['construction'] = synthesis.admit_prepared(root, prepared) return result1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""project_answer - a question asked in an open project, answered from the project's own text (revised 12.0, 2026-11-17).
With a folder open, "Where does the writer decide how many sentences to write?" or "How are sizes read?" is a question
about this project, not about the world: before this it reached the page discussion and was offered a Wikipedia lookup.
Here the question's content words (the store's lemmas, closed-class words and question words left out) are matched
against each function's and module's own words: its name split at underscores, its docstring and its comments. The
answer names file:line and quotes the code's own description; every sentence is a project record, cited by path and line.
A question none of the project's text answers well enough returns None and keeps its existing owner.
Would not solve: code with no names, docstrings or comments that share the asker's words (a reader of the code's
behaviour, not its words, would be needed); questions about runtime behaviour, which are runs, not readings.
"""
import ast
import re
from pathlib import Path
SKIP = {".git", "__pycache__", "node_modules", ".venv", "venv", "local", "state"}
QUESTION = {"where", "what", "which", "who", "when", "why", "how", "does", "do", "did", "is", "are", "was", "were", "can",
"could", "should", "would", "will", "the", "this", "that", "these", "those", "code", "project", "file",
"function", "part", "happen", "happens", "get", "gets", "done", "decide", "decides", "handle", "handles"}
def _lemmas(text, reader):
out = set()
for w in re.findall(r"[a-z]{3,}", text.lower().replace("_", " ")):
if w in QUESTION:
continue
pos = reader.d.pos(w) if reader is not None else set()
if pos & {"article", "det", "pron", "prep", "conj", "particle"}:
continue
out.add(reader.d.lemma(w, "noun" if "noun" in pos else "verb" if "verb" in pos else None) if reader is not None else w)
return out
def _units(root, limit=600):
"""(path, line, name, args, own words, description) for each module and function of the project"""
base = Path(root).resolve()
seen = 0
for path in sorted(base.rglob("*.py")):
if any(part in SKIP or part.startswith(".") for part in path.relative_to(base).parts[:-1]):
continue
seen += 1
if seen > limit:
return
try:
source = path.read_text(encoding="utf-8")
tree = ast.parse(source)
except (SyntaxError, UnicodeError, OSError):
continue
lines = source.splitlines()
rel = path.relative_to(base).as_posix()
doc = ast.get_docstring(tree) or ""
if doc:
yield rel, 1, path.stem, [], path.stem + " " + doc, doc
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
body = lines[node.lineno - 1: getattr(node, "end_lineno", node.lineno)][:60]
comments = " ".join(c for line in body for c in re.findall(r"#\s*(.+)$", line))
fdoc = ast.get_docstring(node) or ""
args = [a.arg for a in getattr(getattr(node, "args", None), "args", [])][:6]
yield rel, node.lineno, node.name, args, " ".join([node.name, fdoc, comments]), fdoc or comments
def answer(text, root, reader, k=3):
# a question that names one of the project's files is that file's explainer's (code_discussion), not a search
for named in re.findall(r"[\w./-]+\.\w+", text):
if (Path(root) / named).is_file():
return None
asked = _lemmas(text, reader) - QUESTION
if len(asked) < 2:
return None
scored = []
for rel, line, name, args, words, description in _units(root):
own = _lemmas(words, reader)
hit = asked & own
if len(hit) >= max(2, (len(asked) + 1) // 2):
in_name = len(asked & _lemmas(name, reader))
scored.append((len(hit) + in_name, rel, line, name, args, description, sorted(hit)))
if not scored:
return None
scored.sort(key=lambda s: (-s[0], s[1], s[2]))
rows, refs = [], []
for i, (_score, rel, line, name, args, description, hit) in enumerate(scored[:k], 1):
first = re.split(r"(?<=[.!?])\s+", " ".join(description.split()))[0][:300] if description else ""
rows.append("%s%s at %s:%d%s [%d]" % (name, "(%s)" % ", ".join(args) if args or name != Path(rel).stem else "",
rel, line, (": " + first) if first else "", i))
refs.append("%d. %s:%d (this project's own text; words matched: %s)" % (i, rel, line, ", ".join(hit)))
return {"status": "answered", "path": "bench:code:where",
"response": "In this project:\n" + "\n".join("- " + r for r in rows) + "\n\n### Sources\n\n" + "\n".join(refs),
"records": [r.split(" ")[1] for r in refs],
"basis": {"kind": "project record", "asked": sorted(asked), "matches": len(scored)},
"execution": {"state": "read", "check": {"ok": True}}}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849"""Keep a received new project while the conversation chooses its workspace."""import copyimport re
def receive(text, request, native, turn): if turn.env is not None: return None pending = turn.s.get('pending_work') if pending and re.fullmatch(r'(?i)\s*(?:cancel|never\s*mind|forget that|stop)[.! ]*', text): turn.s.pop('pending_work', None) turn.save() return {'status': 'answered', 'path': 'bench:work:context:cancel', 'response': 'Cancelled the project request waiting for a folder.', 'execution': {'state': 'read', 'started': False, 'changed': False}} import project_intent if not project_intent.owns_turn(request['reading'], None, reading=native): return None pending = {'text': text, 'request': copy.deepcopy(request), 'reading': copy.deepcopy(native)} if turn.s.get('pending_work') and turn.s['pending_work']['text'] != text: turn.s.setdefault('pending_work_history', []).append(turn.s['pending_work']) turn.s['pending_work'] = pending turn.s['pending_context_focus'] = 'work' turn.save() return {'status': 'offered', 'path': 'bench:work:context', 'response': 'I have kept this project request: ' + text + '\n\nWhich project folder should hold it? Open the folder with `open <folder path>`; I will continue from this request.', 'execution': {'state': 'waiting', 'started': False, 'changed': False}, 'missing_evidence': [{'kind': 'project_folder', 'needed': 'project folder', 'request': text}]}
def resume(sid): import bench turn = bench.Turn(sid) pending = turn.s.get('pending_work') if not pending or turn.env is None or turn.env.kind != 'folder' or turn.s.get('pending_context_focus') not in (None, 'work'): return None result = bench.handle(pending['request']['reading'], sid, reading=pending.get('reading')) if result is None: return {'status': 'hole', 'path': 'bench:work:context', 'response': 'The folder is open, but no work part has received the kept request yet: ' + pending['text'], 'execution': {'state': 'missing', 'started': False, 'changed': False}, 'missing_evidence': [{'kind': 'project_receiver', 'request': pending['text']}]} if (result.get('execution') or {}).get('state') != 'refused': # Reload: the work receiver may have saved its own project and focus. turn = bench.Turn(sid) turn.s.pop('pending_work', None) turn.save() return dict(result, resumed_project_request=pending['text'])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241"""Discuss a received program from its saved meaning, without building or running it.
State, events, conditions, examples and reasons are the vocabulary of the currentproject. Questions bind to that record; a hypothetical state is never reported asthe live application's state. No application-specific templates or topic facts."""import jsonimport re
def _value(value): return json.dumps(value, ensure_ascii=False)
def _mentions(text, name): return bool(name and re.search(r'(?<!\w)' + re.escape(str(name)) + r'(?!\w)', text, re.I))
def _question(text): import language_bridge as language question = language.request_reading(text)['reading'].strip() if language.asks_about(question): return question # A negative work instruction followed by an explanation is a read turn. pieces = [piece for piece in re.split(r'[.;]\s*', question) if piece.strip()] if len(pieces) > 1 and all(re.fullmatch(r"(?i)(?:do not|don't)\s+(?:build|create|modify|change|run)\s+.+", p) for p in pieces[:-1] if p): return pieces[-1] if language.asks_about(pieces[-1]) else None return None
def _expression(expr): if not isinstance(expr, dict): return _value(expr) if 'state' in expr: return '`%s`' % expr['state'] if 'param' in expr: return 'the `%s` input' % expr['param'] args = [_expression(a) for a in expr.get('args', [])] operators = {'eq': 'equals', 'ne': 'does not equal', 'lt': 'is below', 'le': 'is at most', 'gt': 'is above', 'ge': 'is at least', 'add': 'plus', 'subtract': 'minus', 'multiply': 'times', 'divide': 'divided by', 'contains': 'contains'} op = expr.get('op') if op in operators and len(args) == 2: return '%s %s %s' % (args[0], operators[op], args[1]) if op in ('and', 'or'): return (' %s ' % op).join('(' + a + ')' for a in args) if op == 'not' and len(args) == 1: return 'not (' + args[0] + ')' return '`' + json.dumps(expr, ensure_ascii=False) + '`'
def _actions(actions): result = [] for action in actions: op, field = action.get('op'), action.get('field') val = _expression(action.get('value')) if op == 'set': result.append('set `%s` to %s' % (field, val)) elif op == 'append': result.append('append %s to `%s`' % (val, field)) elif op == 'remove': result.append('remove %s from `%s`' % (val, field)) else: result.append('apply the saved `%s` action: `%s`' % (op, _value(action))) return '; then '.join(result) or 'no change is bound yet'
def _hypothesis(text, fields): """Bind a hypothetical clause to named fields or one unique typed state.""" markers = list(re.finditer(r'\b(?:while|when|if)\b', text, re.I)) if not markers: return None, [] tail = text[markers[-1].end():].strip().rstrip('?.!') supplied, holes = {}, [] for name, schema in fields.items(): for explicit in re.finditer(r'\b' + re.escape(name) + r'\s+(?:is|equals|=)\s+("[^"]*"|\S+)', tail, re.I): raw = explicit[1].rstrip(',') try: value = json.loads(raw) except ValueError: value = raw.strip('"\'') if name in supplied and (type(supplied[name]) is not type(value) or supplied[name] != value): holes.append('The hypothetical gives conflicting values for `%s`; clarify which value applies.' % name) else: supplied[name] = value short = re.fullmatch(r'(?i)(?:still\s+)?in\s+("[^"]*"|[\w-]+)', tail) if short: value = short[1].strip('"') candidates = [name for name, schema in fields.items() if schema.get('type') == 'string'] if len(candidates) == 1: supplied[candidates[0]] = value else: holes.append('Name the state field whose hypothetical value is %s.' % _value(value)) for name, value in supplied.items(): schema = fields[name] try: import interactive_program interactive_program._value(value, schema, name) except (ValueError, TypeError, KeyError) as error: holes.append('The hypothetical value for `%s` is outside its declared state: %s.' % (name, error)) return supplied, holes
def _guard_verdict(expr, supplied): """Three-valued evaluation of a saved guard over explicitly supplied facts.""" if not isinstance(expr, dict): return expr, True if 'state' in expr: name = expr['state'] return supplied.get(name), name in supplied if 'param' in expr: return None, False results = [_guard_verdict(a, supplied) for a in expr.get('args', [])] if not all(known for value, known in results): return None, False vals = [v for v, k in results] op = expr.get('op') try: if op in ('eq', 'ne'): same = type(vals[0]) == type(vals[1]) and vals[0] == vals[1] return (same if op == 'eq' else not same), True if op in ('lt', 'le', 'gt', 'ge'): if any(isinstance(v, bool) or not isinstance(v, (int, float)) for v in vals): return None, False return {'lt': lambda: vals[0] < vals[1], 'le': lambda: vals[0] <= vals[1], 'gt': lambda: vals[0] > vals[1], 'ge': lambda: vals[0] >= vals[1]}[op](), True if op in ('and', 'or', 'not') and all(isinstance(v, bool) for v in vals): return (all(vals) if op == 'and' else any(vals) if op == 'or' else not vals[0]), True except (TypeError, ValueError, IndexError): pass return None, False
def answer(text, work, reading=None): intent = (work or {}).get('build_intent') question = _question(text) if not intent or question is None: return None low = question.lower() interactive = intent.get('interactive') or {} contract = interactive.get('contract') or {} fields = contract.get('state') or interactive.get('fields') or {} events = contract.get('events') or {} event_records = interactive.get('events') or {} interactions = bool(re.search(r'\b(?:click|press|button|event|handler|rule)\b', low)) named = [] for name in events: label = event_records.get(name, {}).get('label') or name direct = re.fullmatch(r'(?i)\s*(?:what\s+(?:should|does|will|can)\s+|how\s+does\s+)' + re.escape(label) + r'\s+(?:do|work|behave|change)(?:\s+(?:the\s+)?(?:state|project|app))?[?.! ]*', question) if (interactions or direct) and (_mentions(question, name) or _mentions(question, label)): named.append(name) mentioned_fields = [name for name in fields if _mentions(question, name)] named_file = _mentions(question, intent.get('file')) project_reference = bool(re.search(r'\b(?:project|program|app|work|task|goal|it|its|this|that)\b', low)) reason_question = bool(re.search(r'\b(?:reason|reasons|why|purpose)\b', low)) asked_reason = reason_question and (project_reference or re.search(r'\b(?:i|my|give|gave|asked)\b', low)) if not (named or mentioned_fields or named_file or project_reference or asked_reason): # A guard value can identify a rule even if the question uses a nominal # form of its label ("approval" for Approve); never invent that alias. for name, event in events.items() if re.search(r'\b(?:allowed|wait|condition|only|before|after|guard)\b', low) else (): guard = event.get('guard') or {} if isinstance(guard, dict) and any(isinstance(a, str) and _mentions(question, a) for a in guard.get('args', [])): named.append(name) if not named: return None lines, holes, basis = [], [], [] if asked_reason and not named: reasons = intent.get('reasons') or [] if reasons: lines.append('You gave this reason for the project: ' + '; '.join(reasons)) basis.append('build_intent.reasons') else: holes.append('No separate reason is recorded for this project. Its requested behavior is kept, but I cannot supply your reason from that alone.') elif named: hypothesis, ambiguity = _hypothesis(question, fields) holes.extend(ambiguity) for name in named: event, record = events[name], event_records.get(name, {}) label = record.get('label') or name guard = event.get('guard') required = _expression(guard) if guard is not None else None lines.append('The saved rule for `%s` is to %s%s.' % (label, _actions(event.get('actions', [])), ', only when ' + required if required else '')) basis.append('build_intent.interactive.contract.events.' + name) if hypothesis is not None and not ambiguity: if guard is None: lines.append('This rule has no state condition. The described event would attempt its actions, subject to state and action checks; this is a hypothetical explanation, not a live button click.') else: verdict, known = _guard_verdict(guard, hypothesis) if known: lines.append('With %s, the condition %s. %s No live state has been read or changed.' % (', '.join('`%s` = %s' % (k, _value(v)) for k, v in hypothesis.items()), 'holds' if verdict else 'does not hold', 'The described event would attempt its actions, subject to remaining state and action checks.' if verdict else 'The described event would be rejected and leave the state unchanged.')) else: holes.append('The hypothetical needs enough state values to evaluate ' + required + '.') elif reason_question: source_key = 'condition_source' if record.get('condition_source') else 'source' if record.get(source_key): lines.append('That condition comes from your received rule: ' + record[source_key]) basis.append('build_intent.interactive.events.' + name + '.' + source_key) if intent.get('reasons'): lines.append('The project reason you gave was: ' + '; '.join(intent['reasons'])) else: lines.append('No separate explanation of why you chose this rule is recorded.') elif mentioned_fields: for name in mentioned_fields: schema = fields[name] lines.append('`%s` is %s state, initially %s.' % (name, schema.get('type'), _value(schema.get('initial')))) events_using = [n for n, event in events.items() if any(action.get('field') == name for action in event.get('actions', []))] if events_using: lines.append('The saved events that change it are ' + ', '.join('`%s`' % (event_records.get(n, {}).get('label') or n) for n in events_using) + '.') basis.append('build_intent.interactive.contract.state.' + name) lines.append('These are the requested initial values, not a reading of the running app.') elif re.search(r'\b(?:does|do|should|supposed|understand|asked|description|describe|steps)\b', low): if intent.get('stages'): lines.append('The requested program applies these stages in order: ' + ' → '.join(intent['stages']) + '.') basis.append('build_intent.stages') elif events: for name, event in events.items(): guard = event.get('guard') lines.append('`%s`: %s%s.' % (event_records.get(name, {}).get('label') or name, _actions(event.get('actions', [])), ', only when ' + _expression(guard) if guard else '')) basis.append('build_intent.interactive.contract.events') else: lines.append('Your kept request is: ' + intent['original']) basis.append('build_intent.original') if intent.get('constraints'): lines.append('The constraints remain: ' + '; '.join(c['text'] for c in intent['constraints'])) basis.append('build_intent.constraints') else: return None lines.extend(holes) lines.append('This answers from the saved request. It does not run or rebuild the project.') return {'status': 'hole' if holes else 'answered', 'path': 'bench:work:record:meaning', 'response': '\n\n'.join(lines), 'missing_evidence': [{'kind': 'project_discussion', 'text': h} for h in holes], 'execution': {'state': 'missing' if holes else 'read', 'started': False, 'changed': False, 'work_id': work.get('id'), 'basis': basis}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385"""Receive a described program through the existing work ledger and compiler.
Project nouns are kept verbatim. The existing parts decide which describedstages connect; missing destination/evidence/meaning is filled on later turns."""import astimport copyimport hashlibimport jsonfrom pathlib import Pathimport reimport sysimport tempfile
_OBJECT = r'(?:program|tool|script|app|application|workflow)'_START = re.compile(r'(?is)^\s*(?:(?:can|could|would)\s+you\s+)?(?:please\s+)?(?:(?:build|create|make|write)\s+|I\s+(?:want|need|would like)\s+(?:you\s+to\s+(?:build|create|make|write)\s+)?)' + r'(?:(?![.;\n]).){0,100}?(?:\b' + _OBJECT + r'\b|[\w./-]+\.py\b)')_DEST = re.compile(r'(?is)^(?:(?:call|name)\s+(?:it|the\s+' + _OBJECT + r')\s+|(?:save|write)\s+it\s+as\s+)[`\"\']?([\w./-]+\.py)[`\"\']?[.!]?$')_CHECK = re.compile(r'(?is)^(?:(?:check|test|verify)(?:\s+it)?\s+(?:with|using)|run)\s+`([^`]+)`[.!]?$')_REVISION = re.compile(r'(?is)^\s*(?:instead\s*[,;:]?\s*|I meant\s+|actually\s*[,;:]?\s*)(.+)$')
def _native_opening(reading): graph = (reading or {}).get('graph') or {} if graph.get('act') != 'request': return None parents = {link.get('to') for link in graph.get('links', []) if link.get('kind') == 'relative'} return next((node for node in graph.get('nodes', []) if node.get('id') in parents and node.get('speech_act') == 'request' and node.get('polarity') == 'positive' and node.get('predicate', {}).get('lemma') in {'build', 'create', 'make', 'write', 'want', 'need'}), None)
def _delegated_reasons(text, reading): """Exact reason nodes remain owned here while executable parts read actions.""" result = copy.deepcopy(reading or {}) graph = result.get('graph') or {} nodes = {node.get('id'): node for node in graph.get('nodes', [])} delegated, reasons = [], [] for link in graph.get('links', []): if link.get('kind') != 'reason': continue node, connector = nodes.get(link.get('from'), {}), link.get('connector') or {} pieces = [] for atom in (connector, node): span = atom.get('span') if not isinstance(span, list) or len(span) != 2 or atom.get('source', graph.get('original')) != text: pieces = []; break lo, hi = span if not isinstance(lo, int) or not isinstance(hi, int) or not 0 <= lo <= hi <= len(text) or text[lo:hi] != atom.get('text'): pieces = []; break pieces.append({'span': list(span), 'owner': 'reason', 'text': text[lo:hi], 'node': node.get('id')}) if pieces: for piece in pieces: if not any(existing['span'] == piece['span'] for existing in delegated): delegated.append(piece) reason = ' '.join(piece['text'] for piece in pieces) if reason not in reasons: reasons.append(reason) result['project_delegated'] = delegated return result, reasons
def _masked(text): literals = {} def keep(match): key = 'O7LITERAL%dTOKEN' % len(literals) literals[key] = match.group() return key masked = re.sub(r'`[^`]*`|"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'', keep, text) return masked, literals
def _restore(text, literals): for key, value in literals.items(): text = text.replace(key, value) return text
def clauses(text): masked, literals = _masked(text) return [_restore(piece.strip(' \t\r\n.;'), literals) for piece in re.split(r'[;\n]+|(?<=[.!?])\s+(?=[A-Z])', masked) if piece.strip(' \t\r\n.;')]
def _literal(text): text = text.strip().rstrip('.').strip() try: value = json.loads(text) except (ValueError, TypeError): value = ast.literal_eval(text) json.dumps(value, allow_nan=False) return value
def example(text): """Examples supply answers independently of the compiler's emitted moves.""" masked, literals = _masked(text) head = re.match(r'(?is)^(?:for|with)\s+(?:the\s+)?input\s+(.+)$', masked) filehead = re.match(r'(?is)^when\s+([\w./-]+)\s+(?:contains|has)\s+(.+)$', masked) bare = not head and not filehead # any clause "<value> (should|must)? give|return|produce|expect|=> <value>" ("100 should give 212") is an example # when both sides read as exact values; nothing else in the clause is guessed (11-17) body = masked if bare else (head.group(1) if head else filehead.group(2)) for divider in re.finditer(r'(?i),?\s+(?:(?:it|the\s+' + _OBJECT + r')\s+)?(?:should\s+|must\s+)?(?:return|produce|give|expect)s?\s+|\s*=>\s*', body): try: value = _literal(_restore(body[:divider.start()], literals)) expected = _literal(_restore(body[divider.end():], literals)) if filehead: if not isinstance(value, str): continue return {'files': {filehead.group(1): value}, 'expected': expected} return {'input': value, 'expected': expected} except (ValueError, SyntaxError, TypeError): continue if bare: # several examples in one clause ("2 gives 7 and 10 gives 23"): every part must read as an example on its own parts = [p for p in re.split(r'(?i)\s*(?:;|,|\band\b)\s*', _restore(masked, literals)) if p.strip()] if len(parts) > 1: read = [example(p) for p in parts] if all(r and 'input' in r for r in read): return dict(read[0], more=read[1:]) return None return {'hole': 'Give the input and expected result as literal values, for example: For input [1, 2], return 3.'}
def _directive(text, reading=None): # Only grammatical wrappers and verb inflection are changed. The compiler # must still connect every remaining stage; no requested behavior is guessed. t = re.sub(r'(?is)^(?:it|the\s+' + _OBJECT + r')\s+(?:should|must|will|can)\s+', '', text.strip()) first = re.match(r'([A-Za-z]+)\b', t) if first: word = first.group(1) native = next((node.get('predicate', {}).get('lemma') for node in (reading or {}).get('graph', {}).get('nodes', []) if node.get('predicate', {}).get('text', '').lower() == word.lower() and node.get('predicate', {}).get('lemma')), None) if native: word = native elif word.endswith('ies'): word = word[:-3] + 'y' elif word.endswith('s') and not word.endswith(('ss', 'us')): word = word[:-1] t = word + t[first.end():] return t
def _stages(text, reading=None): import make masked, literals = _masked(text) # A coordinated requested action stays a separate obligation, even when the # old compiler would otherwise accept only its first verb. masked = re.sub(r'\s+and\s+', '; ', masked, flags=re.I) return [_directive(_restore(stage, literals), reading) for stage in make.steps_of(masked)]
def _is_continuation(text, intent): if not intent: return False t = text.strip() if _DEST.match(t) or _CHECK.match(t) or example(t) is not None or _REVISION.match(t): return True if re.fullmatch(r'[\w./-]+\.py[.!]?', t) and not intent.get('file'): return True return bool(re.match(r'(?i)^(?:also\s+|add\s+(?:a\s+)?step\s*:?|drop\s+(?:the\s+)?requirement\s+|replace\s+|change\s+|because\s+|' r'(?:it|the\s+\w+)\s+(?:should|must|needs? to|remembers?|retains?|starts?)\b)', t))
def owns_turn(text, work=None, reading=None): """Conversation can defer an actual build/fill while retaining ordinary questions.""" if re.match(r'(?i)^\s*(?:why|how|what|explain|discuss|compare|tell me)\b', text) or text.rstrip().endswith('?') and not (_START.match(text) or _native_opening(reading)): return False return accepts(text, kept=work, reading=reading)
def accepts(text, root=None, kept=None, reading=None): intent = (kept or {}).get('build_intent') if _is_continuation(text, intent): return True try: import program_prose if program_prose.receive(text, kept=(intent or {}).get('interactive'), reading=reading) is not None: return True except ImportError: pass if not _START.match(text) and not _native_opening(reading): return False if re.match(r'(?i)^\s*(?:what if|explain|discuss|compare)\b', text): return False # Explicit existing table-project command syntax retains its owner. import project if project.ENTRY.search(text): return False # A build over a named table with an outcome someone can see is the table # project's request (its store, sha reuse and judges): the same ownership # work_tasks.accepts states, applied before this receiver takes the turn. if project.DATA.search(text) and project.is_project(text, None, root): return False mask, unused = _masked(text) if re.match(r'(?is)^\s*(?:build|create|make|write)\s+[\w./-]+\.py\s+from\s+[\w./-]+\.(?:steps|txt|md)\b', mask): return False # the earlier description-file connection keeps its owner return bool(re.search(r'(?i)\b(?:that|which|to)\b|:\s*\S|\b(?:browser|interactive)\b', mask))
def receive(text, kept=None, reading=None): prior = copy.deepcopy(kept) if kept else None if prior and (prior.get('original') == text or prior.get('turns') and prior['turns'][-1]['text'] == text): return prior part_reading, native_reasons_received = _delegated_reasons(text, reading) try: import program_prose interactive = program_prose.receive(text, kept=(prior or {}).get('interactive'), reading=part_reading) except ImportError: interactive = None fresh = bool(_START.match(text) or _native_opening(reading)) and not _REVISION.match(text) fresh = fresh or bool(interactive and interactive.get('original') == text and (prior or {}).get('original') != text) intent = {'version': 1, 'original': text, 'turns': [], 'mode': 'pipeline', 'file': None, 'stages': [], 'examples': [], 'reasons': [], 'constraints': [], 'requirements': [], 'unbound': []} if fresh or not prior else prior intent['turns'].append({'text': text, 'reading': copy.deepcopy(reading)}) if reading and reading.get('graph'): intent.setdefault('graphs', []).append(copy.deepcopy(reading['graph'])) if interactive is not None: intent['mode'], intent['interactive'] = 'interactive', interactive for reason in native_reasons_received: if reason not in intent['reasons']: intent['reasons'].append(reason) correction = _REVISION.match(text) pieces = clauses(correction.group(1) if correction else text) if fresh and pieces: destinations = re.findall(r'(?<![\w])([\w./-]+\.py)\b', pieces[0]) if len(set(destinations)) == 1: intent['file'] = destinations[0] graph = (reading or {}).get('graph') or {} reason_ids = {link.get('from') for link in graph.get('links', []) if link.get('kind') == 'reason'} native_reasons = {node.get('text', '').strip(' .;') for node in graph.get('nodes', []) if node.get('id') in reason_ids} for piece in pieces: record = {'id': 'I%d' % (len(intent['requirements']) + 1), 'text': piece, 'kind': 'behavior'} record['reading_nodes'] = [node['id'] for node in graph.get('nodes', []) if node.get('text') and node['text'] in piece] dest = _DEST.match(piece) drop = re.match(r'(?is)^drop\s+(?:the\s+)?requirement\s+(.+)$', piece) if drop: named = drop.group(1).strip('`"\' ') matching = [item for item in intent['unbound'] if item['text'].strip(' .;') == named.strip(' .;')] stage_matches = [stage for stage in intent['stages'] if stage == named] if len(matching) + len(stage_matches) == 1: intent['unbound'] = [item for item in intent['unbound'] if item not in matching] intent['stages'] = [stage for stage in intent['stages'] if stage not in stage_matches] intent.setdefault('revisions', []).append({'before': named, 'after': None, 'request': piece}) record['kind'] = 'revision' else: intent['unbound'].append({'text': piece, 'hole': 'Name one exact kept requirement to drop.'}) elif not dest and not intent.get('file') and re.fullmatch(r'[\w./-]+\.py', piece): intent['file'] = piece; record.update(kind='destination', field='file') elif dest: intent['file'] = dest.group(1); record.update(kind='destination', field='file') elif _CHECK.match(piece): intent['check'] = _CHECK.match(piece).group(1); record.update(kind='evidence', field='check') elif example(piece) is not None: received = example(piece) if 'hole' in received: intent['unbound'].append({'text': piece, 'hole': received['hole'], 'field': 'examples'}) else: intent['unbound'] = [item for item in intent['unbound'] if item.get('field') != 'examples'] # An explicitly revised example replaces its same input only. for one in [dict((k, v) for k, v in received.items() if k != 'more')] + list(received.get('more') or []): key = {k: v for k, v in one.items() if k != 'expected'} intent['examples'] = [old for old in intent['examples'] if {k: v for k, v in old.items() if k != 'expected'} != key] intent['examples'].append(one) record.update(kind='evidence', field='examples') elif re.match(r'(?i)^because\b', piece) or piece in native_reasons: intent['reasons'].append(piece); record['kind'] = 'reason' elif re.search(r"(?i)\b(?:do not|don't|must not|never|without)\b", piece): intent['constraints'].append({'text': piece}); record['kind'] = 'constraint' elif intent['mode'] == 'interactive': record['owner'] = 'interactive' if interactive is None: intent['unbound'].append({'text': piece, 'hole': 'The browser program has no connected meaning for this requirement yet: ' + piece, 'field': 'behavior'}) else: body = piece header = _START.match(body) native_header = _native_opening(reading) if not header and native_header and body.startswith(native_header['text']): body = re.sub(r'(?is)^\s*(?:that|which|to|:)\s*', '', body[len(native_header['text']):]) record.update(kind='goal', native_owner=native_header['id']) if header: prefix = header.group() output = re.findall(r'[\w./-]+\.py\b', prefix) if len(output) == 1: intent['file'] = output[0] body = re.sub(r'(?is)^\s*(?:that|which|to|:)\s*', '', body[header.end():]) # Named project purpose is retained in the original; every # remaining requested stage must be connected below. record['kind'] = 'goal' masked, literals = _masked(body) reason = re.search(r'(?i)\s+because\s+', masked) if reason: intent['reasons'].append(_restore(masked[reason.start():].strip(), literals)) body = _restore(masked[:reason.start()], literals) change = re.match(r'(?is)^(?:replace|change)\s+(.+?)\s+(?:with|to)\s+(.+)$', body) if change: old, new = change.groups() matches = [i for i, stage in enumerate(intent['stages']) if stage.lower() == old.strip('`"\' ').lower()] if len(matches) == 1: intent.setdefault('revisions', []).append({'before': intent['stages'][matches[0]], 'after': new, 'request': piece}) intent['stages'][matches[0]:matches[0]+1] = _stages(new.strip('`"\' '), reading) else: intent['unbound'].append({'text': piece, 'hole': 'Name the exact stage to replace; the earlier stages remain kept.'}) elif correction: stages = _stages(body, reading) if len(stages) == 1: verb = stages[0].split()[0].lower() if stages[0].split() else '' matches = [i for i, stage in enumerate(intent['stages']) if stage.split()[0].lower() == verb] if len(matches) == 1: intent.setdefault('revisions', []).append({'before': intent['stages'][matches[0]], 'after': stages[0], 'request': piece}) intent['stages'][matches[0]] = stages[0] else: intent['unbound'].append({'text': piece, 'hole': 'Name the stage this correction replaces; the full correction is kept.'}) else: intent['unbound'].append({'text': piece, 'hole': 'Name the stage or complete description this correction replaces.'}) elif body.strip(): body = re.sub(r'(?i)^(?:also\s+|add\s+(?:a\s+)?step\s*:?\s*)', '', body) for stage in _stages(body, reading): # a stage that names the destination ("call it temps.py") or gives examples ("2 gives 7") is that # destination or evidence, not a program step; a stage mixing them is read part by part parts = [p.strip().rstrip('.') for p in re.split(r',\s*', stage) if p.strip()] kinds = [('dest', _DEST.match(p)) if _DEST.match(p) else ('example', example(p)) for p in parts] if all(found and (kind == 'dest' or 'input' in found) for kind, found in kinds): for kind, found in kinds: if kind == 'dest': intent['file'] = found.group(1) else: intent['examples'] += [dict((k, v) for k, v in found.items() if k != 'more')] + list(found.get('more') or []) else: intent['stages'].append(stage) intent['requirements'].append(record) return intent
def semantic(intent): result = {key: copy.deepcopy(intent.get(key)) for key in ('mode', 'file', 'stages', 'examples', 'check', 'constraints', 'unbound')} if intent.get('interactive'): result['interactive'] = {key: copy.deepcopy(intent['interactive'].get(key)) for key in ('contract', 'holes', 'ready')} return result
def holes(intent): found = [{'kind': 'meaning', 'text': item['hole'], 'received': item['text']} for item in intent.get('unbound', [])] if not intent.get('file'): found.append({'kind': 'destination', 'text': 'What should the program file be called? For example, call it report.py.'}) if intent['mode'] == 'interactive': found.extend(dict(item, text=item.get('needed') or item['text'], received=item.get('text')) for item in intent['interactive'].get('holes', [])) else: if not intent.get('stages'): found.append({'kind': 'description', 'text': 'Describe what the program should do to its input.'}) if not intent.get('examples') and not intent.get('check'): found.append({'kind': 'behavior', 'text': 'Give an input and its expected result, or name the existing behavior check. The described stages are kept.'}) return found
def build(root, intent, runenv=None): import work_tasks as work missing = holes(intent) if missing: raise work.WorkHole('project-input', ' '.join(item['text'] for item in missing), fields=missing) if intent['mode'] == 'interactive': import work_bindings result = work_bindings.execute('interactive_program', {'contract': intent['interactive']['contract'], 'file': intent['file']}, root, runenv) else: import program_steps args = {'description': '; '.join(intent['stages']), 'file': intent['file'], 'examples': intent.get('examples') or []} if intent.get('check') and not intent.get('examples'): args['check'] = intent['check'] result = program_steps.build(root, args, runenv) else: with tempfile.TemporaryDirectory(prefix='oracle7-received-check-') as directory: request = Path(directory) / 'examples.json' request.write_text(json.dumps({'source': str(work._path(root, intent['file'])), 'examples': intent['examples']}, allow_nan=False), encoding='utf-8') example_check = [sys.executable, '-I', str(Path(__file__).with_name('program_examples.py')), str(request)] args['check'] = intent.get('check') or example_check if intent.get('check'): args['postcondition'] = example_check result = program_steps.build(root, args, runenv) result['received'] = {'original': intent['original'], 'requirements': intent['requirements'], 'reasons': intent['reasons'], 'examples': intent['examples'], 'revisions': intent.get('revisions', [])} return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541"""Record interaction part: a selection, typed edit and explicit relation write.
Connects a project's source shape to the existing table/three.js scene. Thewriter embeds runtime_source() after project_sources.runtime_source(); generatedprograms use only the standard library. Every editable cell has a source row,and every relationship has declared endpoint columns. No first-file writeback."""import reimport project_sources as PS
_RUNTIME = r'''import csv as _i_csvimport hashlib as _i_hashimport html as _i_htmlimport io as _i_ioimport json as _i_jsonimport math as _i_mathimport os as _i_osimport secrets as _i_secretsimport tempfile as _i_tempfileimport threading as _i_threadingfrom pathlib import Path as _IPathfrom http.server import BaseHTTPRequestHandler as _IHandler, ThreadingHTTPServer as _IServerfrom urllib.parse import urlsplit as _i_urlsplit
_I_LOCK = _i_threading.RLock()_I_TOKEN = _i_secrets.token_urlsafe(32)
class InteractionError(ValueError): def __init__(self, message, status=400): super().__init__(message) self.status = status
def _i_path(root, filename): base = _IPath(root).resolve() path = (base / filename).resolve() if base not in path.parents or path.suffix.lower() not in ('.csv', '.json', '.jsonl'): raise InteractionError('name a CSV, JSON or JSONL file inside the project folder') return path
def _i_files(graph): if graph.get('op') == 'read': return [graph['file']] children = graph.get('inputs', []) if graph.get('op') == 'union' else [graph['left'], graph['right']] return list(dict.fromkeys(filename for child in children for filename in _i_files(child)))
def _i_origins(graph, root): """Rows paired with cell origins (file, row index, original column).""" op = graph['op'] if op == 'read': cols, rows = source_snapshot(graph, root) return cols, [(row, {c: (graph['file'], i, c) for c in cols}) for i, row in enumerate(rows)] if op == 'union': cols, result = source_snapshot(graph, root)[0], [] for child in graph['inputs']: result.extend(_i_origins(child, root)[1]) return cols, result lc, left = _i_origins(graph['left'], root) rc, right = _i_origins(graph['right'], root) left_keys, right_keys = zip(*graph['keys']) extra = [c for c in rc if c not in right_keys] index = {} for row, provenance in right: key = _source_key(row, right_keys) if key is not None: index.setdefault(key, []).append((row, provenance)) result = [] for row, provenance in left: key = _source_key(row, left_keys) matches = index.get(key, []) if key is not None else [] for other, origins in matches: result.append((dict(row, **{c: other[c] for c in extra}), dict(provenance, **{c: origins[c] for c in extra}))) if not matches and graph.get('how') == 'left': result.append((dict(row, **{c: None for c in extra}), dict(provenance))) return lc + extra, result
def _i_id(value): if value is None or isinstance(value, (list, dict, bool)) or not str(value).strip(): raise InteractionError('each record needs a nonempty scalar identity; name a unique identity column') if isinstance(value, float) and not _i_math.isfinite(value): raise InteractionError('record identities must be finite values') return str(value)
def _i_index(rows, identity): index = {} for row in rows: if identity not in row: raise InteractionError('the view does not retain identity column %s; retain it before enabling edits' % identity) key = _i_id(row[identity]) if key in index: raise InteractionError('identity %s occurs more than once; name a unique record identity or remove join fan-out' % key) index[key] = row return index
def _i_versions(binding, root): files = _i_files(binding['source']) + ([binding['edges']['file']] if binding.get('edges') else []) marks = {} for filename in files: path = _i_path(root, filename) marks[filename] = _i_hash.sha256(path.read_bytes()).hexdigest() if path.exists() else None return marks
def _i_version(marks): return _i_hash.sha256(_i_json.dumps(marks, sort_keys=True).encode()).hexdigest()
def _i_edges(binding, root, all_ids): spec = binding.get('edges') if not spec: return [], [] path = _i_path(root, spec['file']) if not path.exists() and not spec.get('create'): raise InteractionError('relationship file %s is missing; add it or explicitly ask to create relationship storage' % spec['file']) cols, records = source_snapshot({'op': 'read', 'file': spec['file']}, root) if path.exists() else (list(dict.fromkeys([spec['from'], spec['to']] + ([spec['label']] if spec.get('label') else []))), []) if spec['from'] == spec['to'] or any(c not in cols for c in [spec['from'], spec['to']] + ([spec['label']] if spec.get('label') else [])): raise InteractionError('relationship storage needs distinct declared endpoint columns, and its declared label column') seen, edges = set(), [] for record in records: source, target = _i_id(record[spec['from']]), _i_id(record[spec['to']]) if source not in all_ids or target not in all_ids: raise InteractionError('relationship %s -> %s has no corresponding record; correct its endpoints' % (source, target)) if (source, target) in seen: raise InteractionError('relationship %s -> %s is duplicated; give each endpoint pair one record' % (source, target)) seen.add((source, target)) edges.append({'source': source, 'target': target, 'label': str(record.get(spec.get('label'), '') or '')}) return cols, edges
def _i_snapshot(binding, compute, root): before = _i_versions(binding, root) source_snapshot(binding['source'], root) # validate the composed source contract _cols, joined = _i_origins(binding['source'], root) all_rows = [row for row, _origin in joined] all_ids = _i_index(all_rows, binding['identity']) origins = {_i_id(row[binding['identity']]): origin for row, origin in joined} rows = compute() if not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows): raise InteractionError('the editable view must return records') visible = _i_index(rows, binding['identity']) if any(key not in origins for key in visible): raise InteractionError('a displayed record has no owning source row') _edge_columns, edges = _i_edges(binding, root, all_ids) after = _i_versions(binding, root) if before != after: raise InteractionError('the inputs changed while the view was read; refresh and try again', 409) return {'rows': rows, 'origins': origins, 'all_ids': all_ids, 'edges': edges, 'marks': before, 'version': _i_version(before)}
def interactive_state(binding, compute, root='.'): with _I_LOCK: snap = _i_snapshot(binding, compute, root) permissions = {key: [c for c in binding['editable'] if c in snap['origins'][key]] for key in _i_index(snap['rows'], binding['identity'])} return {'version': snap['version'], 'rows': snap['rows'], 'identity': binding['identity'], 'columns': binding['columns'], 'editable': binding['editable'], 'types': binding['types'], 'value': binding.get('value'), 'permissions': permissions, 'edges': snap['edges'], 'relationships': bool(binding.get('edges'))}
def _i_coerce(value, shape, column): kind = shape['type'] if value is None or value == '': if shape.get('nullable'): return None if value is None else '' if kind != 'string': raise InteractionError('%s needs a %s value' % (column, kind)) try: if kind == 'boolean': if value is True or value in ('true', 'True'): return True if value is False or value in ('false', 'False'): return False raise ValueError() if kind in ('integer', 'number'): if isinstance(value, bool): raise ValueError() number = float(value) if not _i_math.isfinite(number) or kind == 'integer' and not number.is_integer(): raise ValueError() return int(number) if kind == 'integer' else number if not isinstance(value, str): raise ValueError() return value except (TypeError, ValueError, OverflowError): raise InteractionError('%s needs a finite %s value' % (column, kind))
def _i_prepare(root, filename, rows, cols, expected): path = _i_path(root, filename) old = path.read_bytes() if path.exists() else None actual = _i_hash.sha256(old).hexdigest() if old is not None else None if actual != expected: raise InteractionError('the file changed since it was read; refresh before saving', 409) encoding = 'utf-8-sig' if old and old.startswith(b'\xef\xbb\xbf') else 'utf-8' if path.suffix.lower() == '.csv': output = _i_io.StringIO(newline='') writer = _i_csv.DictWriter(output, fieldnames=cols) writer.writeheader() writer.writerows(rows) content = output.getvalue() elif path.suffix.lower() == '.jsonl': content = ''.join(_i_json.dumps(row, ensure_ascii=False, allow_nan=False) + '\n' for row in rows) else: original = _i_json.loads(old.decode(encoding)) if old is not None else [] if isinstance(original, dict): wrapper = next((k for k, value in original.items() if isinstance(value, list)), None) if wrapper is None: if len(rows) != 1: raise InteractionError('a single-object JSON source must retain one record') original = rows[0] else: original[wrapper] = rows else: original = rows content = _i_json.dumps(original, indent=2, ensure_ascii=False, allow_nan=False) + '\n' raw = content.encode(encoding) return {'file': filename, 'old': old, 'raw': raw, 'before': expected, 'after': _i_hash.sha256(raw).hexdigest()}
def _i_atomic_bytes(path, content): temporary = None try: path.parent.mkdir(parents=True, exist_ok=True) with _i_tempfile.NamedTemporaryFile(mode='wb', dir=str(path.parent), delete=False) as handle: temporary = handle.name handle.write(content) handle.flush() _i_os.fsync(handle.fileno()) if path.exists(): _i_os.chmod(temporary, path.stat().st_mode) _i_os.replace(temporary, path) temporary = None finally: if temporary is not None: _i_os.unlink(temporary)
def _i_commit(binding, compute, root, prepared, marks): """All values are staged first; a failed save restores only our own versions.""" written = [] expected = dict(marks) try: for change in prepared: if _i_versions(binding, root) != expected: raise InteractionError('the inputs changed while the save was prepared; refresh and try again', 409) _i_atomic_bytes(_i_path(root, change['file']), change['raw']) written.append(change) expected[change['file']] = change['after'] return interactive_state(binding, compute, root) except Exception as error: preserved = [] for change in reversed(written): path = _i_path(root, change['file']) current = _i_hash.sha256(path.read_bytes()).hexdigest() if path.exists() else None if current != change['after']: preserved.append(change['file']) continue if change['old'] is None: path.unlink() else: _i_atomic_bytes(path, change['old']) if preserved: raise InteractionError('the save could not complete; newer changes in %s were preserved, and other writes were restored; refresh before continuing' % ', '.join(preserved), 409) from error raise InteractionError('the edit could not be completed; no changes were kept: %s' % error, getattr(error, 'status', 400)) from error
def interactive_update(binding, compute, payload, root='.'): if not isinstance(payload, dict): raise InteractionError('send an action object') with _I_LOCK: snap = _i_snapshot(binding, compute, root) if payload.get('version') != snap['version']: raise InteractionError('these records changed; refresh before saving your edit', 409) action = payload.get('action') if action == 'update': identity = _i_id(payload.get('id')) if identity not in _i_index(snap['rows'], binding['identity']): raise InteractionError('select a record currently shown in this view') changes = payload.get('changes') if not isinstance(changes, dict) or not changes: raise InteractionError('give the fields and values to change') provenance, pending = snap['origins'][identity], {} for column in changes: if column not in binding['editable'] or column not in provenance: raise InteractionError('%s is not an editable source field for this record' % column) for column, value in changes.items(): filename, index, original_column = provenance[column] if filename not in pending: pending[filename] = source_snapshot({'op': 'read', 'file': filename}, root) cols, rows = pending[filename] coerced = _i_coerce(value, binding['types'][column], column) original = _i_coerce(rows[index][original_column], binding['types'][column], column) if coerced == original and type(coerced) is type(original): continue rows[index][original_column] = ('' if coerced is None else str(coerced)) if filename.lower().endswith('.csv') else coerced prepared = [] for filename, (cols, rows) in pending.items(): original_rows = source_snapshot({'op': 'read', 'file': filename}, root)[1] if rows != original_rows: prepared.append(_i_prepare(root, filename, rows, cols, snap['marks'][filename])) elif action in ('edge_add', 'edge_remove'): spec = binding.get('edges') if not spec: raise InteractionError('this view has no declared relationship storage') source, target = _i_id(payload.get('source')), _i_id(payload.get('target')) if source not in snap['all_ids'] or target not in snap['all_ids']: raise InteractionError('both relationship endpoints must identify existing records') path = _i_path(root, spec['file']) if path.exists(): cols, rows = source_snapshot({'op': 'read', 'file': spec['file']}, root) else: cols, rows = list(dict.fromkeys([spec['from'], spec['to']] + ([spec['label']] if spec.get('label') else []))), [] matches = [i for i, row in enumerate(rows) if (_i_id(row[spec['from']]), _i_id(row[spec['to']])) == (source, target)] if action == 'edge_add': if matches: raise InteractionError('that relationship already exists') if any(c not in (spec['from'], spec['to'], spec.get('label')) for c in cols): raise InteractionError('relationship storage has extra required fields; declare their values before adding a relationship') row = {spec['from']: snap['all_ids'][source][binding['identity']], spec['to']: snap['all_ids'][target][binding['identity']]} if spec.get('label'): label = payload.get('label', '') if not isinstance(label, str): raise InteractionError('a relationship label must be text') row[spec['label']] = label rows.append(row) else: if not matches: raise InteractionError('that relationship no longer exists; refresh', 409) rows.pop(matches[0]) prepared = [_i_prepare(root, spec['file'], rows, cols, snap['marks'][spec['file']])] else: raise InteractionError('choose update, edge_add or edge_remove') return _i_commit(binding, compute, root, prepared, snap['marks'])
def interactive_page(page, binding, compute, root='.'): state = interactive_state(binding, compute, root) bootstrap = _i_json.dumps({'state': state, 'token': _I_TOKEN}, ensure_ascii=False, allow_nan=False).replace('<', '\\u003c') panel = _I_PANEL + '<script type="application/json" id="oracle7-interaction">' + bootstrap + '</script><script>' + _I_CLIENT + '</script>' return page.replace('</main>', panel + '</main>', 1) if '</main>' in page else page + panel
def interactive_handler(render, binding, compute, root='.'): class Handler(_IHandler): def log_message(self, *_args): pass def send_json(self, status, value): body = _i_json.dumps(value, ensure_ascii=False, allow_nan=False).encode('utf-8') self.send_response(status) self.send_header('Content-Type', 'application/json; charset=utf-8') self.send_header('Cache-Control', 'no-store') self.send_header('Content-Length', str(len(body))) self.end_headers(); self.wfile.write(body) def valid_host(self): return self.headers.get('Host') in ('127.0.0.1:%d' % self.server.server_port, 'localhost:%d' % self.server.server_port) def do_GET(self): if not self.valid_host(): return self.send_json(403, {'error': 'use this project on its local address'}) try: path = _i_urlsplit(self.path).path if path == '/_oracle7/state': return self.send_json(200, interactive_state(binding, compute, root)) if path not in ('/', '/index.html'): return self.send_json(404, {'error': 'no such project resource'}) body = interactive_page(render(), binding, compute, root).encode('utf-8') self.send_response(200) self.send_header('Content-Type', 'text/html; charset=utf-8') self.send_header('Cache-Control', 'no-store') self.send_header('Content-Length', str(len(body))) self.end_headers(); self.wfile.write(body) except (InteractionError, ProjectSourceError, OSError, ValueError) as error: self.send_json(getattr(error, 'status', 400), {'error': str(error)}) def do_POST(self): if not self.valid_host(): return self.send_json(403, {'error': 'use this project on its local address'}) if _i_urlsplit(self.path).path != '/_oracle7/action': return self.send_json(404, {'error': 'no such project action'}) expected_origin = 'http://' + self.headers.get('Host', '') if self.headers.get('Origin') != expected_origin or self.headers.get('X-Oracle7-Token') != _I_TOKEN: return self.send_json(403, {'error': 'open this project page before saving changes'}) try: size = int(self.headers.get('Content-Length', '0')) if size <= 0 or size > 65536: raise InteractionError('the action must be between 1 and 65536 bytes', 413) if self.headers.get('Content-Type', '').split(';')[0] != 'application/json': raise InteractionError('send a JSON action', 415) payload = _i_json.loads(self.rfile.read(size)) self.send_json(200, interactive_update(binding, compute, payload, root)) except (InteractionError, ProjectSourceError, OSError, ValueError, TypeError) as error: self.send_json(getattr(error, 'status', 400), {'error': str(error)}) return Handler
def serve_interactive(port, render, binding, compute, root='.'): server = _IServer(('127.0.0.1', port), interactive_handler(render, binding, compute, root)) try: server.serve_forever() finally: server.server_close()'''
_PANEL = '''<section id="oracle7-editor" aria-label="Record editor"><h2>Edit selected record</h2><p id="o7-selection">Select a table row or a 3D object.</p><form id="o7-edit-form"><div id="o7-fields"></div><button type="submit" id="o7-save" disabled>Save changes</button><button type="button" id="o7-refresh">Refresh</button></form><div id="o7-relations" hidden><h3>Relationships</h3><form id="o7-edge-form"><label>Connect selected record to <select id="o7-target"></select></label><label>Label <input id="o7-edge-label" type="text"></label><button type="submit">Add relationship</button></form><ul id="o7-edges"></ul></div><p id="o7-message" role="status" aria-live="polite"></p></section><style>#oracle7-editor{padding:20px 0;border-top:1px solid currentColor}#o7-fields{display:flex;gap:12px;flex-wrap:wrap;margin-bottom:12px}#oracle7-editor label{display:flex;gap:6px;flex-direction:column}#oracle7-editor input,#oracle7-editor select{font:inherit;max-width:24em}#oracle7-editor button{font:inherit;margin:4px 8px 4px 0;cursor:pointer}#o7-edge-form{display:flex;gap:12px;align-items:end;flex-wrap:wrap}</style>'''
_CLIENT = r'''(() => { const boot=JSON.parse(document.getElementById('oracle7-interaction').textContent), fields=document.getElementById('o7-fields'); let state=boot.state, selected=null; const message=(text,error=false)=>{const p=document.getElementById('o7-message');p.textContent=text;p.dataset.error=String(error);}; function selection(id){ selected=id==null?null:String(id); const row=state.rows.find(r=>String(r[state.identity])===selected); document.getElementById('o7-selection').textContent=row?'Selected: '+selected:'Select a table row or a 3D object.'; fields.replaceChildren(); document.getElementById('o7-save').disabled=!row; if(row) for(const col of state.editable){ const label=document.createElement('label');label.textContent=col; const input=document.createElement('input');input.name=col;input.dataset.original=JSON.stringify(row[col]); const type=state.types[col].type;input.type=type==='boolean'?'checkbox':(type==='number'||type==='integer'?'number':'text'); if(input.type==='checkbox')input.checked=row[col]===true||String(row[col]).toLowerCase()==='true';else input.value=row[col]??''; if(input.type==='number')input.step=type==='integer'?'1':'any'; input.disabled=!(state.permissions[selected]||[]).includes(col);label.append(input);fields.append(label); } document.querySelectorAll('tr[data-id]').forEach(tr=>tr.classList.toggle('sel',tr.dataset.id===selected)); const target=document.getElementById('o7-target');target.replaceChildren(); for(const row of state.rows){const option=document.createElement('option');option.value=String(row[state.identity]);option.textContent=option.value;target.append(option);} const list=document.getElementById('o7-edges');list.replaceChildren(); for(const edge of state.edges.filter(e=>e.source===selected||e.target===selected)){ const item=document.createElement('li');item.textContent=edge.source+' → '+edge.target+(edge.label?' ('+edge.label+')':'')+' '; const remove=document.createElement('button');remove.type='button';remove.textContent='Remove'; remove.addEventListener('click',()=>action({action:'edge_remove',source:edge.source,target:edge.target}));item.append(remove);list.append(item); } } function render(){ const table=document.querySelector('main table');if(table){table.replaceChildren();const head=document.createElement('tr'); for(const col of state.columns){const th=document.createElement('th');th.textContent=col;head.append(th);}table.append(head); for(const row of state.rows){const tr=document.createElement('tr');tr.dataset.id=String(row[state.identity]);tr.tabIndex=0; for(const col of state.columns){const td=document.createElement('td');td.textContent=row[col]==null?'':String(row[col]);tr.append(td);}table.append(tr);}} const recordPayload=document.getElementById('oracle7-rows');if(recordPayload)recordPayload.textContent=JSON.stringify(state.rows); document.getElementById('o7-relations').hidden=!state.relationships; const records=state.rows.map(r=>({id:String(r[state.identity]),v:state.value==null||r[state.value]==null||r[state.value]===''?null:Number(r[state.value])})); if(window.__o7setRecords)window.__o7setRecords(records); if(window.__o7setEdges)window.__o7setEdges(state.edges); selection(selected);if(selected&&window.__o7select)window.__o7select(selected); window.__o7interaction.state=state;window.dispatchEvent(new CustomEvent('oracle7:state',{detail:state})); } async function action(payload){try{ const response=await fetch('/_oracle7/action',{method:'POST',headers:{'Content-Type':'application/json','X-Oracle7-Token':boot.token},body:JSON.stringify({...payload,version:state.version})}); const next=await response.json();if(!response.ok)throw new Error(next.error||'Save failed');state=next;render();message('Saved. Table and scene refreshed.');return state; }catch(error){message(error.message,true);throw error;}} async function refresh(){const response=await fetch('/_oracle7/state',{cache:'no-store'});const next=await response.json();if(!response.ok)throw new Error(next.error);state=next;render();return state;} document.getElementById('o7-edit-form').addEventListener('submit',event=>{event.preventDefault();const changes={}; for(const input of fields.querySelectorAll('input:not(:disabled)')){const value=input.type==='checkbox'?input.checked:input.value; const original=JSON.parse(input.dataset.original);if(String(value)!==String(original??''))changes[input.name]=value;} if(!Object.keys(changes).length)return message('No values changed.');action({action:'update',id:selected,changes}).catch(()=>{}); }); document.getElementById('o7-edge-form').addEventListener('submit',event=>{event.preventDefault();if(!selected)return message('Select a record first.',true); action({action:'edge_add',source:selected,target:document.getElementById('o7-target').value,label:document.getElementById('o7-edge-label').value}).catch(()=>{});}); document.getElementById('o7-refresh').addEventListener('click',()=>refresh().then(()=>message('Refreshed.')).catch(e=>message(e.message,true))); document.addEventListener('click',event=>{const tr=event.target.closest('tr[data-id]');if(tr){selection(tr.dataset.id);if(window.__o7select)window.__o7select(tr.dataset.id);}}); document.addEventListener('keydown',event=>{if(event.key==='Enter'&&event.target.matches('tr[data-id]')){selection(event.target.dataset.id);if(window.__o7select)window.__o7select(selected);}}); window.addEventListener('oracle7:select',event=>selection(event.detail.id)); window.addEventListener('oracle7:scene-ready',()=>render()); window.__o7interaction={state,select:selection,refresh,save:changes=>action({action:'update',id:selected,changes}), addEdge:(source,target,label='')=>action({action:'edge_add',source,target,label}),removeEdge:(source,target)=>action({action:'edge_remove',source,target})}; render();})();'''
def runtime_source(): return _RUNTIME.strip() + '\n\n_I_PANEL = ' + repr(_PANEL) + '\n_I_CLIENT = ' + repr(_CLIENT) + '\n'
source_snapshot = PS.source_snapshot_source_key = PS._source_keyProjectSourceError = PS.SourceErrorexec(runtime_source())
def _kind(values, parse_strings=True): present = [v for v in values if v is not None and v != ''] nullable = len(present) != len(values) if present and all(isinstance(v, bool) for v in present): return {'type': 'boolean', 'nullable': nullable} if any(isinstance(v, str) for v in present): if not parse_strings or any(re.match(r'^[+-]?0\d+', v) for v in present if isinstance(v, str)): return {'type': 'string' if all(isinstance(v, str) for v in present) else 'structured', 'nullable': nullable} try: numbers = [float(v) for v in present if not isinstance(v, bool)] if present and len(numbers) == len(present) and all(_i_math.isfinite(v) for v in numbers): return {'type': 'integer' if all(v.is_integer() for v in numbers) else 'number', 'nullable': nullable} except (ValueError, TypeError, OverflowError): pass if any(isinstance(v, (list, dict)) for v in present): return {'type': 'structured', 'nullable': nullable} return {'type': 'string', 'nullable': nullable}
def plan_interaction(root, source, rows=None, identity=None, editable=None, edges=None): """Bind editable cells and explicit relations, or say precisely what is missing.""" columns, all_rows = PS.source_snapshot(source, root) rows = all_rows if rows is None else rows identity = identity or ('id' if 'id' in columns else columns[0] if columns else None) if not identity or identity not in columns: raise InteractionError('name a stable identity column from the source records') _i_index(all_rows, identity) _i_index(rows, identity) reserved = {identity} def keys(graph): if graph.get('op') in ('join', 'lookup'): reserved.update(c for pair in graph['keys'] for c in pair) keys(graph['left']); keys(graph['right']) elif graph.get('op') == 'union': for child in graph['inputs']: keys(child) keys(source) _origin_columns, origin_rows = _i_origins(source, root) types = {c: _kind([r.get(c) for r in all_rows], parse_strings=all( origin.get(c, ('',))[0].lower().endswith('.csv') or not isinstance(row.get(c), str) for row, origin in origin_rows)) for c in columns} allowed = [c for c in columns if c not in reserved and types[c]['type'] != 'structured'] if editable is not None: requested = [editable] if isinstance(editable, str) else list(editable) invalid = [c for c in requested if c not in allowed] if invalid: raise InteractionError('these fields have no safe editable binding: %s; identities, join keys and derived values remain fixed' % ', '.join(invalid)) allowed = requested view_columns = list(dict.fromkeys(c for row in rows for c in row)) or columns if any(c not in view_columns for c in allowed): raise InteractionError('retain the editable fields in the displayed records') if edges: edges = dict(edges) if not all(isinstance(edges.get(k), str) and edges[k] for k in ('file', 'from', 'to')): raise InteractionError('name the relationship file and its from/to identity columns') if _i_path(root, edges['file']) in {_i_path(root, f) for f in _i_files(source)}: raise InteractionError('give relationships their own edge table; a record source cannot also be its edge storage') binding = {'v': 1, 'source': source, 'identity': identity, 'editable': allowed, 'columns': view_columns, 'types': {c: types[c] for c in allowed}, 'edges': edges, 'value': next((c for c in view_columns if c != identity and c in types and types[c]['type'] in ('integer', 'number')), None)} interactive_state(binding, lambda: rows, root) return binding123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377"""Named table parts for projects: read, stack, join and reference lookup.
The source shape is retained in the project plan. Columns are read from that
shape, not from the first file mentioned. The writer embeds runtime_source()
so a generated project remains a standalone standard-library program. The
outside judge has its own evaluator in judge/project_sources_judge.py.
"""
import re
from pathlib import Path
# This is also the source embedded in generated projects. Keep all its names
# separate from the older generated table/probe helpers.
_RUNTIME = r'''
import csv as _source_csv
import json as _source_json
import math as _source_math
from pathlib import Path as _SourcePath
class ProjectSourceError(ValueError):
pass
def _source_path(root, name):
base = _SourcePath(root).resolve()
# C15b: the name must stay inside the project folder as written ("../x.csv" is refused); a link the project keeps in
# its own folder (an adopted capability reading Oracle7's live records) is one of its sources
import os as _source_os
named = _SourcePath(_source_os.path.normpath(str(base / name)))
if named != base and base not in named.parents:
raise ProjectSourceError("source %s is outside the project folder" % name)
path = named
if not path.is_file():
raise ProjectSourceError("source %s is not in the project yet; add it and continue" % name)
return path
def _source_table(root, name):
path = _source_path(root, name)
try:
if str(name).lower().endswith('.jsonl'):
rows = [_source_json.loads(line) for line in path.read_text(encoding='utf-8-sig').splitlines() if line.strip()]
cols = list(rows[0]) if rows and isinstance(rows[0], dict) else []
elif str(name).lower().endswith('.json'):
rows = _source_json.loads(path.read_text(encoding='utf-8-sig'))
if isinstance(rows, dict):
rows = next((v for v in rows.values() if isinstance(v, list)), [rows])
if not isinstance(rows, list):
raise ProjectSourceError("%s must contain a table of records" % name)
cols = list(rows[0]) if rows and isinstance(rows[0], dict) else []
elif str(name).lower().endswith('.csv'):
with path.open(encoding='utf-8-sig', newline='') as handle:
reader = _source_csv.DictReader(handle)
cols = list(reader.fieldnames or [])
rows = list(reader)
if len(set(cols)) != len(cols) or any(not c for c in cols):
raise ProjectSourceError("%s has missing or duplicate column names" % name)
else:
raise ProjectSourceError("%s is not a CSV, JSON or JSONL table" % name)
except (OSError, ValueError, TypeError) as exc:
if isinstance(exc, ProjectSourceError):
raise
raise ProjectSourceError("%s could not be read as a table: %s" % (name, exc)) from exc
if any(not isinstance(row, dict) or set(row) != set(cols) for row in rows):
raise ProjectSourceError("%s has records with different columns or non-record rows" % name)
if any(not isinstance(c, str) for c in cols):
raise ProjectSourceError("%s has non-text column names" % name)
return cols, [dict(row) for row in rows]
def _source_key(row, columns):
key = []
for column in columns:
value = row.get(column)
if value is None or str(value).strip() == '':
return None
if isinstance(value, (list, dict)) or isinstance(value, float) and not _source_math.isfinite(value):
raise ProjectSourceError("join column %s must contain finite scalar keys" % column)
key.append(str(value).strip())
return tuple(key)
def source_snapshot(source, root='.'):
"""Return (ordered columns, rows), retaining empty CSV schemas."""
if not isinstance(source, dict):
raise ProjectSourceError("the source shape must name its part")
op = source.get('op')
if op == 'read':
return _source_table(root, source['file'])
if op == 'union':
inputs = source.get('inputs') or []
if not inputs:
raise ProjectSourceError("stacking needs at least one source")
cols, rows = None, []
for child in inputs:
child_cols, child_rows = source_snapshot(child, root)
if not child_cols and not child_rows:
continue
if cols is None:
cols = child_cols
if set(child_cols) != set(cols):
raise ProjectSourceError("stacked sources have different columns: %s versus %s" % (cols, child_cols))
rows.extend({c: row[c] for c in cols} for row in child_rows)
return cols or [], rows
if op not in ('join', 'lookup'):
raise ProjectSourceError("unknown source part %r" % op)
left_cols, left_rows = source_snapshot(source['left'], root)
right_cols, right_rows = source_snapshot(source['right'], root)
keys = source.get('keys') or []
if not keys or any(not isinstance(pair, (list, tuple)) or len(pair) != 2 for pair in keys):
raise ProjectSourceError("a join needs named left and right key columns")
left_keys, right_keys = [p[0] for p in keys], [p[1] for p in keys]
if len(set(left_keys)) != len(left_keys) or len(set(right_keys)) != len(right_keys):
raise ProjectSourceError("a join key column was bound more than once")
if any(c not in left_cols for c in left_keys) or any(c not in right_cols for c in right_keys):
raise ProjectSourceError("join key columns are missing: %s; left %s; right %s" % (keys, left_cols, right_cols))
right_out = [c for c in right_cols if c not in right_keys]
collisions = sorted(set(left_cols) & set(right_out))
if collisions:
raise ProjectSourceError("both sources supply %s; rename the non-key columns explicitly before joining" % ', '.join(collisions))
how = source.get('how', 'inner')
if how not in ('inner', 'left'):
raise ProjectSourceError("join kind %r is not represented; name inner or left" % how)
index = {}
for row in right_rows:
key = _source_key(row, right_keys)
if key is not None:
if op == 'lookup' and key in index:
raise ProjectSourceError("lookup has more than one reference row for key %s" % (key,))
index.setdefault(key, []).append(row)
rows = []
for row in left_rows:
key = _source_key(row, left_keys)
matches = index.get(key, []) if key is not None else []
if not matches and op == 'lookup':
raise ProjectSourceError("lookup has no reference row for key %s; supply a matching reference" % (key,))
for match in matches:
rows.append(dict(row, **{c: match[c] for c in right_out}))
if not matches and how == 'left':
rows.append(dict(row, **{c: None for c in right_out}))
return left_cols + right_out, rows
SOURCE_ROOT = '.' # where this program's sources are read: its folder when run there; an adopted capability's own folder
def read_source(source, root=None):
return source_snapshot(source, SOURCE_ROOT if root is None else root)[1]
'''
exec(_RUNTIME)
SourceError = ProjectSourceError
DATA = re.compile(r"(?<![\w./-])([\w./-]+\.(?:csv|jsonl|json))\b", re.I)
_SINK = re.compile(r"\b(?:save|write|export|output|dump|store)\w*\b[^;!?]{0,180}?\b(?:to|into|as)\s+`?([\w./-]+\.(?:csv|jsonl|json|txt|html))\b", re.I)
_COL = r"[a-zA-Z_][\w]*(?:\.[a-zA-Z_][\w]*)?"
_RELATION_WORDS = "join joins joined joining match matches matched matching inner left outer lookup lookups reference references combine combines combined combining stack stacks stacked stacking append appends appended union concatenate concatenated"
def runtime_source():
"""Standard-library helpers to embed verbatim in a generated module."""
return _RUNTIME.strip() + '\n'
def evaluate(root, source):
return read_source(source, root)
def files(source):
if not source:
return []
if source.get('op') == 'read':
return [source['file']]
children = source.get('inputs') if source.get('op') == 'union' else [source.get('left'), source.get('right')]
return list(dict.fromkeys(f for child in children or [] for f in files(child)))
def input_files(text, output_files=()):
"""Separate file occurrences by role, retaining an explicit read of a sink.
Output-only files never become inputs merely because they exist. If a file
is explicitly read AND written, retain its input role so the caller can
refuse that overwrite before writing the generated project.
"""
outputs = set(output_files)
targets = []
for sink in _SINK.finditer(text):
outputs.add(sink.group(1))
targets.append(sink.span(1))
end = sink.end(1)
# "export to first.csv and second.csv" names two sinks, not a union.
while True:
extra = re.match(r'`?\s*(?:,|and)\s+`?([\w./-]+\.(?:csv|jsonl|json|txt|html))\b', text[end:], re.I)
if not extra:
break
outputs.add(extra.group(1))
targets.append((end + extra.start(1), end + extra.end(1)))
end += extra.end(1)
explicit_input = re.compile(r'\b(?:from|read|reads|reading|load|loads|loading|using|uses|'
r'join|joins|joined|joining|combine|combines|combined|stack|stacks|'
r'append|appends|union|lookup|reference|with|and|of|for)\s+'
r'(?:(?:the|a)\s+)?(?:(?:file|table)\s+(?:(?:named|called)\s+)?)?`?$', re.I)
inputs = []
for mention in DATA.finditer(text):
if any(start <= mention.start(1) and mention.end(1) <= end for start, end in targets):
continue
name = mention.group(1)
if name not in outputs or explicit_input.search(text[:mention.start(1)]):
inputs.append(name)
return list(dict.fromkeys(inputs))
def _numeric(value):
if value is None or isinstance(value, bool):
return False
try:
return bool(str(value).strip()) and __import__('math').isfinite(float(value))
except (ValueError, TypeError):
return False
def describe(root, source):
cols, rows = source_snapshot(source, root)
url = next((c for c in cols if rows and all(re.match(r'^https?://', str(r.get(c, '')), re.I) for r in rows)), None)
key = next((c for c in cols if c != url and rows and len({str(r.get(c)) for r in rows}) == len(rows)
and not all(_numeric(r.get(c)) for r in rows)), None)
if key is None:
key = next((c for c in cols if c != url and rows and len({str(r.get(c)) for r in rows}) == len(rows)), None)
names = files(source)
return {'file': names[0] if names else None, 'files': names, 'source': source, 'cols': cols, 'url': url, 'key': key,
'n': len(rows), 'numeric': [c for c in cols if rows and all(_numeric(r.get(c)) for r in rows)],
'sample': dict(rows[0]) if rows else {},
'hosts': sorted({re.sub(r'^https?://([^/:]+).*$', r'\1', str(r[url])) for r in rows}) if url else []}
def _read(file):
return {'op': 'read', 'file': file}
def _column(token, cols, names):
bits = token.strip('`').split('.')
if len(bits) == 2 and bits[0].lower() not in {Path(n).stem.lower() for n in names}:
return None
return next((c for c in cols if c.lower() == bits[-1].lower()), None)
def _key_phrase(text, left_cols, right_cols, left_files, right_files, allow_incomplete=False):
"""The bounded binding text and raw column pairs, before column validation."""
marker = re.search(r'\b(?:matching|matched|matches|match)(?:\s+(?:on|by))?\s+', text, re.I)
if marker is None:
# An unqualified `on` immediately before a column is the source binding;
# `on a page` and `group by` are not source bindings.
candidates = list(re.finditer(r'\bon\s+(?=' + _COL + r')', text, re.I))
for candidate in reversed(candidates):
word = re.match(_COL, text[candidate.end():])
if word and (_column(word.group(), left_cols, left_files) or _column(word.group(), right_cols, right_files)):
marker = candidate
break
if marker is None:
return None, None
tail = text[marker.end():]
pair = re.match(r'(' + _COL + r')\s*(?:=|\b(?:equals|to|with)\b)\s*(' + _COL + r')', tail, re.I)
if pair:
a, b = pair.groups()
return [[a, b]], (marker.start(), marker.end() + pair.end())
first = re.match(_COL, tail)
if not first:
if allow_incomplete:
return [], (marker.start(), marker.end())
raise SourceError('name a column after matching on')
tokens = [first.group()]
end = first.end()
while True:
more = re.match(r'\s*(?:,|and)\s*(' + _COL + r')', tail[end:], re.I)
if not more:
break
token = more.group(1)
if not (_column(token, left_cols, left_files) and _column(token, right_cols, right_files)):
break
following = tail[end + more.end():]
if re.match(r'\s+(?:is|are|over|above|under|below|more than|less than|at least|at most)\b', following, re.I):
break
tokens.append(token)
end += more.end()
return [[token, token] for token in tokens], (marker.start(), marker.end() + end)
def _keys(text, left_cols, right_cols, left_files, right_files, override=None):
"""Use an explicit correction, an original binding, or one shared column."""
pairs, span = _key_phrase(text, left_cols, right_cols, left_files, right_files, allow_incomplete=override is not None)
if override is not None:
pairs, replacement_span = _key_phrase(override, left_cols, right_cols, left_files, right_files)
if pairs is None:
raise SourceError('the key correction must say matching on a column or left_column = right_column')
remainder = override[:replacement_span[0]] + override[replacement_span[1]:]
if remainder.strip(' \t\r\n.!?'):
raise SourceError('the key correction also contains another request; give only the matching columns, then describe the next operation separately')
if pairs is None:
common = [c for c in left_cols if c in right_cols]
if len(common) != 1:
raise SourceError('name the matching key columns; shared columns are %s' % (', '.join(common) or 'none'))
return [[common[0], common[0]]], None
keys = []
for a, b in pairs:
left = _column(a, left_cols, left_files)
right = _column(b, right_cols, right_files)
if left is None or right is None:
raise SourceError('matching %s to %s does not name a left and right column' % (a, b))
keys.append([left, right])
return keys, span
def resolve(text, root, fallback=None, output_files=(), key_override=None):
"""Receive one command's source shape and resulting columns.
Returns source/world/holes/owned/files/ops_text. The caller reads row
operations against world['cols'], and can use ops_text to avoid interpreting
a join's key binding as an operation on the resulting rows.
"""
names = input_files(text, output_files)
fallback = _read(fallback) if isinstance(fallback, str) else fallback
result = {'source': None, 'world': None, 'holes': [], 'owned': [], 'files': names, 'ops_text': text,
'retired_key_bindings': [], 'key_override': key_override}
low = DATA.sub(' FILE ', text.lower())
join_words = key_override is not None or bool(re.search(r'\b(?:join|joins|joined|joining|matching|matched|matches|match)\b', low))
is_stack = bool(re.search(r'\b(?:combine|combines|combined|combining|stack|stacks|stacked|stacking|append|appends|appended|union|concatenate|concatenates)\b', low))
lookup_words = bool(re.search(r'\b(?:lookup|look up|reference)\b', low))
uses_rate = bool(re.search(r'\b(?:with|using)\s+(?:the\s+)?rates?\b', low))
is_lookup = lookup_words or bool(uses_rate and not is_stack and not re.search(r'\bjoin\w*\b', low))
is_join = join_words or bool(not is_stack and re.search(r'\bwith\b', low) and len(names) >= 2)
try:
if not names:
source = fallback
elif len(names) == 1:
source = _read(names[0])
if is_lookup and fallback and names[0] not in files(fallback):
left, right = fallback, source
keys, span = _keys(text, source_snapshot(left, root)[0], source_snapshot(right, root)[0], files(left), files(right), key_override)
source = {'op': 'lookup', 'left': left, 'right': right, 'keys': keys, 'how': 'left'}
if span:
result['ops_text'] = text[:span[0]] + ' ' + text[span[1]:]
if key_override is not None:
result['retired_key_bindings'] = [text[span[0]:span[1]]]
elif is_lookup or is_join:
if len(names) != 2:
raise SourceError('join or lookup names more than two sources; supply the next pair and its matching columns explicitly')
left, right = _read(names[0]), _read(names[1])
# "lookup rates.csv for prices.csv" names the reference first.
if re.search(r'\b(?:lookup|look up)\s+`?' + re.escape(names[0]) + r'\b', text, re.I):
left, right = right, left
keys, span = _keys(text, source_snapshot(left, root)[0], source_snapshot(right, root)[0], files(left), files(right), key_override)
left_position = text.lower().find(files(left)[0].lower())
before_left = text[:left_position] if left_position >= 0 else ''
keeps_left = re.search(r'\bleft\s+(?:outer\s+)?join\b', low) or re.search(r'\b(?:each|every|all)\b', before_left, re.I)
how = 'left' if is_lookup or keeps_left else 'inner'
if re.search(r'\binner\s+join\b', low):
how = 'inner'
source = {'op': 'lookup' if is_lookup else 'join', 'left': left, 'right': right, 'keys': keys, 'how': how}
if span:
result['ops_text'] = text[:span[0]] + ' ' + text[span[1]:]
if key_override is not None:
result['retired_key_bindings'] = [text[span[0]:span[1]]]
elif is_stack or re.search(r'\bFILE\s*(?:,|and)', low):
source = {'op': 'union', 'inputs': [_read(name) for name in names]}
else:
raise SourceError('several input tables are named; say whether to stack them or join them on named columns')
if source is None:
return result
world = describe(root, source)
result.update(source=source, world=world, files=files(source))
if source.get('op') != 'read':
result['owned'] = _RELATION_WORDS.split()
except (SourceError, KeyError, TypeError, OSError) as exc:
result['holes'].append({'kind': 'source', 'files': names, 'text': str(exc)})
result['source'] = locals().get('source')
return result81 unmodified lines828384858685878889909181 unmodified lines try: con = sqlite3.connect("file:%s?mode=ro" % PAGE_STORE, uri=True) key = re.sub(r"[^a-z0-9]+", "_", topic.lower()).strip("_") # stores normalize titles differently (the Simple English store keeps spaces: "french revolution"); the # underscore key alone found no page with a title of two or more words row = con.execute("select page_id from title_alias where normalized_title = ?", (key,)).fetchone() row = con.execute("select page_id from title_alias where normalized_title in (?, ?)", (key, key.replace("_", " "))).fetchone() if not row: return [] out = []65 unmodified lines666768697069717273747565 unmodified lines try: con = sqlite3.connect("file:%s?mode=ro" % store, uri=True) key = re.sub(r"[^a-z0-9]+", "_", topic.lower()).strip("_") # stores normalize titles differently (the Simple English store keeps spaces: "french revolution"); the # underscore key alone found no page with a title of two or more words row = con.execute("select page_id from title_alias where normalized_title = ?", (key,)).fetchone() row = con.execute("select page_id from title_alias where normalized_title in (?, ?)", (key, key.replace("_", " "))).fetchone() if not row: return [] # page_sentence is indexed by page; a WHERE on the FTS content table would scan the whole store (13 GB, ~130 s)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364"""A question keeps its demanded field while source sentences are read.
The native dictionary and ClaimReader supply open words and clause roles.The closed wh/auxiliary inversion below supplies the missing role, not a listof topics or answers. A match means the source says the answer, not that thesource is independently true. Unknown grammar remains a received hole."""import hashlibimport jsonimport re
UNKNOWN = "o7answerfield"WORD = re.compile(r"[A-Za-z0-9_]+(?:['’-][A-Za-z0-9_]+)*")AUX = set("am is are was were be been being do does did have has had can could will would shall should may might must".split())NEG_AUX = {"don't": "do", "doesn't": "does", "didn't": "did", "isn't": "is", "aren't": "are", "wasn't": "was", "weren't": "were", "cannot": "can", "can't": "can", "won't": "will", "wouldn't": "would", "couldn't": "could", "shouldn't": "should"}COPULA = set("am is are was were be been being".split())DETERMINERS = {"a", "an", "the"}MONTH = r"(?:January|February|March|April|May|June|July|August|September|October|November|December)"DATE = re.compile(r"(?:\d{3,4}(?:\s*(?:BC|BCE|AD|CE))?|\d{1,4}\s*(?:BC|BCE|AD|CE)|" r"\d{1,2}\s+" + MONTH + r"(?:\s+\d{3,4})?|" + MONTH + r"(?:\s+\d{1,2},?)?(?:\s+\d{3,4})?)", re.I)CONDITION = {"condition", "alternative"}
def _digest(value): return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode()).hexdigest()
def _words(text, reader): return tuple(reader.d.lemma(w.lower()) for w in WORD.findall(text) if w.lower() not in DETERMINERS)
def _passive(node, reader): """'was created' read as be + the property 'created' is the passive of create: when the first property after be is a verb's past participle in the store (its forms table), the relation is that verb and the property role is dropped. Read the same way for the question and for every source sentence, so neither side gains a reading the other lacks.""" if node["predicate"].get("lemma") != "be": return None props = [c for c in node["complements"] if c["role"] == "property"] if not props: return None first = props[0]["text"].split() if len(first) != 1: return None word = first[0].lower() try: row = reader.d.db.execute("SELECT lemma FROM forms WHERE form=? AND pos='verb' AND tags_json LIKE '%past%' LIMIT 1", (word,)).fetchone() except Exception: # noqa: BLE001 row = None return (row[0], props[0]) if row else None
def _agent(node, reader): """the by-phrase of a passive clause: its actor ("created by Arlene Klasky")""" passive = _passive(node, reader) if not passive: return None return next((c for c in node["complements"] if c is not passive[1] and str(c.get("marker") or "").lower() == "by"), None)
def _node(node, reader): """A passive clause is read in its active order: the by-phrase is the actor (subject), the grammatical subject is the object. "Rugrats was created by Arlene Klasky" and "Who created Rugrats?" then share one shape; an agentless passive ("When was Bitcoin created?") has an empty actor, which any actor satisfies.""" passive = _passive(node, reader) agent = _agent(node, reader) complements = [c for c in node["complements"] if not (passive and (c is passive[1] or c is agent))] roles = tuple((c["role"], c.get("marker"), _words(c["text"], reader)) for c in complements) subject = _words(node["subject"]["text"], reader) if passive: roles = (("object", None, subject),) + roles subject = _words(agent["text"], reader) if agent else () return {"subject": subject, "relation": passive[0] if passive else node["predicate"]["lemma"], "roles": roles, "polarity": node["polarity"], "modal": (node.get("modal") or {}).get("lemma"), "modifiers": tuple(w for w in (_words(c["text"], reader) for c in node.get("modifiers", [])) if w), # a modifier of determiners only says nothing "attribution": (node["attribution"]["speaker"], node["attribution"]["stance"])}
def _conditions(graph, node_id, reader): nodes = {n["id"]: n for n in graph["nodes"]} return sorted((link["kind"], link["mode"], _digest(_node(nodes[link["from"]], reader))) for link in graph["links"] if link["to"] == node_id and link["kind"] in CONDITION)
def _graph(text, reader, *, source=False): from claim_shape import ClaimReader from claim_judge import shape graph = ClaimReader(reader).read(text) checked = shape(graph, reader.d) if (graph["holes"] and not source) or not checked["passed"]: return None return graph
def receive(question, reader=None, subjects=()): """Receive one field question; return its complete duty or a precise hole.
`subjects` is an optional *already resolved* reference, never a guessed article title. It is deliberately retained separately from original words. """ duty = {"version": 1, "original": str(question), "missing": [], "receiver": "question_obligation.receive"} if reader is None: duty["missing"] = ["the native dictionary reader"] return duty text = str(question).strip().rstrip("?!. ") if len(subjects) == 1: text = re.sub(r"\b(?:it|this|that)\b", lambda _m: str(subjects[0]), text, flags=re.I) tokens = WORD.findall(text) if not tokens: duty["missing"] = ["a question"] return duty first = tokens.pop(0).lower() kind = {"when": "time", "where": "place", "why": "reason", "how": "method", "who": "person", "whom": "person", "what": "value", "which": "value"}.get(first) if kind is None: duty["missing"] = ["a received question field"] return duty count_noun = [] if first in {"what", "which"} and tokens and tokens[0].lower() in {"year", "date", "time"}: kind = "time"; tokens.pop(0) elif first == "how" and tokens and tokens[0].lower() in {"many", "much"}: kind = "number"; tokens.pop(0) boundary = next((i for i, word in enumerate(tokens) if word.lower() in AUX or word.lower() in NEG_AUX), None) if boundary is None: duty["missing"] = ["the count's received noun role"] return duty count_noun, tokens = tokens[:boundary], tokens[boundary:] if not tokens: duty["missing"] = ["the subject and relation being asked about"] return duty first_rest = tokens[0].lower() auxiliary = NEG_AUX.get(first_rest, first_rest) unknown_role = None if auxiliary in AUX: tokens.pop(0) # Locate the lexical predicate using the native dictionary. A proper # name cannot itself become the acting word just because it is a verb. from claim_shape import ClaimReader, SUFFIX cr = ClaimReader(reader) main = " ".join(tokens) joined = SUFFIX.search(main) main_tokens = WORD.findall(main[:joined.start()]) if joined else tokens # A resolved label must occupy the actual subject prefix. It cannot # exchange an object or incidental article title for the actor. anchors = {i for label in subjects if isinstance(label, str) and label for i in range(1, len(main_tokens) + 1) if _words(" ".join(main_tokens[:i]), reader) == _words(label, reader)} split = next(iter(anchors)) if len(anchors) == 1 else None if split is None: candidates = [i for i, word in enumerate(main_tokens) if i and cr._verb(word) and not word[:1].isupper() and word.lower() not in {"not", "never"} and (auxiliary not in {"do", "does", "did"} or reader.d.lemma(word.lower(), "verb") == word.lower())] if len(candidates) > 1: duty["missing"] = ["the subject boundary among the noun/verb readings; name or resolve the subject"] return duty split = candidates[0] if candidates else None if split is None and auxiliary in COPULA: # Inverted copular properties can have no lexical verb at all. # Find an adjective after the subject's nominal head; adjectives # before that head remain inside its noun phrase. nominal = False for i, word in enumerate(main_tokens): roles = reader.d.pos(word.lower()) if i and nominal and "adj" in roles and not word[:1].isupper(): split = i break if word.lower() not in DETERMINERS | {"not", "never"} and (roles & {"noun", "name", "proper noun", "pron"} or not roles): nominal = True if split is None: if auxiliary not in COPULA: duty["missing"] = ["the received predicate after the auxiliary"] return duty split = len(tokens) subject, tail = tokens[:split], tokens[split:] negatives = [word for word in subject if word.lower() in {"not", "never"}] subject = [word for word in subject if word.lower() not in {"not", "never"}] if first_rest in NEG_AUX: negatives.append("not") if not subject: duty["missing"] = ["the subject of the requested relation"] return duty if kind in {"value", "person", "number"}: tail += [UNKNOWN] + count_noun unknown_role = "complement" statement = " ".join(subject + [auxiliary] + negatives + tail) elif kind in {"person", "value"}: statement = " ".join([UNKNOWN] + tokens) unknown_role = "subject" else: # Embedded question clauses ("explain why the valve closes") already # have declarative order; the same native reader judges their roles. statement = " ".join(tokens) graph = _graph(statement + ".", reader) roots = [n for n in (graph or {}).get("nodes", []) if n["id"] in graph["roots"]] if graph else [] if len(roots) != 1: duty["missing"] = ["an unambiguous native clause for the question"] return duty node = roots[0] received = _node(node, reader) duty.update(kind=kind, unknown_role=unknown_role, shape=received, conditions=_conditions(graph, node["id"], reader), reading=graph, resolved_subjects=list(subjects)) duty["key"] = _digest({k: duty[k] for k in ("version", "kind", "unknown_role", "shape", "conditions")}) return duty
def _tail_scope(graph, node, value, sentence, kind): """A checked reason may be quoted without interpreting its trailing relative.
This exception admits no unknown main role, cause link, polarity, or condition. Every unreceived span must be a relative-reference tail directly after the complete received reason; the full source remains attached. """ holes = graph.get("holes", []) if not holes: return {} if kind != "reason" or len(holes) != 1: return None hole = holes[0] a, b = hole.get("span", [-1, -1]) end = value["span"][1] if (hole.get("kind") != "reference" or a < end or sentence[end:a].strip() or not re.match(r"^(?:that|which|who)\b", sentence[a:b], re.I) or sentence[b:].strip(" .!?\r\n\t") or any(n["span"][0] < b and n["span"][1] > a for n in graph["nodes"])): return None # Its exact omission is visible; no pronoun referent or relative scope is # inferred. The quote retains all parsed complements, including without. start = min(node["span"][0], value["span"][0]) return {"source_excerpt": sentence[start:end] + " …", "source_excerpt_span": [start, end], "unresolved_tail": [{"text": sentence[a:b], "span": [a, b], "kind": hole["kind"]}], "reading_scope": "received main clause and explicit reason; trailing relative remains unresolved"}
PAGE_PRONOUNS = {"it", "he", "she", "they"}REASON_MARKERS = {"because", "because of", "due to", "owing to", "since", "as a result of"}
def _same_subject(held, expected, title, reader): """On a page about its title, the clause's subject is that title when it is the title's words, a third-person pronoun standing for the page's own subject ("It is not known who wrote it" on the Beowulf page), or a noun phrase that begins with the expected words and goes on to describe them ("The sky, which is made up of gas molecules, is blue ..."). A phrase that only contains the words ("the Blue Nile" on the Nile page) is another subject.""" held, expected = tuple(held), tuple(expected) if held == expected or not expected: # an agentless passive question names no actor return True page = _words(title, reader) if title else () if len(held) == 1 and held[0] in PAGE_PRONOUNS and expected and page and (expected == page or set(expected) <= set(page)): return True return bool(expected) and held[:len(expected)] == expected and len(held) > len(expected)
def match(duty, sentence, reader=None, title=""): """Read the source independently and bind the demanded field, or return None.""" if duty.get("missing") or reader is None: return None graph = _graph(sentence, reader, source=True) if not graph: return None if title: # a page's own pronoun is resolved by the page (see below) graph = dict(graph, holes=[h for h in graph.get("holes", []) if not ( h.get("kind") == "reference" and str(h.get("text", "")).strip().lower() in PAGE_PRONOUNS)]) # Duties are durable JSON records; tuple/list representation after reload # must not change the received meaning or turn a valid continuation away. expected = json.loads(json.dumps(duty["shape"])) candidates = [] for node in graph["nodes"]: held = json.loads(json.dumps(_node(node, reader))) if title: # the page's own pronoun stands for the page's subject in any role page = list(_words(title, reader)) held["roles"] = [[r, m, page if len(w) == 1 and w[0] in PAGE_PRONOUNS else w] for r, m, w in held["roles"]] if any(held[k] != expected[k] for k in ("relation", "polarity", "modal", "modifiers", "attribution")): continue if duty["unknown_role"] != "subject" and not _same_subject(held["subject"], expected["subject"], title, reader): continue if _digest(_conditions(graph, node["id"], reader)) != _digest(duty["conditions"]): continue # Roles are ordered and owned. Topic overlap cannot exchange actor and # object or let an unrelated date satisfy this clause. required = [r for r in expected["roles"] if UNKNOWN not in r[2]] # a held phrase that ends with the asked words is that role ("According to legend, Rome" ends with "Rome") if any(not any(h[0] == r[0] and h[1] == r[1] and list(h[2])[-len(r[2]):] == list(r[2]) for h in held["roles"]) for r in required if r[2]): continue values = [] if duty["unknown_role"] == "subject": agent = _agent(node, reader) values = [agent] if agent else ([] if _passive(node, reader) else [node["subject"]]) elif duty["unknown_role"] == "complement": wanted = [r for r in expected["roles"] if UNKNOWN in r[2]] for role, marker, words in wanted: words = tuple(words) position = words.index(UNKNOWN) prefix, suffix = words[:position], words[position + 1:] values += [c for c in node["complements"] if c["role"] == role and c.get("marker") == marker and _words(c["text"], reader)[:len(prefix)] == prefix and (not suffix or _words(c["text"], reader)[-len(suffix):] == suffix) and len(_words(c["text"], reader)) > len(prefix) + len(suffix)] elif duty["kind"] == "reason": nodes = {n["id"]: n for n in graph["nodes"]} values = [nodes[link["from"]] for link in graph["links"] if link["to"] == node["id"] and link["kind"] == "reason" and not link.get("scope")] # a reason given as a phrase of the same clause ("is blue because of the random scattering of sunlight") values += [c for c in node["complements"] if str(c.get("marker") or "").lower() in REASON_MARKERS] else: for c in node["complements"]: marker, value = c.get("marker"), c["text"] if duty["kind"] == "time" and marker in {"in", "on", "at", "during", "before", "after", "since", "until"} and DATE.fullmatch(value): values.append(c) elif duty["kind"] == "place" and marker in {"in", "at", "from", "into", "within", "on"} and not DATE.fullmatch(value): values.append(c) elif duty["kind"] == "method" and marker in {"by", "through", "with"}: values.append(c) for value in values: scope = _tail_scope(graph, node, value, sentence, duty["kind"]) if scope is None: continue a, b = value["span"] if sentence[a:b] != value["text"]: continue if duty["kind"] == "number": number = re.search(r"\b\d+(?:[,.]\d+)*\b", value["text"]) if not number: continue a, b = a + number.start(), a + number.end() candidates.append({"value": sentence[a:b], "normalized": _words(sentence[a:b], reader), "value_span": [a, b], "clause_span": node["span"], "duty_key": duty["key"], "sentence": sentence, "sha256": hashlib.sha256(sentence.encode()).hexdigest(), "basis": "native clause roles and demanded field", "title": title, **scope}) # Multiple possible values do not silently become whichever was first. unique = {tuple(c["normalized"]): c for c in candidates} return next(iter(unique.values())) if len(unique) == 1 else None
def select_records(question, records, reader=None, title="", subjects=()): """Select a checked original page record; the caller decides its truth label.""" duty = receive(question, reader, subjects or ((title,) if title else ())) if duty["missing"]: return None selected = [] for record in records: checked = match(duty, record.get("sentence", ""), reader, record.get("title") or title) if checked: selected.append(dict(record, question_obligation=duty, answer_check=checked)) if agreement([record["answer_check"] for record in selected])["conflict"]: return None return selected[0] if selected else None
def agreement(checks): """Agreement on the same demanded value; it says nothing about independence.""" checks = [c for c in checks if c] if len(checks) < 2 or len({c["duty_key"] for c in checks}) != 1: return {"agrees": False, "conflict": False, "values": []} values = {tuple(c["normalized"]) for c in checks} # Values that nest are one answer at two grains ("Africa", "the north of Africa"): every value's words lie inside # the widest. Two values neither of which contains the other still conflict and stay conflicting. widest = max(values, key=len) nested = all(set(v) <= set(widest) for v in values) return {"agrees": len(values) == 1 or nested, "conflict": len(values) > 1 and not nested, "values": [list(value) for value in sorted(values)]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763"""reflect - Oracle7 reflects on its own work, and develops an idea about the world, in the same conversation (12.0 dev,Amendment 14).
What it reflects on is real: a ledger of every delivered turn of this conversation (what was asked, which part of Oracle7handled it, the execution receipt: started, finished, exit, check, files, the change made, what was tried), its parts asits own code describes them (each module's own first docstring line, read from the install, not written here), its frozenidentity, and the thread of ideas the conversation is developing (subjects, claims, deductions, interpretations, theoperator's corrections).
Every sentence it says carries what kind of thing it is: checked a receipt of this conversation, or a claim the store holds (the record shows it) deduction built from checked steps, with the steps shown (examine the steps) interpretation a reading that goes beyond the steps (useful, not established) your claim what the operator said, held as theirsA sentence of its own is built from those pieces; nothing is said that has no piece under it. No language model.
"what parts of yourself did you use for that, and what did each contribute" the task's ledger, part by part "what did the failure reveal about how you approached it" failures, what followed, what they show "how does this connect to what we discussed earlier" shared files, functions, operations, things "what is an implication of these two ideas" / "what follows from that" a chain of the store's claims or the bench's own laws, never stored whole "what would make that wrong" the premises, and counterexamples found "I disagree because ..." the correction weighed against the premises "revisit that given the new result" the thread recomputed from the new receipts "let's think about X (and Y)" / "how are X and Y related" facts, relations, comparison, consequences"""import jsonimport osimport reimport timefrom pathlib import Path
NL = chr(10)WB = Path(__file__).resolve().parentTREE = WB.parentHOME = Path(os.environ.get("ORACLE7_BENCH_HOME") or (Path(os.environ.get("ORACLE7_STATE") or Path.home() / ".oracle7") / "bench"))
# which part of Oracle7 a delivered path came from: (path prefix, module file under the install, short name)PARTS = [ ("bench:repair", "workbench/repair.py", "the change composer (repair.py)"), ("bench:compose", "workbench/compose_code.py", "the code composer (compose_code.py, composer_v3 over value shapes)"), ("bench:store", "workbench/code_store.py", "the code store on the Tree of Life spine (functions kept after a passing check, lit by a goal's facts)"), ("bench:audit", "workbench/findings.py", "the findings reader (findings.py)"), ("bench:fix", "workbench/findings.py", "the findings reader (findings.py)"), ("bench:run", "workbench/bench.py", "the bench's runner"), ("bench:edit", "workbench/bench.py", "the bench's editor"), ("bench:write", "workbench/bench.py", "the bench's editor"), ("bench:undo", "workbench/bench.py", "the bench's editor"), ("bench:log", "workbench/bench.py", "the bench's log reader"), ("bench:solved", "workbench/bench.py", "the bench's log reader"), ("bench:", "workbench/bench.py", "the bench"), ("tool:make", "workbench/make.py", "the program builder (make.py)"), ("tool:want", "workbench/planner.py", "the planner (planner.py)"), ("tool:", "workbench/tools.py", "the workspace tools (tools.py)"), ("converse:parts", "workbench/converse/parts.py", "the parts writer (parts.py)"), ("converse:record", "workbench/converse/ownrecord.py", "the record reader (ownrecord.py)"), ("converse:report", "workbench/converse/writeup.py", "the report writer (writeup.py)"), ("writeup", "workbench/converse/writeup.py", "the write-up reader (writeup.py)"), ("converse:accord", "workbench/converse/accord.py", "the talk forms (accord.py)"), ("converse:", "workbench/converse/session.py", "the conversation organ (session.py)"), ("learn:", "workbench/learn.py", "the lookup (learn.py)"), ("reflect:", "workbench/reflect.py", "reflection (reflect.py)"),]KIND = {"checked": "checked", "deduction": "deduction", "interpretation": "interpretation", "yours": "your claim"}
def part_of(path): p = str(path or "") for pre, f, name in PARTS: if p.startswith(pre): return name, f return "the head (chat_core and its specialists)", "oracle7.py"
def own_words(module): """the part's own account of itself: the first line of its docstring, as installed""" try: s = (TREE / module).read_text(encoding="utf-8", errors="ignore") m = re.search(r'^\s*(?:#![^\n]*\n)?\s*(?:#[^\n]*\n)*\s*"""(.*?)(?:\n|""")', s, re.S) return " ".join(m.group(1).split())[:220] if m else None except Exception: # noqa: BLE001 return None
# ---------------------------------------------------------------- the ledger and the threaddef _f(sid): HOME.mkdir(parents=True, exist_ok=True) return HOME / ("reflect_%s.json" % re.sub(r"[^A-Za-z0-9_-]", "", str(sid))[:60])
def load(sid): try: return json.load(open(_f(sid))) except Exception: # noqa: BLE001 return {"ledger": [], "thread": []}
def save(sid, st): p = _f(sid) tmp = p.with_suffix(".tmp%d" % os.getpid()) json.dump(st, open(tmp, "w"), indent=1) os.replace(tmp, p)
def record(text, sid, r): """every delivered turn, once, with its receipt""" try: st = load(sid) ex = r.get("execution") or {} # C11: the turn's number is the conversation's own sequence, kept with it; never the length of the recall window # (which stops at 400 and gave every later turn the number 401). Turns leaving the window go to the archive, whole. seq = int(st.get("seq") or (st["ledger"][-1]["n"] if st["ledger"] else 0)) + 1 st["seq"] = seq st["ledger"].append({"n": seq, "eid": "%s:%d" % (sid, seq), "t": time.time(), "you": str(text), "path": str(r.get("path", "")), "status": r.get("status"), "ex": ex, "said": str(r.get("response", ""))[:600]}) if len(st["ledger"]) > 400: with open(_f(sid).with_suffix(".archive.jsonl"), "a", encoding="utf-8") as fh: for e in st["ledger"][:-400]: fh.write(json.dumps(e, default=str) + "\n") st["ledger"] = st["ledger"][-400:] save(sid, st) except Exception: # noqa: BLE001 pass
def _say(kind, text, basis=None): return {"kind": kind, "text": text, "basis": basis or []}
def _render(lines, head=None): out = [head] if head else [] for ln in lines: b = (" [%s]" % "; ".join(str(x) for x in ln["basis"][:4])) if ln["basis"] else "" out.append("- (%s) %s%s" % (KIND.get(ln["kind"], ln["kind"]), ln["text"], b)) return NL.join(out)
def _reply(sid, st, lines, head, path, thread=None): if thread: thread["t"] = time.time() st["thread"].append(thread) st["thread"] = st["thread"][-40:] save(sid, st) return {"status": "answered" if lines else "hole", "path": "reflect:" + path, "response": _render(lines, head), "execution": {"state": "read", "kinds": sorted({ln["kind"] for ln in lines})}}
def _task(st): """the entries of the current task: back to the last turn that opened an environment or set a new goal""" L = [e for e in st["ledger"] if not e["path"].startswith("reflect:")] start = 0 for i, e in enumerate(L): if e["path"].startswith("bench:open"): start = i return L[start:]
# ---------------------------------------------------------------- reflection on its own workdef contribution(e): """what this turn's part did, from its receipt""" ex, path, said = e.get("ex") or {}, e["path"], e.get("said", "") first = said.strip().splitlines()[0] if said.strip() else "" st = ex.get("state") if path.startswith("bench:repair"): if st == "changed-checked": return "found %s and made the change \"%s\"; the check passed after it (%s candidate%s tried)" % ( ex.get("function", "the function"), ex.get("what", "?"), ex.get("tried", "?"), "" if ex.get("tried") == 1 else "s") if st == "changed-untested": return "made the change \"%s\" in %s; no check tested it" % (ex.get("what", "?"), ex.get("function", "?")) if st == "waiting": return "stopped to ask for one detail: " + first[:160] return "could not compose the change: " + first[:200] if path.startswith("bench:run"): if st in ("running", "queued"): return "started job %s" % ex.get("job") if st == "interrupted": return "job %s stopped without an exit status: interrupted, outcome not known" % ex.get("job") return "ran it: exit %s, %s" % (ex.get("exit"), "passed" if st == "passed" else "failed") if path.startswith(("bench:fix", "bench:audit")): return first[:200] if path.startswith("bench:edit") or path.startswith("bench:write"): return "made edit %s to %s as given" % (ex.get("edit"), ", ".join(ex.get("files") or [])) if path.startswith("bench:open"): return first[:200] if path.startswith("bench:log"): return "read the log of job %s" % ex.get("job") return "%s (%s)" % (first[:160], e.get("status"))
def parts_used(sid, st): T = _task(st) if not T: return None by = {} for e in T: name, mod = part_of(e["path"]) by.setdefault(name, {"mod": mod, "turns": []})["turns"].append(e) lines = [] for name, v in by.items(): own = own_words(v["mod"]) lines.append(_say("checked", "%s%s" % (name, (": by its own account, \"%s\"" % own) if own else ""), [v["mod"]])) for e in v["turns"][-4:]: lines.append(_say("checked", " turn %d, \"%s\": %s" % (e["n"], e["you"][:70], contribution(e)), ["receipt of turn %d" % e["n"]])) states = [(e.get("ex") or {}).get("state") for e in T] if "changed-checked" in states or "passed" in states: lines.append(_say("deduction", "what made the result stand was the check, not the part that proposed it: a change was kept " "only after a check passed", ["turns %s" % ", ".join(str(e["n"]) for e in T if (e.get("ex") or {}).get("state") in ("changed-checked", "passed"))])) return _reply(sid, st, lines, "For this task (since turn %d):" % T[0]["n"], "parts", {"kind": "parts", "subject": "the task", "turns": [e["n"] for e in T]})
SOURCE = { # where in its own code each kind of failure is decided: (module, a line that only that place carries) "bench:repair:locate": ("workbench/repair.py", '"missing": "locate"'), "bench:repair:change": ("workbench/repair.py", 'none made the check pass, and each was put back'), "bench:repair:check": ("workbench/repair.py", '"missing": "check"'), "bench:repair:value": ("workbench/repair.py", '"missing": "value"'), "bench:edit:match": ("workbench/bench.py", "it must occur exactly once"), "bench:run:interrupted": ("workbench/bench.py", 'j["state"], j["t_end"] = "interrupted"'), "bench:run": ("workbench/bench.py", 'j["passed"] = j["exit"] == 0'), "bench:fix:authority": ("workbench/bench.py", "Prepared, not applied"), "tool:make": ("workbench/tools.py", "it did not run cleanly"), "bench:newfn:gap": ("workbench/bench.py", "I could not compose every step of"),}
def src_line(path): """the file and line of its own code that decided an outcome of this kind, read from the install as it is""" for pre, (mod, needle) in SOURCE.items(): if path.startswith(pre): try: for i, ln in enumerate((TREE / mod).read_text(encoding="utf-8").splitlines(), 1): if needle in ln: return "%s:%d" % (mod, i), ln.strip()[:140] except Exception: # noqa: BLE001 return None return None
REVEAL = [ # (path prefix of the failure, what it shows about the approach) ("bench:run:interrupted", "a run stopped without an exit status; I do not assume it finished or that it did nothing, and " "before repeating it I look at what changed"), ("bench:newfn:gap", "the program builder composes from the moves it has; a step none of them does is named, not guessed"), ("bench:repair:locate", "I find the code by the words of the request and by the frames of a failing run; this request " "named nothing I could match and no run had failed yet, so there was nothing to hold on to"), ("bench:repair:change", "the changes I compose are single moves (an operator, a comparison, a term, a constant, a guard); " "none passed the check, so what is needed is more than one move, or a move of another kind"), ("bench:repair:check", "with no check in the project I cannot tell a right change from a wrong one unless the request names " "both what the code does and what it should do"), ("bench:repair:value", "the request left one thing open (what to give in the empty case) and no test says it, so I asked " "rather than choose"), ("bench:edit:match", "an exact edit needs its text to occur once; I do not guess which occurrence was meant"), ("bench:run", "the run itself failed: the receipt says so, and the next step reads its log, not my expectation"), ("bench:fix:authority", "I prepared the correction but did not apply it: this conversation could only read"), ("tool:make", "the program builder put the steps together but one step failed when run, and its repair loop could not mend it"),]
def _job_now(sid, L): """a turn that started a job reported it running; what became of the job is read now, from the bench (a job interrupted or failed after its turn is a failure of that turn: acceptance I3, run 2)""" try: import bench as _b env = _b.Turn(sid).env if env is None: return L jobs = {j["id"]: j for j in _b._jobs(env)} except Exception: # noqa: BLE001 return L out = [] for e in L: ex = e.get("ex") or {} j = jobs.get(ex.get("job")) if ex.get("job") else None if j and ex.get("state") in ("running", "queued") and j["state"] in ("interrupted", "finished"): st = "interrupted" if j["state"] == "interrupted" else ("passed" if j.get("passed") else "failed") e = dict(e, ex=dict(ex, state=st, exit=j.get("exit")), path="bench:run:interrupted" if st == "interrupted" else e["path"], said=(j.get("result") or e.get("said", ""))) out.append(e) return out
def failures(sid, st): L = _job_now(sid, [e for e in st["ledger"] if not e["path"].startswith("reflect:")]) bad = [e for e in L if (e.get("ex") or {}).get("state") in ("failed", "missing", "blocked", "refused", "interrupted") or (e["status"] == "hole" and e["path"].startswith(("bench:", "tool:")))] if not bad: return _reply(sid, st, [_say("checked", "nothing failed in this conversation's work so far", ["%d turns" % len(L)])], None, "failure") lines = [] for e in bad[-4:]: lines.append(_say("checked", "turn %d (\"%s\") did not succeed: %s" % (e["n"], e["you"][:70], contribution(e)), ["receipt of turn %d" % e["n"]])) why = next((w for pre, w in REVEAL if e["path"].startswith(pre)), None) if why: lines.append(_say("deduction", "it shows that " + why, ["path %s" % e["path"]])) sl = src_line(e["path"]) if sl: lines.append(_say("checked", "the place in my code that decided it: %s `%s`" % sl, [sl[0]])) caps = (e.get("ex") or {}).get("caps") or {} if caps: lines.append(_say("checked", "the search reached its own limit%s: %s" % ("s" if len(caps) > 1 else "", ", ".join( "%s = %s" % kv for kv in sorted(caps.items()))), ["receipt of turn %d" % e["n"]])) after = [x for x in L if x["n"] > e["n"] and (x.get("ex") or {}).get("state") in ("changed-checked", "passed")] if after: x = after[0] lines.append(_say("checked", "what changed the outcome: turn %d (\"%s\"): %s" % (x["n"], x["you"][:60], contribution(x)), ["receipt of turn %d" % x["n"]])) if x["path"].startswith("bench:repair") and e["path"].startswith("bench:run"): lines.append(_say("interpretation", "the failure was useful to me: its frames and its assertion told me where to " "look, and the same test then judged the change", ["turns %d, %d" % (e["n"], x["n"])])) else: lines.append(_say("checked", "nothing after it has passed yet: it is still open", [])) return _reply(sid, st, lines, None, "failure", {"kind": "failure", "turns": [e["n"] for e in bad]})
# ---------------------------------------------------------------- the world: things, relations, implications_ST = {}
def store(): if "p" not in _ST: import sys sys.path[:0] = [str(WB / "converse")] import parts as P _ST["p"] = P.Parts(str(TREE), str(WB / "converse" / "data" / "parts" / "parts.json")) return _ST["p"]
def qid(name): P = store() t = " ".join(name.strip(" .?!,'\"").split()) best = None for c in dict.fromkeys((t, t[:1].upper() + t[1:], t.title(), "The " + t.title(), t.lower())): q = P.S.qid_of_title(c) if q is not None: n = len(P.S.facts(q)) if best is None or n > best[1]: best = (q, n) return best[0] if best else None
def plabel(p): P = store() lab = (P.S.props.get(p) or ("", ""))[1] if not lab or re.fullmatch(r"P\d+", str(lab)): al = [a for a in P.S.alias.get(p, []) if a] lab = al[0] if al else "P%d" % p return str(lab)
SKIP_P = {5008, 1889, 910, 1343, 373, 935, 8402, 2184, 1151, 1424} # the store's housekeeping: lists, "not to be confused with", categories
def claim_text(s, p, o): P = store() t = P.say(s, p, o) return t or "%s - %s - %s" % (P.S.label(s), plabel(p), P.S.label(o))
TRANSITIVE = {131: "located in", 361: "part of", 279: "subclass of", 17: "country", 276: "location"}
def relate(a, b): """how two things are related in the store: direct claims, shared objects, chains of two""" P = store() fa = [x for x in P.S.facts(a)[:600] if x[0] not in SKIP_P] fb = [x for x in P.S.facts(b)[:600] if x[0] not in SKIP_P] direct = [(a, p, o) for p, o in fa if o == b] + [(b, p, o) for p, o in fb if o == a] oa, ob = {}, {} for p, o in fa: oa.setdefault(o, []).append(p) for p, o in fb: ob.setdefault(o, []).append(p) shared = [(o, oa[o][0], ob[o][0]) for o in oa if o in ob and o not in (a, b)] shared.sort(key=lambda x: -P.S.links(x[0])) return direct, shared[:6]
def think(sid, st, names): P = store() qs = [(n, qid(n)) for n in names] missing = [n for n, q in qs if q is None] if missing: return {"status": "hole", "path": "reflect:think:missing", "execution": {"state": "missing"}, "response": "I hold no record that I can match to %s, so I have nothing checked to think with about %s. " "Give me another name for it, or say go and I'll read about it." % (", ".join(missing), " and ".join(missing))} lines = [] for n, q in qs: r = P.about(q, limit=5) if r: for (s, p, o) in r["claims"]: if p in SKIP_P: continue lines.append(_say("checked", claim_text(s, p, o), ["wd:Q%d P%d" % (s, p)])) thread = {"kind": "think", "subjects": [[n, q] for n, q in qs], "claims": [], "premises": []} if len(qs) >= 2: (na, a), (nb, b) = qs[0], qs[1] direct, shared = relate(a, b) for s, p, o in direct[:3]: lines.append(_say("checked", claim_text(s, p, o), ["wd:Q%d P%d" % (s, p)])) thread["claims"].append([s, p, o]) for o, pa, pb in shared[:3]: lines.append(_say("checked", "%s and %s both have %s as %s / %s" % (P.S.label(a), P.S.label(b), P.S.label(o), plabel(pa), plabel(pb)), ["wd:Q%d P%d Q%d" % (a, pa, o), "wd:Q%d P%d Q%d" % (b, pb, o)])) thread["claims"] += [[a, pa, o], [b, pb, o]] if not direct and not shared: lines.append(_say("checked", "the store holds no claim joining %s and %s directly or through one shared thing" % ( P.S.label(a), P.S.label(b)), [])) return _reply(sid, st, lines, "What I hold on %s:" % " and ".join(P.S.label(q) for _n, q in qs), "think", thread)
def _last(st, kinds): for th in reversed(st["thread"]): if th["kind"] in kinds: return th return None
LAWS = [ # the bench's own laws as conditionals (read in bench.py / repair.py docstrings); id, if, then ("L1", "a change is kept", "a check passed after it"), ("L2", "a check passed before a change and after it", "the check does not test the change"), ("L3", "the check does not test the change", "the change is reported as changed, not yet tested"), ("L4", "a run fails", "its receipt says failed and its status is never answered"), ("L5", "a fix needs more moves than one", "no fix is found"), ("L6", "no fix is found", "the task stays open and the missing step is named"), ("L7", "a conversation may only read", "a prepared correction waits for allow changes and go"),]
def law_instances(ledger): """the turns of this conversation that are cases of each law: what the receipts show the rules doing""" out = {} for e in ledger: ex, path = e.get("ex") or {}, e["path"] st = ex.get("state") if st == "changed-checked": out.setdefault("L1", []).append(e["n"]) if st == "changed-untested" and ex.get("check") == "not testing this": out.setdefault("L2", []).append(e["n"]) if st == "changed-untested": out.setdefault("L3", []).append(e["n"]) if st == "failed" and path.startswith("bench:run"): out.setdefault("L4", []).append(e["n"]) if path.startswith("bench:repair:change"): out.setdefault("L5", []).append(e["n"]) if st in ("missing", "waiting") and path.startswith(("bench:repair", "bench:newfn")): out.setdefault("L6", []).append(e["n"]) if path.startswith("bench:fix:authority"): out.setdefault("L7", []).append(e["n"]) return out
def chain_laws(seed=None): """two laws whose then is the other's if: a conditional no file states whole""" out = [] for i1, if1, th1 in LAWS: for i2, if2, th2 in LAWS: if i1 != i2 and th1 == if2: out.append((i1, i2, if1, th2, th1)) if seed: out.sort(key=lambda c: -len(set(seed.lower().split()) & set((c[2] + " " + c[3]).lower().split()))) return out
def _idea(st): """the idea under discussion: the last thread that carries one (things with claims, or rules), not a connect or a question about it; a correction or a falsification carries its idea forward""" for th in reversed(st["thread"]): if th.get("subjects") or th.get("laws") or [x for x in th.get("premises", []) if len(x) == 3]: return th return None
def implication(sid, st): th = _idea(st) or _last(st, ("parts", "failure")) if th and th["kind"] in ("think", "implication") and len(th.get("subjects", [])) >= 2: P = store() (na, a), (nb, b) = th["subjects"][:2] lines, prem = [], [] for x, nx in ((a, na), (b, nb)): for p, o in P.S.facts(x)[:400]: if p not in TRANSITIVE: continue for p2, o2 in P.S.facts(o)[:200]: if p2 == p and o2 not in (a, b) and not P.S.holds(x, p, o2): lines.append(_say("deduction", "%s is %s %s, which is %s %s; so %s is %s %s - a claim the store does not " "hold in one piece" % (P.S.label(x), TRANSITIVE[p], P.S.label(o), TRANSITIVE[p], P.S.label(o2), P.S.label(x), TRANSITIVE[p], P.S.label(o2)), ["wd:Q%d P%d Q%d" % (x, p, o), "wd:Q%d P%d Q%d" % (o, p, o2)])) prem += [[x, p, o], [o, p, o2]] break if len(lines) >= 2: break direct, shared = relate(a, b) if shared: o, pa, pb = shared[0] if pa == pb: lines.append(_say("interpretation", "since %s and %s share %s as %s, what is true of %s through that %s may bear on " "both; that is a reading of the link, not a claim the store makes" % ( P.S.label(a), P.S.label(b), P.S.label(o), plabel(pa), P.S.label(o), plabel(pa)), ["wd:Q%d P%d Q%d" % (a, pa, o), "wd:Q%d P%d Q%d" % (b, pb, o)])) prem += [[a, pa, o], [b, pb, o]] if not lines: return _reply(sid, st, [_say("checked", "from what I hold on %s and %s I can build no step the store does not already " "hold; I won't offer one with nothing under it" % (P.S.label(a), P.S.label(b)), [])], None, "implication") return _reply(sid, st, lines, "Built from claims I hold, not stored as such:", "implication", {"kind": "implication", "subjects": th["subjects"], "premises": prem, "lines": [l["text"] for l in lines]}) seed = " ".join(e["you"] for e in st["ledger"][-6:]) ch = chain_laws(seed) if not ch: return None i1, i2, if1, th2, mid = ch[0] lines = [_say("checked", "%s: if %s, then %s" % (i1, LAWS[[l[0] for l in LAWS].index(i1)][1], mid), ["bench.py / repair.py"]), _say("checked", "%s: if %s, then %s" % (i2, mid, th2), ["bench.py / repair.py"]), _say("deduction", "so: if %s, then %s" % (if1, th2), [i1, i2])] rec = [e for e in st["ledger"] if (e.get("ex") or {}).get("state") == "changed-untested"] if rec and "check" in if1: lines.append(_say("interpretation", "that is what happened at turn %d: a passing check was not evidence for the change" % rec[-1]["n"], ["receipt of turn %d" % rec[-1]["n"]])) return _reply(sid, st, lines, "An implication of two of my own rules, not written anywhere as one:", "implication", {"kind": "implication", "laws": [i1, i2], "premises": [[i1], [i2]], "lines": [l["text"] for l in lines]})
def falsify(sid, st): th = _idea(st) or _last(st, ("failure", "parts")) if not th: return None lines = [] if th.get("laws"): for lid in th["laws"]: l = next(x for x in LAWS if x[0] == lid) lines.append(_say("deduction", "it is wrong if %s does not hold: if %s and yet not %s" % (lid, l[1], l[2]), [lid])) lines.append(_say("checked", "a test of that: a run where a change was kept with no check passing after it would break %s; " "no receipt in this conversation shows one" % th["laws"][0], ["%d turns" % len(st["ledger"])])) for s, p, o in [tuple(x) for x in th.get("premises", []) if len(x) == 3][:4]: P = store() lines.append(_say("deduction", "it rests on \"%s\"; if that claim is wrong, what was built on it falls" % claim_text(s, p, o), ["wd:Q%d P%d" % (s, p)])) if th["kind"] == "implication" and any("interpretation" in t for t in th.get("lines", [])) or th.get("subjects"): lines.append(_say("interpretation", "a shared link is not a shared property: two things in one place need not share what " "that place has; one counterexample of that kind defeats the reading", [])) if th.get("yours"): lines.append(_say("yours", "and your point stands against it: " + th["yours"][-1], [])) return _reply(sid, st, lines, "What would make that wrong:", "falsify", dict(th, kind="falsify", of=th["kind"])) # the idea is carried forward, laws and premises with it
NEG = re.compile(r"(?i)\b(?:not|isn't|is not|aren't|doesn't|does not|never|no longer|wasn't|false|wrong|untrue)\b")
def disagree(sid, st, text): th = _idea(st) or _last(st, ("failure", "parts")) why = re.sub(r"(?i)^\s*(?:i\s+)?(?:disagree|don't agree|do not agree|that's not right|that is not right|no)[,:]?\s*(?:because|since|as)?\s*", "", text).strip() if not th: return None words = {w.lower() for w in re.findall(r"[A-Za-z]{4,}", why)} hit = [] for lid in th.get("laws", []): l = next(x for x in LAWS if x[0] == lid) if words & set((l[1] + " " + l[2]).lower().split()): hit.append(("law", lid, l)) P = None prem = [x for x in th.get("premises", []) if len(x) == 3] pm = re.match(r"(?i)^(.+?)\s+(?:is|are|was|were)\s+not\s+(?:(?:located|situated)\s+in|part of|in|on|a|an|the)?\s*(.+?)\s*[.!]?$", why) if pm and prem: # "X is not (in) Y": the step whose two ends are X and Y, exactly P = store() xs, ys = pm.group(1).strip().lower(), pm.group(2).strip().lower() exact = [x for x in prem if str(P.S.label(x[0]) or "").lower() == xs and str(P.S.label(x[2]) or "").lower() == ys] for x in exact: hit.append(("claim", x, None)) if not hit: for x in prem: P = P or store() lab = " ".join(str(P.S.label(q) or "") for q in (x[0], x[2])).lower() if words & set(lab.split()): hit.append(("claim", x, None)) lines = [_say("yours", why or text, [])] negates = bool(NEG.search(why)) if hit and negates: for kind, what, l in hit[:2]: if kind == "law": lines.append(_say("checked", "that disputes %s (if %s, then %s), which the conclusion rested on" % (what, l[1], l[2]), [what])) else: lines.append(_say("checked", "that disputes \"%s\", a step it rested on" % claim_text(*what), ["wd:Q%d P%d" % (what[0], what[1])])) lines.append(_say("deduction", "so the conclusion no longer follows; I withdraw it until the disputed step is settled", [])) rec = [e for e in st["ledger"] if (e.get("ex") or {}).get("state")] if any(kind == "law" for kind, _w, _l in hit): lines.append(_say("checked", "what the record can settle: %d receipts in this conversation; ask me to check them against " "your point (\"revisit that\")" % len(rec), [])) status = "withdrawn" elif hit: lines.append(_say("deduction", "it touches %s without denying it; I keep the conclusion with your point as a condition on it" % ( ", ".join(h[1] if h[0] == "law" else claim_text(*h[1]) for h in hit[:2])), [])) status = "conditioned" else: lines.append(_say("deduction", "it does not meet any step the conclusion rested on (%s), so the conclusion stands; your " "point is held as yours alongside it" % ", ".join(th.get("laws") or [claim_text(*x) for x in th.get("premises", []) if len(x) == 3][:2] or ["its steps"]), [])) status = "unaffected" new = dict(th, kind="revised", status=status, yours=(th.get("yours") or []) + [why or text]) return _reply(sid, st, lines, None, "disagree", new)
def revisit(sid, st): th = _idea(st) or _last(st, ("failure", "parts")) if not th: return None L = [e for e in st["ledger"] if not e["path"].startswith("reflect:")] since = [e for e in L if e["t"] > th.get("t", 0)] lines = [_say("checked", "since that (%d turn%s of work): %s" % (len(since), "" if len(since) == 1 else "s", "; ".join("turn %d %s" % (e["n"], contribution(e)[:90]) for e in since[-3:]) or "nothing"), ["receipts"])] if th.get("laws"): broke = [e for e in since if (e.get("ex") or {}).get("state") == "changed-checked" and "passed" not in contribution(e)] held = [e for e in since if (e.get("ex") or {}).get("state") in ("changed-checked", "changed-untested", "passed", "failed")] if broke: lines.append(_say("deduction", "turn %d is a counterexample to %s: the conclusion falls" % (broke[0]["n"], th["laws"][0]), [])) elif held: lines.append(_say("deduction", "the new receipts agree with %s: %s" % (" and ".join(th["laws"]), "; ".join( "turn %d %s" % (e["n"], (e.get("ex") or {}).get("state")) for e in held[-3:])), ["receipts"])) if th.get("status") == "withdrawn" and held and not broke: lines.append(_say("deduction", "your objection disputed one of those rules; the new receipts show it holding in %d more " "case%s, so I'd restore the conclusion, with your objection still on record" % (len(held), "" if len(held) == 1 else "s"), ["receipts"])) if th["kind"] in ("failure", "parts"): return failures(sid, st) if th["kind"] == "failure" else parts_used(sid, st) if th.get("subjects") and not th.get("laws"): lines.append(_say("checked", "the work since does not touch %s; what I said about it stands as it was" % " and ".join( n for n, _q in th["subjects"]), [])) return _reply(sid, st, lines, "Revisiting what I said:", "revisit", dict(th, kind=th["kind"], t=time.time()))
def connect(sid, st): L = [e for e in st["ledger"] if not e["path"].startswith("reflect:")] if len(L) < 2: return None cur = L[-1] cw = _keys(cur) best = [] for e in L[:-1]: sh = cw & _keys(e) if sh: best.append((len(sh), e, sh)) th_subj = [th for th in st["thread"] if th.get("subjects")] lines = [] for n, e, sh in sorted(best, key=lambda x: -x[0])[:3]: lines.append(_say("checked", "turn %d (\"%s\") and the last turn share %s" % (e["n"], e["you"][:60], ", ".join(sorted(sh)[:5])), ["turns %d, %d" % (e["n"], cur["n"])])) # the work through its rules: which turns are cases of which of the bench's laws, and which laws chain inst = law_instances(L) for lid, turns in sorted(inst.items()): l = next(x for x in LAWS if x[0] == lid) lines.append(_say("checked", "turn%s %s %s a case of %s (if %s, then %s)" % ("s" if len(turns) > 1 else "", ", ".join(map(str, turns[-4:])), "are" if len(turns) > 1 else "is", lid, l[1], l[2]), ["receipts of turns %s" % ", ".join(map(str, turns[-4:]))])) for i1, i2, if1, th2, mid in chain_laws(): if i1 in inst and i2 in inst: lines.append(_say("deduction", "%s and %s chain through those turns: if %s, then %s" % (i1, i2, if1, th2), [i1, i2])) # ideas through the store: an earlier thing and a later thing, joined by a claim or a shared thing if len(th_subj) >= 2: a_s, b_s = th_subj[-2]["subjects"], th_subj[-1]["subjects"] for na, qa in a_s[:2]: for nb, qb in b_s[:2]: if qa == qb: continue direct, shared = relate(qa, qb) for s, p, o in direct[:1]: lines.append(_say("checked", claim_text(s, p, o), ["wd:Q%d P%d" % (s, p)])) for o, pa, pb in shared[:1]: lines.append(_say("checked", "%s (earlier) and %s (now) both have %s as %s" % (na, nb, store().S.label(o), plabel(pa)), ["wd:Q%d P%d Q%d" % (qa, pa, o), "wd:Q%d P%d Q%d" % (qb, pb, o)])) if th_subj and inst: s = th_subj[-1]["subjects"] lines.append(_say("interpretation", "the thread on %s and the work share a method, not a subject: what I said about %s stands on " "claims I can cite, and each result of the work stands on a receipt; no claim I hold joins the two subjects" % ( " and ".join(x[0] for x in s), s[0][0]), [])) if not lines: lines.append(_say("checked", "the last turn shares no file, function, operation or named thing with anything earlier here", [])) return _reply(sid, st, lines, None, "connect", {"kind": "connect", "turns": [e["n"] for _n, e, _s in best[:3]]})
_STOPK = set("what that this with from have your about there their them they then than were when will would could should " "into just like make made does done again also only very more most some such".split())
def _keys(e): ex = e.get("ex") or {} ks = {w.lower() for w in re.findall(r"[A-Za-z_][A-Za-z0-9_]{3,}", e["you"] + " " + " ".join(ex.get("files") or []) + " " + str(ex.get("function") or ""))} return {k for k in ks if k not in _STOPK}
# ---------------------------------------------------------------- the door_PARTS = re.compile(r"(?i)\b(?:what|which) (?:parts?|pieces?) (?:of (?:yourself|you)\s+)?(?:did you use|were used|did you draw on)|" r"\bwhat did each (?:part )?contribute\b|\bhow did you do (?:that|it)\b")_FAIL = re.compile(r"(?i)\bwhat did (?:the |that |those )?(?:failures?|mistakes?|errors?) (?:reveal|show|teach|tell)|" r"\bwhat (?:did you learn|does it reveal) from (?:the |that )?(?:failure|mistake)|\bwhy did (?:you|it) fail at first\b")_CONNECT = re.compile(r"(?i)\bhow does (?:this|that|it) (?:connect|relate|tie) (?:to|with|back)|\bconnect (?:this|that) to (?:what|our|the earlier)")_IMPL = re.compile(r"(?i)\b(?:an?|the|what(?:'s| is)(?: an?| the)?) implications?\b|\bwhat follows from\b|\bwhat does that imply\b|" r"\bconsequences? of (?:these|those|the) two\b")_FALS = re.compile(r"(?i)\bwhat would (?:make|prove|show) (?:that|this|it)(?: \w+){0,2} (?:wrong|false|fail|mistaken)|" r"\bhow could (?:that|this)(?: \w+)? be wrong|\bcounter-?examples?\b|\bwhat would (?:falsify|refute|undermine)\b")_DIS = re.compile(r"(?i)^\s*(?:i\s+)?(?:disagree|don't agree|do not agree|that's not right|that is not right)\b")_REV = re.compile(r"(?i)\brevisit\b|\b(?:given|with|in light of) (?:the|this|that) new result\b|\bdoes (?:the|this|that) (?:new )?result change\b")_THINK = re.compile(r"(?i)^\s*(?:let'?s think about|think about|what do you make of|reflect on|how (?:are|is) (.+?) (?:and|related to) (.+?) related)\s*(.*?)\s*\??$")_REL = re.compile(r"(?i)^\s*(?:how (?:are|is)|what(?:'s| is) the (?:relationship|connection|link) between)\s+(.+?)\s+(?:and|to)\s+(.+?)(?:\s+related| connected)?\s*\??$")
def claims(text, sid): """this turn is reflection's (so the bench does not read it as a change to make): asked about its own work or the thread""" t = (text or "").strip() st = load(sid) if not (st["ledger"] or st["thread"]): return False return bool(_PARTS.search(t) or _FAIL.search(t) or _FALS.search(t) or (_DIS.match(t) and st["thread"]) or (_REV.search(t) and st["thread"]) or _IMPL.search(t) or _CONNECT.search(t))
def after_head(text, sid, head): """things to think about, asked as a question the head may answer: only where the head did not answer""" t = (text or "").strip() if head.get("status") == "answered": return None m = _REL.match(t) if not m: return None st = load(sid) try: return think(sid, st, [m.group(1), m.group(2)]) except Exception: # noqa: BLE001 return None
def handle(text, sid="default"): t = (text or "").strip() if not t: return None st = load(sid) work = any(e["path"].startswith(("bench:", "tool:")) for e in st["ledger"]) or bool(st["thread"]) try: m = re.match(r"(?i)^\s*(?:let'?s think about|think about|what do you make of|reflect on)\s+(.+?)\s*\??$", t) if m: names = re.split(r"\s+and\s+", m.group(1), maxsplit=1) return think(sid, st, names) if not work: return None # nothing done here yet to reflect on: the chat is unchanged if _PARTS.search(t) and st["ledger"]: return parts_used(sid, st) if _FAIL.search(t) and st["ledger"]: return failures(sid, st) if _FALS.search(t) and st["thread"]: return falsify(sid, st) if _DIS.match(t) and st["thread"]: return disagree(sid, st, t) if _REV.search(t) and st["thread"]: return revisit(sid, st) if _IMPL.search(t) and (st["thread"] or st["ledger"]): return implication(sid, st) if _CONNECT.search(t) and st["ledger"]: return connect(sid, st) except Exception as e: # noqa: BLE001 return {"status": "hole", "path": "reflect:error", "response": "Reflection did not complete: %s" % repr(e)[:240], "execution": {"state": "failed"}} return None120 unmodified lines12112212312412412512612712812913013127 unmodified lines1591601611621631641651661671681691701711721731741751611761771781791651801811671821831841859 unmodified lines195196197183198199185200201202203204205206207208209194195210211212213214215120 unmodified lines ins_all = tx["transaction"]["message"]["instructions"]
memos = [ins.get("parsed") for ins in ins_all if ins.get("program") == "spl-memo" or ins.get("programId") == MEMO_PROGRAM]
burned = 0
for ins in ins_all: # BurnChecked/Burn of the $ORACLE7 mint, authorised by the signer
for ins in ins_all: # BurnChecked/Burn of the $ORACLE7 mint, by the Token-2022 program, authorised by the signer
pr = ins.get("parsed") if isinstance(ins.get("parsed"), dict) else {}
info = pr.get("info") or {}
if ins.get("programId") != TOKEN_2022: # the same words from another program are not a burn of this coin
continue
if pr.get("type") in ("burn", "burnChecked") and info.get("mint") == ORACLE7_MINT and info.get("authority") == signer:
amt = (info.get("tokenAmount") or {}).get("amount") or info.get("amount") or "0"
burned += int(amt)27 unmodified lines return []
def memo_matches(m, f):
"""every field the memo commits to, against the fingerprint now: the specialist's id, its files, its held-out verdict and
its held-out set (as written into the memo: id to 40 characters, held-out set to 64). The release is reported apart
(same_release): a specialist examined on an earlier release is still that specialist, and says which release it was."""
return bool(m) and (m.get("id") == f["id"][:40] and m.get("files") == f["files"] and m.get("verdict") == f["verdict"]
and m.get("heldout") == f["heldout"][:64])
def burn_ok(t):
"""a registration burns exactly 1 $ORACLE7, as the memo contract and the browser's transaction say: no more, no less"""
return t["burned_raw"] == BURN_RAW
def record(d, kind, signature):
"""keep a signature only after reading it back: confirmed, ours, and matching this specialist's files now"""
"""keep a signature only after reading it back: confirmed, ours, and matching this specialist's fingerprint now"""
t = read_tx(signature)
f = fingerprint(d)
m = parse_memo(t["memo"])
if not t["ok"] or not m or m.get("kind") != kind or m.get("files") != f["files"] or m.get("verdict") != f["verdict"]:
if not t["ok"] or not m or m.get("kind") != kind or not memo_matches(m, f):
raise ValueError("that transaction does not carry this specialist's %s memo" % kind)
if kind == "register" and t["burned_raw"] < BURN_RAW:
if kind == "register" and not burn_ok(t):
raise ValueError("a registration must burn 1 $ORACLE7 in the same transaction; this one burned %s" % (t["burned_raw"] / 10 ** DECIMALS))
recs = [r for r in records(d) if r["signature"] != signature]
recs.append({"kind": kind, "signature": signature, "signer": t["signer"], "time": t["time"]})9 unmodified lines try:
t = read_tx(r["signature"])
m = parse_memo(t["memo"]) or {}
match = t["ok"] and m.get("files") == f["files"] and m.get("verdict") == f["verdict"]
match = t["ok"] and memo_matches(m, f)
if m.get("kind") == "register":
match = match and t["burned_raw"] >= BURN_RAW # no burn, no registration
match = match and burn_ok(t) # exactly the one burn, or no registration
bal = oracle7_balance(t["signer"]) if t["signer"] else 0.0
out.append({"kind": m.get("kind", r["kind"]), "signer": t["signer"], "time": t["time"], "matches_files": match,
"same_release": m.get("release") == f["release"][:16],
"burned": t["burned_raw"] / 10 ** DECIMALS,
"oracle7": bal, "signature": r["signature"], "explorer": "https://explorer.solana.com/tx/%s" % r["signature"]})
except Exception as e: # noqa: BLE001
out.append({"kind": r.get("kind"), "signature": r.get("signature"), "error": str(e)})
reg = [x for x in out if x.get("kind") == "register" and x.get("matches_files")]
att = [x for x in out if x.get("kind") == "attest" and x.get("matches_files")]
return {"id": f["id"], "files": f["files"], "registered": bool(reg), "attestations": len(att), "oracle7_burned": sum(x["burned"] for x in reg),
"vouching_oracle7": round(sum(x["oracle7"] for x in reg + att), 6), "records": out, "mint": ORACLE7_MINT} # one wallet is one voice: attestations count distinct signers, and a wallet's holding is counted once however many
# records it signed. A holding is a financial fact shown as it is, not a measure of correctness or expertise.
holding = {x["signer"]: x["oracle7"] for x in reg + att if x.get("signer")}
return {"id": f["id"], "files": f["files"], "registered": bool(reg), "attestations": len({x["signer"] for x in att}),
"oracle7_burned": sum(x["burned"] for x in reg), "vouching_oracle7": round(sum(holding.values()), 6),
"distinct_signers": len(holding), "records": out, "mint": ORACLE7_MINT}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091"""relay - the far end of the browser link: carries the page's HTTP requests to the harness on this machine, one JSON line in,one JSON line out, over the stdin/stdout of an ordinary ssh session (no port forwarding needed). Starts the harness server ifnothing answers on the port, and stops the one it started when the link closes.
12.0 C11: each request is carried in its own thread and answered with its id, so a status or a stop goes through while along turn runs; the first line names what the harness runs (its /api/identity: the loaded build, its tree, its state root),never only that something answered at /.
usage (run by o7_browser.py over ssh): python3 relay.py <port> <tree> <state dir>"""import base64import jsonimport osimport subprocessimport sysimport threadingimport timeimport urllib.errorimport urllib.request
PORT, TREE, STATE = int(sys.argv[1]), sys.argv[2], sys.argv[3]BASE = "http://127.0.0.1:%d" % PORTHOP = {"connection", "keep-alive", "transfer-encoding", "content-length", "host", "accept-encoding"}OUT = threading.Lock()
def up(): try: urllib.request.urlopen(BASE + "/", timeout=3).read(1) return True except Exception: # noqa: BLE001 return False
def ident(): try: return json.load(urllib.request.urlopen(BASE + "/api/identity", timeout=60)) except Exception as e: # noqa: BLE001 return {"error": "the harness on port %d answered at / but not /api/identity (%r): it is not this build's server" % (PORT, e)}
def say(obj): with OUT: sys.stdout.write(json.dumps(obj) + "\n") sys.stdout.flush()
def carry(q): try: req = urllib.request.Request(BASE + q["path"], data=base64.b64decode(q["body"]) if q.get("body") else None, method=q.get("method", "GET"), headers={k: v for k, v in q.get("headers", {}).items() if k.lower() not in HOP}) try: r = urllib.request.urlopen(req, timeout=7200) code, hdrs, body = r.status, dict(r.headers), r.read() except urllib.error.HTTPError as e: code, hdrs, body = e.code, dict(e.headers), e.read() say({"id": q.get("id"), "status": code, "headers": {k: v for k, v in hdrs.items() if k.lower() not in HOP}, "body": base64.b64encode(body).decode()}) except Exception as e: # noqa: BLE001 say({"id": q.get("id"), "status": 502, "headers": {"Content-Type": "text/plain"}, "body": base64.b64encode(("relay: %r" % e).encode()).decode()})
started = Noneif not up(): os.makedirs(STATE, exist_ok=True) os.makedirs(os.path.join(os.path.dirname(STATE), "o7tmp"), exist_ok=True) env = dict(os.environ, ORACLE7_STATE=STATE, TMPDIR=os.path.join(os.path.dirname(STATE), "o7tmp"), ORACLE7_WORKSPACE=TREE) py = "/opt/oracle7/venv/bin/python" if os.path.isfile("/opt/oracle7/venv/bin/python") else sys.executable started = subprocess.Popen([py, "oracle7.py", "--workbench", str(PORT)], cwd=TREE, env=env, stdin=subprocess.DEVNULL, stdout=open(os.path.join(STATE, "server.log"), "ab"), stderr=subprocess.STDOUT) for _ in range(180): if up(): break time.sleep(2)ready = up()say({"ready": ready, "started": started is not None, "identity": ident() if ready else None})try: for line in sys.stdin: try: q = json.loads(line) except ValueError: continue threading.Thread(target=carry, args=(q,), daemon=True).start()finally: if started is not None: started.terminate() try: started.wait(10) except Exception: # noqa: BLE001 started.kill()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519"""repair - a described change turned into an edit, and the project's own checks decide it (12.0 dev, Amendment 13).
receive the requested behaviour -> find the code it is about -> bind the change to that code -> compose candidate changes -> run the checks on each -> keep the one the checks pass, or name the step that could not be built
The description is read for two things: what the code is about (its words, matched to function names, docstrings and theframes of the last failing run) and which operations it names (a word list of operations: "adds", "subtracts", "less than","at least", "empty case" ...). Candidate changes are the code's own operations swapped for others of the same kind(arithmetic, comparison, boolean), constants moved by one, a condition negated, and a guard for the empty case; the onesthat turn an operation the description says is wrong into the one it says is wanted are tried first. The project's tests arethe judge: a change is kept only if they pass, and kept untested only when the description itself names both the wrongand the wanted operation. Nothing is written by a language model; every change is a move on the code that is there."""import astimport osimport reimport subprocessimport sysfrom pathlib import Path
NL = chr(10)# how far the search goes; a failure that reached one of these says so in its receipt (Amendment 15: the self-development loop# proposes a change to exactly these lines, builds it as a candidate, and the judge outside the candidate decides)SINGLE_CAP = 80 # single moves tried, at mostSPAN_CAP = 14 # moves considered for pairs, at mostPAIR_CAP = 90 # pairs tried, at mostOPS = { # ast operator class name -> (kind, source token, words that name it) "Add": ("arith", "+", "add adds added adding addition plus sum sums summing total"), "Sub": ("arith", "-", "subtract subtracts subtracted subtracting subtraction minus difference"), "Mult": ("arith", "*", "multiply multiplies multiplied multiplying multiplication times product"), "Div": ("arith", "/", "divide divides divided dividing division quotient ratio"), "FloorDiv": ("arith", "//", "floor integer-division"), "Mod": ("arith", "%", "modulo mod remainder"), "Pow": ("arith", "**", "power exponent squared"), "Lt": ("cmp", "<", "less smaller below under fewer"), "LtE": ("cmp", "<=", "at-most no-more-than up-to"), "Gt": ("cmp", ">", "greater larger bigger above over more exceeds"), "GtE": ("cmp", ">=", "at-least no-less-than"), "Eq": ("cmp", "==", "equal equals same"), "NotEq": ("cmp", "!=", "different unequal not-equal"), "And": ("bool", "and", "both all"), "Or": ("bool", "or", "either any"),}STOP = set("""a an the it its this that these those is are was were be been to of in on for and or but with by from as atshould would could will can must not no do does did done fix fixes correct correction repair wrong instead make makes madeplease function method code test tests run running rerun then also too so when what which there here into out up use usesused using give gives return returns value values case cases broken bug""".split())_TOKEN = re.compile(r"[A-Za-z][a-z]+|[A-Z]+(?![a-z])|\d+")
def _stem(w): w = w.lower() for suf in ("ition", "ation", "ing", "ies", "es", "ed", "s"): if len(w) > len(suf) + 2 and w.endswith(suf): return w[: -len(suf)] return w
def _words(text): return [w.lower() for w in _TOKEN.findall(text.replace("_", " "))]
def ops_named(text): """the operations a text names, in order""" low = " " + " ".join(_words(text)) + " " low = low.replace(" at least ", " at-least ").replace(" at most ", " at-most ").replace(" no more than ", " no-more-than ") \ .replace(" no less than ", " no-less-than ").replace(" up to ", " up-to ").replace(" not equal ", " not-equal ") out = [] for w in low.split(): for name, (_k, _t, ws) in OPS.items(): if w in ws.split() and name not in out: out.append(name) return out
def read_request(text): """what the description is about, what it says the code does, what it wants""" t = " ".join(text.split()) m = re.split(r"(?i)\b(?:should|instead|but it should|must|needs to|correct it to|make it|it ought to|meant to|supposed to)\b", t, 1) said, wanted = (m[0], m[1]) if len(m) == 2 else (t, "") about = [w for w in _words(t) if w not in STOP and len(w) > 2] empty = bool(re.search(r"(?i)\bempty\b|\bno (?:items|elements|values|input)\b|\bzero[- ]length\b", t)) value = None mv = re.search(r"(?i)\b(?:return|give|yield)s?\s+(none|0|0\.0|\[\]|''|\"\"|false|true|-?\d+(?:\.\d+)?)\b", t) if mv: value = mv.group(1) if re.search(r"(?i)\braises?\b.*\berror\b|\braise\s+\w+error", t): me = re.search(r"(?i)\b(\w*Error)\b", t) value = "raise " + (me.group(1) if me else "ValueError") return {"text": t, "about": about, "said_ops": ops_named(said), "wanted_ops": ops_named(wanted), "empty": empty, "value": value}
# ---------------------------------------------------------------- finding the codedef _py_files(root, limit=4000): n = 0 for dp, dns, fns in os.walk(root): dns[:] = sorted(d for d in dns if not d.startswith(".") and d not in {"node_modules", "__pycache__", "venv", ".venv", "build", "dist", "site-packages"}) for f in sorted(fns): if f.endswith(".py"): n += 1 if n > limit: return yield Path(dp) / f
def is_test_file(p): return p.name.startswith("test_") or p.name.endswith("_test.py") or "tests" in p.parts
def frames_of(log_text, root): """the project's own files and lines in a traceback, innermost last""" out = [] for f, ln in re.findall(r'File "([^"]+)", line (\d+)', log_text or ""): p = Path(f) if not p.is_absolute(): p = Path(root) / f try: p.resolve().relative_to(Path(root).resolve()) except ValueError: continue out.append((p.resolve(), int(ln))) return out
def _functions(path): try: src = path.read_text(encoding="utf-8") tree = ast.parse(src) except Exception: # noqa: BLE001 return None, [] fns = [n for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))] return src, fns
def _called_in(log_text, src_lines, frames): """names called on the failing lines of the tests (assert add(2, 3) == 5 -> add)""" names = set() for p, ln in frames: try: line = p.read_text(encoding="utf-8").splitlines()[ln - 1] except Exception: # noqa: BLE001 continue names.update(re.findall(r"\b([A-Za-z_]\w*)\s*\(", line)) names.update(re.findall(r"\b([A-Za-z_]\w*)\s*\(", log_text or "")) return names
def locate(root, req, log_text=""): """functions of the project, best first: named by the description, in the failing frames, called on a failing line""" root = Path(root) frames = frames_of(log_text, root) framed = {} for p, ln in frames: framed.setdefault(p, []).append(ln) called = _called_in(log_text, None, frames) about = {_stem(w) for w in req["about"]} want_ops = set(req["said_ops"]) | set(req["wanted_ops"]) cands = [] files = list(framed) + [p for p in _py_files(root) if p.resolve() not in framed] for p in files[:4000]: if is_test_file(p): continue try: head = p.read_text(encoding="utf-8", errors="ignore") except Exception: # noqa: BLE001 continue defs = set(re.findall(r"def\s+(\w+)", head)) def_stems = {_stem(w) for d in defs for w in _words(d)} if not (p.resolve() in framed or any(w in head.lower() for w in req["about"] if len(w) > 3) or called & defs or def_stems & about or any(set(ops_named(d.replace("_", " "))) & want_ops for d in defs)): continue src, fns = _functions(p) for fn in fns: name_w = {_stem(w) for w in _words(fn.name)} doc = ast.get_docstring(fn) or "" doc_w = {_stem(w) for w in _words(doc)} name_ops = set(ops_named(fn.name.replace("_", " "))) score = 3.0 * len(name_w & about) + 1.0 * len(doc_w & about) + 2.5 * len(name_ops & want_ops) if fn.name in called: score += 4.0 lines = framed.get(p.resolve(), []) if any(fn.lineno <= ln <= (fn.end_lineno or fn.lineno) for ln in lines): score += 6.0 if score > 0: cands.append((score, p, fn, src)) cands.sort(key=lambda c: -c[0]) return cands
# ---------------------------------------------------------------- candidate changesdef _seg_offsets(src): starts, acc = [0], 0 for ln in src.splitlines(keepends=True): acc += len(ln) starts.append(acc) return starts
def _off(starts, line, col): return starts[line - 1] + col
def _op_span(src, starts, left, right, token): """the operator token between two operands, as a span of the source""" a = _off(starts, left.end_lineno, left.end_col_offset) b = _off(starts, right.lineno, right.col_offset) seg = src[a:b] m = None for mm in re.finditer(re.escape(token), seg): before, after = seg[max(0, mm.start() - 1):mm.start()], seg[mm.end():mm.end() + 1] if token in ("<", ">") and (after == "=" or before in "<>=!"): continue if token in ("*", "/") and (after == token or before == token): continue if token == "=" or (token in ("and", "or") and not re.match(r"\s", after or " ")): continue m = mm break if not m: return None return a + m.start(), a + m.end()
def candidates(src, fn, req, wanted_value=None): """(priority, description, new source) for every move on the function; directed moves first""" starts = _seg_offsets(src) said, wanted = set(req["said_ops"]), set(req["wanted_ops"]) name_ops = set(ops_named(fn.name.replace("_", " "))) target = wanted or (name_ops - said) or name_ops out = []
def add(pri, what, a, b, new_text): out.append((pri, what, src[:a] + new_text + src[b:], (a, b, new_text)))
for node in ast.walk(fn): pairs = [] if isinstance(node, ast.BinOp): pairs = [(node.left, node.right, type(node.op).__name__)] elif isinstance(node, ast.Compare): prev = node.left for op, cmp in zip(node.ops, node.comparators): pairs.append((prev, cmp, type(op).__name__)) prev = cmp elif isinstance(node, ast.BoolOp) and len(node.values) >= 2: pairs = [(node.values[0], node.values[1], type(node.op).__name__)] for left, right, opname in pairs: if opname not in OPS: continue kind, tok, _ = OPS[opname] span = _op_span(src, starts, left, right, tok) if not span: continue for other, (k2, t2, _w) in OPS.items(): if k2 != kind or other == opname: continue pri = 50 if other in target and (opname in said or opname not in target): pri = 0 # turns what it is said to do into what is wanted elif other in target: pri = 10 elif opname in said: pri = 20 add(pri, "%s -> %s on line %d" % (tok, t2, left.lineno), span[0], span[1], t2) if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub)) and isinstance(node.right, ast.Constant) \ and type(node.right.value) is int: # an off-by-something term dropped: x - 1 -> x a = _off(starts, node.lineno, node.col_offset) b = _off(starts, node.end_lineno, node.end_col_offset) l0, l1 = _off(starts, node.left.lineno, node.left.col_offset), _off(starts, node.left.end_lineno, node.left.end_col_offset) add(30, "the term %s %d dropped on line %d" % (OPS[type(node.op).__name__][1], node.right.value, node.lineno), a, b, src[l0:l1]) if isinstance(node, ast.Constant) and type(node.value) is int and not isinstance(node.value, bool): a, b = _off(starts, node.lineno, node.col_offset), _off(starts, node.end_lineno, node.end_col_offset) for d in (1, -1): add(60, "%d -> %d on line %d" % (node.value, node.value + d, node.lineno), a, b, str(node.value + d)) if isinstance(node, (ast.If, ast.While)): t = node.test a, b = _off(starts, t.lineno, t.col_offset), _off(starts, t.end_lineno, t.end_col_offset) add(70, "condition negated on line %d" % t.lineno, a, b, "not (%s)" % src[a:b]) if req.get("empty"): g = guard(src, fn, wanted_value) if g: out.append(g) out.sort(key=lambda c: c[0]) return out
def seq_param(fn): """the parameter the function treats as a sequence (len, sum, indexing, iteration, min/max)""" params = [a.arg for a in fn.args.args if a.arg not in ("self", "cls")] use = {} for n in ast.walk(fn): if isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id in ("len", "sum", "min", "max", "sorted") \ and n.args and isinstance(n.args[0], ast.Name): use[n.args[0].id] = use.get(n.args[0].id, 0) + 2 if isinstance(n, ast.Subscript) and isinstance(n.value, ast.Name): use[n.value.id] = use.get(n.value.id, 0) + 1 if isinstance(n, (ast.For, ast.comprehension)) and isinstance(n.iter, ast.Name): use[n.iter.id] = use.get(n.iter.id, 0) + 1 ps = [p for p in params if p in use] return max(ps, key=lambda p: use[p]) if ps else None
def guard(src, fn, value): """an empty-case guard at the head of the function; needs the value to give (None -> the caller asks)""" p = seq_param(fn) if not p or value is None: return None body0 = fn.body[0] if isinstance(body0, ast.Expr) and isinstance(getattr(body0, "value", None), ast.Constant) and isinstance(body0.value.value, str): after = body0 # after the docstring line = after.end_lineno else: line = body0.lineno - 1 lines = src.splitlines(keepends=True) indent = re.match(r"\s*", lines[body0.lineno - 1]).group(0) stmt = value if value.startswith("raise ") else "return " + value if stmt.startswith("raise ") and "(" not in stmt: stmt += "(%r)" % ("%s is empty" % p) ins = "%sif not %s:%s%s %s%s" % (indent, p, NL, indent, stmt, NL) new = "".join(lines[:line]) + ins + "".join(lines[line:]) return (1, "guard for an empty %s at the head of %s (%s)" % (p, fn.name, stmt), new, None)
def value_from_tests(root, fname): """what the project's tests expect the function to give for an empty input""" for p in _py_files(root): if not is_test_file(p): continue try: s = p.read_text(encoding="utf-8") except Exception: # noqa: BLE001 continue m = re.search(r"\b%s\(\s*(?:\[\]|\(\)|''|\"\"|\{\})\s*\)\s*(?:==|is)\s*([^\s,#)]+)" % re.escape(fname), s) if m: return m.group(1) if re.search(r"raises\(\s*(\w+)\s*\)[^\n]*\n[^\n]*\b%s\(\s*(?:\[\]|\(\))" % re.escape(fname), s): return "raise " + re.search(r"raises\(\s*(\w+)", s).group(1) return None
# ---------------------------------------------------------------- checksdef test_command(root): root = Path(root) tests = [p for p in _py_files(root) if is_test_file(p) and p.name.endswith(".py")] if not tests: return None try: import pytest # noqa: F401 has_pytest = True except Exception: # noqa: BLE001 has_pytest = False funcs = any(re.search(r"(?m)^\s*def test_", p.read_text(encoding="utf-8", errors="ignore")) for p in tests) if has_pytest and funcs: return "%s -m pytest -q -x" % sys.executable cmds = [] for p in tests[:20]: rel = str(p.relative_to(root)).replace(os.sep, "/") if re.search(r"(?m)^\s*def test_", p.read_text(encoding="utf-8", errors="ignore")): # test functions with no pytest here: each one called, the first failure fails the check cmds.append('%s -c "import runpy,sys; sys.path.insert(0,\'.\'); m=runpy.run_path(\'%s\'); ' 't=[v for k,v in sorted(m.items()) if k.startswith(\'test_\') and callable(v)]; ' '[f() for f in t]; print(len(t), \'tests passed\')"' % (sys.executable, rel)) else: cmds.append("%s %s" % (sys.executable, rel)) return " && ".join(cmds)
def _runenv(root): """round-3 R2: the project's check runs in the run jail (runjail.env), never with Oracle7's own settings""" import runjail return runjail.env(root=root, PYTHONDONTWRITEBYTECODE="1")
def run_check(cmd, root, timeout=90): """no bytecode is written or trusted: a one-character change of the same size in the same second would otherwise run the old compiled code (found in the first acceptance run: every right candidate was judged by the stale file)""" try: r = subprocess.run(cmd, shell=True, cwd=str(root), capture_output=True, text=True, timeout=timeout, env=_runenv(root)) return r.returncode == 0, ((r.stdout or "") + (r.stderr or ""))[-3000:], r.returncode except subprocess.TimeoutExpired: return False, "the check ran past %d s" % timeout, None
def attempt(root, req, check_cmd, log_text="", limit=None, prefer=None): """try the moves on the located functions; the check decides. Returns a dict describing what happened. prefer: (file, function) the conversation was last working on ("handle the empty case too" means that function). If the check already passes before any change, it cannot tell which change the request wants: only a change the description itself directs is made, and it is reported as passing a check that did not test it.""" root = Path(root) limit = SINGLE_CAP if limit is None else limit caps = {} # which of the search's limits this attempt reached found = locate(root, req, log_text) if prefer: pf, pn = Path(prefer[0]).resolve(), prefer[1] hit = [c for c in found if c[1].resolve() == pf and c[2].name == pn] if not hit: src, fns = _functions(pf) hit = [(0.0, pf, fn, src) for fn in fns if fn.name == pn] if hit and not [w for w in req["about"] if any(_stem(w) == _stem(x) for c in found[:1] for x in _words(c[2].name))]: found = hit + [c for c in found if c not in hit] baseline_ok = None _cmd_again = [check_cmd] if check_cmd is not None: baseline_ok = run_check(check_cmd, root)[0] if baseline_ok: check_cmd = None # the check passes already: it cannot judge this change if not found: return {"done": False, "missing": "locate", "say": "I found no function in %s that the description or the failing run " "points to. Name the file or the function." % root} tried, considered = 0, [] for score, p, fn, src in found[:4]: value = req.get("value") if req.get("empty") and value is None: value = value_from_tests(root, fn.name) if value is None and seq_param(fn): return {"done": False, "missing": "value", "file": p, "function": fn.name, "param": seq_param(fn), "say": "%s() in %s reads %s as a list. What should it give when %s is empty? (for example: " "return 0, return None, raise ValueError)" % (fn.name, p.relative_to(root), seq_param(fn), seq_param(fn))} cs = candidates(src, fn, req, value) considered.append("%s() in %s (%d possible changes)" % (fn.name, p.relative_to(root), len(cs))) if check_cmd is None: directed = [c for c in cs if c[0] <= 1] if directed and (req["said_ops"] or req["wanted_ops"] or req.get("empty")): pri, what, new = directed[0][:3] res = {"done": True, "file": p, "function": fn.name, "what": what, "before": src, "after": new, "checked": False, "considered": considered, "baseline_ok": baseline_ok} if baseline_ok: # run the check after it all the same: it must still pass _write(p, new) ok, out, code = run_check(_cmd_again[0], root) if not ok: _write(p, src) return {"done": False, "missing": "change", "considered": considered, "tried": 1, "say": "The change the description directs (%s in %s()) breaks the project's check, so it " "was put back:%s%s" % (what, fn.name, NL, out[-600:])} res.update(check_out=out, still_passes=True) return res continue for pri, what, new, _span in cs: if tried >= limit: caps["SINGLE_CAP"] = limit break try: compile(new, str(p), "exec") except SyntaxError: continue tried += 1 _write(p, new) ok, out, code = run_check(check_cmd, root) if ok: return {"done": True, "file": p, "function": fn.name, "what": what, "before": src, "after": new, "checked": True, "check_out": out, "tried": tried, "considered": considered} _write(p, src) # Amendment 13b: no single move passes - two moves together, the most likely first, on parts that do not overlap all_spans = [c for c in cs if c[3] is not None] spans = all_spans[:SPAN_CAP] if len(all_spans) > SPAN_CAP: caps["SPAN_CAP"] = SPAN_CAP pairs = 0 for i in range(len(spans)): for j in range(i + 1, len(spans)): if pairs >= PAIR_CAP: caps["PAIR_CAP"] = PAIR_CAP break (pa, wa, _na, sa), (pb, wb, _nb, sb) = spans[i], spans[j] if not (sa[1] <= sb[0] or sb[1] <= sa[0]): continue first, second = (sa, sb) if sa[0] > sb[0] else (sb, sa) # the later span first, offsets stay true new = src[:first[0]] + first[2] + src[first[1]:] new = new[:second[0]] + second[2] + new[second[1]:] try: compile(new, str(p), "exec") except SyntaxError: continue pairs += 1 tried += 1 _write(p, new) ok, out, code = run_check(check_cmd, root) if ok: return {"done": True, "file": p, "function": fn.name, "what": "%s, and %s" % (wa, wb), "before": src, "after": new, "checked": True, "check_out": out, "tried": tried, "considered": considered} _write(p, src) if check_cmd is None and baseline_ok: return {"done": False, "missing": "change", "considered": considered, "say": "The project's check already passes, so it cannot tell which change you mean, and the description does " "not name the operation to change. Looked at %s. Say what it should do differently." % "; ".join(considered[:3])} if check_cmd is None: return {"done": False, "missing": "check", "considered": considered, "say": "I found %s, but the project has no tests and the description does not name both what the code does and " "what it should do, so I can't tell which change is right. Say what it should do (\"it should add\"), " "or name a command that checks it." % "; ".join(considered[:3])} return {"done": False, "missing": "change", "considered": considered, "tried": tried, "caps": caps, "say": "I tried %d changes on %s; none made the check pass, and each was put back.%s What should the code do " "differently? Or point me at the line." % (tried, "; ".join(considered[:3]), ( " The search stopped at its own limit%s (%s), so a fix further out was not reached." % ( "s" if len(caps) > 1 else "", ", ".join("%s = %s" % kv for kv in sorted(caps.items())))) if caps else "")}
def _write(p, text): p = Path(p) if p.is_file(): os.unlink(p) # never through a hardlink p.write_text(text, encoding="utf-8") drop_bytecode(p)
def drop_bytecode(p): """the compiled copies of a changed module, so no later run uses the old code""" p = Path(p) if p.suffix != ".py": return d = p.parent / "__pycache__" if d.is_dir(): for c in d.glob(p.stem + ".*.pyc"): try: os.unlink(c) except OSError: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278"""resolve - a request in any wording read as one of the bench's operations, by Oracle7's own word meanings (12.0 Amendment 16).
The bench knows its operations by a few shapes of sentence. A request worded another way ("can you put back what you justchanged", "is anything broken", "pull up calc.py") is read here: its content words are compared, by the word meaningsOracle7 derived from its own corpus with no training (converse/data/ladder/wordvec.npz), with the words that describe eachoperation; the operation it reads is the one that clearly wins (a floor and a margin over the next). The things the requestnames are bound from the open environment: a file or function of the project, a quoted text.
The field proposes, the law sanctions: an operation that only reads is done, and the reply says how the request was read; anoperation that changes or runs anything is offered, and done only on go. Nothing is read when no operation clearly wins: thereply names the two nearest and asks. No language model."""import osimport refrom pathlib import Path
WB = Path(__file__).resolve().parentOPS = [ # name, the words that describe it, changes anything, the bench sentence it becomes ({file}, {text}) ("status", "where status progress state standing going done finished overview summary update", False, "where are we"), ("log", "fail failed failure error errors wrong broke broken crash crashed log output traceback problem", False, "what failed"), ("diff", "change changed changes diff difference modified edits edited altered", False, "what changed"), ("read", "show read open view display see look contents print file", False, "read {file}"), ("grep", "find search locate grep where mentions occurrences usage used", False, "grep {text}"), ("ls", "list files folder directory contents inventory", False, "ls"), ("tasks", "tasks todo remaining left outstanding pending list", False, "tasks"), ("tests", "test tests testing suite verify verification check checks pass", True, "run the tests"), ("undo", "undo revert reverse rollback restore cancel back", True, "undo"), ("again", "again rerun repeat retry", True, "run it again"), ("audit", "audit security harden hardening vulnerabilities secure exposure", False, "audit the {text} config"),]STOP = set("""a an the it its this that these those i you we me my your our us please can could would will should shalldo does did is are was were be been to of in on for and or but with by from as at just now then so what how any all somethere here up out about into over once more yes no ok okay hey oracle oracle7 thing things stuff somethinganything everything nothing anyone everyone someone noone anybody everybody somebody nobody""".split())# the indefinite pronouns as a class (the list held "something" but not its siblings: Amendment 17)_V = {}
def vectors(): if "V" not in _V: import numpy as np w = np.load(WB / "converse" / "data" / "ladder" / "wordvec.npz", allow_pickle=True) V = w["vec"].astype("float32") V /= (np.linalg.norm(V, axis=1, keepdims=True) + 1e-9) _V["V"], _V["ix"] = V, {x: i for i, x in enumerate(w["words"])} _V["np"] = np return _V
def _ops_matrix(): if "O" not in _V: D = vectors() _V["O"] = [[D["V"][D["ix"][w]] for w in desc.split() if w in D["ix"]] for _n, desc, _c, _s in OPS] return _V["O"]
def content(text): """the request's content words; a compound written apart whose joined form is a word of an operation ("to do" -> todo, "roll back" -> rollback) is read joined (Amendment 19)""" allw = set().union(*(set(d.split()) for _n, d, _c, _s in OPS)) raw, out, i = re.findall(r"[a-z]+", text.lower()), [], 0 while i < len(raw): if i + 1 < len(raw) and raw[i] + raw[i + 1] in allw: out.append(raw[i] + raw[i + 1]) i += 2 continue out.append(raw[i]) i += 1 return [w for w in out if w not in STOP and len(w) > 1]
INFO = {"status", "log", "diff", "tasks"} # a question about the state of the work: only a question asks itQUESTION = re.compile(r"(?i)^\s*(?:(?:so|and|ok(?:ay)?|hey|well)[\s,]+)*(?:whats|wheres|hows|whys|what|where|how|which|why|is|are|was|were|did|does|do|" r"has|have|any|anything|show|tell|give|let me see|list)\b|\?\s*$")
def score(text, drop=()): """each operation's score: the request's strongest word for it (an exact word of the operation counts fully), with the share of the request's words that fit it at all (coverage); the words that name things in the project are left out""" D = vectors() np = D["np"] allw = set().union(*(set(d.split()) for _n, d, _c, _s in OPS)) ws = [w for w in content(text) if (w in D["ix"] or w in allw) and w not in drop] # an operation's own word counts out = [] # even where no meaning is held for it for (name, desc, changes, sent), M in zip(OPS, _ops_matrix()): own = set(desc.split()) sims = [] for w in ws: sims.append(1.0 if w in own else float(np.max(np.stack(M) @ D["V"][D["ix"][w]])) if (M and w in D["ix"]) else 0.0) top = max(sims) if sims else 0.0 cover = (sum(1 for s in sims if s >= 0.45) / len(sims)) if sims else 0.0 out.append((top, name, changes, sent, cover)) out.sort(key=lambda x: -x[0]) return out
_TURN = {} # 12.5 step 9: the turn's own binding, read once (cleared each turn)
def new_turn(): """called by the one exit's turn start: what a turn bound is never carried into the next""" _TURN.clear()
def bind(text, env): """what the request names in the environment, read once per turn (12.5 step 9, design 4.C): the walk of the folder and the reading of its functions are costly, and four readers of one turn asked for the same binding""" key = (text, getattr(env, "kind", None), str(getattr(env, "root", "")), getattr(env, "host", None)) import time as _time hit = _TURN.get(key) if hit is None or _time.time() - hit[0] > 5.0: # outside a chat turn nothing clears it: an entry lives 5 s at most hit = _TURN[key] = (_time.time(), _bind(text, env)) b = hit[1] return {"file": b["file"], "function": b["function"], "quoted": b["quoted"]}
def _bind(text, env): """what the request names in the environment: a file (by name or stem), a function defined there, a quoted text""" q = re.findall(r"[`\"']([^`\"']{1,120})[`\"']", text) f, fn = None, None if env is not None and env.kind == "folder": names = {} for p in env.walk(limit=20000): names.setdefault(os.path.basename(p).lower(), p) for tok in re.findall(r"[\w./-]+", text): t = tok.lower().strip("./") if t in names: f = names[t] break for cand in (t + ".py", t + ".js", t + ".md", t + ".txt"): if cand in names and t not in STOP: f = names[cand] break if f: break defs = set() for p in list(names.values())[:400]: if p.endswith(".py"): try: defs |= set(re.findall(r"(?m)^\s*def\s+(\w+)", open(p, encoding="utf-8", errors="ignore").read())) except Exception: # noqa: BLE001 pass fn = next((w for w in re.findall(r"\w+", text) if w in defs), None) return {"file": f, "function": fn, "quoted": q[0] if q else None}
def _wordings_path(): base = Path(os.environ.get("ORACLE7_BENCH_HOME") or (Path(os.environ.get("ORACLE7_STATE") or Path.home() / ".oracle7") / "bench")) return base / "wordings.json"
def frame(text, drop=()): """a wording's frame: its content words, without the things it names, in order of first use ("pull up X" -> pull)""" return [w for w in dict.fromkeys(content(text)) if w not in drop]
def learned(text, drop=()): """12.0 C29 (receive): the operation a wording with this frame was confirmed to mean, or None""" f = frame(text, drop) if not f: return None try: import json kept = json.loads(_wordings_path().read_text(encoding="utf-8")) except Exception: # noqa: BLE001 return None hit = kept.get(" ".join(f)) return hit.get("op") if isinstance(hit, dict) else None
def learn(text, op, env=None): """keep what an operator confirmed: this wording's frame means this operation (said once, sure after)""" b = bind(text, env) if env is not None else {"file": None, "function": None, "quoted": None} drop = set() for x in (b.get("file"), b.get("function")): if x: stem = os.path.splitext(os.path.basename(x))[0].lower() drop |= {stem} | set(re.findall(r"[a-z]+", stem)) if b.get("quoted"): drop |= set(re.findall(r"[a-z]+", b["quoted"].lower())) drop |= {"py", "js", "md", "txt"} f = frame(text, drop) if not f or len(f) > 4 or op not in {n for n, _d, _c, _s in OPS}: return False # a long or empty frame is not a wording; only known operations import json p = _wordings_path() try: kept = json.loads(p.read_text(encoding="utf-8")) except Exception: # noqa: BLE001 kept = {} import time as _t kept[" ".join(f)] = {"op": op, "from": text[:200], "t": _t.time()} p.parent.mkdir(parents=True, exist_ok=True) tmp = p.with_suffix(".tmp") tmp.write_text(json.dumps(kept, indent=1), encoding="utf-8") os.replace(tmp, p) return True
FLOOR, MARGIN, COVER, NEAR = 0.6, 0.08, 0.5, 0.45USES = 0.1 # a reading that uses what the request names (Amendment 17)MAX_WORDS = 12 # a long turn is an instruction or a thought, not one operation# 12.5 C34: polarity. "do not show poem.txt" read as "read poem.txt" because "do" is a stop word and "not" means no# operation; the negator was dropped and the reading inverted. A told (not asked) turn whose clause carries a negator asks# that the operation not be done: it is no reading to carry out. A negated question ("isn't anything broken?") still asks.NEGATOR = re.compile(r"(?i)\b(?:not|never|don'?t|dont|doesn'?t|mustn'?t|shouldn'?t|won'?t|no\s+need\s+to)\b|n't\b")
def negated(text): """True when the turn tells, in a negated clause, rather than asks""" if text.strip().endswith("?") or re.match(r"(?i)\s*(?:what|where|how|which|why|who|when|whats|wheres|is|are|was|were|" r"did|does|has|have|isn'?t|aren'?t|wasn'?t|didn'?t|hasn'?t|haven'?t)\b", text): return False # a question, even a negated one, asks return any(NEGATOR.search(c) for c in re.split(r"[.;!?]|\bbut\b|\bthen\b", text) if c.strip())
def resolve(text, env, near_ok=False): """-> (bench sentence, operation, changes, sure) ; sure False means the nearest reading, to be offered, not done. (None, None, None, the nearest two) when nothing is close enough.""" if len(re.findall(r"\w+", text)) > MAX_WORDS or negated(text): return None, None, None, [] b = bind(text, env) drop = set() for x in (b["file"], b["function"]): if x: stem = os.path.splitext(os.path.basename(x))[0].lower() drop |= {stem} | set(re.findall(r"[a-z]+", stem)) if b["quoted"]: drop |= set(re.findall(r"[a-z]+", b["quoted"].lower())) drop |= {"py", "js", "md", "txt"} n_content = len([w for w in content(text) if w not in drop]) sc = [x for x in score(text, drop) if not (x[1] in INFO and not QUESTION.search(text)) and not (x[1] == "again" and (n_content > 3 or QUESTION.search(text)))] # "again" as an adverb asks no rerun # what the request names binds its reading (Amendment 17): a reading whose sentence needs a thing the request does not # name cannot be the reading; one that uses what the request names outranks one that leaves it unused, by USES named_text = bool(b["quoted"] or b["function"]) def _fits(x): sent_ = x[3] if "{file}" in sent_ and not b["file"]: return False if "{text}" in sent_ and x[1] != "audit" and not named_text: return False return True def _uses(x): sent_ = x[3] return ("{file}" in sent_ and b["file"]) or ("{text}" in sent_ and x[1] != "audit" and named_text) sc = sorted(((x[0] + (USES if _uses(x) else 0.0),) + tuple(x[1:]) for x in sc if _fits(x)), key=lambda x: -x[0]) was = learned(text, drop) # C29: a wording the operator confirmed before is that reading, sure if was: for name_, _d, changes_, sent_ in OPS: x = (2.0, name_, changes_, sent_, 1.0) if name_ == was and _fits(x): sc = [x] + [y for y in sc if y[1] != name_] break if (not sc or sc[0][0] < NEAR) and (b["file"] or b["function"]) and near_ok: # Amendment 18: the words decide nothing, but the request names a thing that exists in the project; the reading falls # to the operation that takes that thing, offered (never done) so the operator confirms or rewords for name, _d, changes, sent in OPS: if (b["file"] and "{file}" in sent) or (not b["file"] and b["function"] and "{text}" in sent and name != "audit"): sent = sent.replace("{file}", env.rel(b["file"]) if b["file"] else "").replace("{text}", b["function"] or "") return sent, name, changes, False if not sc or sc[0][0] < NEAR: return None, None, None, sc[:2] s, name, changes, sent, cover = sc[0] sure = s >= FLOOR and (len(sc) < 2 or s - sc[1][0] >= MARGIN) and cover >= COVER if not sure and not near_ok: return None, None, None, sc[:2] if "{file}" in sent: if not b["file"]: return None, None, None, sc[:2] sent = sent.replace("{file}", env.rel(b["file"])) if "{text}" in sent: t = b["quoted"] or b["function"] if name == "audit": t = next((w for w in ("ssh", "nginx", "ports", "logs") if w in text.lower()), None) if not t: return None, None, None, sc[:2] sent = sent.replace("{text}", t) return sent, name, changes, sure123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263"""runjail - the environment every run of project code gets (revised 12.0, round-3 design P0, step R2).
A project's checks, tests and programs are not Oracle7. They run without Oracle7's own state and store locations, with aprivate home and temporary folder, and with the head's own listening port refused even on loopback (the network scopeguard in bench.GUARD reads O7_DENY_PORTS). Before this, a hostile repository's test could rewrite the hole record, thewriting and reflection state, or post "go" to the head (round-3 COMBINED_DESIGN S1).
What is removed is named by the names Oracle7 itself gives its settings (the ORACLE7_, ORACLE_ and O7_ families), so asetting added later is covered without editing this file. Would not solve: a program not written in Python ignores theport guard (bench.GUARD's own limit); a run with the head's operating-system user can still open files by absolute path."""import hashlibimport osfrom pathlib import Path
OWN = ("ORACLE7_", "ORACLE_", "O7_") # Oracle7's own setting familiesKEEP = {"O7_NET_SCOPE", "O7_DENY_PORTS"} # set below for the run itself
def head_ports(): """the ports the head listens on (set by server.main at start)""" return [p for p in (os.environ.get("ORACLE7_HEAD_PORT") or "").split(",") if p.strip().isdigit()]
def _private(root): """a home and temp folder for runs in this project, outside the project and outside Oracle7's state records""" import tempfile base = Path(tempfile.gettempdir()) / "oracle7-runs" # never under the state folder ($HOME/.. must not reach it) d = base / hashlib.sha256(str(root or "-").encode()).hexdigest()[:16] for sub in ("home", "tmp"): (d / sub).mkdir(parents=True, exist_ok=True) return d / "home", d / "tmp"
def _guard_dir(): """the network scope guard (bench.GUARD) as a sitecustomize every Python run loads first""" from bench import GUARD import tempfile g = Path(tempfile.gettempdir()) / "oracle7-runs" / "guard" # not under the state folder: its path is on every run's g.mkdir(parents=True, exist_ok=True) f = g / "sitecustomize.py" if not f.is_file() or f.read_text() != GUARD: f.write_text(GUARD) return g
def env(base=None, root=None, net_scope=(), **extra): """-> the environment for one run of project code under `root`: Oracle7's own settings removed, a private home and temp folder, the network scope guard first on the path, the head's ports refused""" deny, g = head_ports(), _guard_dir() e = {k: v for k, v in dict(os.environ if base is None else base).items() if not (k.startswith(OWN) and k not in KEEP)} home, tmp = _private(root) e["HOME"] = e["USERPROFILE"] = str(home) # Python's home is USERPROFILE on Windows, HOME elsewhere for k in ("TMPDIR", "TEMP", "TMP"): e[k] = str(tmp) if os.name == "nt": # per-user application folders on Windows e["APPDATA"] = e["LOCALAPPDATA"] = str(home) e["O7_DENY_PORTS"] = ",".join(deny) e["O7_NET_SCOPE"] = ",".join(net_scope or []) e.update({k: str(v) for k, v in extra.items()}) e["PYTHONPATH"] = str(g) + (os.pathsep + e["PYTHONPATH"] if e.get("PYTHONPATH") else "") return e123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155"""seal - the judge at the one exit every reply leaves through (12.5, round-2 design section 1.1; organ 1 of 4).
A reply is said only as far as its receipts read back. The seal splits the delivered text into sentences, each with the
receipts its producer attached, and reads every receipt back against its record with its own code:
[wd:Q<s> P<p> Q<o>] the relation store holds (s, p, o) and the sentence says the object's name and the subject's (or a
pronoun standing for it);
[hole:<id>] the hole record holds that id (a hole says what is not held; it is never an assertion).
Other receipt families (a page record [n], a proving path, a reading receipt) are counted by family; until the seal reads
a family back it is "not read by the seal" and changes nothing. Sentences with no receipt are counted.
The seal only lowers: a reply's label is the lower of what its producer said and what its receipts bear. It never raises a
hole to an answer, never adds a sentence, and never rewrites one. No language model; no hand-written list about data.
This module is pure: it is given the stores and the reply and returns the verdict; wiring it at the one exit is step 3."""
import json
import os
import re
RECEIPT = re.compile(r"\[([^\[\]]{1,200})\]")
# a receipt has a shape: family:value (wd:, hole:, scene:, turn:, enwiki_...:) or page record numbers; a bracket holding code or
# a list ([x for x in xs], ['a', 'b']) is text, not a receipt
SHAPE = re.compile(r"^(?:[A-Za-z][\w-]{0,40}:\S.*|\d+(?:\s*,\s*\d+)*)$")
WD = re.compile(r"^wd:Q(\d+)\s+P(\d+)\s+Q(\d+)$")
HOLE = re.compile(r"^hole:([\w-]+)$")
PRONOUN = {"it", "he", "she", "they", "its", "his", "her", "their", "this", "these"}
ORDER = {"answered": 3, "offered": 2, "hole": 1}
def sentences(text):
"""the body as [(sentence, [receipts])]: a sentence ends at . ! ? followed by its receipt group; sections a reply marks as
sources or how it was made are not sentences of the body"""
body, fence = [], False
for ln in str(text or "").splitlines():
if ln.strip().startswith("```"):
fence = not fence # code shown in a reply is not a sentence of it
continue
if fence:
continue
s = ln.strip()
if re.match(r"^(?:#+\s*|\*\*|_)?(?:sources|how this was made)\b", s, re.I):
break
if s and not s.startswith(("#", "```")):
body.append(s)
text = re.sub(r"`[^`]*`", "", " ".join(body)) # inline code is not a sentence's content or a receipt
out, pos = [], 0
for m in re.finditer(r"[.!?][\"')\]]*((?:\s*\[[^\[\]]{1,200}\])*)(?=\s+[A-Z0-9\"(]|\s*$)", text):
seg = text[pos:m.end()].strip()
pos = m.end()
if seg:
out.append((RECEIPT.sub("", seg).strip(), [x for x in RECEIPT.findall(seg) if SHAPE.match(x.strip())]))
tail = text[pos:].strip()
if tail:
out.append((RECEIPT.sub("", tail).strip(), [x for x in RECEIPT.findall(tail) if SHAPE.match(x.strip())]))
return [(s, rc) for s, rc in out if s or rc]
def _words(s):
return {w for w in re.findall(r"[a-z0-9]+", s.lower()) if len(w) > 2}
def read_back(sentence, receipts, store, holes):
"""-> (family, ok or None). ok None = a family the seal does not read yet"""
if not receipts:
return "none", None
fams = []
for rc in receipts:
rc = rc.strip()
m = WD.match(rc)
if m:
s, p, o = (int(x) for x in m.groups())
ok = bool(store.holds(s, p, o))
if ok:
ow, sw, ws = _words(store.label(o) or ""), _words(store.label(s) or ""), _words(sentence)
ok = (not ow or bool(ow & ws)) and (not sw or bool(sw & ws) or bool(PRONOUN & set(sentence.lower().split())))
fams.append(("wd", ok))
continue
m = HOLE.match(rc)
if m:
fams.append(("hole", m.group(1) in holes))
continue
if re.fullmatch(r"\d+(?:\s*,\s*\d+)*", rc):
fams.append(("page", None))
continue
fams.append(("other:" + rc.split(":")[0][:20].lower(), None))
known = [ok for _f, ok in fams if ok is not None]
fam = fams[0][0] if len({f for f, _ in fams}) == 1 else "+".join(sorted({f for f, _ in fams}))
if not known:
return fam, None
return fam, all(known)
def holes_of(state_dir):
p = os.path.join(state_dir, "holes.jsonl") if state_dir else None
out = set()
if p and os.path.isfile(p):
for ln in open(p, encoding="utf-8", errors="replace"):
try:
out.add(str(json.loads(ln)["id"]))
except (ValueError, KeyError):
continue
return out
def registry(tree):
"""the names of this release's verified parts (RELEASE_HASHES.json, the registry verify_install checks); empty when absent"""
try:
return set(json.load(open(os.path.join(tree, "RELEASE_HASHES.json"), encoding="utf-8")).get("parts") or {})
except (OSError, ValueError):
return set()
def proof_reads(reply, parts):
"""-> (ok, why) for a proving-path receipt: every part it names is a part of this release's registry"""
pr = reply.get("proof") or {}
names = list(pr.get("parts") or [])
if not names:
return None, None
missing = [n for n in names if n not in parts]
if missing:
return False, "its proof names %s, which %s not a part of this release" % (", ".join(missing), "is" if len(missing) == 1 else "are")
return True, "proved by %s" % ", ".join(names)
def executed(reply):
"""a record of what ran: the bench's receipt (state) or the workspace tools' run receipt (started, returncode)"""
ex = reply.get("execution") or {}
return isinstance(ex, dict) and (bool(ex.get("state")) or (ex.get("started") is True and "returncode" in ex))
def seal(reply, store, holes=frozenset(), parts=frozenset()):
"""-> the verdict: each sentence's family and read-back, the label the receipts bear (never above the producer's), and
what would be lowered and why. Pure: the reply is not changed here."""
status = reply.get("status") or "hole"
rows = []
for s, rc in sentences(reply.get("response")):
fam, ok = read_back(s, rc, store, holes)
rows.append({"text": s, "receipts": rc, "family": fam, "ok": ok})
asserted = [r for r in rows if r["family"] not in ("hole",)]
failed = [r for r in asserted if r["ok"] is False]
bare = [r for r in asserted if r["family"] == "none"]
unread = [r for r in asserted if r["ok"] is None and r["family"] != "none"]
label = status
why = []
pok, pwhy = proof_reads(reply, parts)
if status == "answered":
if failed:
label, why = "offered", ["%d receipted sentence(s) do not read back" % len(failed)]
elif pok is False:
label, why = "offered", [pwhy]
elif (bare and not any(r["ok"] for r in asserted) and not unread and pok is None and not executed(reply)):
label, why = "offered", ["no sentence carries a receipt, a proof or a record of what ran"]
if ORDER.get(label, 0) > ORDER.get(status, 0):
label = status # the seal only lowers
return {"status": status, "label": label, "lowered": label != status, "why": why, "proof": pwhy, "rows": rows,
"counts": {"sentences": len(rows), "read_back": sum(1 for r in rows if r["ok"]), "failed": len(failed),
"bare": len(bare), "unread_family": len(unread)}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374"""selfdev - Oracle7 proposes a change to itself from a failure it recorded, builds it as a candidate, and a judge outside the
candidate decides; the operator adopts it or not (12.0 Amendment 15).
propose an improvement to yourself the last failure of this conversation whose receipt shows the change composer
stopped at one of its own search limits: the limit, the line of its code that sets it
(read from the install), and the proposed value - and what it would cost
go the candidate: a copy of repair.py with only those lines changed, in its own folder;
then the judge (workbench/judge/judge_repair.py, which the candidate does not touch)
as a job: the recorded failure reproduced, the frozen repair tasks re-run
adopt it (or go, after JUDGE PASS) the candidate replaces the running repair.py (the old one kept); used from the next
turn. Nothing is adopted without the judge's pass and the operator's word.
The code composer too (12.0 C9): a code goal it declined at its own time or memory bound gives a proposal for its time
bounds (compose_code.py's GOAL_SECONDS and CHAIN_SECONDS), built as a candidate copy and judged by workbench/judge/
judge_compose.py, outside the candidate: the recorded goals must compose with it, and no goal of a fixed regression set that
the running composer composes may be lost or answer differently. Search limits are what this step proposes: a change of
any other kind is named as beyond it.
A feature of Oracle7 itself, through the project route (12.0 C10): "build into yourself: <a project over my own records>"
(the code store, its holes, retirements, dreams) is received as a project in a candidate folder with copies of the
records it names, planned, written and then judged by workbench/judge/judge_project.py (outside the candidate: the
project's ledger, every requirement against what the module does); "adopt it" after JUDGE PASS puts the module in
workbench/self/, reading the live records, and judges it again there. No language model."""
import importlib
import json
import os
import re
import shutil
import sys
import time
from pathlib import Path
NL = chr(10)
WB = Path(__file__).resolve().parent
TREE = WB.parent
LIMITS = ("SINGLE_CAP", "SPAN_CAP", "PAIR_CAP")
def _line_of(name, src):
for i, ln in enumerate(src.splitlines(), 1):
if re.match(r"^%s\s*=\s*\d+" % name, ln):
return i, ln.strip()
return None, None
def proposal_for(caps):
"""the new values: a limit that was reached is doubled; pairs follow the moves considered for pairs"""
src = (WB / "repair.py").read_text(encoding="utf-8")
cur = {k: int(re.search(r"(?m)^%s\s*=\s*(\d+)" % k, src).group(1)) for k in LIMITS}
new = dict(cur)
for k in caps:
if k in new:
new[k] = cur[k] * 2
if "SPAN_CAP" in caps or "PAIR_CAP" in caps:
n = new["SPAN_CAP"]
new["PAIR_CAP"] = max(new["PAIR_CAP"], min(800, n * (n - 1) // 2))
return cur, {k: v for k, v in new.items() if v != cur[k]}, src
COMPOSER_LIMITS = ("GOAL_SECONDS", "CHAIN_SECONDS")
COMPOSER_MAX = {"GOAL_SECONDS": 150, "CHAIN_SECONDS": 200}
def propose_composer(turn, e):
"""a code goal declined at the composer's own bound: its time bounds raised by half, as a candidate"""
from bench import _r
src = (WB / "compose_code.py").read_text(encoding="utf-8")
cur = {k: int(re.search(r"(?m)^%s\s*=\s*(\d+)" % k, src).group(1)) for k in COMPOSER_LIMITS}
new = {k: min(COMPOSER_MAX[k], int(cur[k] * 1.5)) for k in COMPOSER_LIMITS}
new = {k: v for k, v in new.items() if v != cur[k]}
if not new:
return _r("Turn %d's code goal stopped at my composer's bounds, but they are already at the most this step proposes "
"(%s); what it needs is beyond a limit." % (e["n"], ", ".join("%s = %d" % kv for kv in sorted(cur.items()))),
"missing", "selfdev:none")
names = ", ".join(g["name"] for g in e["ex"]["cgoals"])
lines = ["Turn %d (\"%s\") declined %s after my code composer reached its own bound. [receipt of turn %d]" % (
e["n"], e["you"][:70], names, e["n"])]
for k, v in sorted(new.items()):
i, ln = _line_of(k, src)
lines.append("- workbench/compose_code.py:%s `%s` -> %s = %d" % (i, ln, k, v))
lines.append("What it costs: up to %d s more on each goal that does not compose; what it may gain: a program further out "
"in the search. That is a proposal, not a result." % (new.get("GOAL_SECONDS", cur["GOAL_SECONDS"]) -
cur["GOAL_SECONDS"]))
lines.append("Say go and I build it as a candidate (its own copy; the running composer is not touched) and run the judge on "
"it: %s composed with it, and the fixed regression goals answered as the running composer answers them." % names)
turn.offer({"kind": "selfdev_build", "file": "compose_code.py", "new": new, "goals": e["ex"]["cgoals"], "turn": e["n"]})
return _r(NL.join(lines), "waiting", "selfdev:propose", proposal=new)
def propose(turn, ledger):
"""turn: the bench conversation; ledger: reflect's record of it"""
from bench import _r
cfail = [e for e in ledger if (e.get("ex") or {}).get("ccaps") and (e.get("ex") or {}).get("cgoals")]
fail = [e for e in ledger if (e.get("ex") or {}).get("caps") and (e.get("ex") or {}).get("request")]
if cfail and (not fail or cfail[-1]["n"] > fail[-1]["n"]):
return propose_composer(turn, cfail[-1])
if not fail:
other = [e for e in ledger if (e.get("ex") or {}).get("state") in ("failed", "missing", "interrupted")]
if other:
return _r("The failures recorded here (turn%s %s) did not stop at one of my search limits, so the one kind of change "
"I can propose to myself (a search limit, judged on a candidate) would not address them. What they need "
"is beyond this step: \"what did the failure reveal\" names it." % (
"s" if len(other) > 1 else "", ", ".join(str(e["n"]) for e in other[-4:])), "missing", "selfdev:none")
return _r("Nothing has failed here that a change to me would address.", "done", "selfdev:none")
e = fail[-1]
caps = e["ex"]["caps"]
cur, new, src = proposal_for(caps)
lines = ["Turn %d (\"%s\") failed after my change composer stopped at its own limit%s: %s. [receipt of turn %d]" % (
e["n"], e["you"][:70], "s" if len(caps) > 1 else "", ", ".join("%s = %s" % kv for kv in sorted(caps.items())), e["n"])]
for k, v in sorted(new.items()):
i, ln = _line_of(k, src)
lines.append("- workbench/repair.py:%s `%s` -> %s = %d" % (i, ln, k, v))
lines.append("What it costs: up to %d more check runs on such a request; what it may gain: a fix further out in the search. "
"That is a proposal, not a result." % max(0, (new.get("SINGLE_CAP", cur["SINGLE_CAP"]) - cur["SINGLE_CAP"]) +
(new.get("PAIR_CAP", cur["PAIR_CAP"]) - cur["PAIR_CAP"])))
lines.append("Say go and I build it as a candidate (its own copy; the running code is not touched) and run the judge on it: "
"the failure of turn %d reproduced, and the frozen repair tasks again." % e["n"])
turn.offer({"kind": "selfdev_build", "new": new, "request": e["ex"]["request"], "turn": e["n"]})
return _r(NL.join(lines), "waiting", "selfdev:propose", proposal=new)
def build(turn, o):
from bench import _r, run_cmd, _load, _save, _e, HOME
fname = o.get("file", "repair.py")
src = (WB / fname).read_text(encoding="utf-8")
new_src = src
for k, v in o["new"].items():
new_src = re.sub(r"(?m)^(%s\s*=\s*)\d+" % k, r"\g<1>%d" % v, new_src, count=1)
n = int(time.time())
d = HOME / "candidates" / str(n)
d.mkdir(parents=True, exist_ok=True)
(d / fname).write_text(new_src, encoding="utf-8")
try:
compile(new_src, str(d / fname), "exec")
except SyntaxError as e:
return _r("The candidate would not compile (%s); nothing was run." % e, "failed", "selfdev:build", started=False)
json.dump({"new": o["new"], "turn": o["turn"], "t": n, "file": fname}, open(d / "candidate.json", "w"))
names = _load(_e(turn.env, "names.json"), {})
if fname == "compose_code.py":
json.dump(o["goals"], open(d / "goals.json", "w"))
judge = WB / "judge" / "judge_compose.py"
cmd = "%s %s %s %s %s" % (sys.executable, judge, d / fname, d / "goals.json", WB / fname)
else:
json.dump(o["request"], open(d / "request.json", "w"))
judge = WB / "judge" / "judge_repair.py"
cmd = "%s %s %s %s %s" % (sys.executable, judge, d / "repair.py", d / "request.json", WB / "repair.py")
names["judge"] = {"cmd": cmd, "alone": False, "passes": "JUDGE PASS"}
_save(_e(turn.env, "names.json"), names)
turn.s["candidate"] = str(d)
turn.save()
r = run_cmd(turn, cmd, "judge")
head = "Candidate %d built in %s (only %s changed in %s). The judge is outside it: %s.%s" % (
n, d, ", ".join("%s = %d" % kv for kv in sorted(o["new"].items())), fname, judge, NL)
r["response"] = head + r["response"]
if (r.get("execution") or {}).get("state") == "passed":
turn.offer({"kind": "selfdev_adopt", "dir": str(d)})
r["response"] += NL + "The judge passed it. Say \"adopt it\" (or go) to use it from the next turn; the current code is kept."
return r
SELF_RECORDS = ("code_parts.jsonl", "code_holes.jsonl", "code_retired.jsonl", "code_dreams.jsonl")
def self_records():
"""Oracle7's own records a project over itself may read: -> {file name: live path}"""
import code_store as CS
out = {}
for n in SELF_RECORDS:
p = CS.store_path() if n == "code_parts.jsonl" else CS.store_path().with_name(n)
if p.is_file():
out[n] = p
return out
def open_candidate(turn):
"""the candidate of myself this conversation left with holes (kept, so the next explanation goes on from it), or None"""
d = turn.s.get("self_open")
if not d or not Path(d).is_dir():
return None
meta = json.load(open(Path(d) / "candidate.json")) if (Path(d) / "candidate.json").is_file() else {}
return Path(d) if meta.get("status") == "holes" else None
def self_project(turn, req, cont=None):
"""a feature of Oracle7 itself, received as a project over its own records, built as a candidate, judged outside it.
cont: the candidate folder a hole was left in; this turn's words go on from it (an explanation, a drop, examples)"""
import subprocess
from bench import _r, HOME
import project as PJ
recs = self_records()
kept = PJ.load_project(cont) if cont else None
named = sorted({f for c in ((kept or {}).get("clauses") or []) + [req] for f in PJ.DATA.findall(c) if f in recs})
if not named:
return _r("A change to myself as a project works on my own records; name the one it reads (%s)." % (
", ".join(sorted(recs)) or "none are kept yet"), "missing", "selfdev:project", started=False)
n = int(time.time())
d = Path(cont) if cont else HOME / "candidates" / ("self%d" % n)
d.mkdir(parents=True, exist_ok=True)
for f in named:
if not (d / f).is_file():
shutil.copyfile(recs[f], d / f) # the candidate works on a copy; the live records are not touched
shape = PJ.receive(req, d, kept)
pipes, holes, reqs, world = PJ.plan(shape, d)
comp = PJ.compose_holes(d, shape, holes)
if comp:
pipes, holes, reqs, world = PJ.plan(shape, d)
PJ.save_project(d, shape)
if holes: # C11: the candidate is kept before the hole is returned
json.dump({"kind": "project", "status": "holes", "file": shape.get("module"), "t": n,
"tables": {f: str(recs[f]) for f in named}, "holes": [h["text"] for h in holes]},
open(d / "candidate.json", "w"), indent=1)
turn.s["self_open"] = str(d)
turn.s["focus"] = "self"
turn.save()
return _r("I read it as a project over my own records (%s), kept as candidate %s; not all of it can be built yet, so "
"nothing was written. The requirements as I read them:%s%s%sWhat would fill each hole (the next turn goes "
"on from this candidate):%s%s" % (", ".join(named), d.name, NL, NL.join(" " + x for x in PJ.ledger_lines(reqs)),
NL, NL, NL.join(" - " + h["text"] for h in holes)), "missing",
"selfdev:project", started=False, holes=[h["text"] for h in holes], candidate=d.name,
requirements=[{"id": r["id"], "kind": r["kind"], "status": r["status"]} for r in reqs])
turn.s.pop("self_open", None)
src = PJ.write(shape, pipes, reqs, world)
try:
compile(src, shape["module"], "exec")
except SyntaxError as e:
return _r("The candidate would not compile (%s); nothing was run." % e, "failed", "selfdev:project", started=False)
(d / shape["module"]).write_text(src, encoding="utf-8")
judge = WB / "judge" / "judge_project.py"
jr = subprocess.run([sys.executable, str(judge), str(d)], capture_output=True, text=True, timeout=900)
passed = jr.stdout.strip().splitlines()[-1:] == ["JUDGE PASS"]
json.dump({"kind": "project", "status": "judged", "file": shape["module"], "tables": {f: str(recs[f]) for f in named}, "t": n,
"request": " ".join(shape.get("clauses") or []),
"judge": {"cmd": "%s %s %s" % (sys.executable, judge, d), "passed": passed, "out": jr.stdout[-3000:]}},
open(d / "candidate.json", "w"), indent=1)
turn.s["candidate"] = str(d)
turn.save()
pl = [" `python3 %s %s%s`: %s" % (shape["module"], nm, "".join(" " + a for a in shape["entries"][nm]["args"]),
" -> ".join(l["part"] for l in pp["links"])) for nm, pp in pipes.items()]
body = ("Candidate %s: a feature of myself, built as a project over a copy of %s in %s. The plan:%s%s%sThe judge is "
"outside it (%s):%s%s" % (d.name, ", ".join(named), d, NL, NL.join(pl), NL, judge, NL,
NL.join(" " + x for x in jr.stdout.strip().splitlines()[-30:])))
if passed:
turn.offer({"kind": "selfdev_adopt", "dir": str(d)})
return _r(body + NL + "The judge passed it. Say \"adopt it\" to put it in workbench/self/, reading my live records; "
"nothing of mine changes until then.", "waiting", "selfdev:project", files=[str(d / shape["module"])])
return _r(body + NL + "The judge did not pass it, so it is not offered for adoption.", "failed", "selfdev:project",
files=[str(d / shape["module"])])
def adopt_project(turn, d, meta):
"""the module the judge passed, into workbench/self/, reading the live records; judged again where it now lives"""
import subprocess
from bench import _r
if not (meta.get("judge") or {}).get("passed"):
return _r("The judge has not passed candidate %s, so it is not adopted." % d.name, "refused", "selfdev:adopt",
started=False)
import hashlib
import continuation as CT
import project as PJ
name = Path(meta["file"]).stem
tgt = WB / "self" / name
stage = WB / "self" / (".stage_" + name) # C11: built and judged beside the one in use; switched only on a pass
if stage.exists():
shutil.rmtree(stage)
stage.mkdir(parents=True)
src = (d / meta["file"]).read_text(encoding="utf-8")
for f, live in meta["tables"].items():
src = src.replace("TABLE = %r" % f, "TABLE = %r" % live)
# C15c: a program reading named sources reads them from its own folder once adopted (the links to my live records are
# there); what it makes still lands where it is run
src = src.replace("SOURCE_ROOT = '.'", "SOURCE_ROOT = str(_SourcePath(__file__).resolve().parent)", 1)
(stage / meta["file"]).write_text(src, encoding="utf-8")
shutil.copytree(d / ".oracle7", stage / ".oracle7")
for f in meta["tables"]: # the judge reads the same records the module reads
os.symlink(meta["tables"][f], stage / f)
jr = subprocess.run([sys.executable, str(WB / "judge" / "judge_project.py"), str(stage)], capture_output=True, text=True,
timeout=900)
passed = jr.stdout.strip().splitlines()[-1:] == ["JUDGE PASS"]
if not passed:
shutil.rmtree(stage)
return _r("Candidate %s did not pass the judge where it would live (reading my live records): %s. Nothing was "
"switched; %s." % (d.name, jr.stdout.strip()[-300:], "the version in use is unchanged" if tgt.exists() else
"nothing of mine changed"), "failed", "selfdev:adopt", started=False)
prev = None
if tgt.exists(): # the version in use is kept, whole, for a roll back
prev = WB / "self" / ".prev" / ("%s_%d" % (name, int(time.time())))
prev.parent.mkdir(parents=True, exist_ok=True)
os.rename(tgt, prev)
os.rename(stage, tgt)
shape = json.loads((tgt / ".oracle7" / "project.json").read_text(encoding="utf-8"))
entry, e = next(iter(shape["entries"].items()))
_p, _h, reqs, _w = PJ.plan(shape, tgt)
outputs = sorted({r["file"] for r in reqs if r["kind"] == "file" and r.get("file") and r["status"] != "dropped"})
request = " ".join(shape.get("clauses") or [])
generic = {"build", "make", "python3", "that", "the", "from", "and", "with", "into", "yourself", "prints", "print",
"save", "saves", "show", "shows", "rows", "row", "each", "for", "its", "all", "jsonl", "json", "csv", "file",
"write", "writes", "table", "what", "this", "per", "are", "which", "whose", "have", "has", "many", "how"}
said = PJ.ENTRY.sub(" ", request) # its words: what it does and what it reads - not its command, not
for f in outputs: # the file it writes
said = said.replace(f, " ")
said = re.sub(r"\b([\w-]+)\.(?:csv|jsonl|json)\b", lambda m: m.group(1).replace("_", " "), said)
words = sorted({w for w in re.findall(r"[a-z]+", said.lower()) if len(w) > 2 and w not in generic})
old = next((c for c in CT.capabilities() if c["name"] == name), None)
cap = CT.register({
"name": name, "entry": entry, "argv": [entry] + list(e.get("args") or []), "path": str(tgt / meta["file"]),
"request": request, "words": words, "reads": sorted(meta["tables"].values()), "outputs": outputs,
"sha256": hashlib.sha256(src.encode()).hexdigest(), "candidate": d.name,
"checks": ["judge_project on candidate %s: %s" % (d.name, "PASS" if (meta.get("judge") or {}).get("passed") else "?"),
"judge_project where it lives (live records): PASS"],
"requirements": [{"id": r["id"], "kind": r["kind"]} for r in reqs if r["status"] != "dropped"],
"previous": {"dir": str(prev), "record": old} if prev else None, "adopted": time.time()})
cmds = ", ".join("`python3 workbench/self/%s/%s %s%s`" % (tgt.name, meta["file"], nm, "".join(
" " + a for a in ee["args"])) for nm, ee in shape["entries"].items())
return _r("Adopted candidate %s: workbench/self/%s/%s, reading my live records (%s). Judged again where it lives: JUDGE "
"PASS. It is now one of my capabilities: asked for in its own words (%s) it runs, \"what have you added to "
"yourself\" lists it, and a project that needs %s gets it made. Run it as %s.%s" % (
d.name, tgt.name, meta["file"], ", ".join(meta["tables"].values()), ", ".join(words[:8]),
", ".join(outputs) or "its printed lines", cmds,
(" The version it replaced is kept (%s); \"roll back %s\" restores it." % (prev.name, name)) if prev else ""),
"done", "selfdev:adopt", files=["workbench/self/%s/%s" % (tgt.name, meta["file"])], capability=cap["name"],
sha256=cap["sha256"])
def rollback(turn, name):
"""the capability in use put back to the version it replaced (kept whole at adoption); the registry with it"""
from bench import _r
import continuation as CT
cap = next((c for c in CT.capabilities() if c["name"] == name), None)
if not cap or not cap.get("previous"):
return _r("There is no earlier version of %s to roll back to." % name, "missing", "selfdev:rollback", started=False)
tgt, prev = WB / "self" / name, Path(cap["previous"]["dir"])
if not prev.is_dir():
return _r("The earlier version of %s is no longer kept (%s)." % (name, prev), "missing", "selfdev:rollback", started=False)
out = WB / "self" / ".prev" / ("%s_rolledback_%d" % (name, int(time.time())))
os.rename(tgt, out)
os.rename(prev, tgt)
rec = cap["previous"].get("record")
if rec:
CT.register(rec)
return _r("Rolled back %s: the version adopted before is in use again; the one taken out is kept at %s." % (name, out),
"done", "selfdev:rollback", files=["workbench/self/%s" % name])
def adopt(turn, d=None):
from bench import _r, _jobs
d = Path(d or turn.s.get("candidate") or "")
meta = json.load(open(d / "candidate.json")) if (d / "candidate.json").is_file() else {}
if meta.get("kind") == "project":
return adopt_project(turn, d, meta)
fname = meta.get("file", "repair.py")
if not (d / fname).is_file():
return _r("There is no candidate to adopt in this conversation.", "missing", "selfdev:adopt", started=False)
js = [j for j in _jobs(turn.env) if j.get("name") == "judge" and str(d) in j["cmd"]]
if not js or js[-1]["state"] != "finished" or not js[-1].get("passed"):
st = js[-1]["state"] if js else "not run"
return _r("The judge has not passed candidate %s (%s), so it is not adopted." % (d.name, st if st != "finished" else "FAILED"),
"refused", "selfdev:adopt", started=False)
live = WB / fname
keep = d / ("previous_" + fname)
shutil.copyfile(live, keep)
tmp = live.with_name(live.name + ".o7new") # C11: switched in one step (a new file renamed over the old:
shutil.copyfile(d / fname, tmp) # never written through a hardlink, never half-written)
try:
compile(tmp.read_text(encoding="utf-8"), str(live), "exec")
except SyntaxError as e:
os.unlink(tmp)
return _r("Candidate %s would not compile where it would live (%s); nothing was switched." % (d.name, e), "failed",
"selfdev:adopt", started=False)
os.replace(tmp, live)
mod = fname[:-3]
if mod in sys.modules:
importlib.reload(sys.modules[mod])
return _r("Adopted candidate %s: workbench/%s now has %s (the previous file is kept at %s). It is used from this turn on. "
"Before a release, the gate and the acceptance runs decide whether it stays." % (
d.name, fname, ", ".join("%s = %d" % kv for kv in sorted(meta["new"].items())), keep),
"done", "selfdev:adopt", files=["workbench/" + fname])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288"""Named outside-service parts for the existing workbench.
Configuration names endpoints and environment variables, never credential values.An email is a kept draft first; sending takes authority for that exact draft.No provider, account, recipient or network authority is invented by this part."""import base64from contextlib import contextmanagerimport hashlibimport jsonimport osfrom pathlib import Pathimport reimport tempfileimport threadingimport timeimport urllib.errorimport urllib.parseimport urllib.request
class ServiceHole(ValueError): def __init__(self, kind, text): super().__init__(text) self.kind = kind
_FILE_LOCKS = {}_FILE_LOCKS_GUARD = threading.Lock()
@contextmanagerdef _file_lock(path): # Lexical identity: resolving/statting the target before its lock can itself # hold a Windows handle that prevents another thread's atomic replacement. key = os.path.normcase(os.path.abspath(os.fspath(path))) with _FILE_LOCKS_GUARD: lock = _FILE_LOCKS.setdefault(key, threading.RLock()) with lock: yield
@contextmanagerdef _draft_lock(path): """Protect every draft read as well as its replacement, within and across processes.""" path.parent.mkdir(parents=True, exist_ok=True) with _file_lock(path): lock = path.with_suffix(".sending") try: handle = os.open(lock, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) except FileExistsError: raise ServiceHole("delivery", "this draft is already sending, or its sender was interrupted; inspect its receipt before retrying") try: yield finally: os.close(handle) lock.unlink(missing_ok=True)
def _state(root): return Path(root).resolve() / ".oracle7" / "services"
def _read(path, default): with _file_lock(path): return json.loads(path.read_text(encoding="utf-8")) if path.is_file() else default
def _save(path, value): path.parent.mkdir(parents=True, exist_ok=True) with _file_lock(path): handle, name = tempfile.mkstemp(prefix=path.name + ".", suffix=".new", dir=path.parent) temporary = Path(name) try: with os.fdopen(handle, "w", encoding="utf-8") as stream: json.dump(value, stream, indent=2, ensure_ascii=False) stream.flush() os.fsync(stream.fileno()) os.replace(temporary, path) finally: temporary.unlink(missing_ok=True)
def _name(value): if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z][A-Za-z0-9_-]{0,63}", value): raise ServiceHole("configuration", "name the service or operation with letters, numbers, underscores or hyphens") return value
def _origin(url): p = urllib.parse.urlsplit(url) if p.scheme not in ("http", "https") or not p.hostname or p.username or p.password or p.fragment: raise ServiceHole("configuration", "the service needs an http(s) address without embedded credentials or fragments") return p.scheme, p.hostname.lower(), p.port or (443 if p.scheme == "https" else 80)
def configure(root, name, contract): """Keep a reusable service contract, without making a network request.""" name = _name(name) contract = json.loads(json.dumps(contract)) if set(contract) - {"base_url", "operations", "auth", "description"}: raise ServiceHole("configuration", "the service contract accepts base_url, operations, description and environment-backed auth only") _origin(contract.get("base_url", "")) operations = contract.get("operations") if not isinstance(operations, dict) or not operations: raise ServiceHole("configuration", "name at least one service operation and its method/path") for operation, spec in operations.items(): _name(operation) if not isinstance(spec, dict) or spec.get("method", "GET").upper() not in ("GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"): raise ServiceHole("configuration", "operation %s needs a supported HTTP method" % operation) if set(spec) - {"method", "path", "encoding", "response", "status", "result_path", "fields", "description"}: raise ServiceHole("configuration", "operation %s contains an unconnected option; receive its method/path, encoding, response/status, result_path or fields contract explicitly" % operation) destination = urllib.parse.urljoin(contract["base_url"].rstrip("/") + "/", spec.get("path", "")) if _origin(destination) != _origin(contract["base_url"]): raise ServiceHole("configuration", "operation %s must remain at its service's origin" % operation) if spec.get("encoding", "json") not in ("json", "form"): raise ServiceHole("configuration", "operation encoding must be json or form") auth = contract.get("auth") or {} if auth: if auth.get("kind", "bearer") not in ("bearer", "basic", "header") or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", auth.get("env", "")): raise ServiceHole("configuration", "authentication names a credential environment variable and bearer/basic/header kind") allowed = {"kind", "env", "username_env", "header"} if set(auth) - allowed: raise ServiceHole("configuration", "store credential environment-variable names, not credential values") for key in ("username_env",): if key in auth and not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", auth[key]): raise ServiceHole("configuration", "invalid credential environment-variable name") if contract.get("headers") or any(spec.get("headers") for spec in operations.values()): raise ServiceHole("configuration", "headers belong to the auth contract; credential values must not be kept in configuration") registry_path = _state(root) / "contracts.json" registry = _read(registry_path, {}) registry[name] = contract _save(registry_path, registry) return {"state": "checked", "service": name, "operations": sorted(operations), "network_used": False}
def contracts(root): return _read(_state(root) / "contracts.json", {})
class _NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None # credentials never follow an unreceived destination
def request(root, service, operation, params=None, payload=None, *, path_params=None, runenv=None, allowed_hosts=(), timeout=15, request_id=None): """One received operation. Missing configuration and unreachable transport stay distinct.""" try: contract = contracts(root).get(_name(service)) if contract is None: raise ServiceHole("missing", "service %s is not configured; provide its base_url and named operations" % service) spec = contract["operations"].get(_name(operation)) if spec is None: raise ServiceHole("missing", "service %s has no operation %s; configured operations: %s" % (service, operation, ", ".join(contract["operations"]))) path = spec.get("path", "") for name in re.findall(r"\{([A-Za-z_]\w*)\}", path): if name not in (path_params or {}): raise ServiceHole("input", "operation %s needs path input %s" % (operation, name)) path = path.replace("{" + name + "}", urllib.parse.quote(str(path_params[name]), safe="")) url = urllib.parse.urljoin(contract["base_url"].rstrip("/") + "/", path) origin = _origin(url) if origin != _origin(contract["base_url"]): raise ServiceHole("configuration", "the operation leaves its configured service origin") permitted = {str(host).lower() for host in allowed_hosts} | {"127.0.0.1", "localhost", "::1"} if origin[1] not in permitted: raise ServiceHole("authority", "the project has no network authority for %s; authorize that host" % origin[1]) if params: url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params, doseq=True) headers = {"Accept": "application/json", "User-Agent": "Oracle7-service-part/12"} # a credential given with the call wins; otherwise the harness's own settings. The run jail strips these from what # project code receives (round-3 R2), so a project's test never reads them, while the service part still does. auth, environment = contract.get("auth") or {}, dict(os.environ, **(runenv or {})) if auth: secret = environment.get(auth["env"]) if not secret: raise ServiceHole("configuration", "set %s in the harness environment for service %s" % (auth["env"], service)) kind = auth.get("kind", "bearer") if kind == "basic": username = environment.get(auth.get("username_env", ""), "") if not username: raise ServiceHole("configuration", "set the configured username environment variable for service %s" % service) value = "Basic " + base64.b64encode((username + ":" + secret).encode()).decode() else: value = ("Bearer " if kind == "bearer" else "") + secret header = auth.get("header", "Authorization") if not re.fullmatch(r"[A-Za-z][A-Za-z0-9-]*", header) or "\r" in value or "\n" in value: raise ServiceHole("configuration", "authentication contains an invalid header") headers[header] = value if request_id: headers["Idempotency-Key"] = str(request_id) body = None if payload is not None: mapping = spec.get("fields") or {} if mapping: payload = {destination: payload[source] for source, destination in mapping.items() if source in payload} encoding = spec.get("encoding", "json") body = (json.dumps(payload, ensure_ascii=False) if encoding == "json" else urllib.parse.urlencode(payload, doseq=True)).encode("utf-8") headers["Content-Type"] = "application/json; charset=utf-8" if encoding == "json" else "application/x-www-form-urlencoded" req = urllib.request.Request(url, data=body, headers=headers, method=spec.get("method", "GET").upper()) opener = urllib.request.build_opener(_NoRedirect) with opener.open(req, timeout=timeout) as response: raw = response.read(2_000_001) status = response.status if len(raw) > 2_000_000: raise ServiceHole("response", "the service response exceeds the received two-megabyte limit") expected = spec.get("status") if expected is not None and status not in (expected if isinstance(expected, list) else [expected]): raise ServiceHole("response", "service returned status %s, expected %s" % (status, expected)) text = raw.decode("utf-8") value = json.loads(text) if spec.get("response", "json") == "json" and text else text for key in spec.get("result_path", []): value = value[key] return {"ok": True, "state": "checked", "service": service, "operation": operation, "status": status, "value": value} except ServiceHole as exc: return {"ok": False, "state": exc.kind, "hole": {"kind": exc.kind, "text": str(exc)}} except urllib.error.HTTPError as exc: return {"ok": False, "state": "failed", "status": exc.code, "hole": {"kind": "response", "text": "service returned HTTP %s; check the endpoint and its authorization" % exc.code}} except (urllib.error.URLError, TimeoutError, OSError) as exc: # Error class, not arbitrary server text: credential values never enter receipts. return {"ok": False, "state": "unreachable", "hole": {"kind": "transport", "text": "service could not be reached (%s); keep this step and check the address/network" % type(exc).__name__}} except (ValueError, KeyError, TypeError, IndexError, UnicodeError): return {"ok": False, "state": "failed", "hole": {"kind": "response", "text": "the response does not satisfy the service's JSON/result-path contract"}}
def draft_email(root, to, subject, body, sender=None): recipients = [to] if isinstance(to, str) else list(to) if not recipients or any(not isinstance(address, str) or not re.fullmatch(r"[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+", address) for address in recipients): raise ServiceHole("input", "name the email recipient addresses") if not isinstance(subject, str) or "\n" in subject or "\r" in subject or not isinstance(body, str): raise ServiceHole("input", "an email needs a single-line subject and a text body") if sender is not None and (not isinstance(sender, str) or "\n" in sender or "\r" in sender): raise ServiceHole("input", "the email sender is invalid") content = {"to": recipients, "subject": subject, "body": body} if sender: content["from"] = sender digest = hashlib.sha256(json.dumps(content, sort_keys=True, ensure_ascii=False).encode()).hexdigest() draft_id = "draft-" + digest[:20] path = _state(root) / "drafts" / (draft_id + ".json") with _draft_lock(path): draft = _read(path, None) if draft is None: draft = {"id": draft_id, "sha256": digest, "content": content, "state": "draft", "created": time.time()} _save(path, draft) return draft
def _send_email(root, draft_id, authorization, *, service, operation="send", runenv=None, allowed_hosts=()): """Send only the reviewed content, once. An uncertain transport is never retried automatically.""" if not re.fullmatch(r"draft-[0-9a-f]{20}", str(draft_id)): return {"ok": False, "state": "missing", "hole": {"kind": "draft", "text": "name a kept email draft"}} path = _state(root) / "drafts" / (draft_id + ".json") draft = _read(path, None) if draft is None: return {"ok": False, "state": "missing", "hole": {"kind": "draft", "text": "that email draft is not kept in this project"}} digest = hashlib.sha256(json.dumps(draft["content"], sort_keys=True, ensure_ascii=False).encode()).hexdigest() if not isinstance(authorization, dict) or authorization.get("send") is not True or authorization.get("draft_id") != draft_id or authorization.get("sha256") != digest: return {"ok": False, "state": "authority", "hole": {"kind": "authority", "text": "sending requires explicit authorization for this draft's recipient, subject and body"}, "draft": draft} if draft["state"] == "sent": return {"ok": True, "state": "sent", "duplicate_prevented": True, "draft_id": draft_id, "receipt": draft.get("receipt")} if draft["state"] in ("sending", "uncertain"): return {"ok": False, "state": "uncertain", "hole": {"kind": "delivery", "text": "delivery may already have happened; inspect the provider receipt before any retry"}} draft["state"] = "sending" _save(path, draft) result = request(root, service, operation, payload=draft["content"], runenv=runenv, allowed_hosts=allowed_hosts, request_id=draft_id) if result.get("ok"): draft.update(state="sent", receipt={"service": service, "operation": operation, "status": result.get("status"), "at": time.time()}) else: # A failed local precondition did not transmit. A transport/response failure is ambiguous. draft["state"] = "draft" if result["state"] in ("missing", "configuration", "authority") else "uncertain" _save(path, draft) return dict(result, draft_id=draft_id, delivery_state=draft["state"])
def send_email(root, draft_id, authorization, *, service, operation="send", runenv=None, allowed_hosts=()): """Serialize delivery across browser turns/processes, including two simultaneous clicks.""" if not re.fullmatch(r"draft-[0-9a-f]{20}", str(draft_id)): return {"ok": False, "state": "missing", "hole": {"kind": "draft", "text": "name a kept email draft"}} directory = _state(root) / "drafts" if not directory.is_dir(): return {"ok": False, "state": "missing", "hole": {"kind": "draft", "text": "that email draft is not kept in this project"}} try: with _draft_lock(directory / (draft_id + ".json")): return _send_email(root, draft_id, authorization, service=service, operation=operation, runenv=runenv, allowed_hosts=allowed_hosts) except ServiceHole as exc: return {"ok": False, "state": "uncertain" if exc.kind == "delivery" else exc.kind, "hole": {"kind": exc.kind, "text": str(exc)}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142"""shadow - the sufficiency judge run beside the composer, changing no answer (12.5 step 12c(i), round-2 design 3.B).
For a program the composer chose (one expression, or a decision list), it asks: does any rival the bank already holds,which gives every example too, answer differently on an input made from the examples? Rivals: every banked program thatfits all examples within the size the examples evidence (`evidenced`), and for a decision list each guard or arm swappedone at a time for a banked program with the same values on the examples it covers. Probes: the composer's own `probes`plus inputs re-drawn with replacement from the examples' pooled parts, in their observed shapes and length range, seededby the examples' sha plus a nonce kept in the record (replayable, not predictable from the examples alone).
It writes one record per chosen program to ORACLE7_SHADOW_LOG (only when that is set) and returns it; the composer'sanswer is never changed here. Rival and probe counts are named guards; a cut is recorded."""import hashlibimport jsonimport osimport randomimport time
RIVAL_CAP = 300 # fitting rivals probed per goal (a guard; the count cut is recorded)SWAP_CAP = 30 # alternatives per guard or arm of a decision listREDRAW = 40 # inputs re-drawn from the examples' partsSECONDS = 10.0 # the shadow's own allowance per goal (a guard; a stop is recorded)
def _redraw(ex, rng, k=REDRAW): ins = [list(a) for a, _o, _t in ex] seen = {repr(a) for a in ins} out = [] for _ in range(k * 3): if len(out) >= k: break b = [] for i in range(len(ins[0])): vals = [a[i] for a in ins] v0 = vals[0] if isinstance(v0, list): pool = [e for v in vals if isinstance(v, list) for e in v] lo, hi = min(len(v) for v in vals), max(len(v) for v in vals) b.append([rng.choice(pool) for _ in range(rng.randint(lo, hi))] if pool else list(v0)) elif isinstance(v0, str) and any(" " in v for v in vals if isinstance(v, str)): pool = [w for v in vals if isinstance(v, str) for w in v.split()] lens = [len(v.split()) for v in vals if isinstance(v, str)] b.append(" ".join(rng.choice(pool) for _ in range(rng.randint(min(lens), max(lens)))) if pool else v0) elif isinstance(v0, str): pool = [c for v in vals if isinstance(v, str) for c in v] lens = [len(v) for v in vals if isinstance(v, str)] b.append("".join(rng.choice(pool) for _ in range(rng.randint(min(lens), max(lens)))) if pool else v0) else: b.append(rng.choice(vals)) if repr(b) not in seen: seen.add(repr(b)) out.append(b) return out
def _route(steps, inp, C): for j, (c, _e) in enumerate(steps): if c is None or C.evalx(c, inp) is True: return j return None
def judge(res, ex, goal_name, C): """-> the shadow record for the composer's chosen result (C: the compose_code module)""" t0 = time.time() bank = res.get("bank") kind = res.get("kind") sha = hashlib.sha256(repr([(list(a), o) for a, o, _t in ex]).encode()).hexdigest() nonce = os.urandom(8).hex() rec = {"goal": goal_name, "kind": kind, "examples": len(ex), "ex_sha": sha[:16], "nonce": nonce} if bank is None or kind not in ("expr", "branches"): rec["skipped"] = "no chosen program" return rec if kind == "expr": best = res["x"] run_best = lambda p: C.evalx(best, p) # noqa: E731 chosen_ids = {id(best)} else: steps = res["steps"] run_best = lambda p: C.eval_steps(steps, p) # noqa: E731 chosen_ids = {id(x) for st in steps for x in st if x is not None} n = len(ex) fitting = sorted((y for y in bank.seen.values() if not y.dead and y.inp and id(y) not in chosen_ids and C.fits_all(y, ex) and C.evidenced(y, n)), key=lambda y: y.cost) rivals = [("fit", y, (lambda y_: lambda p: C.evalx(y_, p))(y)) for y in fitting[:RIVAL_CAP]] rec["fitting_cut"] = max(0, len(fitting) - RIVAL_CAP) if kind == "branches": routes = [_route(steps, list(a), C) for a, _o, _t in ex] alive = [y for y in bank.seen.values() if not y.dead and y.inp] for j, (c, e) in enumerate(steps): mine = [i for i, r in enumerate(routes) if r == j] arm_alts = [y for y in alive if y is not e and all(i < len(y.val) and C.same(y.val[i], ex[i][1], ex[i][2]) for i in mine)] for y in sorted(arm_alts, key=lambda y: y.cost)[:SWAP_CAP]: sw = list(steps) sw[j] = (c, y) rivals.append(("arm%d" % j, y, (lambda s_: lambda p: C.eval_steps(s_, p))(sw))) if c is not None: g_alts = [y for y in alive if y is not c and y.t == "bool" and list(y.val) == list(c.val)] for y in sorted(g_alts, key=lambda y: y.cost)[:SWAP_CAP]: sw = list(steps) sw[j] = (y, e) rivals.append(("guard%d" % j, y, (lambda s_: lambda p: C.eval_steps(s_, p))(sw))) rng = random.Random(sha + nonce) inputs = list(C.probes(ex)) + _redraw(ex, rng) rec.update(rivals_probed=len(rivals), probes=len(inputs)) fork = None for p in inputs: if time.time() - t0 > SECONDS: rec["stopped"] = "the shadow's %.0f s allowance" % SECONDS break bv = run_best(p) if bv is C.ERR: continue for how, y, run in rivals: yv = run(p) if yv is not C.ERR and not C.same(yv, bv) and not C.same(bv, yv): fork = {"how": how, "probe": repr(p)[:200], "chosen_gives": repr(bv)[:120], "rival_gives": repr(yv)[:120]} break if fork: break rec["shadow_fork"] = bool(fork) if fork: rec["fork"] = fork rec["seconds"] = round(time.time() - t0, 2) return rec
def record(res, ex, goal_name, C): """run the shadow when ORACLE7_SHADOW_LOG is set; never raises, never changes res""" path = os.environ.get("ORACLE7_SHADOW_LOG") if not path: return None try: rec = judge(res, ex, goal_name, C) except Exception as e: # noqa: BLE001 rec = {"goal": goal_name, "error": repr(e)[:200]} try: with open(path, "a", encoding="utf-8") as f: f.write(json.dumps(rec) + "\n") except OSError: pass return rec123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Oracle7</title><style>@font-face { font-family: "O7 Mono"; src: url(/static/fonts/JetBrainsMono.ttf) format("truetype"); font-weight: 100 800; font-display: swap; }:root { color-scheme: light; /* every colour, radius, shadow, font and duration is a token; nothing below this block names a raw value */ --bg: 0 0% 100%; --side: 40 14% 97%; --fg: 30 8% 12%; --fg-soft: 30 5% 38%; --fg-dim: 30 4% 56%; --line: 35 12% 89%; --line-strong: 35 10% 80%; --bubble: 40 14% 95%; --block: 40 16% 97%; --accent: 22 78% 46%; --accent-fg: 0 0% 100%; --ok: 150 48% 34%; --offer: 36 80% 38%; --gap: 0 0% 46%; --focus: 22 78% 46%; --r-s: 8px; --r-m: 14px; --r-l: 22px; --shadow-tab: 0 1px 2px hsl(var(--fg) / .12); --shadow-box: 0 1px 2px hsl(var(--fg) / .05), 0 8px 28px hsl(var(--fg) / .07); --sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; --mono: "O7 Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; --col: 46rem; --dur: 160ms; --ease: cubic-bezier(.2, .7, .2, 1);}* { box-sizing: border-box; }html, body { height: 100%; margin: 0; }body { background: hsl(var(--bg)); color: hsl(var(--fg)); font: 16px/1.6 var(--sans); -webkit-font-smoothing: antialiased; }button, textarea { font: inherit; color: inherit; }:focus-visible { outline: 2px solid hsl(var(--focus)); outline-offset: 2px; border-radius: var(--r-s); }.app { display: grid; grid-template-columns: 17rem minmax(0, 1fr); height: 100%; }
/* sidebar */.side { background: hsl(var(--side)); border-right: 1px solid hsl(var(--line)); display: flex; flex-direction: column; min-height: 0; }.brand { display: flex; align-items: center; gap: .6rem; padding: 1rem 1rem .6rem; font-weight: 650; letter-spacing: -.01em; }.mark { width: 1.35rem; height: 1.35rem; border-radius: 50%; border: 2px solid hsl(var(--fg)); position: relative; flex: none; }.mark::after { content: ""; position: absolute; inset: 4px; border-radius: 50%; background: hsl(var(--accent)); }.new { margin: .4rem .75rem .6rem; padding: .55rem .8rem; text-align: left; background: hsl(var(--bg)); border: 1px solid hsl(var(--line-strong)); border-radius: var(--r-s); cursor: pointer; transition: background var(--dur) var(--ease); }.new:hover { background: hsl(var(--bubble)); }.side h2 { font-size: .72rem; font-weight: 600; color: hsl(var(--fg-dim)); margin: .8rem 1rem .3rem; }.convs { list-style: none; margin: 0; padding: 0 .5rem; overflow-y: auto; flex: 1; min-height: 0; }.convs button { width: 100%; text-align: left; background: none; border: 0; padding: .45rem .55rem; border-radius: var(--r-s); cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: hsl(var(--fg-soft)); font-size: .92rem; }.convs button:hover, .convs button[aria-current="true"] { background: hsl(var(--bubble)); color: hsl(var(--fg)); }.foot { border-top: 1px solid hsl(var(--line)); padding: .7rem 1rem; font-size: .82rem; color: hsl(var(--fg-dim)); display: grid; gap: .25rem; }.foot a { color: hsl(var(--fg-soft)); text-decoration: none; }.foot a:hover { color: hsl(var(--fg)); text-decoration: underline; }
/* main */.main { display: flex; flex-direction: column; min-width: 0; min-height: 0; }.top { display: flex; align-items: center; gap: .6rem; padding: .7rem 1rem; color: hsl(var(--fg-dim)); font-size: .85rem; }.tabs { display: flex; gap: .25rem; margin-left: auto; margin-right: auto; background: hsl(var(--side)); border: 1px solid hsl(var(--line)); border-radius: 999px; padding: .2rem; }.tabs button { border: 0; background: none; padding: .3rem .95rem; border-radius: 999px; cursor: pointer; color: hsl(var(--fg-soft)); font-size: .88rem; transition: background var(--dur) var(--ease), color var(--dur) var(--ease); }.tabs button[aria-selected="true"] { background: hsl(var(--bg)); color: hsl(var(--fg)); box-shadow: var(--shadow-tab); font-weight: 600; }.view[hidden] { display: none; }.view { display: flex; flex-direction: column; flex: 1; min-height: 0; }.sat-head { padding: 2.2rem 0 1.2rem; }.sat-head h1 { font-size: 1.5rem; font-weight: 600; letter-spacing: -.02em; margin: 0 0 .3rem; }.sat-head p { color: hsl(var(--fg-soft)); margin: 0; }.sats { display: grid; grid-template-columns: 1fr 1fr; gap: .8rem; padding-bottom: 2rem; }.sat { border: 1px solid hsl(var(--line)); border-radius: var(--r-m); padding: 1rem 1.1rem; display: flex; flex-direction: column; gap: .5rem; background: hsl(var(--bg)); }.sat h2 { font-size: 1.02rem; font-weight: 650; margin: 0; text-transform: capitalize; display: flex; align-items: center; gap: .5rem; }.sat p { margin: 0; color: hsl(var(--fg-soft)); font-size: .92rem; line-height: 1.5; flex: 1; }.sat .row { display: flex; align-items: center; gap: .7rem; flex-wrap: wrap; font-size: .8rem; color: hsl(var(--fg-dim)); }.sat button { border: 1px solid hsl(var(--line-strong)); background: hsl(var(--bg)); border-radius: var(--r-s); padding: .3rem .7rem; cursor: pointer; font-size: .84rem; transition: background var(--dur) var(--ease); }.sat button:hover:not(:disabled) { background: hsl(var(--bubble)); }.sat button:disabled { opacity: .5; cursor: default; }.sat code { font: .78rem var(--mono); background: hsl(var(--block)); border: 1px solid hsl(var(--line)); border-radius: var(--r-s); padding: .1rem .4rem; color: hsl(var(--fg-soft)); }.sat .res { font: .78rem/1.55 var(--mono); color: hsl(var(--fg-soft)); white-space: pre-wrap; overflow-wrap: anywhere; border-left: 2px solid hsl(var(--line-strong)); padding-left: .7rem; }.menu { display: none; background: none; border: 1px solid hsl(var(--line-strong)); border-radius: var(--r-s); padding: .25rem .55rem; cursor: pointer; }.scroll { flex: 1; overflow-y: auto; min-height: 0; }.col { max-width: var(--col); margin: 0 auto; padding: 0 1.25rem; }.hello { padding: 16vh 0 2rem; text-align: center; }.hello h1 { font-size: 2rem; font-weight: 600; letter-spacing: -.02em; margin: 0 0 .4rem; }.hello p { color: hsl(var(--fg-soft)); margin: 0 auto 1.6rem; max-width: 34rem; }.tries { display: grid; grid-template-columns: 1fr 1fr; gap: .6rem; text-align: left; }.tries button { background: hsl(var(--bg)); border: 1px solid hsl(var(--line)); border-radius: var(--r-m); padding: .7rem .9rem; cursor: pointer; color: hsl(var(--fg-soft)); font-size: .93rem; line-height: 1.4; transition: border-color var(--dur) var(--ease), color var(--dur) var(--ease); }.tries button:hover { border-color: hsl(var(--line-strong)); color: hsl(var(--fg)); }.tries b { display: block; color: hsl(var(--fg)); font-weight: 600; font-size: .82rem; margin-bottom: .1rem; }
.turn { padding: .9rem 0; animation: rise var(--dur) var(--ease); }@keyframes rise { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }.me { display: flex; justify-content: flex-end; }.me div { background: hsl(var(--bubble)); border-radius: var(--r-l); padding: .6rem 1rem; max-width: 85%; white-space: pre-wrap; overflow-wrap: anywhere; }.it { overflow-wrap: anywhere; }.it p { margin: 0 0 .75rem; }.it h3 { font-size: 1.12rem; font-weight: 650; margin: .2rem 0 .6rem; letter-spacing: -.01em; }.it h4 { font-size: .95rem; font-weight: 650; margin: 1rem 0 .4rem; color: hsl(var(--fg-soft)); }.it pre { background: hsl(var(--block)); border: 1px solid hsl(var(--line)); border-radius: var(--r-m); padding: .8rem 1rem; margin: 0 0 .75rem; font: .84rem/1.55 var(--mono); white-space: pre-wrap; overflow-x: auto; }.it ol { margin: 0 0 .75rem; padding-left: 1.3rem; color: hsl(var(--fg-soft)); font-size: .9rem; }.it ul { margin: 0 0 .75rem; padding-left: 1.3rem; }.it ul li { margin-bottom: .4rem; }.cite { display: inline-block; font-size: .72rem; color: hsl(var(--fg-soft)); border: 1px solid hsl(var(--line-strong)); border-radius: 999px; padding: 0 .5rem; margin: 0 .15rem; vertical-align: 1px; white-space: nowrap; }.meta { display: flex; flex-wrap: wrap; align-items: center; gap: .7rem; font-size: .8rem; color: hsl(var(--fg-dim)); margin-top: .1rem; }.st { display: inline-flex; align-items: center; gap: .35rem; }.st i { width: .5rem; height: .5rem; border-radius: 50%; background: hsl(var(--gap)); }.st.answered i { background: hsl(var(--ok)); } .st.offered i { background: hsl(var(--offer)); }details { font-size: .8rem; color: hsl(var(--fg-dim)); }summary { cursor: pointer; list-style: none; } summary::-webkit-details-marker { display: none; }summary:hover { color: hsl(var(--fg-soft)); }.why { margin: .5rem 0 0; padding: .6rem .8rem; border-left: 2px solid hsl(var(--line-strong)); color: hsl(var(--fg-soft)); font: .78rem/1.6 var(--mono); white-space: pre-wrap; }.build-details { margin: .6rem 0; }.build-details > summary { color: hsl(var(--fg-soft)); }.build-details > summary::before { content: "+ "; }.build-details[open] > summary::before { content: "− "; }.it .build-evidence { margin-top: .6rem; }.wait { display: inline-flex; gap: .3rem; padding: .5rem 0; }.wait i { width: .42rem; height: .42rem; border-radius: 50%; background: hsl(var(--fg-dim)); animation: pulse 1.1s infinite var(--ease); }.wait i:nth-child(2) { animation-delay: .15s; } .wait i:nth-child(3) { animation-delay: .3s; }@keyframes pulse { 0%, 100% { opacity: .25; } 50% { opacity: 1; } }
/* composer */.dock { padding: .4rem 0 1rem; }.box { display: flex; align-items: flex-end; gap: .5rem; background: hsl(var(--bg)); border: 1px solid hsl(var(--line-strong)); border-radius: var(--r-l); padding: .55rem .55rem .55rem 1rem; box-shadow: var(--shadow-box); transition: border-color var(--dur) var(--ease); }.box:focus-within { border-color: hsl(var(--fg-dim)); }.box textarea { flex: 1; border: 0; outline: 0; resize: none; background: none; max-height: 12rem; padding: .35rem 0; line-height: 1.5; }.send { width: 2.25rem; height: 2.25rem; flex: none; border: 0; border-radius: 50%; background: hsl(var(--accent)); color: hsl(var(--accent-fg)); cursor: pointer; display: grid; place-items: center; transition: opacity var(--dur) var(--ease), transform var(--dur) var(--ease); }.send:disabled { opacity: .35; cursor: default; }.send:not(:disabled):active { transform: scale(.94); }.note { text-align: center; font-size: .76rem; color: hsl(var(--fg-dim)); margin-top: .55rem; }
@media (max-width: 760px) { .app { grid-template-columns: minmax(0, 1fr); } .side { position: fixed; inset: 0 22% 0 0; z-index: 5; transform: translateX(-102%); transition: transform var(--dur) var(--ease); box-shadow: var(--shadow-box); } .side.open { transform: none; } .menu { display: inline-block; } .tries { grid-template-columns: 1fr; } .sats { grid-template-columns: 1fr; } .hello { padding-top: 9vh; }}@media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } }</style></head><body><div class="app"> <aside class="side" id="side" aria-label="Conversations"> <div class="brand"><span class="mark" aria-hidden="true"></span>Oracle7</div> <button class="new" id="new">New chat</button> <h2>Conversations</h2> <ul class="convs" id="convs"></ul> <div class="foot"> <a href="/full">Full workbench</a> <span id="ver">no language model</span> </div> </aside> <main class="main"> <div class="top"><button class="menu" id="menu" aria-label="Show conversations">Chats</button><span id="head">Oracle7</span> <div class="tabs" role="tablist"><button role="tab" id="tab-chat" aria-selected="true">Chat</button><button role="tab" id="tab-sat" aria-selected="false">Satellites</button><button role="tab" id="tab-mac" aria-selected="false">Machines</button></div></div> <div class="view" id="view-chat"> <div class="scroll" id="scroll"> <div class="col" id="log"> <section class="hello" id="hello"> <h1>What do you want to know or build?</h1> <p>Ask, talk, or say what you want made. Every reply shows whether it was checked and how it got there.</p> <div class="tries" id="tries"> <button data-q="What is the capital of Australia?"><b>Ask</b>What is the capital of Australia?</button> <button data-q="explain photosynthesis"><b>Explain</b>explain photosynthesis</button> <button data-q="make t: split it into words, count them, print it. expect 4" data-fill="1"><b>Build</b>make a small program from the steps you describe</button> <button data-q="want the total amount of the regions whose amount is above average" data-fill="1"><b>Plan</b>want a result from a table in your sandbox</button> </div> </section> </div> </div> <div class="dock"><div class="col"> <form class="box" id="form"> <textarea id="q" rows="1" placeholder="Message Oracle7" aria-label="Message Oracle7" autofocus></textarea> <button class="send" id="send" aria-label="Send" disabled> <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M8 13V3M8 3 3.5 7.5M8 3l4.5 4.5" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg> </button> </form> <div class="note">Runs on this computer. Tools: index, find, read, write, run, fetch, make, change, want.</div> </div></div> </div> <div class="view" id="view-mac" hidden> <iframe id="macframe" title="Machines" style="border:0;width:100%;height:100%;display:block"></iframe> </div> <div class="view" id="view-sat" hidden> <div class="scroll"><div class="col"> <div class="sat-head"><h1>Satellites</h1><p>The six orbiters that ship in this release. Each runs on its own beside the core, and each has an exam you can run here from the pack.</p></div> <div class="sats" id="sats"></div> </div></div> </div> </main></div><script>(function () { "use strict"; var $ = function (id) { return document.getElementById(id); }; var log = $("log"), q = $("q"), send = $("send"), scroll = $("scroll"), hello = $("hello"); var sid = newId(), busy = false;
function newId() { var s = "c"; for (var i = 0; i < 13; i++) s += "abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(Math.random() * 36)]; return s; } function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { "&": "&", "<": "<", ">": ">", '"': """ }[c]; }); } function api(path, body) { return fetch(path, body ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : {}) .then(function (r) { return r.json(); }); }
// citations and internal marks, shown as plain source names (the terminal chat does the same) function tidy(t) { return String(t) .replace(/\s*\[(?:turn|form|scene|op|ledger):[^\]]*\]/g, "").replace(/\s*\[none\]/g, "") .replace(/\[simplewiki_[0-9a-f]+\]/g, "\u0001Simple Wikipedia\u0002").replace(/\[enwiki_[0-9a-f]+\]/g, "\u0001Wikipedia\u0002") .replace(/\[wd:(Q\d+)[^\]]*\]/g, "\u0001Wikidata $1\u0002").replace(/\[(wiktionary|wordnet|conceptnet|openstax)[^\]]*\]/gi, function (m, a) { return "\u0001" + a.charAt(0).toUpperCase() + a.slice(1) + "\u0002"; }) .replace(/\[(rel-[a-z0-9-]+)\]/g, "\u0001$1\u0002"); } function inline(s) { return esc(s).replace(/\u0001([^\u0002]*)\u0002/g, '<span class="cite">$1</span>'); } // the reply as blocks: headings, numbered sources, indented or step-like output as a monospace block, the rest as paragraphs function render(text) { var lines = tidy(text).split("\n"), out = [], para = [], pre = [], ol = [], ul = []; function flush() { if (para.length) { out.push("<p>" + inline(para.join(" ")) + "</p>"); para = []; } if (pre.length) { out.push("<pre>" + inline(pre.join("\n")) + "</pre>"); pre = []; } if (ol.length) { out.push("<ol>" + ol.map(function (x) { return "<li>" + inline(x) + "</li>"; }).join("") + "</ol>"); ol = []; } if (ul.length) { out.push("<ul>" + ul.map(function (x) { return "<li>" + inline(x) + "</li>"; }).join("") + "</ul>"); ul = []; } } var listy = /^(Built |Ran: |Planned from |Changed |Indexed |I could not |check: )/; var inBlock = false; lines.forEach(function (ln) { var m; if (!ln.trim()) { if (!inBlock) flush(); else pre.push(""); return; } if ((m = ln.match(/^#{1,2}\s+(.*)$/))) { flush(); inBlock = false; out.push("<h3>" + inline(m[1]) + "</h3>"); return; } if ((m = ln.match(/^#{3,}\s+(.*)$/))) { flush(); inBlock = false; out.push("<h4>" + inline(m[1]) + "</h4>"); return; } // every list the reply writes is shown as a list: numbered lines (sources, steps) and "- " lines (a record's points) if (!inBlock && (m = ln.match(/^\s{0,1}(\d+)\.\s+(\S.*)$/))) { if (para.length || pre.length || ul.length) flush(); ol.push(m[2]); return; } if (!inBlock && (m = ln.match(/^\s{0,1}[-*•]\s+(\S.*)$/))) { if (para.length || pre.length || ol.length) flush(); ul.push(m[1]); return; } if (listy.test(ln) || /^\s{2,}\S/.test(ln) || inBlock) { if (para.length || ol.length) flush(); inBlock = true; pre.push(ln); return; } para.push(ln.trim()); }); flush(); return out.join(""); } function statusLine(st) { var label = { answered: "checked", offered: "offered, not checked as an answer", hole: "a gap it names", declined: "declined" }[st] || st || ""; return '<span class="st ' + esc(st || "") + '"><i></i>' + esc(label) + "</span>"; } function add(html, cls) { var d = document.createElement("div"); d.className = "turn " + cls; d.innerHTML = html; log.appendChild(d); scroll.scrollTop = scroll.scrollHeight; return d; } function addMe(t) { hello.hidden = true; add("<div>" + esc(t) + "</div>", "me"); } function addIt(r) { var steps = (r.trace || []).map(function (s) { return s[1]; }).filter(Boolean).join(" → "); var why = [steps, r.why || "", r.path ? "path: " + r.path : "", r.ms ? r.ms + " ms" : ""].filter(Boolean).join("\n"); var response = r.response || "", details = typeof r.details === "string" ? r.details : ""; // The API keeps the complete response. Only move an exactly matching evidence suffix out of its visible summary. if (details && response.slice(-details.length) === details) response = response.slice(0, -details.length); var evidence = details ? '<details class="build-details"><summary>Build details</summary><pre class="build-evidence"></pre></details>' : ""; var turn = add(render(response) + evidence + '<div class="meta">' + statusLine(r.status) + (why ? "<details><summary>How it got there</summary><div class=\"why\">" + esc(why) + "</div></details>" : "") + "</div>", "it"); if (details) turn.querySelector(".build-evidence").textContent = details; return turn; }
// a long turn goes on as a job on the box: its stage is shown while it runs, its result when it ends; status and stop // can be said meanwhile (the link carries them beside it) var following = {}; function follow(s, job) { if (following[job]) return; var line = add('<div class="meta"><span class="st offered"><i></i>job ' + esc(job) + ': running</span></div>', "it"); following[job] = setInterval(function () { api("/api/turn?sid=" + encodeURIComponent(s)).then(function (t) { var j = t.job; if (!j || j.id !== job) return; if (j.state === "running") { line.querySelector(".st").lastChild.textContent = "job " + job + ": " + (j.stage || "running"); return; } clearInterval(following[job]); line.remove(); if (s !== sid || j.shown) return; api("/api/turn?take=1&sid=" + encodeURIComponent(s)).then(function () { var r = j.result || { response: "(the job ended without a kept result)", status: "hole" }; addIt(Object.assign({}, r, { response: "Job " + job + " " + j.state + ":\n" + (r.response || "") })); }); }).catch(function () {}); }, 3000); } api("/api/identity").then(function (i) { if (!i || !i.build) return; $("ver").textContent = "build " + i.build + (i.running_is_on_disk ? "" : " (restart to load changes)") + " · no language model"; $("ver").title = "tree " + i.tree + "\nstate " + i.state + "\npid " + i.pid + "\nworkbench " + i.workbench_at_start.sha256 + (i.running_is_release ? "\n= the assembled release's workbench" : "\nnot the assembled release's workbench (" + (i.workbench_in_release.sha256 || "none") + ")"); }).catch(function () {});
function ask(text) { if (busy || !text.trim()) return; busy = true; send.disabled = true; addMe(text); q.value = ""; grow(); var w = add('<span class="wait" aria-label="Working"><i></i><i></i><i></i></span>', "it"); api("/api/chat", { text: text, sid: sid, deadline: 40 }).then(function (r) { w.remove(); addIt(r.error ? { response: r.error, status: "declined" } : r); var ex = r.execution || {}; if (ex.state === "running" && ex.job) follow(sid, ex.job); }).catch(function (e) { w.remove(); addIt({ response: "The workbench did not answer: " + e.message, status: "declined" }); }).then(function () { busy = false; send.disabled = !q.value.trim(); q.focus(); convs(); }); }
function convs() { api("/api/convs").then(function (r) { var ul = $("convs"); ul.innerHTML = ""; (r.items || []).slice(0, 60).forEach(function (c) { var li = document.createElement("li"), b = document.createElement("button"); b.textContent = c.title && c.title !== "(untitled)" ? c.title : "Conversation"; if (c.id === sid) b.setAttribute("aria-current", "true"); b.onclick = function () { open(c.id); }; li.appendChild(b); ul.appendChild(li); }); }).catch(function () {}); } function clear() { Array.prototype.slice.call(log.querySelectorAll(".turn")).forEach(function (n) { n.remove(); }); } function open(id) { api("/api/conv?id=" + encodeURIComponent(id)).then(function (c) { sid = id; clear(); hello.hidden = (c.turns || []).length > 0; (c.turns || []).forEach(function (t) { addMe(t.q); addIt(t); }); $("side").classList.remove("open"); convs(); }); } function fresh() { sid = newId(); clear(); hello.hidden = false; $("side").classList.remove("open"); convs(); q.focus(); } function grow() { q.style.height = "auto"; q.style.height = Math.min(q.scrollHeight, 192) + "px"; }
q.addEventListener("input", function () { grow(); send.disabled = busy || !q.value.trim(); }); q.addEventListener("keydown", function (e) { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); ask(q.value); } }); $("form").addEventListener("submit", function (e) { e.preventDefault(); ask(q.value); }); $("new").onclick = fresh; $("menu").onclick = function () { $("side").classList.toggle("open"); }; $("tries").addEventListener("click", function (e) { var b = e.target.closest("button"); if (!b) return; if (b.dataset.fill) { q.value = b.dataset.q; grow(); send.disabled = false; q.focus(); } else ask(b.dataset.q); }); // the satellites tab function tab(which) { $("view-chat").hidden = which !== "chat"; $("view-sat").hidden = which !== "sat"; $("view-mac").hidden = which !== "mac"; $("tab-chat").setAttribute("aria-selected", which === "chat"); $("tab-sat").setAttribute("aria-selected", which === "sat"); $("tab-mac").setAttribute("aria-selected", which === "mac"); if (which === "sat") sats(); if (which === "mac" && !$("macframe").src) $("macframe").src = "/static/machines.html"; } $("tab-chat").onclick = function () { tab("chat"); }; $("tab-sat").onclick = function () { tab("sat"); }; $("tab-mac").onclick = function () { tab("mac"); }; var satsLoaded = false; function sats() { if (satsLoaded) return; api("/api/orbiters").then(function (r) { satsLoaded = true; var box = $("sats"); box.innerHTML = ""; (r.items || []).forEach(function (c) { var d = document.createElement("article"); d.className = "sat"; var ready = !c.needs || !c.needs.length; d.innerHTML = "<h2>" + esc(c.name) + "</h2><p>" + esc(c.good_for || "") + "</p>" + '<div class="row"><span class="st ' + (ready ? "answered" : "offered") + '"><i></i>' + (ready ? "ready on this computer" : "needs " + esc(c.needs.join(", "))) + "</span>" + "<code>oracle7.py " + esc(c.name) + "</code></div>" + '<div class="row"><button' + (ready ? "" : " disabled") + ">Run its exam</button></div><div class=\"res\" hidden></div>"; var b = d.querySelector("button"), res = d.querySelector(".res"); b.onclick = function () { b.disabled = true; b.textContent = "Running\u2026"; res.hidden = false; res.textContent = "running its exam from the pack"; api("/api/orbiters/exam", { name: c.name }).then(function (x) { res.textContent = (x.status || "") + (x.summary ? "\n" + x.summary : "") + (x.detail ? "\n" + x.detail : "") + (x.error ? "\n" + x.error : ""); }).catch(function (e) { res.textContent = "did not answer: " + e.message; }) .then(function () { b.disabled = false; b.textContent = "Run its exam"; }); }; box.appendChild(d); }); if (!(r.items || []).length) box.textContent = "No orbiters were found in this install."; }).catch(function () { $("sats").textContent = "The workbench did not answer."; }); } api("/api/state").then(function (s) { var tip = s && (s.tip || s.head || (s.engine && s.engine.tip)); if (tip) $("ver").textContent = String(tip).replace("oracle_release_runtime_", "") + " · no language model"; }).catch(function () {}); convs();})();</script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Machines</title><style>:root{ --page:#e9ebef; --canvas:#ffffff; --ink:#1f2328; --ink2:#57606a; --ink3:#8c959f; --line:#d0d7de; --home-bg:#eef7ea; --home-bd:#7fb36a; --cloud-bg:#fff6ea; --cloud-bd:#e8a752; --card-peach:#fdebd3; --card-peach-bd:#e8a752; --card-blue:#dbe9fb; --card-blue-bd:#7aa7e0; --card-white:#fff; --ok:#1a7f37; --ok-bg:#dafbe1; --warn:#9a6700; --warn-bg:#fff4c2; --bad:#cf222e; --bad-bg:#ffe1e0; --info:#0969da; --info-bg:#ddf4ff; --bar-bg:#eaeef2; --link:#24292f; --link-ssh:#2f6fdb; --link-bak:#8250df; --chip-yellow:#ffe58f; --chip-pink:#f7c6f0; --chip-cyan:#bdeefa;}@media (prefers-color-scheme: dark){ :root:not([data-theme="light"]){ --page:#0d1117; --canvas:#161b22; --ink:#e6edf3; --ink2:#9ea7b3; --ink3:#6e7781; --line:#30363d; --home-bg:#132116; --home-bd:#3f7a39; --cloud-bg:#241a0e; --cloud-bd:#a8742f; --card-peach:#2d2013; --card-peach-bd:#a8742f; --card-blue:#122236; --card-blue-bd:#3b6aa8; --card-white:#1c2128; --ok:#3fb950; --ok-bg:#12261a; --warn:#d29922; --warn-bg:#2b2111; --bad:#f85149; --bad-bg:#2d1415; --info:#58a6ff; --info-bg:#0f2238; --bar-bg:#262c34; --link:#c9d1d9; --link-ssh:#58a6ff; --link-bak:#a371f7; --chip-yellow:#5c4a0b; --chip-pink:#5a2652; --chip-cyan:#0f4555; }}:root[data-theme="dark"]{ --page:#0d1117; --canvas:#161b22; --ink:#e6edf3; --ink2:#9ea7b3; --ink3:#6e7781; --line:#30363d; --home-bg:#132116; --home-bd:#3f7a39; --cloud-bg:#241a0e; --cloud-bd:#a8742f; --card-peach:#2d2013; --card-peach-bd:#a8742f; --card-blue:#122236; --card-blue-bd:#3b6aa8; --card-white:#1c2128; --ok:#3fb950; --ok-bg:#12261a; --warn:#d29922; --warn-bg:#2b2111; --bad:#f85149; --bad-bg:#2d1415; --info:#58a6ff; --info-bg:#0f2238; --bar-bg:#262c34; --link:#c9d1d9; --link-ssh:#58a6ff; --link-bak:#a371f7; --chip-yellow:#5c4a0b; --chip-pink:#5a2652; --chip-cyan:#0f4555;}*{box-sizing:border-box}body{margin:0;background:var(--page);color:var(--ink);font:13px/1.35 "Segoe UI",system-ui,-apple-system,sans-serif}.canvas{position:relative;overflow:hidden;max-width:1500px;margin:16px auto;background:var(--canvas);border-radius:14px;padding:20px 22px 24px;box-shadow:0 1px 3px #0002}header{display:flex;align-items:flex-start;gap:16px;flex-wrap:wrap}h1{font-size:22px;margin:0}.sub{color:var(--ink2);font-size:12px;margin-top:2px}.tools{margin-left:auto;display:flex;gap:8px;align-items:center;flex-wrap:wrap}.tools input{border:1px solid var(--line);background:var(--canvas);color:var(--ink);border-radius:6px;padding:6px 9px;width:220px;font:inherit}.tools button{border:1px solid var(--line);background:var(--canvas);color:var(--ink);border-radius:6px;padding:6px 10px;cursor:pointer;font:inherit}.stamp{color:var(--ink2);font-size:12px}.stamp.stale{color:var(--bad);font-weight:600}
#links{position:absolute;inset:0;pointer-events:none;overflow:visible;z-index:0}.layer{position:relative;z-index:1}
.top{display:flex;justify-content:center;margin:6px 0 18px}.cloud{position:relative;padding:14px 46px;font-weight:600;font-size:14px;color:#1f2328}.cloud svg{position:absolute;inset:-6px -10px;width:calc(100% + 20px);height:calc(100% + 12px);z-index:-1}.cloud .ip{display:block;font-weight:400;font-size:11px;color:#444c56;text-align:center}
.grid{display:grid;grid-template-columns:minmax(330px,0.9fr) 2fr;gap:22px;align-items:start}@media (max-width:1050px){.grid{grid-template-columns:1fr}}
.region{border:2px dashed;border-radius:16px;padding:14px;position:relative}.region.home{background:var(--home-bg);border-color:var(--home-bd)}.region.cloudr{background:var(--cloud-bg);border-color:var(--cloud-bd)}.rhead{display:flex;align-items:center;gap:10px;margin-bottom:12px}.rhead .title{font-size:16px;font-weight:700}.rhead .meta{font-size:11.5px;color:var(--info)}.rhead .meta.g{color:var(--ok)}.badges{margin-left:auto;display:flex;gap:6px}.badge{display:flex;flex-direction:column;align-items:center;font-size:10px;color:var(--ink2);gap:2px;text-align:center}.badge i{display:grid;place-items:center;width:28px;height:28px;border-radius:6px;border:1px solid #0003;font-style:normal;font-size:13px}
.card{border:1.5px solid var(--card-peach-bd);background:var(--card-peach);border-radius:10px;padding:10px 12px;margin-bottom:12px;position:relative}.card.blue{background:var(--card-blue);border-color:var(--card-blue-bd)}.card.white{background:var(--card-white);border-color:var(--line)}.card.dashed{border-style:dashed}.card.click{cursor:pointer;transition:box-shadow .15s,transform .15s}.card.click:hover{box-shadow:0 3px 12px #0002;transform:translateY(-1px)}.card.down{border-color:var(--bad);background:var(--bad-bg)}.chead{display:flex;gap:10px;align-items:flex-start}.icon{flex:none;width:34px;height:34px;border-radius:8px;display:grid;place-items:center;font-weight:700;color:#fff;font-size:14px}.cname{font-weight:700;font-size:13.5px}.cspec{color:var(--info);font-size:11.5px}.crole{color:var(--ok);font-size:11.5px}.edge{position:absolute;right:-11px;top:10px;display:flex;flex-direction:column;gap:5px}.edge i{width:22px;height:22px;border-radius:5px;border:1px solid #0004;display:grid;place-items:center;font-style:normal;font-size:11px;background:var(--chip-yellow)}
.meters{display:grid;grid-template-columns:auto 1fr auto;gap:3px 8px;align-items:center;margin:9px 0 4px;font-size:11px;color:var(--ink2)}.bar{height:7px;border-radius:4px;background:var(--bar-bg);overflow:hidden}.bar b{display:block;height:100%;border-radius:4px;background:var(--ok)}.bar b.warn{background:#d4a72c}.bar b.bad{background:var(--bad)}.meters .v{font-variant-numeric:tabular-nums;text-align:right;color:var(--ink)}.spark{width:100%;height:26px;display:block;margin-top:4px}
.chips{display:flex;flex-wrap:wrap;gap:5px;margin-top:6px}.chip{font-size:10.5px;padding:1px 7px;border-radius:10px;border:1px solid transparent;white-space:nowrap}.chip.ok{background:var(--ok-bg);color:var(--ok);border-color:#1a7f3733}.chip.warn{background:var(--warn-bg);color:var(--warn);border-color:#9a670033}.chip.bad{background:var(--bad-bg);color:var(--bad);border-color:#cf222e33}.chip.info{background:var(--info-bg);color:var(--info);border-color:#0969da33}
.svcs{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:6px 12px;margin-top:9px}.svc{display:flex;gap:7px;align-items:center;min-width:0}.svc .t{flex:none;width:22px;height:22px;border-radius:5px;display:grid;place-items:center;font-size:10px;font-weight:700;color:#fff}.svc .n{font-weight:600;font-size:11.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.svc .p{font-size:10.5px;color:var(--ok)}.svc.pub .p::after{content:" · public";color:var(--bad)}.more{font-size:11px;color:var(--info);margin-top:6px}
.pubbox{border:1.5px solid var(--home-bd);background:var(--home-bg);border-radius:9px;padding:8px 10px;margin-top:9px}.pubbox .h{display:flex;gap:8px;align-items:center;font-size:11.5px;font-weight:600}.pubbox .h .s{font-weight:400;color:var(--ink2)}.dots{display:flex;flex-wrap:wrap;gap:3px;margin-top:6px}.dot{width:10px;height:10px;border-radius:3px;background:var(--ok)}.dot.r{background:#d4a72c}.dot.x{background:var(--bad)}
.vps{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.vps .card{margin:0}@media (max-width:760px){.vps{grid-template-columns:1fr}.svcs{grid-template-columns:1fr}}
.folders{margin-top:8px;display:flex;flex-direction:column;gap:4px}.folder{display:grid;grid-template-columns:22px 1fr auto;gap:7px;align-items:center;font-size:11.5px}.folder .t{width:22px;height:22px;border-radius:5px;display:grid;place-items:center;font-size:10px;font-weight:700;color:#fff}.folder small{color:var(--ink2)}.folder .sz{font-variant-numeric:tabular-nums;color:var(--ink2)}
.bottom{display:grid;grid-template-columns:1.3fr 1fr 1fr;gap:16px;margin-top:20px}@media (max-width:1050px){.bottom{grid-template-columns:1fr}}.panel{border:1.5px solid var(--line);border-radius:10px;padding:12px 14px;background:var(--card-white)}.panel h3{margin:0 0 8px;font-size:13.5px}.alert{display:flex;gap:8px;align-items:baseline;font-size:12px;padding:3px 0;border-bottom:1px dashed var(--line)}.alert:last-child{border-bottom:0}.alert .who{font-weight:600;white-space:nowrap}.legend div{display:flex;gap:8px;align-items:center;font-size:11.5px;margin:3px 0;color:var(--ink2)}.legend svg{flex:none}.sw{width:16px;height:12px;border-radius:3px;border:1.5px solid;flex:none}
.hidden{display:none!important}mark{background:#fff8c5;color:inherit;border-radius:2px}
/* drawer */#drawer{position:fixed;top:0;right:0;height:100%;width:min(560px,100%);background:var(--canvas);box-shadow:-6px 0 24px #0003;transform:translateX(105%);transition:transform .2s;z-index:10;display:flex;flex-direction:column}#drawer.open{transform:none}#drawer .dh{padding:14px 16px;border-bottom:1px solid var(--line);display:flex;gap:10px;align-items:center}#drawer .dh button{margin-left:auto;border:1px solid var(--line);background:none;color:var(--ink);border-radius:6px;padding:4px 10px;cursor:pointer}#drawer .db{overflow:auto;padding:12px 16px 30px}#drawer h4{margin:16px 0 6px;font-size:12.5px;text-transform:uppercase;letter-spacing:.04em;color:var(--ink2)}table{width:100%;border-collapse:collapse;font-size:12px}td,th{padding:4px 6px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}th{color:var(--ink2);font-weight:600}td.num{text-align:right;font-variant-numeric:tabular-nums}td a{color:var(--info);text-decoration:none}.code{font-weight:700;font-variant-numeric:tabular-nums}.code.ok{color:var(--ok)}.code.warn{color:var(--warn)}.code.bad{color:var(--bad)}#scrim{position:fixed;inset:0;background:#0003;z-index:9;display:none}#scrim.open{display:block}.empty{color:var(--ink3);font-size:12px}</style></head><body><div class="canvas" id="canvas"> <svg id="links"></svg> <div class="layer"> <header> <div> <h1>Machines</h1> <div class="sub">this computer and the machines it reaches over ssh · read-only</div> </div> <div class="tools"> <span class="stamp" id="stamp">loading…</span> <input id="q" placeholder="Find a site, service or port…" autocomplete="off"> <button id="collect" title="Read every machine now">Read now</button> <button id="theme" title="Toggle theme">◐</button> </div> </header>
<div class="top"> <div class="cloud" id="internet"> <svg viewBox="0 0 200 70" preserveAspectRatio="none"><path d="M40 62 C10 62 6 36 30 33 C26 12 58 6 72 20 C82 2 120 2 128 20 C142 8 176 14 170 36 C196 38 192 62 166 62 Z" fill="#cfe3fb" stroke="#7aa7e0" stroke-width="1.5"/></svg> Internet </div> </div>
<div class="grid"> <div> <div class="region home" id="home"> <div class="rhead"> <div class="icon" style="background:#3b7d2f">⌂</div> <div> <div class="title">Home</div> <div class="meta g">the computer Oracle7 runs on · ssh out to every listed machine</div> </div> </div> <div id="laptop"></div> <div id="drive"></div> </div> </div> <div> <div class="region cloudr" id="cloudr"> <div class="rhead"> <div class="icon" style="background:#0969da">S</div> <div> <div class="title">Servers</div> <div class="meta" id="srvmeta">key-only ssh · read-only probe</div> </div> <div class="badges" id="cloudBadges"></div> </div> <div class="vps" id="vps"></div> </div> </div> </div>
<div class="bottom"> <div class="panel"><h3>Watch list</h3><div id="alerts"></div></div> <div class="panel"><h3>Machines on this map</h3><div id="flows" style="font-size:12px;color:var(--ink2)"></div></div> <div class="panel legend"><h3>Legend</h3> <div><svg width="34" height="8"><line x1="0" y1="4" x2="34" y2="4" stroke="var(--link)" stroke-width="1.6"/></svg> network link</div> <div><svg width="34" height="8"><line x1="0" y1="4" x2="34" y2="4" stroke="var(--link-ssh)" stroke-width="1.6" stroke-dasharray="5 4"/></svg> SSH admin (laptop → servers)</div> <div><svg width="34" height="8"><line x1="0" y1="4" x2="34" y2="4" stroke="var(--link-bak)" stroke-width="1.6" stroke-dasharray="2 3"/></svg> offload / backup to the drive</div> <div><span class="sw" style="background:var(--card-peach);border-color:var(--card-peach-bd)"></span> server or machine · dashed = unreachable</div> <div><span class="sw" style="background:var(--home-bg);border-color:var(--home-bd)"></span> public sites (nginx vhosts, checked every run)</div> <div><span class="dot"></span><span class="dot r"></span><span class="dot x"></span> 2xx-3xx · 4xx · down/5xx</div> <div><span class="chip info">:8050</span> listening port · <span class="chip warn">public</span> bound to 0.0.0.0</div> <div>Click any server for every site, service, port, cert and failed unit.</div> </div> </div> </div></div>
<div id="scrim"></div><aside id="drawer"><div class="dh" id="dh"></div><div class="db" id="db"></div></aside>
<script>let META = {};const $ = s => document.querySelector(s);const esc = s => String(s ?? "").replace(/[&<>"]/g, c => ({"&":"&","<":"<",">":">",'"':"""}[c]));const gb = b => b >= 1e12 ? (b/1e12).toFixed(2)+" TB" : b >= 1e9 ? (b/1e9).toFixed(b>=1e11?0:1)+" GB" : (b/1e6).toFixed(0)+" MB";const pct = (u,t) => t ? 100*u/t : 0;const lvl = (p, w=80, b=90) => p >= b ? "bad" : p >= w ? "warn" : "";const dur = s => { const d=Math.floor(s/86400), h=Math.floor(s%86400/3600); return d ? `${d}d ${h}h` : `${h}h ${Math.floor(s%3600/60)}m`; };const ago = t => { const s = Date.now()/1000 - t; return s < 90 ? "just now" : s < 5400 ? Math.round(s/60)+" min ago" : Math.round(s/3600)+" h ago"; };
const PALETTE = ["#0969da","#1a7f37","#8250df","#bf3989","#e95420","#9a6700","#0a7ea4","#cf222e","#57606a","#6639ba"];function tileColor(name){ if (/nginx/.test(name)) return "#009639"; if (/postgres|pg/.test(name)) return "#336791"; if (/redis/.test(name)) return "#d82c20"; if (/docker/.test(name)) return "#1d63ed"; if (/fail2ban|foldwall|guard/.test(name)) return "#24292f"; let h=0; for (const c of name) h=(h*31+c.charCodeAt(0))>>>0; return PALETTE[h % PALETTE.length];}const tileText = n => n.replace(/^[a-z0-9]{1,6}-/i,"").slice(0,2).toUpperCase();
function meter(label, used, total, extra){ const p = pct(used,total); return `<span>${label}</span><div class="bar"><b class="${lvl(p)}" style="width:${Math.min(100,p).toFixed(1)}%"></b></div><span class="v">${extra ?? `${p.toFixed(0)}% · ${gb(total-used)} free`}</span>`;}function spark(points){ if (!points || points.length < 2) return `<div class="empty" style="font-size:10.5px;margin-top:4px">trend appears after a few runs</div>`; const W=300,H=26, t0=points[0][0], t1=points.at(-1)[0] || t0+1; const line = (i,color,dash="") => `<polyline fill="none" stroke="${color}" stroke-width="1.4" ${dash} points="${points.map(p=>`${((p[0]-t0)/(t1-t0||1)*W).toFixed(1)},${(H-2-Math.min(100,p[i])/100*(H-4)).toFixed(1)}`).join(" ")}"/>`; return `<svg class="spark" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" title="24 h: disk / memory / load">${line(1,"#cf222e")}${line(2,"#0969da")}${line(3,"#8c959f",'stroke-dasharray="3 2"')}</svg>`;}const codeClass = c => c === null ? "" : (c >= 200 && c < 400) ? "ok" : (c >= 400 && c < 500) ? "warn" : "bad";const dotClass = c => ({ok:"",warn:"r",bad:"x"})[codeClass(c)] ?? "";
let DATA = null, FILTER = "";
function renderLaptop(L){ const h = DATA.history.laptop; $("#laptop").innerHTML = ` <div class="card click" data-open="laptop" id="n-laptop"> <div class="edge"><i style="background:var(--chip-pink)" title="USB drive attached">⇵</i></div> <div class="chead"> <div class="icon" style="background:#0078d4">⊞</div> <div><div class="cname">Laptop · ${esc(L.model)}</div> <div class="cspec">${esc(L.cpu_model.replace(" with Radeon Graphics",""))} · ${L.cpus} threads · ${gb(L.mem.total)} RAM</div> <div class="crole">${esc(L.os)} · ${esc(L.hostname)} · workstation</div></div> </div> <div class="meters"> ${meter("C: SSD", L.disk.used, L.disk.total)} ${meter("RAM", L.mem.used, L.mem.total, `${pct(L.mem.used,L.mem.total).toFixed(0)}% · ${gb(L.mem.total-L.mem.used)} free`)} ${meter("CPU", L.cpu_pct, 100, `${L.cpu_pct}%`)} </div> ${spark(h)} <div class="chips"> <span class="chip info">up ${dur(L.uptime_s)}</span> ${L.battery!=null ? `<span class="chip ${L.battery<20&&!L.on_power?"bad":"ok"}">battery ${L.battery}%${L.on_power?" · plugged in":""}</span>`:""} <span class="chip info">${esc(L.disk_name||"NVMe SSD")}</span> </div> </div>`;}
function renderDrive(D){ if (!D.connected){ $("#drive").innerHTML = `<div class="card dashed down" id="n-drive"><div class="chead"><div class="icon" style="background:#57606a">⛁</div><div><div class="cname">Other drive</div><div class="crole">none attached</div></div></div></div>`; return; } const fs = [...D.folders].sort((a,b)=>b.bytes-a.bytes); const kind = n => /^Box/i.test(n) ? ["#e95420","offload"] : /Cold/i.test(n) ? ["#0969da","cold storage"] : /Archive/i.test(n) ? ["#8250df","archive"] : /Film/i.test(n) ? ["#bf3989","media"] : ["#57606a","misc"]; $("#drive").innerHTML = ` <div class="card click" data-open="drive" id="n-drive"> <div class="chead"> <div class="icon" style="background:#57606a">⛁</div> <div><div class="cname">Drive ${esc(D.label)}</div> <div class="cspec">${esc(D.model||"USB")} · ${gb(D.total)} · ${esc(D.fs)} · USB</div> </div> </div> <div class="meters">${meter(esc(D.label), D.used, D.total)}</div> ${spark((DATA.history.drive||[]).map(p=>[p[0],p[1],null,null]).map(p=>[p[0],p[1],0,0]))} <div class="folders">${fs.map(f=>{const [c,k]=kind(f.name);return `<div class="folder" data-s="${esc(f.name.toLowerCase())}"><span class="t" style="background:${c}">${k[0].toUpperCase()}</span><div>${esc(f.name)} <small>· ${k} · ${f.files.toLocaleString()} files</small></div><span class="sz">${gb(f.bytes)}</span></div>`}).join("")}</div> </div>`;}
function siteDots(sites){ return sites.filter(s=>!s.domain.startsWith("*.")).map(s=>`<span class="dot ${dotClass(s.code)}" title="${esc(s.domain)} → ${s.code||"no answer"}"></span>`).join("");}
function renderBox(id, b){ const m = META[id]; m.glyph = m.glyph || String(m.name||id).trim().split(/\s+/).pop().slice(0,1).toUpperCase(); if (b.unreachable){ return `<div class="card dashed down click" data-open="${id}" id="n-${id}"><div class="chead"><div class="icon" style="background:${m.color}">${m.glyph}</div><div><div class="cname">${esc(m.name)} · ${esc(m.ssh)}</div><div class="crole" style="color:var(--bad)">unreachable over SSH at ${new Date(b.probed_at*1000).toLocaleTimeString()}</div><div class="cspec">${esc(m.role)}</div></div></div></div>`; } const sites = b.sites||[], up = sites.filter(s=>codeClass(s.code)==="ok").length, real = sites.filter(s=>!s.domain.startsWith("*.")).length; const svcs = b.services.filter(s=>!/^(nginx|fail2ban|foldwall)$/.test(s.name)); const top = [...svcs].sort((a,b)=>(b.ports.length>0)-(a.ports.length>0)).slice(0,10); const swapP = pct(b.mem.swap_used,b.mem.swap_total); const loadP = 100*b.load[0]/b.cpus; return ` <div class="card click" data-open="${id}" id="n-${id}"> <div class="edge"> <i title="nginx reverse proxy + Let's Encrypt" style="background:var(--chip-yellow)">⇄</i> ${b.services.some(s=>s.name==="foldwall")?`<i title="foldwall + fail2ban" style="background:var(--chip-cyan)">⛨</i>`:""} </div> <div class="chead"> <div class="icon" style="background:${m.color}">${m.glyph}</div> <div><div class="cname">${m.name} · ${esc(b.cpu_model.replace(" Processor",""))}</div> <div class="cspec">${b.cpus} vCPU · ${gb(b.mem.total)} RAM · ${gb(b.disk.total)} disk · ${esc(b.os)}</div> <div class="crole">${esc(m.role)}</div></div> </div> <div class="meters"> ${meter("disk", b.disk.used, b.disk.total)} ${meter("RAM", b.mem.used, b.mem.total, `${pct(b.mem.used,b.mem.total).toFixed(0)}% · swap ${swapP.toFixed(0)}%`)} ${meter("load", Math.min(loadP,100), 100, `${b.load.map(x=>x.toFixed(2)).join(" ")}`)} </div> ${spark(DATA.history[id])} ${real ? `<div class="pubbox"><div class="h">🌐 Public sites <span class="s">${up}/${real} answering · ${b.certs.length} certs</span></div><div class="dots">${siteDots(sites)}</div></div>` : ""} <div class="svcs">${top.map(s=>`<div class="svc ${s.public?"pub":""}" data-s="${esc((s.name+" "+s.ports.join(" ")).toLowerCase())}"><span class="t" style="background:${tileColor(s.name)}">${esc(tileText(s.name))}</span><div style="min-width:0"><div class="n">${esc(s.name)}</div><div class="p">${s.ports.length?":"+s.ports.join(" :"):"worker"}</div></div></div>`).join("")}</div> ${svcs.length>top.length?`<div class="more">+ ${svcs.length-top.length} more services · ${b.service_count} units running</div>`:""} <div class="chips"> <span class="chip info">${esc(m.ssh)}</span> <span class="chip info">up ${dur(b.uptime_s)}</span> ${b.reboot_required?`<span class="chip warn">reboot pending</span>`:""} ${b.failed.length?`<span class="chip bad">${b.failed.length} failed unit${b.failed.length>1?"s":""}</span>`:`<span class="chip ok">no failed units</span>`} ${b.containers.length?`<span class="chip info">${b.containers.length} containers</span>`:""} </div> </div>`;}
function alerts(){ const out = []; const add = (sev, who, msg) => out.push({sev, who, msg}); const age = Date.now()/1000 - DATA.collected_at; if (age > 1800) add(2, "Collector", `last run ${ago(DATA.collected_at)} — scheduled task may have stopped`); for (const [id,b] of Object.entries(DATA.boxes)){ const n = META[id].name; if (b.unreachable){ add(3, n, "unreachable over SSH"); continue; } const dp = pct(b.disk.used,b.disk.total); if (dp >= 90) add(3, n, `disk ${dp.toFixed(0)}% full · ${gb(b.disk.free)} left`); else if (dp >= 80) add(2, n, `disk ${dp.toFixed(0)}% · ${gb(b.disk.free)} left`); const sp = pct(b.mem.swap_used,b.mem.swap_total); if (sp >= 80) add(2, n, `swap ${sp.toFixed(0)}% used`); if (b.load[1]/b.cpus > 1.5) add(2, n, `load ${b.load[1].toFixed(1)} on ${b.cpus} vCPU`); if (b.failed.length) add(2, n, `${b.failed.length} failed unit${b.failed.length>1?"s":""}: ${b.failed.map(f=>f.replace(".service","")).join(", ")}`); for (const s of b.sites||[]) if (s.code !== null && (s.code === 0 || s.code >= 500)) add(3, n, `${s.domain} ${s.code? "returns "+s.code : "not answering"}`); for (const c of b.certs||[]) if (c.days_left !== null && c.days_left < 21) add(c.days_left < 7 ? 3 : 2, n, `cert ${c.name} ${c.days_left < 0 ? "EXPIRED "+(-c.days_left)+"d ago" : "expires in "+c.days_left+"d"}`); if (b.reboot_required) add(1, n, "reboot pending (kernel/security updates)"); } const L = DATA.laptop; if (L.disk.free < 25e9) add(2, "Laptop", `C: ${gb(L.disk.free)} free`); if (pct(L.mem.used,L.mem.total) > 90) add(1, "Laptop", `RAM ${pct(L.mem.used,L.mem.total).toFixed(0)}% used`); if (!DATA.drive.connected) {} else if (DATA.drive.free < 50e9) add(2, "Drive", `${esc(DATA.drive.label)} ${gb(DATA.drive.free)} free`); out.sort((a,b)=>b.sev-a.sev); const tag = {3:["bad","crit"],2:["warn","warn"],1:["info","info"]}; $("#alerts").innerHTML = out.length ? out.map(a=>`<div class="alert"><span class="chip ${tag[a.sev][0]}">${tag[a.sev][1]}</span><span class="who">${esc(a.who)}</span><span>${esc(a.msg)}</span></div>`).join("") : `<div class="empty">All clear.</div>`; const crit = out.filter(a=>a.sev===3).length; document.title = crit ? `(${crit}) Machines` : "Machines";}
function renderFlows(){ const rows = Object.values(META).map(m=>`<tr><td><b>${esc(m.name)}</b><br><small>${esc(m.role||"")}</small></td><td><code>ssh ${esc(m.ssh)}</code></td><td><button data-rm="${esc(m.id)}" title="Take it off the map">×</button></td></tr>`).join(""); $("#flows").innerHTML = ` <div>Each machine is read by <code>ssh</code> with your own keys (read-only: <code>/proc</code>, services, ports, sites). The list is kept on this computer only.</div> <table style="margin-top:8px;width:100%">${rows || "<tr><td>No machines listed yet.</td></tr>"}</table> <form id="addm" style="margin-top:8px;display:grid;grid-template-columns:1fr 1fr;gap:6px"> <input name="name" placeholder="Name (Web server)" required> <input name="ssh" placeholder="ssh alias or user@host" required> <input name="role" placeholder="What it does (optional)" style="grid-column:1/3"> <button style="grid-column:1/3">Add to the map</button> </form>`; $("#addm").onsubmit = e=>{ e.preventDefault(); const f = new FormData(e.target); const name = String(f.get("name")).trim(), id = name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,24) || "m"+Date.now()%1000; saveList([...Object.values(META), {id, name, ssh:String(f.get("ssh")).trim(), role:String(f.get("role")||"")}]); }; document.querySelectorAll("[data-rm]").forEach(b=>b.onclick = ()=>saveList(Object.values(META).filter(m=>m.id!==b.dataset.rm)));}function saveList(items){ fetch("/api/machines/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machines:items})}) .then(r=>r.json()).then(x=>{ if (x.error){ alert(x.error); return; } loadData(); });}
function renderBadges(){ const bs = Object.values(DATA.boxes).filter(b=>!b.unreachable); const sites = bs.reduce((a,b)=>a+(b.sites||[]).filter(s=>!s.domain.startsWith("*.")).length,0); const svc = bs.reduce((a,b)=>a+b.services.length,0); const disk = bs.reduce((a,b)=>a+b.disk.total,0); $("#cloudBadges").innerHTML = [ ["⇄","var(--chip-yellow)",`nginx`], ["🌐","var(--home-bg)",`${sites} sites`], ["⚙","var(--chip-cyan)",`${svc} services`], ["⛁","var(--chip-pink)",gb(disk)], ].map(([i,c,l])=>`<div class="badge"><i style="background:${c}">${i}</i>${l}</div>`).join("");}
function render(){ if (!window.HOMELAB) { $("#stamp").textContent = "nothing read yet — press Read now"; return; } DATA = window.HOMELAB; renderLaptop(DATA.laptop); renderDrive(DATA.drive); $("#vps").innerHTML = Object.keys(META).map(id=>renderBox(id, DATA.boxes[id] || {unreachable:true, probed_at:DATA.collected_at})).join(""); renderBadges(); alerts(); renderFlows(); applyFilter(); const st = $("#stamp"); st.textContent = `collected ${ago(DATA.collected_at)} · ${new Date(DATA.collected_at*1000).toLocaleTimeString()}`; st.classList.toggle("stale", Date.now()/1000 - DATA.collected_at > 1800); requestAnimationFrame(drawLinks); if ($("#drawer").classList.contains("open")) openDrawer($("#drawer").dataset.id);}
/* ---------- links ---------- */function rel(el){ const c = $("#canvas").getBoundingClientRect(), r = el.getBoundingClientRect(); return {x:r.left-c.left, y:r.top-c.top, w:r.width, h:r.height, cx:r.left-c.left+r.width/2, cy:r.top-c.top+r.height/2};}function drawLinks(){ const svg = $("#links"), cv = $("#canvas"); svg.setAttribute("width", cv.scrollWidth); svg.setAttribute("height", cv.scrollHeight); const I = rel($("#internet")), H = rel($("#home")), C = rel($("#cloudr")); const stacked = C.y > H.y + H.h - 5; const path = (d, cls, label, lx, ly) => `<path d="${d}" fill="none" ${cls}/>${label?`<text x="${lx}" y="${ly}" font-size="10.5" fill="var(--ink2)" text-anchor="middle" style="paint-order:stroke;stroke:var(--canvas);stroke-width:4px">${label}</text>`:""}`; const solid = `stroke="var(--link)" stroke-width="1.4"`; const ssh = `stroke="var(--link-ssh)" stroke-width="1.4" stroke-dasharray="5 4"`; const bak = `stroke="var(--link-bak)" stroke-width="1.6" stroke-dasharray="2 3"`; let s = ""; // internet -> home, internet -> cloud s += path(`M${I.x} ${I.cy} H${H.cx} V${H.y}`, solid, "fibre / ISP", (I.x+H.cx)/2, I.cy-4); if (!stacked) s += path(`M${I.x+I.w} ${I.cy} H${C.cx} V${C.y}`, solid, "servers", (I.x+I.w+C.cx)/2, I.cy-4); const lap = $("#n-laptop"), drv = $("#n-drive"); if (lap && drv){ const a = rel(lap), d = rel(drv); s += path(`M${a.x+a.w+11} ${a.y+21} H${a.x+a.w+24} V${d.y+18} H${d.x+d.w}`, `stroke="var(--link)" stroke-width="1.4"`, "", 0, 0); s += `<text x="${a.x+a.w+28}" y="${(a.y+21+d.y+18)/2}" font-size="10.5" fill="var(--ink2)" style="paint-order:stroke;stroke:var(--home-bg);stroke-width:4px">USB</text>`; if (!stacked){ // ssh fan-out: laptop -> each box (into the region edge), offloads: each box -> drive const ids = Object.keys(META).filter(id=>document.getElementById("n-"+id)); const xBus = H.x + H.w + 11; ids.forEach((id,i)=>{ const b = rel(document.getElementById("n-"+id)); const y = b.y + 22; const targetX = b.x; s += path(`M${a.x+a.w} ${a.y+a.h-14} H${xBus} V${y} H${targetX}`, ssh, "", 0, 0); }); s += `<text x="${xBus+4}" y="${a.y+a.h-18}" font-size="10.5" fill="var(--link-ssh)" style="paint-order:stroke;stroke:var(--canvas);stroke-width:4px">SSH</text>`; const xb = H.x - 11; const offs = false; if (offs){ s += path(`M${C.x+20} ${C.y+C.h} V${C.y+C.h+0} M${C.x+20} ${C.y+C.h} V${Math.max(C.y+C.h, d.y+d.h)+14} H${xb} V${d.y+d.h-16} H${d.x}`, bak, "", 0, 0); s += `<text x="${(C.x+20+xb)/2}" y="${Math.max(C.y+C.h, d.y+d.h)+10}" font-size="10.5" fill="var(--link-bak)" text-anchor="middle" style="paint-order:stroke;stroke:var(--canvas);stroke-width:4px">offloads (sha-verified tarballs)</text>`; } } } svg.innerHTML = s;}
/* ---------- drawer ---------- */function openDrawer(id){ const d = $("#drawer"); d.dataset.id = id; let head = "", body = ""; if (id === "laptop"){ const L = DATA.laptop; head = `<div class="icon" style="background:#0078d4">⊞</div><div><div class="cname">${esc(L.model)}</div><div class="cspec">${esc(L.hostname)} · ${esc(L.os)}</div></div>`; body = `<table> <tr><th>CPU</th><td>${esc(L.cpu_model)} · ${L.cpus} threads · ${L.cpu_pct}% now</td></tr> <tr><th>Memory</th><td>${gb(L.mem.used)} of ${gb(L.mem.total)}</td></tr> <tr><th>C: SSD</th><td>${esc(L.disk_name)} · ${gb(L.disk.used)} used · ${gb(L.disk.free)} free</td></tr> <tr><th>Uptime</th><td>${dur(L.uptime_s)}</td></tr> <tr><th>Battery</th><td>${L.battery ?? "—"}% ${L.on_power?"· on power":""}</td></tr></table> <h4>Reaches</h4><table>${Object.entries(META).map(([k,m])=>`<tr><td>${m.name}</td><td>ssh ${esc(m.ssh)}</td></tr>`).join("")}</table>`; } else if (id === "drive"){ const D = DATA.drive; head = `<div class="icon" style="background:#57606a">⛁</div><div><div class="cname">D: ${esc(D.label)}</div><div class="cspec">${esc(D.model)} · ${esc(D.fs)} · ${gb(D.total)}</div></div>`; body = `<table><tr><th>Folder</th><th>Files</th><th class="num">Size</th><th>Modified</th></tr>${[...D.folders].sort((a,b)=>b.bytes-a.bytes).map(f=>`<tr><td>${esc(f.name)}</td><td class="num">${f.files.toLocaleString()}</td><td class="num">${gb(f.bytes)}</td><td>${f.modified}</td></tr>`).join("")}</table>`; } else { const b = DATA.boxes[id], m = META[id]; head = `<div class="icon" style="background:${m.color}">${m.glyph}</div><div><div class="cname">${esc(m.name)} · ${esc(m.ssh)}</div><div class="cspec">${esc(b.hostname||"")} · ${esc(b.os||"")}</div><div class="crole">${esc(m.role)}</div></div>`; if (b.unreachable){ body = `<p>Unreachable over SSH at last run.</p>`; } else { const sites = b.sites||[]; body = ` <h4>Sites (${sites.length})</h4> <table><tr><th>Domain</th><th>→ port</th><th class="num">HTTP</th></tr>${sites.map(s=>`<tr data-s="${esc(s.domain.toLowerCase()+" "+(s.port||""))}"><td>${s.domain.startsWith("*.")?esc(s.domain):`<a href="${s.ssl?"https":"http"}://${esc(s.domain)}/" target="_blank" rel="noopener">${esc(s.domain)}</a>`}</td><td>${s.port?":"+s.port:(s.static?"static":"—")}</td><td class="num code ${codeClass(s.code)}">${s.code===null?"—":s.code||"down"}</td></tr>`).join("") || `<tr><td class="empty" colspan=3>no nginx vhosts</td></tr>`}</table> <h4>Services (${b.services.length} of ${b.service_count} running units)</h4> <table><tr><th>Unit</th><th>Ports</th></tr>${b.services.map(s=>`<tr data-s="${esc((s.name+" "+s.ports.join(" ")).toLowerCase())}"><td>${esc(s.name)}</td><td>${s.ports.map(p=>":"+p).join(" ")}${s.public?` <span class="chip warn">0.0.0.0</span>`:""}</td></tr>`).join("")}</table> ${b.failed.length?`<h4>Failed units</h4><table>${b.failed.map(f=>`<tr><td class="code bad">${esc(f)}</td></tr>`).join("")}</table>`:""} ${b.containers.length?`<h4>Containers</h4><table>${b.containers.map(c=>`<tr><td>${esc(c.name)}</td><td>${esc(c.image)}</td><td>${esc(c.status)}</td></tr>`).join("")}</table>`:""} <h4>TLS certificates (${b.certs.length})</h4> <table>${b.certs.map(c=>`<tr><td>${esc(c.name)}</td><td class="num code ${c.days_left<7?"bad":c.days_left<21?"warn":"ok"}">${c.days_left??"?"} d</td></tr>`).join("") || `<tr><td class="empty">none</td></tr>`}</table> <h4>Machine</h4> <table><tr><th>CPU</th><td>${b.cpus} × ${esc(b.cpu_model)} · load ${b.load.join(" / ")}</td></tr> <tr><th>Memory</th><td>${gb(b.mem.used)} of ${gb(b.mem.total)} · swap ${gb(b.mem.swap_used)} of ${gb(b.mem.swap_total)}</td></tr> <tr><th>Disk /</th><td>${gb(b.disk.used)} of ${gb(b.disk.total)} · ${gb(b.disk.free)} free</td></tr> <tr><th>Uptime</th><td>${dur(b.uptime_s)}${b.reboot_required?" · reboot pending":""}</td></tr> <tr><th>SSH</th><td><code>ssh ${esc(m.ssh)}</code></td></tr></table>`; } } $("#dh").innerHTML = head + `<button id="close">Close</button>`; $("#db").innerHTML = body; $("#close").onclick = closeDrawer; d.classList.add("open"); $("#scrim").classList.add("open"); applyFilter();}function closeDrawer(){ $("#drawer").classList.remove("open"); $("#scrim").classList.remove("open"); }
/* ---------- search ---------- */function applyFilter(){ const q = FILTER.trim().toLowerCase(); document.querySelectorAll("[data-s]").forEach(el=>el.classList.toggle("hidden", !!q && !el.dataset.s.includes(q))); // when searching, show every service on the cards (not just the top 10) and dim cards with no match document.querySelectorAll(".vps .card").forEach(card=>{ const id = card.dataset.open, b = DATA.boxes[id]; if (!q || !b || b.unreachable){ card.style.opacity = ""; return; } const hit = b.services.some(s=>(s.name+" "+s.ports.join(" ")).toLowerCase().includes(q)) || (b.sites||[]).some(s=>(s.domain+" "+(s.port||"")).toLowerCase().includes(q)); card.style.opacity = hit ? "" : ".35"; });}
$("#q").addEventListener("input", e=>{ FILTER = e.target.value; applyFilter(); });document.addEventListener("click", e=>{ const c = e.target.closest("[data-open]"); if (c && !e.target.closest("a")) openDrawer(c.dataset.open); });$("#scrim").onclick = closeDrawer;document.addEventListener("keydown", e=>{ if (e.key==="Escape") closeDrawer(); if (e.key==="/" && document.activeElement!==$("#q")){ e.preventDefault(); $("#q").focus(); } });$("#theme").onclick = ()=>{ const r=document.documentElement, dark = r.dataset.theme ? r.dataset.theme==="dark" : matchMedia("(prefers-color-scheme: dark)").matches; r.dataset.theme = dark?"light":"dark"; try{localStorage.setItem("homelab-theme", r.dataset.theme)}catch{} requestAnimationFrame(drawLinks); };try{ const t = localStorage.getItem("homelab-theme"); if (t) document.documentElement.dataset.theme = t; }catch{}addEventListener("resize", ()=>requestAnimationFrame(drawLinks));
// the map comes from the harness (the last reading kept); "Read now" reads every machine againfunction loadData(){ fetch("/api/machines").then(r=>r.json()).then(x=>{ META = x.meta || {}; if (!x.map){ window.HOMELAB = null; $("#stamp").textContent = "nothing read yet — press Read now"; renderEmpty(); return; } window.HOMELAB = x.map; render(); }).catch(()=>{ $("#stamp").textContent = "the harness did not answer"; });}function renderEmpty(){ DATA = {boxes:{}, drive:{connected:false}, history:{}}; renderFlows(); }$("#collect").onclick = ()=>{ const b = $("#collect"); b.disabled = true; b.textContent = "Reading…"; fetch("/api/machines/collect",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}).then(r=>r.json()) .then(()=>loadData()).catch(()=>{}).then(()=>{ b.disabled = false; b.textContent = "Read now"; });};loadData();setInterval(loadData, 60000);</script></body></html>workbench/judge/project_sources_judge.pyAdded+154
workbench/kernel/kernel_cli.pyAdded+55
workbench/kernel/kernel_v0.pyAdded+128
workbench/kernel/kernel_v1.pyAdded+92
workbench/kernel/kernel_v2.pyAdded+187
workbench/kernel/kernel_v3.pyAdded+27
workbench/kernel/kernel_v4.pyAdded+176
workbench/kernel/kernel_v5.pyAdded+73
workbench/kernel/kernel_v6.pyAdded+56
workbench/kernel/kernel_v7.pyAdded+106
workbench/kernel/kernel_v8.pyAdded+58
workbench/kernel/kernel_v9.pyAdded+58
workbench/kernel/network_glue_v1.pyAdded+321
workbench/kernel/network_glue_v2.pyAdded+431
workbench/kernel/network_glue_v3.pyAdded+181
workbench/kernel/network_v2.pyAdded+733
workbench/kernel/path_hrr_v1.pyAdded+80
workbench/language_bridge.pyAdded+363
workbench/learn.pyAdded+240
workbench/machine_probe.pyAdded+146
workbench/machines.pyAdded+271
workbench/make.pyAdded+657
workbench/o7_browser.pyAdded+119
workbench/planner.pyAdded+216
workbench/program_examples.pyAdded+81
workbench/program_prose.pyAdded+407
workbench/program_steps.pyAdded+236
workbench/project.pyAdded
workbench/project_answer.pyAdded+92
workbench/project_context.pyAdded+49
workbench/project_discussion.pyAdded+241
workbench/project_intent.pyAdded+385
workbench/project_interactive.pyAdded+541
workbench/project_sources.pyAdded+377
workbench/prosefold/core.py+4-1
workbench/prosefold/options.py+4-1
workbench/question_obligation.pyAdded+364
workbench/reflect.pyAdded+763
workbench/registry.py+28-8
workbench/relay.pyAdded+91
workbench/repair.pyAdded+519
workbench/resolve.pyAdded+278
workbench/runjail.pyAdded+63
workbench/seal.pyAdded+155
workbench/selfdev.pyAdded+374
workbench/server.py
workbench/service_parts.pyAdded+288
workbench/shadow.pyAdded+142
workbench/static/chat.htmlAdded+380
workbench/static/machines.htmlAdded+572