diff --git a/workbench/judge/project_sources_judge.py b/workbench/judge/project_sources_judge.py new file mode 100644 index 0000000000000000000000000000000000000000..c29cca25b2bdff814f602a3d5fc62b9e809e2dc7 --- /dev/null +++ b/workbench/judge/project_sources_judge.py @@ -0,0 +1,154 @@ +"""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] diff --git a/workbench/kernel/kernel_cli.py b/workbench/kernel/kernel_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..343f00f80673ccee26fa6599108a973ee0716dc0 --- /dev/null +++ b/workbench/kernel/kernel_cli.py @@ -0,0 +1,55 @@ +#!/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 json +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.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:])) diff --git a/workbench/kernel/kernel_v0.py b/workbench/kernel/kernel_v0.py new file mode 100644 index 0000000000000000000000000000000000000000..1526b33f8b192a748d2f1b47df2689545053d40a --- /dev/null +++ b/workbench/kernel/kernel_v0.py @@ -0,0 +1,128 @@ +#!/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 come +back 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 """ +from __future__ import annotations + +import collections +import json +import math +import os +import sys +import time +from pathlib import Path + +TREE = Path(os.environ.get("O7_KERNEL_TREE", Path(__file__).resolve().parents[2])) # the released pack the kernel reads +sys.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) diff --git a/workbench/kernel/kernel_v1.py b/workbench/kernel/kernel_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..1d6c6348f39788a6671296f9e774212f2c84f291 --- /dev/null +++ b/workbench/kernel/kernel_v1.py @@ -0,0 +1,92 @@ +#!/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 that +disagree, because a noun like "height", "radius" or "volume" is shared by different shapes - a cone formula's height was +chained into a cylinder formula's; the every-plan-agrees law caught all 9, but a question with ONE such plan would have +nothing 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 by +parts 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 0 +wrong; every answer that changes against grow60 is listed with the reason. +usage: kernel_v1.py """ +from __future__ import annotations + +import collections +import hashlib +import json +import re +import 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) diff --git a/workbench/kernel/kernel_v2.py b/workbench/kernel/kernel_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..0c97a394143f2553c08594d27c8fc8140bc7ec7a --- /dev/null +++ b/workbench/kernel/kernel_v2.py @@ -0,0 +1,187 @@ +#!/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 collections +import json +import os +import re +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE)) +from kernel_v1 import Kernel1 # noqa: E402 +from 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 None diff --git a/workbench/kernel/kernel_v3.py b/workbench/kernel/kernel_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..e5744124981500971617c82ba6a14fe0ec384c72 --- /dev/null +++ b/workbench/kernel/kernel_v3.py @@ -0,0 +1,27 @@ +#!/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, why diff --git a/workbench/kernel/kernel_v4.py b/workbench/kernel/kernel_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..59996edc2656378068e051858bb19ef5d3deef6a --- /dev/null +++ b/workbench/kernel/kernel_v4.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""The Oracle7 kernel, v4: the goal reader. Found by the OpenStax held-out run (126 of 136 independent textbook exercises +declined 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_givens diff --git a/workbench/kernel/kernel_v5.py b/workbench/kernel/kernel_v5.py new file mode 100644 index 0000000000000000000000000000000000000000..f95b1e731c9c18e5dfca267e12b5f18bdd8bac54 --- /dev/null +++ b/workbench/kernel/kernel_v5.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""The Oracle7 kernel, v5: kernel v4 plus the class fix from KERNEL SEALED 2 (m13: "What power, in kilowatts, must the +motor supply? (Neglect friction.)" was answered in watts: the goal reader read the LAST sentence, the parenthetical, so the +asked-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 its +standing 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 json +import os +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.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:])) diff --git a/workbench/kernel/kernel_v6.py b/workbench/kernel/kernel_v6.py new file mode 100644 index 0000000000000000000000000000000000000000..01c6f9a73b20e31a70bf88472049d3f5ee23e954 --- /dev/null +++ b/workbench/kernel/kernel_v6.py @@ -0,0 +1,56 @@ +#!/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 False diff --git a/workbench/kernel/kernel_v7.py b/workbench/kernel/kernel_v7.py new file mode 100644 index 0000000000000000000000000000000000000000..0f9ad99549d0b38e37c4ff116d7a22a0d749f6e7 --- /dev/null +++ b/workbench/kernel/kernel_v7.py @@ -0,0 +1,106 @@ +#!/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 it +learns 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:"). +A named dimensionless quantity or count is never a FREE factor of core arithmetic (the 09-30 law: hidden dimensionless +factors 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 re +import sys + +from kernel_v6 import Kernel6 +import kernel_v5 + +reader = kernel_v5.reader +G1 = 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"(? 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} diff --git a/workbench/kernel/kernel_v9.py b/workbench/kernel/kernel_v9.py new file mode 100644 index 0000000000000000000000000000000000000000..45fd4c51cbb0f944af939cb9c745b3b8e57e54b3 --- /dev/null +++ b/workbench/kernel/kernel_v9.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""The Oracle7 kernel, v9: v8's reader fixes (units with "/" read whole, never short; articles never goal units), WITHOUT +v8'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 hidden +factors: 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_v4 +import kernel_v5 +from kernel_v8 import Kernel8 + +reader = kernel_v5.reader +HEAD = 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 r diff --git a/workbench/kernel/network_glue_v1.py b/workbench/kernel/network_glue_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..027d94de148eee140cbdc3aa3c86217d3295ca09 --- /dev/null +++ b/workbench/kernel/network_glue_v1.py @@ -0,0 +1,321 @@ +#!/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, reply +unit 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 in +q (dimension, role, surface span); the specialist is asked q, and the number in its reply that equals `expect` gives the +output's unit, hence its dimension. The face = template (q with each given's span replaced by a typed slot that remembers +its surface unit) + output dimension. EXAMINED: a face is kept only if, rendered with the givens of ANOTHER dev item of the +same 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 face +reads quantities of its slot types from the pool and writes its output back (the residual-stream analogue). Normalisation +is 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's +template words present in the question (IDF over all learned faces), eligible at fit >= FIT_MIN. The schedule: rounds of +face applications (depth <= MAX_HOPS, derived inputs from core math allowed as in v2), and after any round the remaining +quantities must reach the goal by CORE_MATH using every one of them (v2's rule). Checks unchanged: validity of givens, all +numbers read, multi-step only, no echo. No checked path -> decline. +usage: network_glue_v1.py [question ...]""" +from __future__ import annotations + +import collections +import itertools +import json +import math +import os +import re +import 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.5 +MAX_HOPS = 2 +STOP = 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]) diff --git a/workbench/kernel/network_glue_v2.py b/workbench/kernel/network_glue_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..98a4294fff3c96f301216db740fa887a1e9d33dc --- /dev/null +++ b/workbench/kernel/network_glue_v2.py @@ -0,0 +1,431 @@ +#!/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 [question ...]""" +from __future__ import annotations + +import collections +import itertools +import json +import math +import re +import sys + +from network_glue_v1 import (GlueNetwork, Face, _slot, parse_out, reply_value, words) # noqa: F401 +from 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"(? 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]) diff --git a/workbench/kernel/network_glue_v3.py b/workbench/kernel/network_glue_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..18bdff2c6d77a498a274b4c32ae167770552940a --- /dev/null +++ b/workbench/kernel/network_glue_v3.py @@ -0,0 +1,181 @@ +#!/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 [question ...]""" +from __future__ import annotations + +import collections +import json +import os +import re +import statistics +import sys +import 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 length +for _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.Face2 +WH = 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]) diff --git a/workbench/kernel/network_v2.py b/workbench/kernel/network_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..cc68a663d41a17461d51ec9e38ae1f331e4e9497 --- /dev/null +++ b/workbench/kernel/network_v2.py @@ -0,0 +1,733 @@ +#!/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"(? 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"(? "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]) diff --git a/workbench/kernel/path_hrr_v1.py b/workbench/kernel/path_hrr_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..713bb594eb67d83ebc929b61634476adcc6c9879 --- /dev/null +++ b/workbench/kernel/path_hrr_v1.py @@ -0,0 +1,80 @@ +#!/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 the +query's (partial cue - a new question whose shape overlaps a stored one retrieves that path), then unbind each position +and clean up against the op codebook. Retrieval only ORDERS the plans the network tries; every answer still has to pass +every 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), best diff --git a/workbench/language_bridge.py b/workbench/language_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..8284a3d392ac66d9f21dc8489b00992f74bc8482 --- /dev/null +++ b/workbench/language_bridge.py @@ -0,0 +1,363 @@ +"""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])*"|(? %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 suggestions diff --git a/workbench/learn.py b/workbench/learn.py new file mode 100644 index 0000000000000000000000000000000000000000..bd91da13b2a058575a89a6a3b9014eff3d80b70b --- /dev/null +++ b/workbench/learn.py @@ -0,0 +1,240 @@ +"""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 the +verified 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 citation +No language model; nothing outside the verified list is fetched.""" +import hashlib +import json +import os +import re +import time +import urllib.parse +import urllib.request +from pathlib import Path + +WB = Path(__file__).resolve().parent +STORE = 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"(? {"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)) diff --git a/workbench/machine_probe.py b/workbench/machine_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..1329b4517129788e37c9cd5d41e0373d4951836b --- /dev/null +++ b/workbench/machine_probe.py @@ -0,0 +1,146 @@ +# 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)) diff --git a/workbench/machines.py b/workbench/machines.py new file mode 100644 index 0000000000000000000000000000000000000000..d697f75d3f126be410df29cc0ff0bf5fbcd6c63f --- /dev/null +++ b/workbench/machines.py @@ -0,0 +1,271 @@ +"""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 (or +ORACLE7_WORKBENCH_LOCAL/machines.json), which never ships in a pack. A machine is named by what the user's own ssh +reaches 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, no +password prompt), StrictHostKeyChecking=yes (a host it has never seen is not trusted silently) and no forwarding. This +computer 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 json +import os +import platform +import re +import shutil +import socket +import subprocess +import sys +import time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +HERE = Path(__file__).resolve().parent +PROBE = 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) diff --git a/workbench/make.py b/workbench/make.py new file mode 100644 index 0000000000000000000000000000000000000000..695023756b5c7f1c4bf26d9b129a31ee07bf8772 --- /dev/null +++ b/workbench/make.py @@ -0,0 +1,657 @@ +"""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 imports +The 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 checked +against "expect " if you give one. A step no move can build is reported as a named gap with the nearest workspace +functions, never guessed. No language model.""" +import ast +import json +import re +import threading +from 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: " of each ", " for each ", "for each , """ + 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 = "%s%s
" % ("".join("%s" % esc(str(c)) for c in cols), "".join( + "%s" % "".join("%s" % 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 = "%s
" % "".join("%s" % "".join("%s" % esc(str(v)) for v in p) for p in x) + elif isinstance(x, list): + body = "
    %s
" % "".join("
  • %s
  • " % esc(str(v)) for v in x) + else: + body = "

    %s

    " % 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("%s

    %s

    %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:/ 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 ,] if " + the step that follows + an optional "otherwise " = 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).*?", " ", 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 : ; function : ; main: ". 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 None diff --git a/workbench/o7_browser.py b/workbench/o7_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..a903849edde2dd267ad2b955c26214af273c8897 --- /dev/null +++ b/workbench/o7_browser.py @@ -0,0 +1,119 @@ +"""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) diff --git a/workbench/planner.py b/workbench/planner.py new file mode 100644 index 0000000000000000000000000000000000000000..54986fbc82fd35af66bd513f2ae3b810f7ebb6d7 --- /dev/null +++ b/workbench/planner.py @@ -0,0 +1,216 @@ +"""planner - build what you want, not only what you spell out (12.0; the Pokemon satellite's shape pointed at building: read the +world'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 always +A 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 csv +import io +import re +from 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), why diff --git a/workbench/program_examples.py b/workbench/program_examples.py new file mode 100644 index 0000000000000000000000000000000000000000..65a87603b464f6885717198c13c6a467f4294aff --- /dev/null +++ b/workbench/program_examples.py @@ -0,0 +1,81 @@ +"""Read back a received program's behavior in fresh fixture directories.""" +import contextlib +import importlib.util +import io +import json +import math +from pathlib import Path +import sys +import 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'))))) diff --git a/workbench/program_prose.py b/workbench/program_prose.py new file mode 100644 index 0000000000000000000000000000000000000000..435ce5f63207def56b81091e35e6106e40d9bb05 --- /dev/null +++ b/workbench/program_prose.py @@ -0,0 +1,407 @@ +"""Connect described state/event relationships to the existing browser program part. + +Every accepted clause has an exact source receipt. Unknown behavior remains an +owned hole; this part never treats a retained description as a finished build. +The named grammar is about executable relationships, not application templates. +""" +import copy +import hashlib +import json +import 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) diff --git a/workbench/program_steps.py b/workbench/program_steps.py new file mode 100644 index 0000000000000000000000000000000000000000..9d379e941f7cfb4d9db9b3caee5887946a18e1d7 --- /dev/null +++ b/workbench/program_steps.py @@ -0,0 +1,236 @@ +"""Connect the existing step compiler to the selected work environment.""" +import ast +import hashlib +import os +from pathlib import Path +import re +import textwrap +import 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 result diff --git a/workbench/project.py b/workbench/project.py new file mode 100644 index 0000000000000000000000000000000000000000..7f14e29ab78ac28882ee1223474c1142734edd7a --- /dev/null +++ b/workbench/project.py @@ -0,0 +1,2299 @@ +"""project - a project received as a ledger of requirements, planned over shapes, written from parts, judged by what it +does, and continued from wherever it stopped (12.0 C9, C10; the review: "receive a request as explicit outputs, +constraints, dependencies and completion conditions"; the followup: "account for every requirement"). + + receive each turn's words join the project's clauses. A sentence is read into requirements: OUTCOMES someone can + observe (a file written, rows kept in a database, a page served, lines printed), PROPERTIES of them (a timeout, + an error counted as down, the time to answer, how many results are shown) and OPERATIONS on the rows (group, + total, count, average, largest, smallest, keep only, sort, the first n, a value made from a column). Every + word of a sentence must be owned: by a part's vocabulary, a column of the project's tables, a file, the + project's own name or the words every sentence has. A word nobody owns is a HOLE (what does it mean?), never + dropped: a requirement that is only kept as text is not a requirement. + world the tables the request names (csv, json), read afresh at every plan: their columns, which holds urls, which + holds names. A file not there yet is a hole until it is. + parts declared contracts over shapes: table (file -> rows), probe (rows with urls -> results), compute (rows -> + rows: the operations), keep (rows -> stored), latest (stored -> latest), export (rows -> a file), page + (rows -> page), serve (page -> served), print (rows -> lines). A value made from a column is a part found in + Oracle7's code store (the functions it composed and kept, lit on the Tree of Life spine by the words and the + shape) or composed by the code composer from examples the next turn gives; either way it carries its sha. + plan for each entry (named in the request as `python3 m.py sub ARGS`, or proposed when the request names none): + backward from its outcomes to a source (the table, the servers probed, or what another entry kept), the + operations its words ask for in between. Every requirement is tied to the links that supply it. + write the parts' code in plan order, one module, entries dispatched by name. + judge every requirement against what happened: each entry run as named, rows read back from its database, files + read back and compared with the rows an independent reading of the request gives, the page fetched from it + running, the lines printed. A project is done only when every requirement has passed its judge. + continue a project that stops at a hole is kept as it is (in the conversation and in the project's .oracle7 folder): + the next turn's example, file, explanation or "drop" fills the hole and the build goes on from there, after a + restart too. +No language model.""" +import csv +import hashlib +import json +import os +import re +import socket +import sqlite3 +import subprocess +import sys +import time +from html import unescape as html_unescape +import urllib.request +from pathlib import Path +import project_sources as PS +import project_interactive as PI + +ENTRY = re.compile(r"`\s*(?:python3?\s+)?([\w./-]+\.py)\s+([a-z][\w-]*)((?:\s+[A-Z_]+)*)\s*`") +URLV = re.compile(r"^https?://", re.I) +DATA = re.compile(r"\b([\w./-]+\.(?:csv|jsonl|json))\b") +BUILD = re.compile(r"(?i)\b(?:build|make|create|write|set up|put together|develop)\b") +SINK_FILE = re.compile(r"(?i)\b(?:save|saves|saved|saving|write|writes|written|export|exports|exported|output|outputs|put|puts|" + r"store|stores|dump|dumps)\b(?:(?!\.\s)[^;]){0,140}?\b(?:to|into|in|as)\s+(?:a\s+file\s+(?:called|named)\s+)?" + r"`?([\w./-]+\.(csv|json|txt|html))\b") +SINK_TO = re.compile(SINK_FILE.pattern.replace(r"(?:to|into|in|as)", r"(?:to|into|as)")) +SINK_IN = re.compile(SINK_FILE.pattern.replace("{0,140}?", "{0,140}")) # greedy: the last 'in ' of the sentence +# 12.0 C28: the written file as the verb's own object ("write top.csv with the rows ...", "save a summary.json of ...") +SINK_OBJ = re.compile(r"(?i)\b(?:save|saves|write|writes|export|exports|output|outputs|produce|produces)\s+(?:a\s+|an\s+|the\s+)?" + r"(?:file\s+)?`?([\w./-]+\.(csv|json|txt|html))\b") + + +def sinks(s): + """the files a sentence writes: 'to / into / as ' names where rows go; 'in ' does only when the sentence has + no such target ('save the items in stock.csv ... to low.csv' reads stock.csv and writes low.csv); with neither, the file + the verb writes as its own object ('write top.csv with ...')""" + return list(SINK_TO.finditer(s)) or list(SINK_IN.finditer(s)) or list(SINK_OBJ.finditer(s)) + + +STORED = re.compile(r"(?i)\b(?:database|sqlite|db)\b") +REVISE = re.compile(r"(?i)\b(?:change|changed|update|revise|instead|rather|make it|now)\b") +# the words just before an outcome that rule it out (up to three words between: "do not export the rows", "without a db") +NEGATED = re.compile(r"\b(?:do\s+not|does\s+not|don'?t|doesn'?t|never|without|no|not)\s+(?:[a-z]+\s+){0,3}$") +SERVED = re.compile(r"(?i)\b(?:browser|web ?page|webpage|website|serves?|served|on (?:a|the) page|(?:a|the) page)\b") +PRINTED = re.compile(r"(?i)\b(?:prints?|printed|terminal|console)\b") + +# ---------------------------------------------------------------- the words every sentence has, and each part's own +GENERAL = set("""a an the and or but of to in on at by for from with without into onto as is are was were be been being it its +this that these those each every all any some my our your their his her them they we i me you he she one once two three +four five six seven eight nine ten both other others another than then so such not no do does did done has have had will +would should could can may might must shall also again just only very more most less much many same new old here there +when where which who whom whose what why how up out over under after before while until about per via if else whether +please want need like let able use using called named way ways get gets got go goes going thing things there's it's +want wants make makes made build builds built create creates created write writes written set put together project +program script tool app application run runs command commands file files folder data instead too still yet sure ok okay +now first next last later always never ever own change changes changed update updates updated revise revised rather +don't dont doesn't actually just really well oh hmm hey thanks thank""".split()) +VOCAB = { + "table": "table tables list lists listed listing row rows record records entry entries column columns sheet spreadsheet " + "csv json inventory item items", + "probe": "query queries queried check checks checked checking ping pings request requests fetch fetches fetched health " + "url urls endpoint endpoints answer answers answered respond responds response reach reachable up down status " + "statuses server servers service services site sites host hosts monitor monitors monitoring", + "keep": "keep keeps kept store stores stored storing save saves saved record records recorded log logs logged database " + "sqlite local timestamp timestamps timestamped time times losing lose lost result results history", + "timeout": "within second seconds sec secs timeout slow silent", + "error": "error errors fail fails failed failure failures", + "ms": "millisecond milliseconds ms long took take takes latency", + "latest": "current previous latest recent newest", + "page": "page pages browser show shows shown showing display displays displayed view web html dashboard webpage website", + "serve": "serve serves served port", + "export": "export exports exported save write output outputs dump csv json file", + "print": "print prints printed terminal console screen output", + "ops": "group grouped groups grouping total totals sum sums summed add adds count counts counted number average averages " + "averaged mean largest biggest highest most maximum max smallest lowest least minimum min sort sorted order " + "ordered descending ascending top bottom where filter filtered over above under below greater than equal equals " + "summary summaries summarize summarise report reports breakdown amount amounts across overall value values", + "derive": "convert converted converts column columns", + "design": "look looks feel feels style styled colour colours color colors font fonts typography palette theme dark light " + "mode designed design editorial literary classic formal elegant luxurious quiet calm traditional scholarly warm " + "friendly modern clean minimal technical precise scientific industrial neutral bold playful expressive dramatic " + "accent accents", +} +PART_WORDS = {k: set(v.split()) for k, v in VOCAB.items()} +ALL_PART_WORDS = set().union(*PART_WORDS.values()) + + +def stem(w): + w = w.lower() + if w.endswith("'s"): + w = w[:-2] + for suf in ("ies",): + if len(w) > 4 and w.endswith(suf): + return w[:-3] + "y" + for suf in ("ing", "ed"): + if len(w) > 4 and w.endswith(suf): + return w[: -len(suf)] + # C12b: "es" is a plural ending only after s, x, z, ch, sh ("boxes", "churches"); after another letter the e is the + # word's own ("cubes" -> cube, "tubes" -> tube, not cub, tub) + if len(w) > 4 and w.endswith("es") and re.search(r"(?:s|x|z|ch|sh)es$", w): + return w[:-2] + if len(w) > 3 and w.endswith("s") and not w.endswith(("ss", "us", "is")): + return w[:-1] + return w + + +def wmatch(a, b): + a, b = stem(a), stem(b) + return a == b or (len(a) >= 4 and len(b) >= 4 and (a.startswith(b) or b.startswith(a))) + + +def _owned(w, owners): + return any(wmatch(w, o) for o in owners) + + +# ---------------------------------------------------------------- the world +def read_table(root, name): + """a table of the project: its columns, the rows' values, which column holds urls and which the names""" + p = Path(root) / name + if not p.is_file(): + return {"file": name, "missing": True} + try: + if name.endswith(".jsonl"): + rows = [json.loads(ln) for ln in p.read_text(encoding="utf-8").splitlines() if ln.strip()] + elif name.endswith(".json"): + rows = json.loads(p.read_text(encoding="utf-8")) + if isinstance(rows, dict): + rows = next((v for v in rows.values() if isinstance(v, list)), [rows]) + else: + rows = list(csv.DictReader(p.read_text(encoding="utf-8").splitlines())) + except (ValueError, OSError) as e: + return {"file": name, "unreadable": str(e)[:120]} + rows = [r for r in rows if isinstance(r, dict)] + cols = list(rows[0].keys()) if rows else [] + url = next((c for c in cols if rows and all(URLV.match(str(r.get(c, ""))) for r in rows)), None) + key = next((c for c in cols if c != url and rows and len({str(r[c]) for r in rows}) == len(rows) + and not all(_isnum(r[c]) for r in rows)), None) or \ + next((c for c in cols if c != url and rows and len({str(r[c]) for r in rows}) == len(rows)), None) + numeric = [c for c in cols if rows and all(_isnum(r.get(c)) for r in rows)] + return {"file": name, "cols": cols, "url": url, "key": key, "n": len(rows), "numeric": numeric, + "hosts": sorted({re.sub(r"^https?://([^/:]+).*$", r"\1", str(r[url])) for r in rows}) if url else [], + "sample": {c: rows[0].get(c) for c in cols} if rows else {}} + + +def _isnum(v): + if isinstance(v, bool): + return False + if isinstance(v, (int, float)): + return True + try: + float(str(v).strip()) + return True + except (TypeError, ValueError): + return False + + +def num(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return v + s = str(v).strip() + try: + return int(s) + except ValueError: + try: + return float(s) + except ValueError: + return v + + +def load_rows(root, name): + p = Path(root) / name + if name.endswith(".jsonl"): + return [json.loads(ln) for ln in p.read_text(encoding="utf-8").splitlines() if ln.strip()] + if name.endswith(".json"): + rows = json.loads(p.read_text(encoding="utf-8")) + if isinstance(rows, dict): + rows = next((v for v in rows.values() if isinstance(v, list)), [rows]) + return [dict(r) for r in rows if isinstance(r, dict)] + return list(csv.DictReader(p.read_text(encoding="utf-8").splitlines())) + + +# ---------------------------------------------------------------- receiving: the clauses, the fills +EXAMPLE = re.compile(r"(-?\d+(?:\.\d+)?|'[^']*'|\"[^\"]*\")\s*(?:->|=>|→|gives|becomes)\s*(-?\d+(?:\.\d+)?|'[^']*'|\"[^\"]*\")") +DROP = re.compile(r"(?i)^\s*(?:please\s+)?(?:drop|ignore|forget|leave out|skip)\s+(?:requirement\s+|r)?(\d+)\b") +DROP_WORD = re.compile(r"(?i)^\s*(?:please\s+)?(?:drop|ignore|forget|leave out|skip)\s+(?:the\s+(?:word\s+)?)?['\"`]?([a-z][\w-]*)['\"`]?\s*\.?$") +MEANS = re.compile(r"(?i)['\"`]?([a-z][\w-]*)['\"`]?\s+(?:means|is|meant)\s+(?:the\s+)?([\w\s-]{2,60}?)\s*\.?$") +CONTINUE = re.compile(r"(?i)^\s*(?:please\s+)?(?:continue|resume|go on|carry on|try again|retry|it'?s (?:there|in) now|" + r"(?:i\s+)?added (?:it|the file)|use it|keep going|finish (?:it|the project))\b") + + +def new_shape(): + return {"v": 2, "entries": {}, "module": None, "proposed": False, "clauses": [], "dropped": [], "meanings": {}, + "examples": {}, "derived": {}, "status": "new", "use": {}} + + +def receive(text, root, kept=None): + """the project's shape after this turn's words. kept: the shape the conversation (or the project's folder) holds""" + shape = json.loads(json.dumps(kept)) if kept else new_shape() + if shape.get("v") != 2: # a shape kept by the first version: its clauses are read again + old = shape + shape = new_shape() + shape["clauses"] = list(old.get("clauses") or []) + t = " ".join(text.split()) + fill = False + m = DROP.match(t) + if m and kept: + shape["dropped"].append("R%s" % m.group(1)) + fill = True + m = DROP_WORD.match(t) if not fill else None + if m and kept: + shape["meanings"][m.group(1).lower()] = "" + fill = True + if not fill and kept: + exs = EXAMPLE.findall(t) + open_derive = [h for h in shape.get("holes_kept") or [] if h.get("kind") == "derive"] + source_entries = {h.get("entry", "*") for h in shape.get("holes_kept") or [] if h.get("kind") == "source"} + scope_holes = [h for h in shape.get("holes_kept") or [] if h.get("kind") == "scope"] + named_entry = next((n for n in shape["entries"] if re.fullmatch(r"(?i)(?:the\s+)?`?" + re.escape(n) + r"`?(?:\s+command)?[.!]?", t)), None) + entry_match = ENTRY.fullmatch(t) + if entry_match and entry_match.group(1) == shape.get("module"): + named_entry = entry_match.group(2) + if len(scope_holes) == 1 and named_entry in scope_holes[0].get("entries", []): + shape.setdefault("scope_fills", {})[str(scope_holes[0]["clause"])] = named_entry + fill = True + elif len(source_entries) == 1 and re.match(r"(?i)^\s*(?:match(?:ing|ed)?\s+(?:on|by)\s+|on\s+)[a-z_]", t): + shape.setdefault("source_fills", {})[next(iter(source_entries))] = t + fill = True + elif exs and open_derive: + h = open_derive[0] + shape["examples"][h["fn"]] = shape["examples"].get(h["fn"], []) + [[_lit(a), _lit(b)] for a, b in exs] + shape["example_words"] = (shape.get("example_words", "") + " " + EXAMPLE.sub(" ", t)).strip() + fill = True + elif re.search(r"(?i)\buse\s+(?:it|that|the kept one|[a-z_]+)\b", t) and \ + [h for h in shape.get("holes_kept") or [] if h.get("kind") == "derive" and h.get("offer")]: + h = next(h for h in shape["holes_kept"] if h.get("kind") == "derive" and h.get("offer")) + shape["use"][h["fn"]] = h["offer"]["sha256"] + fill = True + else: + mm = MEANS.search(t) + unread = {w for h in shape.get("holes_kept") or [] if h.get("kind") == "unread" for w in h.get("words", [])} + if mm and mm.group(1).lower() in unread: + shape["meanings"][mm.group(1).lower()] = mm.group(2).strip() + fill = True + elif CONTINUE.match(t): + fill = True + if not fill: + shape["clauses"].append(t) + hits = [(ci, m) for ci, c in enumerate(shape["clauses"]) for m in ENTRY.finditer(c)] + for _ci, m in hits: + shape["module"] = shape["module"] or m.group(1) + shape["entries"].setdefault(m.group(2), {"args": m.group(3).split()}) + return shape + + +def _lit(s): + s = s.strip() + if s[:1] in "'\"": + return s[1:-1] + return num(s) + + +# ---------------------------------------------------------------- reading the requirements +def _sentences(clause): + out, start = [], 0 + for m in re.finditer(r"(?<=[.;!?])\s+", clause): + out.append((start, clause[start:m.start()])) + start = m.end() + out.append((start, clause[start:])) + return [(o, s) for o, s in out if s.strip()] + + +def _segments(clause, hits): + """the clause's sentences, each cut again where it names a command: every piece belongs to the command named at its + start, or to the one named before it, or (before any command) to the whole project ("*"); None when the clause names none""" + starts = [m.start() for m in hits] + for off, s in _sentences(clause): + cuts = [off] + [p for p in starts if off < p < off + len(s)] + [off + len(s)] + for a, b in zip(cuts, cuts[1:]): + piece = clause[a:b].strip(" ,;") + if not piece: + continue + before = [m for m in hits if m.start() <= a] + ent = before[-1].group(2) if before else ("*" if hits else None) + yield a, piece, ent + + +def _words(s): + s = DATA.sub(" ", ENTRY.sub(" ", s)) + s = re.sub(r"\b[\w./-]+\.(?:csv|jsonl|json|txt|html|py|db)\b", " ", s) + return [w for w in re.findall(r"[a-z][a-z']*", s.lower().replace("-", " ")) if len(w) > 2] + + +def project_noun(shape): + """the words the project calls itself: 'build a service-health dashboard ...' -> service, health, dashboard""" + for c in shape["clauses"]: + m = re.search(r"(?i)\b(?:build|make|create|write|set up|put together|develop)\s+(?:me\s+|us\s+)?(?:(?:a|an|the|my|our)\s+)?" + r"((?:[\w-]+\s+){0,3}?[\w-]+?)\s+(?:for|from|that|which|to|using|with|of|in|on|so|where|,|\.|`)", c + " .") + if m: + ws = [w for w in re.findall(r"[a-z]+", m.group(1).lower()) if w not in GENERAL] + if ws: + return ws[:4] + return [] + + +COLW = r"([a-z_]+)" + + +def _col(word, cols, derived=()): + for c in list(cols) + list(derived): + if wmatch(word, c) or wmatch(word, c.replace("_", " ").split()[-1]): + return c + return None + + +def read_ops(s, cols, numeric, derived_names, gcol_hint=None): + """the operations a sentence asks of the rows. -> (ops, owned words, derive requests)""" + low = " " + DATA.sub(" FILE ", s.lower()) + " " + ops, own, derive = [], set(), [] + # A reference supplies a second value, not a unary example-driven function. + calculations = [] + for m in re.finditer(r"\bmultiply\s+(?:each\s+|the\s+)?([a-z_]+)\s+by\s+(?:the\s+)?([a-z_]+)" + r"\s+(?:as|into)\s+([a-z_]+)", low): + left, right = _col(m.group(1), cols), _col(m.group(2), cols) + if left is not None and right is not None: + calculations.append((left, right, m.group(3), m.group(0))) + for m in re.finditer(r"\bconvert(?:s|ed|ing)?\s+(?:each\s+|every\s+|the\s+|all\s+)?([a-z_]+)" + r"(?:\s+from\s+FILE)?\s+(?:with|using)\s+(?:the\s+|its\s+|matching\s+)*([a-z_]+)", low): + left, right = _col(m.group(1), cols), _col(m.group(2), cols) + if left is not None and right is not None: + calculations.append((left, right, "converted_" + left, m.group(0))) + # C15: arithmetic between two columns in ordinary words ("cost as qty times price", "margin being price minus cost", + # "total equal to a plus b", "share as part divided by whole"; "add/subtract/divide a to/from/by b as name") + ARITH = {"times": "mul", "multiplied by": "mul", "x": "mul", "plus": "add", "added to": "add", "minus": "sub", + "less": "sub", "take away": "sub", "divided by": "div", "over": "div", "per": "div"} + arw = "|".join(sorted((re.escape(k) for k in ARITH), key=len, reverse=True)) + for m in re.finditer(r"\b([a-z_]+)\s+(?:as|is|=|being|equal to|which is|worked out as|computed as)\s+(?:the\s+)?([a-z_]+)\s+" + r"(%s)\s+(?:the\s+)?([a-z_]+)\b" % arw, low): + left, right = _col(m.group(2), cols), _col(m.group(4), cols) + if left is not None and right is not None and m.group(1) not in cols: # a new name: exact, not near + calculations.append((left, right, m.group(1), m.group(0), ARITH[m.group(3)])) + for m in re.finditer(r"\b(add|subtract|divide)\s+(?:each\s+|the\s+)?([a-z_]+)\s+(to|from|by)\s+(?:the\s+)?([a-z_]+)" + r"\s+(?:as|into)\s+([a-z_]+)", low): + a, b = _col(m.group(2), cols), _col(m.group(4), cols) + if a is not None and b is not None: + fn = {"add": "add", "subtract": "sub", "divide": "div"}[m.group(1)] + left, right = (b, a) if fn == "sub" else (a, b) # subtract a from b: b - a + calculations.append((left, right, m.group(5), m.group(0), fn)) + calculations = [c if len(c) == 5 else c + ("mul",) for c in calculations] + for left, right, name, phrase, fn in calculations: + if not any(o.get("col") == name for o in ops): + ops.append({"op": "calculate", "col": name, "left": left, "right": right, "fn": fn}) + own |= set(re.findall(r"[a-z_]+", phrase)) | {name} + for _l, _r, _n, phrase, _f in calculations: # C15: a phrase that defines a value is consumed by it - "both equal + low = low.replace(phrase, " CALC ") # to price plus cost" is not also a filter "both == price" + calculated_names = [o["col"] for o in ops] + for m in re.finditer(r"\b([a-z_]+?)s?\s+in\s+([a-z]+)\b(?!\s*\.\w)", low): + c = _col(m.group(1), cols) + tgt = m.group(2) + if c and tgt not in GENERAL and not _col(tgt, cols) and tgt not in ALL_PART_WORDS and tgt != "file": + derive.append({"col": c, "name": tgt, "phrase": m.group(0).strip()}) + own |= {m.group(1), tgt} + for m in re.finditer(r"\bconvert(?:s|ed|ing)?\s+(?:each\s+|every\s+|the\s+|all\s+)?([a-z_]+?)s?\s+(?:to|into)\s+([a-z]+)\b", low): + c = _col(m.group(1), cols) + if c and not _col(m.group(2), cols): + derive.append({"col": c, "name": m.group(2), "phrase": m.group(0).strip()}) + own |= {m.group(1), m.group(2)} + for m in re.finditer(r"\b([a-z]+)\s+(?:made|computed|worked out|derived|calculated|figured)\s+(?:out\s+)?from\s+" + r"(?:the\s+|its\s+|their\s+|each\s+)?([a-z_]+?)s?\b", low): # C11: "its weight made from units" + c = _col(m.group(2), cols) + if c and not _col(m.group(1), cols) and m.group(1) not in GENERAL and not any(d["name"] == m.group(1) for d in derive): + derive.append({"col": c, "name": m.group(1), "phrase": m.group(0).strip()}) + own |= {m.group(1), m.group(2), "made", "computed", "worked", "out", "derived", "calculated", "figured", "from"} + dmap = {d["col"]: d["name"] for d in derive} + names = list(derived_names) + calculated_names + [d["name"] for d in derive] + + def col_of(w): + c = _col(w, cols, names) + return dmap.get(c, c) + for m in re.finditer(r"\b(?:group(?:ed|s|ing)?\s+(?:[a-z_.]+\s+){0,3}?by|by|per|for each|for every)\s+(?:the\s+|their\s+|its\s+)?" + + COLW, low): + c = _col(m.group(1), cols) + if c and c not in numeric: + if not any(o["op"] == "group" for o in ops): + ops.append({"op": "group", "col": c}) + own.add(m.group(1)) + break + aggs = [(r"\b(?:total|totals|sum|sums|add up|adds up)\s+(?:of\s+|up\s+)?(?:the\s+|all\s+|their\s+|its\s+|each\s+)?" + COLW, "sum"), + (r"\b(?:average|averages|mean)\s+(?:of\s+)?(?:the\s+|all\s+|their\s+)?" + COLW, "mean"), + (r"\b(?:largest|biggest|highest|maximum|max)\s+(?:of\s+)?(?:the\s+)?" + COLW, "max"), + (r"\b(?:smallest|lowest|minimum|min)\s+(?:of\s+)?(?:the\s+)?" + COLW, "min")] + for rx, fn in aggs: + for m in re.finditer(rx, low): + c = col_of(m.group(1)) + if c and (c in numeric or c in names): + if not any(o["op"] == "agg" and o["fn"] == fn and o["col"] == c for o in ops): + ops.append({"op": "agg", "fn": fn, "col": c}) + own.add(m.group(1)) + elif fn == "sum" and len([x for x in numeric if x != gcol_hint]) == 1 and re.match(r"\s*(?:by|per|for)\b", low[m.end(1) - len(m.group(1)):][len(m.group(1)):]): + pass + # a word that is both an operation and a column of the table is the column where the sentence uses it as one + # ("whose count is below 3", "sorted by the total"): such a use does not ask for the operation + low_ops = re.sub(r"\b(?:whose|where|with|its|their|by|the)\s+([a-z_]+)\b(?!\s+of\b)", + lambda m: " COLUSE " if m.group(1) in ("count", "counts", "total", "totals", "sum", "number") and + _col(m.group(1), cols) else m.group(0), low) + if re.search(r"\btotals?\b", low_ops) and not any(o["op"] == "agg" and o["fn"] == "sum" for o in ops): + cand = [c for c in numeric if c != gcol_hint] + if len(cand) == 1: + ops.append({"op": "agg", "fn": "sum", "col": dmap.get(cand[0], cand[0])}) + if re.search(r"\b(?:count|counts|how many|number of)\b", low_ops): + ops.append({"op": "agg", "fn": "count", "col": None}) + CMPW = r"(?:over|above|more|greater|at|under|below|less|fewer)\b" + for m in re.finditer(r"\b(?:where|whose|with)\s+(?:the\s+|its\s+|their\s+)?" + COLW + + r"\s+(?:is|are|=|equals|equal to|of)\s+(?!" + CMPW + r")['\"`]?([\w.-]+)['\"`]?", low): + c = col_of(m.group(1)) + if c: + ops.append({"op": "filter", "col": c, "cmp": "==", "val": num(m.group(2))}) + own |= {m.group(1), m.group(2)} + for m in re.finditer(COLW + r"\s+(?:is\s+|are\s+)?(over|above|more than|greater than|at least|under|below|less than|fewer than|at most)\s+(-?\d+(?:\.\d+)?)", low): + c = col_of(m.group(1)) + if c: + cmp = {"over": ">", "above": ">", "more than": ">", "greater than": ">", "at least": ">=", "under": "<", + "below": "<", "less than": "<", "fewer than": "<", "at most": "<="}[m.group(2)] + ops.append({"op": "filter", "col": c, "cmp": cmp, "val": num(m.group(3))}) + own.add(m.group(1)) + m = re.search(r"\b(?:sort(?:ed|s)?|order(?:ed|s)?)\s+by\s+(?:the\s+|their\s+)?" + COLW + r"(\s+(?:descending|highest first|largest first|biggest first))?", low) + if m and col_of(m.group(1)): + ops.append({"op": "sort", "col": col_of(m.group(1)), "desc": bool(m.group(2))}) + own.add(m.group(1)) + elif re.search(r"\b(?:highest|largest|biggest|most)\s+first\b", low): + ops.append({"op": "sort", "col": None, "desc": True}) + elif re.search(r"\b(?:lowest|smallest|least)\s+first\b", low): + ops.append({"op": "sort", "col": None, "desc": False}) + m = re.search(r"\b(?:top|first)\s+(\d+)\b", low) + if m: + ops.append({"op": "top", "n": int(m.group(1))}) + return ops, own, derive + + +def _interaction_request(text): + """Receive record actions and a separately named relationship source.""" + visible = DATA.sub(lambda m: " " * len(m.group()), text) + edits = list(re.finditer(r"(?i)\beditable\b|\b(?:edit|modify|update|change)\s+(?:(?:the|these|my|each)\s+)?(?:records?|rows?|values|data)\b|\bread[- ]only\b", visible)) + edit = bool(edits and not NEGATED.search(visible[:edits[-1].start()].lower()) + and not re.fullmatch(r"(?i)read[- ]only", edits[-1].group())) + relations = list(re.finditer(r"(?i)\b(?:relationships?|connections?|edges|links)\b", visible)) + relation = relations[-1] if relations and not NEGATED.search(visible[:relations[-1].start()].lower()) else None + if not edits and not relations and not re.search(r"(?i)\binteractive\b", visible): + return None + edge, owned = None, set() + owned.update("interactive selecting select selection click controls control".split()) + if edits: + owned.update("editable edit modify update change edits changes editing modifying updating persist persists persistent save saving form fields field values read only".split()) + if relations: + owned.update("relationship relationships connection connections edge edges link links linked connect connecting draw drawing drawn between endpoint endpoints source target create remove delete adding add".split()) + if relation: + tail = text[relation.end():] + named = re.match(r"(?i)\s+(?:from|in|using|stored in)\s+`?([\w./-]+\.(?:csv|jsonl|json))\b", tail) + edge = {"file": named.group(1) if named else ".oracle7/relationships.csv", "create": not bool(named)} + suffix = tail[named.end():] if named else tail + cols = re.search(r"(?i)\b(?:using\s+|with\s+)?([a-z_]\w*)\s+(?:and|to|->)\s+([a-z_]\w*)\s+(?:as\s+)?(?:columns|endpoints)\b", suffix) + if cols: + edge.update({"from": cols.group(1), "to": cols.group(2)}) + owned.update(cols.groups()) + return {"edit": edit, "edges": edge, "owned": sorted(owned)} + + +def _source_contexts(shape, root): + """Resolve sources in command scope; a named command never borrows another's columns.""" + output_files = {m.group(1) for c in shape["clauses"] for m in sinks(c)} + groups = {"*": []} + for ci, clause in enumerate(shape["clauses"]): + for _off, sentence, entry in _segments(clause, list(ENTRY.finditer(clause))): + if entry in (None, "*"): + entry = shape.get("scope_fills", {}).get(str(ci), entry) + groups.setdefault(entry or "*", []).append(sentence) + texts = {name: " ".join(pieces) for name, pieces in groups.items()} + source_fills = shape.get("source_fills", {}) + interactions = {name: _interaction_request(text) for name, text in texts.items()} + auxiliary = {i["edges"]["file"] for i in interactions.values() if i and i.get("edges")} + primary = lambda text: DATA.sub(lambda m: " " * len(m.group()) if m.group(1) in auxiliary else m.group(), text) + default = PS.resolve(primary(texts["*"]), root, output_files=output_files, key_override=source_fills.get("*")) + default["interaction"] = interactions.get("*") + contexts = {} + for name, text in texts.items(): + if name != "*": + contexts[name] = PS.resolve(primary(text), root, fallback=default["source"], output_files=output_files, + key_override=source_fills.get(name)) + contexts[name]["explicit"] = bool(PS.input_files(primary(text), output_files)) + contexts[name]["interaction"] = interactions.get(name) or interactions.get("*") + distinct = {json.dumps(c["source"], sort_keys=True): c for c in contexts.values() if c.get("source")} + if not default["source"] and not default["holes"] and len(distinct) == 1: + inherited = next(iter(distinct.values())) + default = dict(inherited, explicit=False, ops_text=texts["*"]) + default.setdefault("explicit", bool(PS.input_files(primary(texts["*"]), output_files))) + contexts["*"] = default + for name in shape["entries"]: + if name not in contexts or (not contexts[name]["source"] and not contexts[name]["holes"]): + named = [m for m in contexts if m not in (name, "*") and contexts[m].get("source") and + re.search(r"(?i)\b(?:from|of|what)\s+`?" + re.escape(m) + r"`?\b", texts.get(name, ""))] + contexts[name] = dict(contexts[named[0]] if len(named) == 1 else default, explicit=False) + shape["sources"] = {n: c.get("source") for n, c in contexts.items()} + shape["auxiliary_inputs"] = sorted(auxiliary) + return contexts, output_files + + +def _source_ops_text(text, source): + """Matching keys select rows across tables; they are not a request to group the result.""" + if not source or source.get("op") not in ("join", "lookup"): + return text + columns = {c for pair in source.get("keys", []) for c in pair} + token = r"(?:[a-z_][\w]*\.)?(?:" + "|".join(re.escape(c) for c in sorted(columns)) + r")\b" + return re.sub(r"\b(?:matching\s+(?:(?:on|by)\s+)?|matched\s+(?:(?:on|by)\s+)?|on\s+)" + token + + r"(?:\s*(?:=|equals|to|with|,|and)\s*" + token + r")*", " ", text, flags=re.I) + + +def requirements(shape, root): + """the ledger: every requirement the clauses make, each with its kind, its entry, the words it came from; and the + holes reading leaves (words nobody owns, tables not there)""" + contexts, out_files = _source_contexts(shape, root) + shape["source_contexts"] = contexts + tables = {f: read_table(root, f) for c in shape["clauses"] for f in PS.input_files(c, out_files) if f not in shape.get("auxiliary_inputs", [])} + world = contexts["*"].get("world") or next((c["world"] for c in contexts.values() if c.get("world")), None) or \ + next(iter(tables.values()), None) + if world: + world = dict(world, hosts=sorted({h for w in tables.values() for h in w.get("hosts", [])})) + cols = (world or {}).get("cols", []) + numeric = (world or {}).get("numeric", []) + stems = set() + for f in list(tables): # C11: a table read names its rows ("each city in weather.csv"); a file written + b = Path(f).stem.lower() # names nothing else in the sentence ("the lively products ... to lively.csv") + stems |= {b} | set(re.findall(r"[a-z]+", b)) + noun = project_noun(shape) + entries = list(shape["entries"]) + reqs, holes = [], [] + derived_names = list((shape.get("derived") or {}).keys()) + meanings = shape.get("meanings") or {} + + ids = shape.setdefault("ids", {}) # a requirement's id is kept by what it is: a drop or a fill never renumbers the rest + + def add(kind, text, ci, entry=None, **kw): + key = (kind, kw.get("file"), kw.get("op_key"), entry if kind in ("served", "printed", "stored", "file", "op", "derive", "interaction") else None) + for r in reqs: + if r["key"] == list(key): + if text not in r["from"]: + r["from"].append(text) + old = {k: r.get(k) for k in kw if r.get(k) != kw[k]} + if old: # a later sentence's value replaces the earlier one ("5" -> "2") + r.setdefault("superseded", []).append(old) + r.update(kw) + r["clause"] = ci + return r + o = kw.get("op") + if kind == "op" and o and REVISE.search(shape["clauses"][ci]): + # a revision ("change it so ...", "instead", "now") names an operation the project already has on the same + # column: the new one replaces it, the old kept as superseded + same = [r for r in reqs if r["kind"] == "op" and r["entry"] == entry and r["clause"] < ci and r["op"]["op"] == o["op"] and + r["op"].get("col") == o.get("col") and r["op"].get("fn") == o.get("fn")] + if same: + r = same[-1] + r.setdefault("superseded", []).append({k: v for k, v in r["op"].items() if o.get(k) != v}) + r.update(kw) + r["key"], r["clause"] = list(key), ci + r["from"].append(text) + return r + kid = json.dumps(list(key)) + old_key = json.dumps([kind, kw.get("file"), kw.get("op_key"), None]) + if kid not in ids and kind in ("op", "derive") and old_key in ids and not any(r["id"] == ids[old_key] for r in reqs): + ids[kid] = ids[old_key] # retain requirement identity when an older single-source project is continued + if kid not in ids: + ids[kid] = "R%d" % (max([int(v[1:]) for v in ids.values()] or [0]) + 1) + r = {"id": ids[kid], "kind": kind, "entry": entry, "from": [text], "clause": ci, "key": list(key), + "status": "open"} + r.update(kw) + reqs.append(r) + return r + + for ci, clause in enumerate(shape["clauses"]): + hits = list(ENTRY.finditer(clause)) + for off, s, ent in _segments(clause, hits): + if ent in (None, "*"): + ent = shape.get("scope_fills", {}).get(str(ci), ent) + context = contexts.get(ent or "*", contexts["*"]) + # The original clauses remain the audit trail. An answered key hole + # retires only its old binding phrase from this reading, so an old + # misspelling cannot remain an unread requirement. Adjacent row + # operations and outcomes are still read normally. + for binding in context.get("retired_key_bindings", []): + s = re.sub(r"(? 1 + # a word given a meaning ("flags means the rows whose amount is over 100") is read as its meaning; a meaning + # that names nothing to do (no outcome, no operation, no value) leaves the word a hole that says so + unbound = [] + for w, v in meanings.items(): + if v and re.search(r"(?i)(?= 2: + head_ops = read_ops(s[:at[1]], cols, numeric, derived_names)[0] + for i in range(1, len(at)): + piece_ops = read_ops(s[at[i]:at[i + 1] if i + 1 < len(at) else len(s)], cols, numeric, derived_names)[0] + for o in ops: + if o["op"] in ("agg", "group", "top") and o not in head_ops and o in piece_ops: + scoped.setdefault(json.dumps(o, sort_keys=True), at[i]) + excluded = [(k, {x: y for x, y in kw.items() if x != "_at"}) for k, kw in excluded] + for k, kw in excluded: # an outcome the request rules out: judged as not done + add("excluded", s, ci, ent, what=k, op_key="not " + k + (" " + kw["file"] if kw.get("file") else ""), + **({"file": kw["file"]} if kw.get("file") else {})) + if not kinds and not props and not ops and not derive and not excluded: + if ci == 0 and (BUILD.search(s) or DATA.search(s)) and not unowned: + add("context", s, ci, None) + continue + if not unowned: + add("context", s, ci, None) + continue + out_at = {} + for k, kw in kinds: + tgt_entry = ent + out_at[kw.get("_at", 0)] = add(k, s, ci, tgt_entry, **{x: y for x, y in kw.items() if x != "_at"})["id"] + for k, kw in props: + add(k, s, ci, None, **kw) + if interaction and _interaction_request(s): + add("interaction", s, ci, ent, op_key="record actions", actions=interaction) + for o in ops: + ok_ = json.dumps(o, sort_keys=True) + if ok_ in scoped: + add("op", s, ci, op_entry, op=o, op_key=ok_ + " @" + out_at[scoped[ok_]], out=out_at[scoped[ok_]]) + else: + add("op", s, ci, op_entry, op=o, op_key=ok_) + for d in derive: + fn = "%s_of_%s" % (re.sub(r"\W+", "_", d["name"]).strip("_"), d["col"]) + add("derive", s, ci, ent, col=d["col"], name=d["name"], fn=fn, op_key=fn) + if unowned: + # its identity is the sentence it sits in, not which of its words are still unread: a word dropped or + # explained leaves the rest of the hole under the same id + r = add("unread", s, ci, ent, words=unowned, op_key="unread %d %d" % (ci, off)) + r["status"] = "hole" + for r in reqs: + if r["id"] in shape.get("dropped", []): + r["status"] = "dropped" + reqs.sort(key=lambda r: int(r["id"][1:])) + return reqs, world, tables + + +# ---------------------------------------------------------------- planning: entries, sources, links, holes +def _propose(shape, reqs): + """entries for a request that names none: one that does the work (named by its verb) and one that serves the page""" + outs = [r for r in reqs if r["kind"] in ("file", "stored", "printed", "served") and r["status"] != "dropped"] + if not outs: + return + text = " ".join(shape["clauses"]).lower() + if not shape.get("module"): + noun = project_noun(shape) + if not noun: # no name of its own: its table and what it makes + tbl = next((f for c in shape["clauses"] for f in DATA.findall(c)), "project") + noun = [re.sub(r"\W+", "_", Path(tbl).stem).strip("_") or "project", + "page" if all(r["kind"] == "served" for r in outs) else "report"] + shape["module"] = "_".join(noun[:3]) + ".py" + batch = [r for r in outs if r["kind"] != "served"] + served = [r for r in outs if r["kind"] == "served"] + entries = {} + if batch: + verb = next((v for v in ("check", "report", "export", "update", "summarize", "collect", "refresh", "scan", "import", + "sync", "build") if re.search(r"\b%s" % v, text)), "run") + entries[verb] = {"args": [], "proposed": True} + if served: + entries["serve"] = {"args": ["PORT"], "proposed": True} + shape["entries"] = entries + shape["proposed"] = True + bname = next((n for n in entries if n != "serve"), None) + for r in outs: + r["entry"] = "serve" if r["kind"] == "served" else bname + + +def _store_offer(fn, name, col, sample): + """a kept function of Oracle7's store for a value made from a column: lit on the spine by the words and the shape, + its name saying both the value and the column, its own evidence still holding""" + try: + sys.path.insert(0, str(Path(__file__).resolve().parent)) + import code_store as CS + entries = CS.load() + except Exception: # noqa: BLE001 + return None, [] + if not entries: + return None, [] + words = [stem(w) for w in re.findall(r"[a-z]+", name.lower())] + [stem(w) for w in re.findall(r"[a-z]+", col.lower())] + shp = "'int'" if isinstance(sample, int) else "'float'" if isinstance(sample, float) else "'str'" + try: + lit = [e for _r, e in CS.CodeFlash(entries).light([shp], None, words)] + except Exception: # noqa: BLE001 + lit = entries + by_sha = {e["sha256"]: e for e in entries} + for e in lit: + if len(e.get("params") or []) != 1: + continue + ew = [stem(w) for w in re.findall(r"[a-z]+", e["name"].lower())] + if not all(any(wmatch(w, x) for x in ew) for w in words): + continue + if e.get("in_shapes") and e["in_shapes"][0] not in (shp, "'int'", "'float'") and shp != "'str'": + continue + why = CS.replay(e, by_sha) + if why is None: + deps = [] + seen = set() + + def addd(x): + for _n, sha in (x.get("deps") or {}).items(): + d = by_sha.get(sha) + if d is not None and sha not in seen: + seen.add(sha) + addd(d) + deps.append(d) + addd(e) + return e, deps + return None, [] + + +def plan(shape, root): + """-> (pipes, holes, reqs, world). pipes: entry -> {source, ops, derive, sinks, links}; every open requirement tied + to the links that supply it, or a hole saying what would fill it""" + reqs, world, tables = requirements(shape, root) + if not shape["entries"]: + _propose(shape, reqs) + gone = {r["id"] for r in reqs if r["status"] == "dropped"} + for r in reqs: # an operation of one outcome goes when that outcome is dropped + if r.get("out") in gone and r["status"] != "dropped": + r["status"], r["dropped_with"] = "dropped", r["out"] + live = [r for r in reqs if r["status"] != "dropped"] + holes = [] + contexts = shape.get("source_contexts", {}) + for name, context in contexts.items(): + for hole in context.get("holes", []): + h = dict(hole, entry=name) + if not any(x.get("text") == h.get("text") for x in holes): + holes.append(h) + for r in live: + if r["kind"] == "scope": + holes.append({"kind": "scope", "req": r["id"], "clause": r["clause"], "entries": r["entries"], "text": "%s: which command does this correction belong to? Say its name: %s. The correction is kept." % (r["id"], ", ".join("`%s`" % n for n in r["entries"]))}) + if r["kind"] == "unread": + given = [(w, shape["meanings"][w]) for w in r["words"] if (shape.get("meanings") or {}).get(w)] + if given: + holes.append({"kind": "unread", "req": r["id"], "words": r["words"], + "text": "%s: you said %s, but I can't read that as something to do: no file, page, database, " + "printing or operation on the rows. Say it as one (\"%s means the rows whose ... is " + "over ...\"), or \"drop %s\"." % (r["id"], "; ".join("'%s' means '%s'" % g for g in given), + given[0][0], r["id"][1:])}) + continue + holes.append({"kind": "unread", "req": r["id"], "words": r["words"], + "text": "%s: I don't know what %s means here (\"%s\"). Say what it means (\"%s means ...\"), or " + "\"drop %s\"." % (r["id"], ", ".join("'%s'" % w for w in r["words"]), r["from"][0][:140], + r["words"][0], r["id"][1:])}) + for f, w in (tables or {}).items(): + if w.get("missing"): + holes.append({"kind": "world", "file": f, "text": "%s is not in the project yet. Add it and say \"continue\"." % f}) + elif w.get("unreadable"): + holes.append({"kind": "world", "file": f, "text": "%s could not be read as a table (%s)." % (f, w["unreadable"])}) + if not world and any(r["kind"] in ("file", "stored", "served", "printed") for r in live): + holes.append({"kind": "world", "text": "the request names no table of the project (a .csv or .json file) to work from."}) + for r in live: + if r["kind"] == "file" and any(Path(root, r.get("file", "")).resolve() == Path(root, f).resolve() for f in tables): + holes.append({"kind": "outcome", "req": r["id"], + "text": "%s: writing to %s would replace the table the project reads. Name another file to write " + "(\"... to out.csv\"), or \"drop %s\"." % (r["id"], r["file"], r["id"][1:])}) + entries = shape["entries"] + names = list(entries) + if not names: + holes.append({"kind": "outcome", "text": "nothing in the request is an outcome I can observe (a file written, rows kept " + "in a database, a page in the browser, lines printed)."}) + return {}, holes, reqs, world + serve_name = next((n for n in names if "PORT" in entries[n]["args"]), None) + if serve_name is None and any(r["kind"] == "served" for r in live): + # a page asked of a project whose commands all run and stop: a command that serves it is proposed beside them + entries["serve"] = {"args": ["PORT"], "proposed": True} + names.append("serve") + serve_name = "serve" + for r in live: + if r["kind"] == "served": + r["entry"] = None + batch_names = [n for n in names if n != serve_name] or names[:1] + for r in live: # an outcome named before any entry, or added later: its entry by kind + if r["kind"] == "interaction" and (r["entry"] not in names or "PORT" not in entries[r["entry"]]["args"]): + r["entry"] = serve_name or batch_names[0] + if r["kind"] in ("file", "stored", "served", "printed") and (r["entry"] in (None, "*") or r["entry"] not in names): + r["entry"] = serve_name if r["kind"] == "served" and serve_name else batch_names[0] + if r["kind"] in ("op", "derive") and r["entry"] not in names: + r["entry"] = "*" + first = {} + for r in live: # the same outcome asked again (a change saying "on the page"): one record + if r["kind"] in ("file", "stored", "served", "printed"): + k = (r["kind"], r.get("file"), r["entry"]) + if k in first: + first[k]["from"] += [x for x in r["from"] if x not in first[k]["from"]] + r["status"] = "dropped" + r["merged_into"] = first[k]["id"] + else: + first[k] = r + live = [r for r in live if r["status"] != "dropped"] + probe_words = PART_WORDS["probe"] - {"answer", "answers", "answered", "up", "down", "status", "server", "servers"} + pipes = {} + stores = {} + for n in names: + outs = [r for r in live if r["entry"] == n and r["kind"] in ("file", "stored", "served", "printed")] + words = " ".join(x for r in live if r["entry"] in (n, "*") for x in r["from"]).lower() + context = contexts.get(n, contexts.get("*", {})) + pw = context.get("world") or {} + probe = bool(pw.get("url") and any(re.search(r"\b%s\b" % w, words) for w in probe_words)) + has_store = any(r["kind"] == "stored" for r in outs) + stores[n] = (probe, has_store) + pipes[n] = {"outs": [r["id"] for r in outs], "probe": probe, "input": context.get("source"), + "world": pw, "explicit_source": context.get("explicit", False)} + store_names = [n for n in names if stores[n][1]] + for n in store_names: + table_name = "results_" + re.sub(r"\W", "_", n) + if sum(re.sub(r"\W", "_", m) == re.sub(r"\W", "_", n) for m in store_names) > 1: + table_name += "_" + hashlib.sha256(n.encode()).hexdigest()[:8] + pipes[n]["store_table"] = "results" if len(store_names) == 1 else table_name + for n in names: + p = pipes[n] + pw = p["world"] + outs = [r for r in live if r["id"] in p["outs"]] + only_view = outs and all(r["kind"] in ("served", "printed") for r in outs) + other_stores = [m for m in names if m != n and stores[m][1]] + view_words = " ".join(x for r in outs for x in r["from"]) + named_stores = [m for m in other_stores if re.search(r"(?i)\b(?:from|of|what)\s+`?" + re.escape(m) + r"`?\b", view_words)] + other_store = named_stores[0] if len(named_stores) == 1 else other_stores[0] if len(other_stores) == 1 else None + if only_view and not p["explicit_source"] and len(other_stores) > 1 and other_store is None: + holes.append({"kind": "source", "entry": n, "text": "`%s` could read several stored results; name the command it reads from: %s." % (n, ", ".join(other_stores))}) + if only_view and other_store and not p["explicit_source"]: + src = "stored" # a view of what another command keeps reads it back + elif p["probe"]: + src = "probe" + else: + src = "table" + p["source"] = src + p["numeric"] = list(pw.get("numeric") or []) + # a proposed view of a project that keeps nothing shows what the project's commands compute: their operations + inherit = [m for m in names if m != n and pipes[m].get("input") == p.get("input")] if entries[n].get("proposed") and only_view and src == "table" else [] + p["ops"] = [r["op"] for r in live if r["kind"] == "op" and r["entry"] in [n, "*"] + inherit and not r.get("out")] \ + if src != "stored" else [] + p["out_ops"] = {} # C11: the operations one outcome asks for itself + for r in live: + if r["kind"] == "op" and r.get("out") in p["outs"]: + p["out_ops"].setdefault(r["out"], []).append(r["op"]) + p["derive"] = [r for r in live if r["kind"] == "derive" and r["entry"] in [n, "*"] + inherit] if src == "table" else [] + for operation in p["ops"] + [o for operations in p["out_ops"].values() for o in operations]: + if operation["op"] == "calculate" and pw.get("n", 0) and any(c not in p["numeric"] for c in (operation["left"], operation["right"])): + holes.append({"kind": "source", "entry": n, "text": "`%s` needs numeric values in both %s and %s to calculate %s. Correct those input values and continue." % (n, operation["left"], operation["right"], operation["col"])}) + if src == "stored" and other_store: + p["ops"] = [r["op"] for r in live if r["kind"] == "op" and r["entry"] == n and not r.get("out")] + p["from"] = other_store + p["store_probe"] = stores[other_store][0] + p["store_table"] = pipes[other_store].get("store_table", "results") + p["input"], p["world"] = pipes[other_store]["input"], pipes[other_store]["world"] + pw = p["world"] + p["numeric"] = list(pw.get("numeric") or []) + if p["store_probe"] and (p["ops"] or p["out_ops"]): + holes.append({"kind": "part", "entry": n, "text": "`%s` asks to transform stored probe results; say whether to use all history or only the latest result per server before that transformation." % n}) + if src != "stored" and not p.get("input") and p["outs"]: + holes.append({"kind": "source", "entry": n, "text": "`%s` needs an input table or an explicitly named combination of tables." % n}) + links = [] + if src == "probe": + links += [{"part": "table", "why": "the servers are listed in %s" % pw["file"]}, + {"part": "probe", "why": "each row's url is asked once"}] + elif src == "table": + graph = p.get("input") or {} + relationship = graph.get("op", "read") + why = "%s: %s" % (relationship, ", ".join(PS.files(graph)) or "the table") + if graph.get("keys"): + why += " matching " + ", ".join("%s = %s" % tuple(k) for k in graph["keys"]) + links.append({"part": "table", "why": why}) + else: + links += [{"part": "db", "why": "the rows `%s` keeps" % other_store}] + if stores[other_store][0]: + links.append({"part": "latest", "why": "each row's most recent results are read back"}) + for d in p["derive"]: + links.append({"part": "derive", "why": "%s made from %s" % (d["name"], d["col"]), "req": d["id"]}) + if p["ops"]: + links.append({"part": "compute", "why": "; ".join(_op_text(o) for o in p["ops"])}) + for r in outs: + part = {"file": "export", "stored": "keep", "served": "page", "printed": "print"}[r["kind"]] + if p["out_ops"].get(r["id"]): + links.append({"part": "compute", "why": "for %s only: %s" % (r["id"], "; ".join( + _op_text(o) for o in p["out_ops"][r["id"]])), "req": r["id"]}) + links.append({"part": part, "why": {"file": "written to %s" % r.get("file"), "stored": "kept in the project's database", + "served": "laid out as a page", "printed": "printed"}[r["kind"]], "req": r["id"]}) + if part == "page": + links.append({"part": "serve", "why": "served to a browser on PORT", "req": r["id"]}) + p["links"] = links + if src == "stored" and not stores[other_store][0]: + p["record_fields"] = None + if any(p["source"] == "probe" for p in pipes.values()): + for n, p in pipes.items(): + if p["ops"] and p["source"] == "probe": + holes.append({"kind": "part", "text": "`%s %s`: %s of probe results is not a part I have yet." % ( + shape["module"], n, _op_text(p["ops"][0]))}) + pw = p.get("world", {}) + if p["source"] == "probe" and not (pw.get("url") and pw.get("key")): + holes.append({"kind": "world", "text": "%s has no column of urls and one of names (columns: %s)" % ( + pw.get("file"), ", ".join(pw.get("cols", [])))}) + # values made from a column: the store first, then the composer from examples + derived = shape.setdefault("derived", {}) + for r in live: + if r["kind"] != "derive": + continue + fn = r["fn"] + if fn in derived: + continue + sample = num((pipes.get(r["entry"], {}).get("world") or world or {}).get("sample", {}).get(r["col"])) + e, deps = _store_offer(fn, r["name"], r["col"], sample) + if e is not None and (e["sha256"] == (shape.get("use") or {}).get(fn) or _names_equal(e["name"], fn)): + derived[fn] = {"name": r["name"], "col": r["col"], "fn": e["name"], "source": e["source"], "sha256": e["sha256"], + "imports": e.get("imports") or [], "deps": [{"name": d["name"], "source": d["source"], + "sha256": d["sha256"]} for d in deps], + "from": "store", "project": e.get("project"), "id": e["id"]} + continue + exs = (shape.get("examples") or {}).get(fn) + if not exs: # C11: examples given in the sentence that asked for the value + got = [[_lit(a), _lit(b)] for t in r["from"] for a, b in EXAMPLE.findall(t)] + if len(got) >= 3: + exs = shape.setdefault("examples", {})[fn] = got + if exs and len(exs) >= 3: + holes.append({"kind": "compose", "req": r["id"], "fn": fn, "col": r["col"], "name": r["name"], "examples": exs, + "text": "%s: %s made from %s - composing it from the %d examples given." % ( + r["id"], r["name"], r["col"], len(exs))}) + continue + h = {"kind": "derive", "req": r["id"], "fn": fn, "col": r["col"], "name": r["name"], + "text": "%s: no part I have makes %s from %s (\"%s\"). Give three examples of %s -> %s (like `%s -> ...`), " + "and I compose it and keep it." % (r["id"], r["name"], r["col"], r["from"][0][:120], r["col"], r["name"], + sample if sample is not None else "...")} + if e is not None: + h["offer"] = {"name": e["name"], "sha256": e["sha256"], "project": e.get("project")} + h["text"] += " My store has %s (sha %s, kept from %s): say \"use it\" if that is what you mean." % ( + e["name"], e["sha256"][:12], e.get("project") or "earlier work") + holes.append(h) + if any(r["kind"] == "served" for r in live): + shape["design"] = design_for([r for r in live if r["kind"] == "look"]) + for r in live: + if r["kind"] != "interaction": + continue + p = pipes.get(r["entry"], {}) + if not p.get("input"): + continue + try: + if p.get("source") != "table": + raise PI.InteractionError("name the source records to edit; a stored history or probe result is not its source record") + actions = (contexts.get(r["entry"]) or contexts.get("*") or {}).get("interaction") or r["actions"] + edges = dict(actions["edges"]) if actions.get("edges") else None + if edges and not all(edges.get(k) for k in ("from", "to")): + if edges.get("create"): + edges.update({"from": "source", "to": "target", "label": "label"}) + else: + edge_columns, _edge_rows = PS.source_snapshot({"op": "read", "file": edges["file"]}, root) + pairs = [(a, b) for a, b in (("source", "target"), ("from", "to"), ("source_id", "target_id"), + ("from_id", "to_id"), ("parent", "child")) if a in edge_columns and b in edge_columns] + if len(pairs) != 1: + raise PI.InteractionError("name the relationship endpoints: relationships from %s using COLUMN and COLUMN as endpoints" % edges["file"]) + edges.update({"from": pairs[0][0], "to": pairs[0][1]}) + if "label" in edge_columns: + edges["label"] = "label" + if any(o["op"] in ("agg", "group") for o in p.get("ops", [])): + raise PI.InteractionError("give the editor a view of individual source records; grouped totals have several owning records") + shown = expected_rows(root, world, p, shape.get("derived") or {}) + identity = next(iter(shown[0]), None) if shown else next(iter(p["world"].get("cols", [])), None) + p["interaction"] = PI.plan_interaction(root, p["input"], shown, identity=identity, + editable=None if actions["edit"] else [], edges=edges) + r["binding"] = p["interaction"] + p["links"].append({"part": "record actions", "why": "selection, source edits and relationships share the displayed record identities", "req": r["id"]}) + except (ValueError, OSError, KeyError, TypeError, AttributeError) as error: + holes.append({"kind": "interaction", "req": r["id"], "text": "%s: %s" % (r["id"], error)}) + shape["status"] = "blocked" if holes else "planned" + shape["holes_kept"] = holes + return pipes, holes, reqs, world + + +def _names_equal(a, b): + wa = sorted(stem(w) for w in re.findall(r"[a-z]+", a.lower())) + wb = sorted(stem(w) for w in re.findall(r"[a-z]+", b.lower())) + return wa == wb + + +def _op_text(o): + if o["op"] == "calculate": + return "%s made as %s %s %s" % (o["col"], o["left"], {"mul": "times", "add": "plus", "sub": "minus", + "div": "divided by"}.get(o.get("fn"), "?"), o["right"]) + if o["op"] == "group": + return "grouped by %s" % o["col"] + if o["op"] == "agg": + return {"sum": "total", "mean": "average", "max": "largest", "min": "smallest", "count": "count"}[o["fn"]] + \ + ("" if o["col"] is None else " of %s" % o["col"]) + if o["op"] == "filter": + return "only rows whose %s %s %s" % (o["col"], o["cmp"], o["val"]) + if o["op"] == "sort": + return "sorted by %s%s" % (o["col"] or "the summary", ", highest first" if o["desc"] else "") + if o["op"] == "top": + return "the first %d" % o["n"] + return str(o) + + +def sort_col(o, p, aggs): + """what "highest first" sorts by when the request names no column: the summary it asks for, else the value it makes + from a column, else the table's one column of numbers""" + if o.get("col"): + return o["col"] + if aggs: + return agg_name(aggs[0]) + if p.get("derive"): + return p["derive"][-1]["name"] + nums = p.get("numeric") or [] + return nums[0] if len(nums) == 1 else None + + +def agg_name(o): + if o["fn"] == "count": + return "count" + return {"sum": "total", "mean": "average", "max": "largest", "min": "smallest"}[o["fn"]] + "_" + o["col"] + + +def settings(reqs): + s = {"timeout": 10.0, "error_down": False, "ms": False, "timed": False, "keep_last": 1} + for r in reqs: + if r["status"] == "dropped": + continue + if r["kind"] == "timeout": + s["timeout"] = r["seconds"] + elif r["kind"] == "error_down": + s["error_down"] = True + elif r["kind"] == "ms": + s["ms"] = True + elif r["kind"] == "timestamp": + s["timed"] = True + elif r["kind"] == "keep_last": + s["keep_last"] = max(s["keep_last"], r["n"]) + return s + + +# ---------------------------------------------------------------- writing: each part's code +def write(shape, pipes, reqs, world): + st = settings(reqs) + mod = shape["module"] + db = Path(mod).stem + ".db" + probe = any(p["source"] == "probe" or p.get("store_probe") for p in pipes.values()) + derived = shape.get("derived") or {} + used_fns = [derived[d["fn"]] for p in pipes.values() for d in p.get("derive", []) if d["fn"] in derived] + imports = sorted({"csv", "html", "http.server", "json", "sqlite3", "sys", "time"} | + ({"urllib.error", "urllib.request"} if probe else set()) | + {i for f in used_fns for i in f.get("imports") or []}) + parts_used = sorted({l["part"] for p in pipes.values() for l in p["links"]}) + L = ['"""%s - written by Oracle7 from the request (its parts: %s)."""' % (mod, ", ".join(parts_used))] + L += ["import %s" % i for i in imports] + ["", ""] + default_input = (world or {}).get("source") or {"op": "read", "file": world["file"]} + L += PS.runtime_source().splitlines() + ["", ""] + if any(p.get("interaction") for p in pipes.values()): + L += PI.runtime_source().splitlines() + ["", ""] + L += ["TABLE = %r" % world["file"], "DEFAULT_INPUT = %r" % default_input, "DB = %r" % db] + if probe: + fields = ["key", "url", "at", "status", "code", "error"] + (["ms"] if st["ms"] else []) + probe_world = next((p.get("world") or world for p in pipes.values() if p["source"] == "probe"), world) + L += ["KEY, URL = %r, %r" % (probe_world["key"], probe_world["url"]), "TIMEOUT = %r" % st["timeout"]] + else: + fields = None + L += ["KEEP_LAST = %d" % st["keep_last"], "", ""] + L += ["def table(source=None):", ' """the rows of a named source shape, read afresh"""', + " return read_source(DEFAULT_INPUT if source is None else source)", "", "", + "def num(v):", ' """a number written as text, read as a number; other values as they are"""', + " if isinstance(v, (int, float)) and not isinstance(v, bool):", " return v", + " s = str(v).strip()", " try:", " return int(s)", " except ValueError:", " pass", + " try:", " return float(s)", " except ValueError:", " return v", "", ""] + if probe: + L += _emit_probe(st) + for f in used_fns: + for d in f.get("deps") or []: + L += ["# kept function %s from Oracle7's store (sha %s)" % (d["name"], d["sha256"][:16])] + d["source"].splitlines() + ["", ""] + L += ["# %s: %s made from %s - %s (sha %s)" % ( + f["fn"], f["name"], f["col"], "kept function from Oracle7's store, from %s" % (f.get("project") or "earlier work") + if f.get("from") == "store" else "composed by Oracle7's code composer from the examples given", f["sha256"][:16])] + L += f["source"].splitlines() + ["", ""] + for n, p in pipes.items(): + if p["source"] in ("table", "stored"): + provider = pipes.get(p.get("from"), p) + stored_rows = "stored(%r)" % provider.get("store_table", p.get("store_table", "results")) if p["source"] == "stored" else None + L += _emit_compute(n, p, derived, stored_rows) + for rid in p.get("out_ops") or {}: + L += _emit_compute(n, view(p, rid), derived, stored_rows, rid) + rec_fields = {} + store_tables = {} + for n, p in pipes.items(): + if any(r["kind"] == "stored" for r in reqs if r["id"] in p["outs"]): + sr = next(r["id"] for r in reqs if r["id"] in p["outs"] and r["kind"] == "stored") + rec_fields[n] = list(dict.fromkeys(fields if p["source"] == "probe" else + out_columns(view(p, sr), p.get("world") or world, derived) + ["at"])) + store_tables[p.get("store_table", "results")] = rec_fields[n] + if not store_tables: + store_tables["results"] = fields if probe else ["at"] + L += ["STORE_FIELDS = %r" % store_tables, + "FIELDS = %r" % (fields if probe else next(iter(rec_fields.values()), ["at"])), "", "", + "def _qid(value):", " return chr(34) + str(value).replace(chr(34), chr(34) * 2) + chr(34)", "", "", + "def connect(store='results'):", ' """one named result table per source command; previous rows stay"""', + " fs = STORE_FIELDS[store]", + " c = sqlite3.connect(DB)", + " c.execute('create table if not exists %s (%s)' % (_qid(store), ', '.join(_qid(f) for f in fs)))", + " have = [r[1] for r in c.execute('pragma table_info(%s)' % _qid(store))]", + " for f in fs:", " if f not in have:", " c.execute('alter table %s add column %s' % (_qid(store), _qid(f)))", + " return c", "", "", + "def keep(rows, store='results'):", ' """every row kept in its command\'s table, with its time"""', + " c = connect(store)", " fs = STORE_FIELDS[store]", " at = time.strftime('%Y-%m-%d %H:%M:%S')", + " with c:", " for r in rows:", " r.setdefault('at', at)", + " c.execute('insert into %s (%s) values (%s)' % (_qid(store), ', '.join(_qid(f) for f in fs), ', '.join('?' * len(fs))),", + " [r.get(f) for f in fs])", " c.close()", " return len(rows)", "", "", + "def stored(store='results'):", ' """every row in this command\'s table, oldest first"""', " c = connect(store)", + " fs = STORE_FIELDS[store]", + " rows = [dict(zip(fs, x)) for x in c.execute('select %s from %s order by rowid' % (', '.join(_qid(f) for f in fs), _qid(store)))]", + " c.close()", " return rows", "", ""] + head, why = design_head(shape.get("design")) + L += ["DOC = %r" % '%s', + "# the look: Oracle7's design family (palette, type, layout, motion): " + why, + "HEAD = %r" % head, "STAGE = %r" % (tuple((shape.get("design") or {}).get("stage") or ()) or None,), "", ""] + if probe: + L += _emit_latest_page(st) + L += ["def scene_records(rows):", + ' """the records a scene is bound to (12.0 C12): each row\'s id (its first column) and value (the first column after', + ' it whose values are all numbers), in the page\'s order"""', + " cols = []", " for r in rows:", " for k in r:", " if k not in cols:", " cols.append(k)", + " if not cols:", " return []", + " vc = next((c for c in cols[1:] if c != 'at' and rows and all(isinstance(num(r.get(c)), (int, float)) for r in rows)), None)", + " return [{'id': str(r.get(cols[0])), 'v': num(r.get(vc)) if vc else None} for r in rows]", "", ""] + L += ["def page_rows(rows, title):", ' """the rows as a page: one line each, the columns side by side"""', + " cols = []", " for r in rows:", " for k in r:", " if k not in cols:", " cols.append(k)", + " head = ''.join('%s' % html.escape(str(c)) for c in cols)", + " body = ''.join('%s' % (html.escape(str(r.get(cols[0]))), ''.join(", + " '%s' % html.escape('' if r.get(c) is None else str(r.get(c))) for c in cols)) for r in rows)", + " stage = (STAGE[1] + STAGE[2].replace('__ROWS__', json.dumps(scene_records(rows)).replace('

    %s

    ' % html.escape(title) + stage +", + " '%s%s
    ' % (head, body, record_json))", "", "", + "def serve(port, render):", ' """the page, served on loopback; made afresh on every visit"""', + " class H(http.server.BaseHTTPRequestHandler):", " def do_GET(self):", + " b = render().encode()", " self.send_response(200)", + " self.send_header('Content-Type', 'text/html; charset=utf-8')", " self.end_headers()", + " self.wfile.write(b)", "", " def log_message(self, *a):", " pass", "", + " http.server.ThreadingHTTPServer(('127.0.0.1', port), H).serve_forever()", "", "", + "def export(rows, path, columns=()):", ' """the rows written to a file; an empty CSV still declares its columns"""', + " cols = []", " for r in rows:", " for k in r:", " if k not in cols:", " cols.append(k)", + " if not cols:", " cols = list(columns)", + " if path.endswith('.json'):", " json.dump(rows, open(path, 'w'), indent=1, default=str)", " return len(rows)", + " with open(path, 'w', newline='') as f:", " w = csv.DictWriter(f, fieldnames=cols)", " w.writeheader()", + " for r in rows:", " w.writerow(r)", " return len(rows)", "", ""] + own_name = [w for w in project_noun(shape) if w not in ("page", "site", "website", "tool", "project", "app", "view") + and w not in PART_WORDS["design"]] # the look's words describe the page, they do not name it + title = " ".join(w.capitalize() for w in (own_name or re.findall(r"[a-z]+", Path(world["file"]).stem.lower()) or + [Path(mod).stem])).replace("_", " ") # a generic noun names nothing: the table + L += ["TITLE = %r" % title, "", "", "def main(argv):"] + for n, p in pipes.items(): + outs = [r for r in reqs if r["id"] in p["outs"]] + provider = pipes.get(p.get("from"), p) + store_table = provider.get("store_table", "results") if p["source"] == "stored" else p.get("store_table", "results") + input_shape = p.get("input") or default_input + L.append(" if argv[:1] == [%r]:" % n) + if p["source"] == "probe": + pw = p.get("world") or world + L.append(" rows = probe(table(%r), key=%r, url=%r)" % (input_shape, pw["key"], pw["url"])) + elif p["source"] in ("table", "stored"): + L.append(" rows = compute_%s()" % _compute_ident(n)) + else: + L.append(" rows = stored(%r)" % store_table) + for r in outs: + if r["kind"] == "stored": + L.append(" print('%%d rows kept in %%s' %% (keep(%s, %r), DB))" % (_rows_for(n, p, r["id"]), p.get("store_table", "results"))) + for r in outs: + if r["kind"] == "file": + src = "stored(%r)" % store_table if (r.get("every") and any(x["kind"] == "stored" for x in outs)) else _rows_for(n, p, r["id"]) + cols = (store_tables[store_table] if r.get("every") and any(x["kind"] == "stored" for x in outs) else + fields if p["source"] == "probe" or p.get("store_probe") else + out_columns(view(p, r["id"]), p.get("world") or world, derived)) + L.append(" print('%%d rows written to %%s' %% (export(%s, %r, %r), %r))" % (src, r["file"], cols, r["file"])) + for r in outs: + if r["kind"] == "printed": + L.append(" for r in %s:" % _rows_for(n, p, r["id"])) + L.append(" print(' '.join('%s %s' % (k, v) for k, v in r.items() if k != 'at'))") + served = [r for r in outs if r["kind"] == "served"] + if served: + if p.get("interaction"): + compute = "compute_%s" % _compute_ident(n, served[0]["id"] if (p.get("out_ops") or {}).get(served[0]["id"]) else None) + L.append(" return serve_interactive(int(argv[1]) if len(argv) > 1 else 8000, lambda: page_rows(%s(), TITLE), %r, %s)" % (compute, p["interaction"], compute)) + elif (p["source"] == "stored" and p.get("store_probe") and not p.get("ops") and + not p.get("derive") and not (p.get("out_ops") or {}).get(served[0]["id"])): + pw = provider.get("world") or world + L.append(" return serve(int(argv[1]) if len(argv) > 1 else 8000, lambda: page_latest(%r, %r, %r))" % ( + provider.get("input") or default_input, pw["key"], store_table)) + elif p["source"] in ("table", "stored"): + L.append(" return serve(int(argv[1]) if len(argv) > 1 else 8000, lambda: page_rows(compute_%s(), TITLE))" + % _compute_ident(n, served[0]["id"] if (p.get("out_ops") or {}).get(served[0]["id"]) else None)) + else: + L.append(" return serve(int(argv[1]) if len(argv) > 1 else 8000, lambda: page_rows(rows, TITLE))") + L.append(" return 0") + usage = " | ".join("%s %s%s" % (mod, n, "".join(" " + a for a in e["args"])) for n, e in shape["entries"].items()) + L += [" print(%r)" % ("usage: " + usage), " return 2", "", "", + "if __name__ == '__main__':", " sys.exit(main(sys.argv[1:]))", ""] + return "\n".join(L) + + +def _ident(n): + # Separate namespaces keep e.g. `report-a` distinct from `report_a`, even + # when an ordinary command happens to contain an encoded-looking suffix. + return "w_" + n if re.fullmatch(r"\w+", n) else "e_" + n.encode("utf-8").hex() + + +def _compute_ident(name, outcome=None): + if outcome is None: + return "entry_" + _ident(name) + # Encoding each component makes a command named `report__r1` different + # from the outcome r1 of report, with no separator ambiguity. + return "outcome_" + name.encode("utf-8").hex() + "_" + outcome.encode("utf-8").hex() + + +def view(p, rid): + """the pipe as one outcome sees it: the command's operations, then the ones that outcome asked for itself (C11)""" + own = (p.get("out_ops") or {}).get(rid) if p else None + return dict(p, ops=list(p["ops"]) + list(own)) if own else p + + +def _rows_for(n, p, rid): + return "compute_%s()" % _compute_ident(n, rid) if (p.get("out_ops") or {}).get(rid) else "rows" + + +def out_columns(p, world, derived): + ops = p.get("ops") or [] + g = next((o["col"] for o in ops if o["op"] == "group"), None) + aggs = [o for o in ops if o["op"] == "agg"] + if aggs: + return ([g] if g else []) + [agg_name(o) for o in aggs] + world = p.get("world") or world + return list(dict.fromkeys(list((world or {}).get("cols", [])) + + [d["name"] for d in p.get("derive", []) if d["fn"] in derived] + + [o["col"] for o in ops if o["op"] == "calculate"])) + + +def _emit_compute(n, p, derived, rows_expr=None, outcome=None): + """the operations, in the order a reader would do them: values made, rows kept, grouped and summed, sorted, cut""" + if rows_expr is None: + rows_expr = "table(%r)" % p["input"] if p.get("input") else "table()" + L = ["def compute_%s():" % _compute_ident(n, outcome), ' """%s"""' % ("; ".join(_op_text(o) for o in p["ops"]) or "the rows as they are"), + " rows = " + rows_expr] + for d in p.get("derive", []): + f = derived.get(d["fn"]) + if f: + L += [" for r in rows:", " r[%r] = %s(num(r[%r]))" % (d["name"], f["fn"], d["col"])] + for o in p["ops"]: + if o["op"] == "calculate": + if o.get("fn") not in ("mul", "add", "sub", "div"): + raise ValueError("calculation part %r is not represented" % o.get("fn")) + L += [" for r in rows:", " factors = [num(r[%r]), num(r[%r])]" % (o["left"], o["right"]), + " if any(isinstance(v, bool) or not isinstance(v, (int, float)) or (isinstance(v, float) and not _source_math.isfinite(v)) for v in factors):", + " raise ValueError(%r)" % ("%s requires finite numeric values in %s and %s" % (o["col"], o["left"], o["right"])), + " if %r == 'div' and factors[1] == 0:" % o.get("fn"), + " raise ValueError(%r)" % ("%s divides by a zero %s" % (o["col"], o["right"])), + " value = %s" % {"mul": "factors[0] * factors[1]", "add": "factors[0] + factors[1]", + "sub": "factors[0] - factors[1]", "div": "factors[0] / factors[1]"}[o.get("fn", "mul")], + " if isinstance(value, float) and not _source_math.isfinite(value):", + " raise ValueError(%r)" % ("%s exceeds the finite numeric range" % o["col"]), + " r[%r] = value" % o["col"]] + for o in p["ops"]: + if o["op"] == "filter": + L.append(" rows = [r for r in rows if _cmp(num(r[%r]), %r, %r)]" % (o["col"], o["cmp"], o["val"])) + g = next((o["col"] for o in p["ops"] if o["op"] == "group"), None) + aggs = [o for o in p["ops"] if o["op"] == "agg"] + if aggs: + L += [" groups = {}", " for r in rows:", + " groups.setdefault(%s, []).append(r)" % ("r[%r]" % g if g else "None"), " out = []", + " for k, rs in groups.items():", " o = {%s}" % ("%r: k" % g if g else "")] + for o in aggs: + nm = agg_name(o) + if o["fn"] == "count": + L.append(" o[%r] = len(rs)" % nm) + else: + vals = "[num(r[%r]) for r in rs]" % o["col"] + L.append(" o[%r] = %s" % (nm, {"sum": "round(sum(%s), 10)" % vals, "mean": "round(sum(%s) / len(rs), 10)" % vals, + "max": "max(%s)" % vals, "min": "min(%s)" % vals}[o["fn"]])) + L += [" out.append(o)", " rows = out"] + for o in p["ops"]: + if o["op"] == "sort": + col = sort_col(o, p, aggs) + if col: + L.append(" rows.sort(key=lambda r: num(r[%r]), reverse=%r)" % (col, o["desc"])) + for o in p["ops"]: + if o["op"] == "top": + L.append(" rows = rows[:%d]" % o["n"]) + L += [" return rows", "", "", + "def _cmp(a, op, b):", " if isinstance(a, str) or isinstance(b, str):", " a, b = str(a).lower(), str(b).lower()", + " return {'==': a == b, '>': a > b, '<': a < b, '>=': a >= b, '<=': a <= b}[op]", "", ""] + return L + + +def _emit_probe(st): + L = ["def probe(rows, key=KEY, url=URL):", + ' """each url asked once; no answer within TIMEOUT s%s is down, and the others go on"""' % ( + ", or an error status," if st["error_down"] else ""), + " out = []", " for r in rows:", + " t0 = time.time()", " res = {'key': r[key], 'url': r[url], 'at': time.strftime('%Y-%m-%d %H:%M:%S'),", + " 'status': 'down', 'code': None, 'error': None}", + " try:", " with urllib.request.urlopen(r[url], timeout=TIMEOUT) as a:", + " res['code'] = a.status", " res['status'] = 'up'", + " except urllib.error.HTTPError as e:", " res['code'] = e.code", + " res['error'] = 'HTTP %d' % e.code" if st["error_down"] else + " res['status'], res['error'] = 'up', 'HTTP %d' % e.code", + " except Exception as e: # noqa: BLE001 (no answer in time, refused, unreachable)", + " res['error'] = type(e).__name__ + ': ' + str(e)[:120]"] + if st["ms"]: + L += [" if res['status'] == 'up':", " res['ms'] = round((time.time() - t0) * 1000)", + " else:", " res['ms'] = None"] + L += [" out.append(res)", " return out", "", ""] + return L + + +def _emit_latest_page(st): + shown = ["status", "at"] + (["ms"] if st["ms"] else []) + ["code", "error"] + heads = ["current", "previous"] if st["keep_last"] == 2 else ["result %d" % (i + 1) for i in range(st["keep_last"])] + return ["def latest(source=None, key=KEY, store='results'):", ' """each server\'s last KEEP_LAST results, newest first, in its source\'s order"""', + " c = connect(store)", " fs = STORE_FIELDS[store]", " out = []", " for r in table(source):", + " rows = c.execute('select %s from %s where key = ? order by rowid desc limit ?' % (', '.join(_qid(f) for f in fs), _qid(store)),", + " (r[key], KEEP_LAST)).fetchall()", + " out.append((r[key], [dict(zip(fs, x)) for x in rows]))", " c.close()", " return out", "", "", + "SHOWN = %r" % shown, "HEADS = %r" % heads, "", "", + "def page_latest(source=None, key=KEY, store='results'):", ' """the page: one row per server, its results side by side"""', + " def cell(x):", " if x is None:", " return '-'", + " return '' % html.escape(str(x['status'])) + '
    '.join(", + " html.escape('%s: %s' % (f, '' if x.get(f) is None else x.get(f))) for f in SHOWN) + ''", + " body = ''.join('%s%s' % (html.escape(str(k)), ''.join(cell(rs[i] if i < len(rs) else None)", + " for i in range(len(HEADS)))) for k, rs in latest(source, key, store))", + " return (DOC % 'Service health' + HEAD + '

    Service health

    %s%s'", + " '
    server
    ' % (''.join('%s' % h for h in HEADS), body))", "", ""] + + +# ---------------------------------------------------------------- the rows the request asks for, read independently +def expected_rows(root, world, p, derived, initial_rows=None): + """what a reader of the request would compute from the table: the judge's own reading, not the written code's""" + from judge.project_sources_judge import expected_source_rows + if initial_rows is None: + source = p.get("input") or {"op": "read", "file": (p.get("world") or world)["file"]} + rows = expected_source_rows(root, source) + else: + rows = [dict(row) for row in initial_rows] + for d in p.get("derive", []): + f = derived.get(d["fn"]) + ns = {} + for i in f.get("imports") or []: + ns[i.split(".")[0]] = __import__(i) + for dep in f.get("deps") or []: + exec(compile(dep["source"], "judge:" + dep["name"], "exec"), ns) + exec(compile(f["source"], "judge:" + f["fn"], "exec"), ns) + for r in rows: + r[d["name"]] = ns[f["fn"]](num(r[d["col"]])) + for o in p["ops"]: + if o["op"] == "calculate": + if o.get("fn") not in ("mul", "add", "sub", "div"): + raise ValueError("the judge does not know calculation %s" % o.get("fn")) + for r in rows: # the judge's own arithmetic, read from the operation's name + a, b = num(r[o["left"]]), num(r[o["right"]]) + if not isinstance(a, (int, float)) or not isinstance(b, (int, float)): + raise ValueError("%s requires numeric %s and %s" % (o["col"], o["left"], o["right"])) + if o["fn"] == "div" and b == 0: + raise ValueError("%s divides by a zero %s" % (o["col"], o["right"])) + r[o["col"]] = {"mul": lambda: a * b, "add": lambda: a + b, "sub": lambda: a - b, "div": lambda: a / b}[o["fn"]]() + for o in p["ops"]: + if o["op"] == "filter": + def ok(r, o=o): + a, b = num(r[o["col"]]), o["val"] + if isinstance(a, str) or isinstance(b, str): + a, b = str(a).lower(), str(b).lower() + return {"==": a == b, ">": a > b, "<": a < b, ">=": a >= b, "<=": a <= b}[o["cmp"]] + rows = [r for r in rows if ok(r)] + g = next((o["col"] for o in p["ops"] if o["op"] == "group"), None) + aggs = [o for o in p["ops"] if o["op"] == "agg"] + if aggs: + keys = [] + for r in rows: + k = r[g] if g else None + if k not in keys: + keys.append(k) + out = [] + for k in keys: + rs = [r for r in rows if (r[g] if g else None) == k] + o = {g: k} if g else {} + for a in aggs: + vals = [num(r[a["col"]]) for r in rs] if a["col"] else [] + o[agg_name(a)] = {"count": len(rs), "sum": sum(vals) if vals else 0, "mean": (sum(vals) / len(vals)) if vals else 0, + "max": max(vals) if vals else None, "min": min(vals) if vals else None}[a["fn"]] + out.append(o) + rows = out + for o in p["ops"]: + if o["op"] == "sort": + col = sort_col(o, p, aggs) + if col: + rows = sorted(rows, key=lambda r: num(r[col]), reverse=o["desc"]) + for o in p["ops"]: + if o["op"] == "top": + rows = rows[:o["n"]] + return rows + + +def _scene_records(rows): + """the judge's own reading of which record each scene object should be (the contract the page's scene_records keeps)""" + cols = [] + for r in rows: + for k in r: + if k not in cols: + cols.append(k) + if not cols: + return [] + vc = next((c for c in cols[1:] if c != "at" and rows and all(isinstance(num(r.get(c)), (int, float)) for r in rows)), None) + return [{"id": str(r.get(cols[0])), "v": num(r.get(vc)) if vc else None} for r in rows] + + +def _same(a, b): + a, b = num(a), num(b) + if isinstance(a, (int, float)) and isinstance(b, (int, float)): + return abs(a - b) <= 1e-6 * max(1.0, abs(a), abs(b)) + return str(a) == str(b) + + +def rows_match(got, want): + """the rows read back give the rows asked for: same number, and each asked row's values among the row read back""" + if len(got) != len(want): + return False, "%d rows, want %d" % (len(got), len(want)) + for i, (g, w) in enumerate(zip(got, want)): + for k, v in w.items(): + if k not in g: + return False, "row %d has no column %s" % (i + 1, k) + # A source's textual identifiers retain their spelling: 001 is not 1. + same = str(g[k]) == v if isinstance(v, str) else (g[k] in (None, "") if v is None else _same(g[k], v)) + if not same: + return False, "row %d: %s is %s, want %s" % (i + 1, k, g[k], v) + return True, "%d rows, every value as asked" % len(want) + + +def _page_rows_match(page, want): + """Read visible table cells together; a city somewhere on a page cannot prove its order's city.""" + candidates = [] + for table in re.findall(r"]*>(.*?)", page, re.I | re.S): + columns, rows = [], [] + for line in re.findall(r"]*>(.*?)", table, re.I | re.S): + heads = re.findall(r"]*>(.*?)", line, re.I | re.S) + cells = re.findall(r"]*>(.*?)", line, re.I | re.S) + clean = lambda value: html_unescape(re.sub(r"<[^>]+>", "", value)) + if heads and not cells: + columns = [clean(value) for value in heads] + elif cells: + if len(cells) != len(columns): + return False, "the page has a row with different columns from its header" + rows.append(dict(zip(columns, [clean(value) for value in cells]))) + if not want or all(column in columns for column in want[0]): + candidates.append(rows_match(rows, want)) + return next((result for result in candidates if result[0]), + candidates[0] if candidates else (False, "the page has no table with the requested columns")) + + +# ---------------------------------------------------------------- judges: every requirement against what happened +def _free_port(): + s = socket.socket() + s.bind(("127.0.0.1", 0)) + p = s.getsockname()[1] + s.close() + return p + + +def _db_rows(db, table="results"): + if not db.exists(): + return [] + try: + c = sqlite3.connect(str(db)) + try: + quoted = '"' + table.replace('"', '""') + '"' + cols = [r[1] for r in c.execute("pragma table_info(%s)" % quoted)] + return [dict(zip(cols, x)) for x in c.execute("select * from %s order by rowid" % quoted)] + finally: + c.close() + except sqlite3.Error: + return [] + + +def _db_has_table(db, table="results"): + if not db.is_file(): + return False + try: + c = sqlite3.connect(str(db)) + try: + return c.execute("select 1 from sqlite_master where type='table' and name=?", (table,)).fetchone() is not None + finally: + c.close() + except sqlite3.Error: + return False + + +def _read_file(path): + if not path.is_file(): + return None + try: + if path.suffix == ".json": + v = json.loads(path.read_text(encoding="utf-8")) + return v if isinstance(v, list) else [v] + if path.suffix == ".csv": + return list(csv.DictReader(path.read_text(encoding="utf-8").splitlines())) + return [{"text": ln} for ln in path.read_text(encoding="utf-8").splitlines()] + except (ValueError, OSError): + return None + + +def _judge_order(pipes, serve_names): + """Run each command once, after the stored command it reads, with servers otherwise last.""" + ordered, visiting, done = [], [], set() + + def visit(name): + if name in done: + return + if name in visiting: + cycle = visiting[visiting.index(name):] + [name] + raise ValueError("stored command dependency cycle: " + " -> ".join(cycle)) + if name not in pipes: + raise ValueError("stored command dependency names an unknown provider: %s" % name) + visiting.append(name) + provider = pipes[name].get("from") + if provider: + visit(provider) + visiting.pop() + done.add(name) + ordered.append(name) + + for name in [n for n in pipes if n not in serve_names] + list(serve_names): + visit(name) + return ordered + + +def judge(root, shape, pipes, reqs, world, runenv=None): + """each entry run as the request names it (batch entries first), every outcome read back, every requirement given + its verdict. -> (passed, lines, holes); reqs carry their status and evidence""" + root = Path(root) + if runenv is None: # round-3 R2: the project's entries run in the run jail + import runjail + runenv = runjail.env(root=root) + mod = shape["module"] + st = settings(reqs) + derived = shape.get("derived") or {} + db = root / (Path(mod).stem + ".db") + live = {r["id"]: r for r in reqs if r["status"] != "dropped"} + seen = {} + lines = [] + names = list(pipes) + excl_before = {r["file"]: ((root / r["file"]).stat().st_mtime if (root / r["file"]).is_file() else None) + for r in live.values() if r["kind"] == "excluded" and r.get("file") and r["file"] != "*"} + files_at_start = {p.name: p.stat().st_mtime for p in root.iterdir() if p.is_file()} + db_before = db.is_file() + serve_names = [n for n in names if "PORT" in shape["entries"][n]["args"]] + try: + run_names = _judge_order(pipes, serve_names) + except ValueError as exc: + message = str(exc) + for requirement in live.values(): + requirement["status"] = "failed" + requirement["evidence"] = message + return False, lines, [message] + for n in run_names: + p = pipes[n] + pw = p.get("world") or world or {} + if n in serve_names: + port = _free_port() + sp = subprocess.Popen([sys.executable, mod, n, str(port)], cwd=str(root), stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, text=True, env=runenv) + page = None + last_error = "" + for _ in range(40): + try: + with urllib.request.urlopen("http://127.0.0.1:%d/" % port, timeout=5) as response: + page = response.read().decode("utf-8", "replace") + break + except Exception as exc: # noqa: BLE001 + last_error = str(exc) + if sp.poll() is not None: + break + time.sleep(0.3) + err = "" + sp.terminate() + try: + _o, err = sp.communicate(timeout=5) + except subprocess.TimeoutExpired: + sp.kill() + _o, err = sp.communicate(timeout=5) + if page is None and not err: + err = last_error + seen[n] = {"page": page, "err": (err or "")[-300:]} + lines.append("`python3 %s %s PORT` %s" % (mod, n, "served a page on loopback" if page is not None else + "served no page: " + (err or "")[-160:])) + continue + table = p.get("store_table") or pipes.get(p.get("from"), {}).get("store_table") or "results" + before = _db_rows(db, table) + files_before = {r["file"]: (root / r["file"]).stat().st_mtime if (root / r["file"]).is_file() else None + for r in live.values() if r["kind"] == "file" and r["entry"] == n} + t0 = time.time() + try: + r = subprocess.run([sys.executable, mod, n], cwd=str(root), capture_output=True, text=True, env=runenv, + timeout=60 + st["timeout"] * max(1, pw.get("n", 1))) + rc, out = r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + rc, out = None, "ran past its time" + took = time.time() - t0 + after = _db_rows(db, table) + seen[n] = {"rc": rc, "out": out, "took": took, "before": before, "added": after[len(before):], "all": after, + "table": table, "table_exists": _db_has_table(db, table), "files_before": files_before} + lines.append("`python3 %s %s` ran in %.1f s, exit %s" % (mod, n, took, rc)) + # each requirement + for rid, r in live.items(): + k = r["kind"] + ev, ok = "", None + p = pipes.get(r["entry"]) if r.get("entry") in pipes else None + pw = (p.get("world") if p else None) or world or {} + want_rows = None + if k in ("stored", "file", "served", "printed") and p: + try: + if p["source"] == "table": + want_rows = expected_rows(root, pw, view(p, rid), derived) + elif p["source"] == "stored" and p.get("from") in pipes: + producer = pipes[p["from"]] + if producer["source"] == "table": + stored_rid = next((item["id"] for item in live.values() + if item["entry"] == p["from"] and item["kind"] == "stored"), None) + stored_rows = list((seen.get(p["from"]) or {}).get("before", [])) + expected_rows( + root, producer.get("world") or world, view(producer, stored_rid), derived) + want_rows = expected_rows(root, pw, view(p, rid), derived, initial_rows=stored_rows) + elif view(p, rid).get("ops"): + want_rows = expected_rows(root, pw, view(p, rid), derived, + initial_rows=(seen.get(p["from"]) or {}).get("all", [])) + except (ValueError, KeyError, TypeError, OSError) as exc: + r["status"], r["evidence"] = "failed", "the independent source judge could not resolve the input: %s" % exc + continue + if k == "context": + ok, ev = True, "read" + elif k in ("unread",): + ok, ev = False, "not read" + elif k == "excluded": # what the request rules out was not done + w = r.get("what") + if w == "file" and r["file"] == "*": # no file at all: nothing new or rewritten beside the program + made = sorted(p.name for p in root.iterdir() if p.is_file() and p.name != mod and + files_at_start.get(p.name) != p.stat().st_mtime) + ok = not made + ev = "no file written, as asked" if ok else "files written though the request ruled it out: %s" % \ + ", ".join(made[:5]) + elif w == "file": + f = root / r["file"] + now = f.stat().st_mtime if f.is_file() else None + ok = now == excl_before.get(r["file"]) + ev = "%s %s" % (r["file"], "not written, as asked" if ok else "was written, though the request ruled it out") + elif w == "stored": + ok = db_before or not db.is_file() + ev = "no database made, as asked" if ok else "%s was made, though the request ruled out a database" % db.name + elif w == "served": + ok = not serve_names + ev = "no page served, as asked" if ok else "a page is served, though the request ruled it out" + else: + outs = [x.get("out", "") for x in seen.values() if "out" in x] + ok = not any((o or "").strip() for o in outs) + ev = "nothing printed, as asked" if ok else "lines were printed, though the request ruled it out" + elif k == "stored": + s = seen.get(r["entry"]) or {} + got = len(s.get("added", [])) + if want_rows is not None: + match, details = rows_match(s.get("all", []), s.get("before", []) + want_rows) + ok = s.get("rc") == 0 and s.get("table_exists", False) and match + ev = "%s, table %s: %s; %d new rows" % (db.name, s.get("table", "results"), details, got) + else: + want = pw.get("n", 0) if p and p["source"] == "probe" else None + ok = s.get("rc") == 0 and got > 0 and (want is None or got == want) + ev = "%d rows kept in %s by one run (want %s)" % (got, db.name, want) + elif k == "file": + s = seen.get(r["entry"]) or {} + path = root / r["file"] + rows = _read_file(path) + fresh = path.is_file() and path.stat().st_mtime != (s.get("files_before") or {}).get(r["file"]) + if rows is None or not fresh or s.get("rc") != 0: + ok, ev = False, "%s was not written by `%s`" % (r["file"], r["entry"]) + elif want_rows is not None: + expected = s.get("before", []) + want_rows if r.get("every") and any( + item["kind"] == "stored" and item["entry"] == r["entry"] for item in live.values()) else want_rows + ok, ev = rows_match(rows, expected) + ev = "%s: %s" % (r["file"], ev) + elif r.get("every"): + ok = len(rows) == len(s.get("all", [])) and len(rows) > 0 + ev = "%s holds %d rows; the database holds %d" % (r["file"], len(rows), len(s.get("all", []))) + else: + want = pw.get("n", 0) + ok = len(rows) == want + ev = "%s holds %d rows (want %d)" % (r["file"], len(rows), want) + elif k == "served": + s = seen.get(r["entry"]) or {} + page = s.get("page") + if page is None: + ok, ev = False, "no page: %s" % s.get("err", "") + elif not judge_look(page, {})[0]: + ok, ev = False, "the page is not made from the design family's tokens: " + judge_look(page, {})[1] + elif want_rows is not None: + want = want_rows + ok, ev = _page_rows_match(page, want) + ev = "the page: " + ev + mR = re.search(r"const R = (\[.*?\]), N = R\.length", page, re.S) + if mR: # C12: the scene's objects are the records asked, with their values + try: + got_r = json.loads(mR.group(1).replace("<\\/", "= 400 and x.get("status") != "down"] + return bool(added) and not bad, "%d rows; an error status recorded as down for every one (%d not)" % (len(added), len(bad)) + if k == "ms": + nums = [x.get("ms") for x in added if x.get("status") == "up"] + kept = bool(nums) and all(isinstance(v, (int, float)) for v in nums) + shown = not pages or all(any(str(v) in pg for v in nums) for pg in pages) + return kept and shown, "milliseconds kept for %d up rows: %s; shown on the page: %s" % (len(nums), kept, shown) + if k == "timestamp": + rows = added or [x for s in seen.values() for x in s.get("added", [])] + return bool(rows) and all(x.get("at") for x in rows), "every kept row has its time: %s" % bool(rows) + if k == "keep_last": + ok = all(("previous" in pg or "result 2" in pg) for pg in pages) if pages else True + return ok, "the page has a column for each of the last %d results: %s" % (r["n"], ok) + return None, "" + + +# ---------------------------------------------------------------- the ledger, kept with the project +def ledger_lines(reqs): + out = [] + for r in reqs: + if r["kind"] == "context": + continue + if r.get("merged_into"): + out.append("%s the same outcome as %s (\"%s\")" % (r["id"], r["merged_into"], r["from"][0][:80])) + continue + what = {"file": "writes %s" % r.get("file"), "stored": "keeps rows in a database", "served": "a page in the browser", + "printed": "prints the rows", "op": _op_text(r["op"]) if r.get("op") else "", "derive": "%s made from %s" % ( + r.get("name"), r.get("col")), "timeout": "no answer within %g s is down" % r.get("seconds", 0), + "error_down": "an error status is down", "ms": "time to answer in milliseconds", + "timestamp": "each row with its time", "keep_last": "the last %d results shown" % r.get("n", 1), + "unread": "words not read: %s" % ", ".join(r.get("words", [])), + "interaction": "record edits and relationships through the page", + "look": "the look asked: %s" % ", ".join(r.get("words", [])), + "excluded": "not done, as asked: %s" % {"file": ("no file written" if r.get("file") == "*" else "no %s written" % r.get("file")), "stored": "no database", + "served": "no page", "printed": "nothing printed"}.get( + r.get("what"), r.get("what"))}.get(r["kind"], r["kind"]) + if r.get("superseded"): + what += " (was %s)" % ", ".join("%s %s" % (k, v) for old in r["superseded"] for k, v in old.items()) + if r.get("out"): + what += " (for %s only)" % r["out"] + if r.get("dropped_with"): + what += " (went with %s)" % r["dropped_with"] + out.append("%s %s%s - %s%s" % (r["id"], what, (" (`%s`)" % r["entry"]) if r.get("entry") not in (None, "*") else "", + r["status"], (": " + r["evidence"]) if r.get("evidence") else "")) + return out + + +# ---------------------------------------------------------------- the look: Oracle7's design family (workbench/design) +_DESIGN = {} + + +def _design(): + if not _DESIGN: + import importlib.util + d = Path(__file__).resolve().parent / "design" + for n in ("palette", "type", "layout", "motion", "scene"): + spec = importlib.util.spec_from_file_location("o7design_" + n, str(d / ("organ_%s.py" % n))) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + _DESIGN[n] = m + return _DESIGN + + +def read_look(sentence): + """the look a sentence asks of its page: a colour (a W3C colour name or a hex), tone words, dark. None when it asks none""" + D = _design() + low = sentence.lower() + words = re.findall(r"[a-z]+", DATA.sub(" ", low)) + seed = next((w for w in words if w in D["palette"].NAMES and w not in ("white", "black")), None) + m = re.search(r"#[0-9a-f]{6}\b", low) + if m: + seed = m.group(0) + tones = [w for w in words if w in D["type"].TONES] + dark = bool(re.search(r"\bdark\b", low)) + scene = None + if re.search(r"\b3-?d\b|\bthree[- ]?d(?:imensional)?\b|\bthree\.?js\b|\bin three dimensions\b|\bscene\b", low): + sw_ = getattr(D["scene"], "SHAPE_WORDS", {g: (g,) for g in D["scene"].GEOM}) + hit = next(((g, w) for w in words for g, names in sw_.items() if any(wmatch(w, n) for n in names)), None) + shape, shape_word = hit if hit else ("box", None) + scene = {"shape": shape, "camera": "static" if re.search(r"\bstill\b|\bstatic\b", low) else "orbit", + "light": next((w for w in words if w in D["scene"].RIGS), "daylight")} + if not (seed or tones or dark or scene): + return None + sw = ([w for w in words if w in ("scene", "three", "dimensions", "dimensional", "camera", "orbit", "orbiting", "still", "static", + scene["light"]) or wmatch(w, scene["shape"]) or (shape_word and wmatch(w, shape_word))] + (["3d"] if re.search(r"\b3-?d\b", low) else []) + if scene else []) + return {"seed": seed, "tone": tones, "dark": dark, "scene": scene, + "words": [w for w in [seed] + tones + (["dark"] if dark else []) if w] + sw} + + +def design_for(looks): + """the design family's answer for a project's pages: palette, type, layout and motion, each from its specialist""" + D = _design() + seed = next((l["seed"] for l in looks if l.get("seed")), None) or "slategray" + tones = [t for l in looks for t in l.get("tone", [])] or ["clean"] + dark = any(l.get("dark") for l in looks) + pal = D["palette"].ask({"seed": seed, "modes": ["dark"] if dark else ["light", "dark"], "series": 0}) + typ = D["type"].ask({"tone": tones, "use": "site"}) + if typ.get("status") != "answered": + typ = D["type"].ask({"tone": ["clean"], "use": "site"}) + lay = D["layout"].ask({"sections": ["table"], "widths": [375, 768, 1440], "body_size": typ.get("body_size", 18)}) + mot = D["motion"].ask({"changes": ["enter", "hover"], "tone": "calm" if "calm" in tones or "quiet" in tones else ""}) + cat = D["type"].catalogue() + gen = lambda fam: "serif" if (cat.get(fam) or {}).get("category") in ("Serif", "Display") else "sans-serif" + sc = next((l["scene"] for l in looks if l.get("scene")), None) + stage = None + if sc: # the scene specialist: one object per row, on the palette's colours + lp = D["palette"].ask({"seed": seed, "modes": ["light"], "series": 2})["modes"]["light"] + stage = D["scene"].stage(sc["shape"], sc["light"], sc["camera"], lp) + return {"seed": seed, "tone": tones, "dark_only": dark, "palette": pal, "type": typ, "layout": lay, "motion": mot, + "generic": {"display": gen(typ.get("display")), "body": gen(typ.get("body"))}, "scene": sc, + "stage": list(stage) if stage else None} + + +def design_head(dz): + """the and ", "not asked" + modes = dz["palette"]["modes"] + t, lay, mot = dz["type"], dz["layout"], dz["motion"] + + def vars_(m): + return ";".join("--%s:%s" % (k, m[k]) for k in ("background", "foreground", "muted", "border", "primary", "accent")) + first = modes.get("light") or modes.get("dark") + css = [":root{%s;--font-display:'%s',%s;--font-body:'%s',%s}" % (vars_(first), t["display"], dz["generic"]["display"], + t["body"], dz["generic"]["body"])] + if "light" in modes and "dark" in modes: + css.append("@media (prefers-color-scheme: dark){:root{%s}}" % vars_(modes["dark"])) + sz = t["sizes"] + g = lay["grids"] + wide = g[max(g, key=int)] + css += ["*{box-sizing:border-box}", + "body{margin:0;background:var(--background);color:var(--foreground);font:400 %dpx/%s var(--font-body)}" % ( + t["body_size"], t["line_height"]), + "main{max-width:%dpx;margin:0 auto;padding:%dpx %dpx}" % (lay["max_width"], g["375"]["margin"] * 2, + g["375"]["margin"]), + "@media (min-width:600px){main{padding:%dpx %dpx}}" % (g["768"]["margin"] * 2, g["768"]["margin"]), + "@media (min-width:1024px){main{padding:%dpx %dpx}}" % (wide["margin"] and 64, 32), + "h1{font:%d %dpx/%s var(--font-display);margin:0 0 %dpx;color:var(--foreground)}" % ( + t["weights"]["display"][0], sz[min(4, len(sz) - 1)], t["display_line_height"], sz[1]), + "table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}", + "th{text-align:left;color:var(--muted);font-weight:%d;border-bottom:2px solid var(--border);padding:12px 16px}" % ( + t["weights"]["body"][-1]), + "td{border-bottom:1px solid var(--border);padding:12px 16px;vertical-align:top}", + "a{color:var(--primary)}", + ".up{box-shadow:inset 4px 0 0 var(--primary)}.down{box-shadow:inset 4px 0 0 var(--accent)}", + "td{transition:filter %dms %s}tr:hover td{filter:brightness(0.96)}" % ( + mot["kinds"]["hover"]["duration_ms"], mot["kinds"]["hover"]["easing"]), + "main{animation:o7in %dms %s both}@keyframes o7in{from{opacity:0;transform:translateY(8px)}to{opacity:1;" + "transform:none}}" % (mot["kinds"]["enter"]["duration_ms"], mot["kinds"]["enter"]["easing"]), + mot["reduced_motion"]["css"]] + fam = lambda f, ws: "family=%s:wght@%s" % (f.replace(" ", "+"), ";".join(str(w) for w in sorted(set(ws)))) + link = ('' % (fam(t["display"], t["weights"]["display"]), fam(t["body"], t["weights"]["body"]))) + why = "palette from %s (%s), type %s / %s at %d px on a %s scale, %d px content, motion %d/%d ms with reduced motion" % ( + dz["seed"], "dark" if dz["dark_only"] else "light and dark", t["display"], t["body"], t["body_size"], t["ratio"], + lay["max_width"], mot["kinds"]["enter"]["duration_ms"], mot["kinds"]["hover"]["duration_ms"]) + if dz.get("stage"): + css.append(dz["stage"][0]) + why += "; a three.js scene of one %s per row (%s light, %s camera)" % (dz["scene"]["shape"], dz["scene"]["light"], + dz["scene"]["camera"]) + return link + "", why + + +def _lum(h): + def lin(c): + c = c / 255.0 + return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 + r, g, b = [lin(int(h[i:i + 2], 16)) for i in (1, 3, 5)] + return 0.2126 * r + 0.7152 * g + 0.0722 * b + + +def judge_look(page, req): + """the page's own tokens read back: text on its background at 7:1 or more in every mode it declares, its fonts named, + a phone's margin, the reduced-motion rule; and what the request asked of the look (its colour's hue, dark)""" + if not page: + return False, "no page" + blocks = re.findall(r"--background:(#[0-9a-f]{6});--foreground:(#[0-9a-f]{6})", page) + if not blocks: + return False, "no colour tokens" + cs = [(max(_lum(f), _lum(b)) + 0.05) / (min(_lum(f), _lum(b)) + 0.05) for b, f in blocks] + why = ["text contrast %s" % ", ".join("%.1f" % c for c in cs)] + ok = all(c >= 7 for c in cs) + fonts = re.findall(r"--font-(?:display|body):'([^']+)'", page) + ok &= len(fonts) == 2 + why.append("fonts %s" % " / ".join(fonts)) + ok &= "prefers-reduced-motion" in page + m = re.search(r"main\{max-width:\d+px;margin:0 auto;padding:\d+px (\d+)px\}", page) + ok &= bool(m) and int(m.group(1)) >= 16 + why.append("phone margin %s px" % (m.group(1) if m else "?")) + if req.get("seed"): + D = _design() + prim = re.search(r"--primary:(#[0-9a-f]{6})", page) + seedhex = D["palette"].NAMES.get(req["seed"], req["seed"]) if not req["seed"].startswith("#") else req["seed"] + _L, C, H = D["palette"].lch_of(seedhex) + if prim and C > 0.02: + ph = D["palette"].lch_of(prim.group(1))[2] + d = min(abs(ph - H) % 360, 360 - abs(ph - H) % 360) + ok &= d <= 20 + why.append("primary %s, %.0f degrees from %s" % (prim.group(1), d, req["seed"])) + if req.get("scene"): + # C12: the scene is bound to the page's records - the record payload's ids are the table rows' ids, in order + mR = re.search(r"const R = (\[.*?\]), N = R\.length", page, re.S) + try: + recs = json.loads(mR.group(1).replace("<\\/", "', page)] + rows = len(tr_ids) + n = re.match(r"(\d+)", str(len(recs))) if recs is not None else None + three = re.search(r"three@\d+\.\d+\.\d+", page) + bound = recs is not None and [str(x.get("id")) for x in recs] == tr_ids + okc = bool(recs is not None and three and 'id="stage"' in page and len(recs) == rows and bound) + # the shape asked is the geometry drawn (spheres asked: SphereGeometry in the stage), not only a stage + want_geo = re.search(r"new THREE\.(\w+Geometry)", _design()["scene"].GEOM.get(req["scene"].get("shape"), "") or "") + geo_ok = bool(want_geo) and ("new THREE.%s(" % want_geo.group(1)) in page + okc &= geo_ok + # the stage's script is run through a JavaScript engine where the box has one (node --check: it parses); + # where none is installed the evidence says the script was not run - it is not counted as checked + js = "\n".join(re.findall(r"", page, re.S)) + ran = _js_parses(js) if js else None + if ran is False: + okc = False + ok &= okc + why.append("a three.js scene of %s objects for %d rows%s%s; %s drawn (%s asked)%s; script %s" % ( + n.group(1) if n else "no", rows, "" if three else ", three.js not pinned", + ", each bound to its row's id" if bound else ", objects NOT bound to the table's rows", + want_geo.group(1) if geo_ok else "not the shape", req["scene"].get("shape"), "", + {True: "parses (node --check)", False: "does not parse (node --check)", + None: "not run: no JavaScript engine on this box"}[ran])) + if req.get("dark"): + Lb = _design()["palette"].lch_of(blocks[0][0])[0] + ok &= Lb < 0.3 + why.append("dark background L %.2f" % Lb) + return bool(ok), "; ".join(why) + + +def _js_parses(js): + """True / False when a JavaScript engine (node) is on this box and the module script parses or not; None without one""" + import shutil + import tempfile + node = shutil.which("node") or shutil.which("nodejs") + if not node: + return None + with tempfile.NamedTemporaryFile("w", suffix=".mjs", delete=False, encoding="utf-8") as f: + f.write(js) + path = f.name + try: + return subprocess.run([node, "--check", path], capture_output=True, timeout=30).returncode == 0 + except Exception: # noqa: BLE001 + return None + finally: + os.unlink(path) + + +def save_project(root, shape): + d = Path(root) / ".oracle7" + d.mkdir(exist_ok=True) + (d / "project.json").write_text(json.dumps(shape, indent=1, default=str), encoding="utf-8") + + +def load_project(root): + p = Path(root) / ".oracle7" / "project.json" + if p.is_file(): + try: + return json.loads(p.read_text(encoding="utf-8")) + except ValueError: + return None + return None + + +def derive_goal(h, shape): + """a value made from a column, as a goal for the code composer: its examples from the turn that gave them""" + exs = [((a,), b, None) for a, b in h["examples"]] + return {"name": h["fn"], "params": [h["col"]], "module": Path(shape["module"] or "project.py").stem, + "examples": exs, "module_text": ""} + + +def sha_of(name, src): + return hashlib.sha256((name + "\n" + src).encode()).hexdigest() + + +def compose_holes(root, shape, holes, net_scope=()): + """the values made from a column that now have examples: each composed by Oracle7's code composer (its search over + typed moves, its read-back in a separate interpreter), the result going back into the plan under its sha. -> lines""" + todo = [h for h in holes if h["kind"] == "compose"] + if not todo: + return [] + sys.path.insert(0, str(Path(__file__).resolve().parent)) + import compose_code as CC + out = [] + for h in todo: + goal = derive_goal(h, shape) + words = " ".join([shape.get("example_words", ""), h["name"], h["col"]] + [c for c in shape["clauses"]]) + res = CC.run_job(str(root), [goal], words=words, net_scope=list(net_scope)) + if res.get("stopped") and sys.modules.get("continuation") is not None: + raise sys.modules["continuation"].Stopped("composing (%s)" % res["error"]) # C14: the examples stay kept + r = (res.get("results") or [{}])[0] if "error" not in res else {"status": "error", "gap": res.get("error")} + if r.get("status") == "composed": + deps = [] + for s in r.get("support") or []: + m = re.search(r"(?m)^def (\w+)\(", s) + if m: + deps.append({"name": m.group(1), "source": s, "sha256": sha_of(m.group(1), s)}) + shape.setdefault("derived", {})[h["fn"]] = { + "name": h["name"], "col": h["col"], "fn": h["fn"], "source": r["source"], "sha256": sha_of(h["fn"], r["source"]), + "imports": sorted(set(r.get("imports") or []) | set(r.get("support_imports") or [])), "deps": deps, + "from": "composed", "r": r, "goal": {"name": goal["name"], "params": goal["params"], + "examples": [[list(a), o] for a, o, _t in goal["examples"]]}} + out.append("%s made from %s: composed from your %d examples - `%s` (read back by a separate interpreter: %s)" % ( + h["name"], h["col"], len(h["examples"]), r["source"].strip().splitlines()[-1].strip(), r.get("read_back"))) + else: + shape["examples"].pop(h["fn"], None) # the next examples start afresh + out.append("%s made from %s: not composed - %s" % (h["name"], h["col"], (r.get("gap") or "")[:300])) + return out + + +def keep_derived(root, shape): + """the values composed for this project, kept in Oracle7's store once the project's judges passed with them (the law + decides, not the composer): -> the kept records""" + sys.path.insert(0, str(Path(__file__).resolve().parent)) + import code_store as CS + added = [] + for fn, d in (shape.get("derived") or {}).items(): + if d.get("from") != "composed" or d.get("kept"): + continue + g = dict(d["goal"]) + e = CS.entry_for(d["r"], g, "%s (%s)" % (shape.get("module"), Path(root).name), []) + got = CS.keep([e]) if e else [] + if e: + d["kept"] = e["id"] + added += got or [e] + return added + + +def is_project(text, kept, root=None): + """a project request: a build verb, and an entry command, a table of the project or an outcome someone can see; not + a request about tests or one function. Or a turn that continues or changes the project kept""" + t = text.strip() + other = re.search(r"(?i)\btests?\b|\bfunction\b|\bclass\b|\bdef\b|\bfix\b|\brepair\b|\bbug\b|\.py\b", t) and not ENTRY.search(t) + if re.search(r"(?i)\b(?:in)?to\s+(?:yourself|oracle7)\b|^\s*(?:please\s+)?(?:build|add|make|give)\s+(?:yourself|oracle7)\s*[:,-]", t): + return False # a feature of Oracle7 itself: selfdev's project route (C10) + if re.match(r"(?i)^\s*make\s+[\w-]+\s*:", t): + return False # the make command's own form: `make name: steps` + if kept and not other: + if _interaction_request(t): + return True + if re.match(r"(?i)^\s*(?:also|and also|now also|change it so|make it also|add|plus|then also)\b", t): + return True + if DROP.match(t) or DROP_WORD.match(t) or CONTINUE.match(t): + return True + if REVISE.search(t) or re.match(r"(?i)^\s*(?:(?:actually|wait|rather)\b|no\s*,)", t): + return True # a revision of the project kept ("actually, make it above 25") + if kept.get("status") == "blocked": + if any(h.get("kind") == "scope" for h in kept.get("holes_kept", [])) and ( + ENTRY.fullmatch(t) or any(re.fullmatch(r"(?i)(?:the\s+)?`?" + re.escape(n) + r"`?(?:\s+command)?[.!]?", t) for n in kept.get("entries", {}))): + return True + if EXAMPLE.search(t) or MEANS.search(t) or re.search(r"(?i)\buse\s+(?:it|that)\b", t): + return True + if any(h.get("kind") == "source" for h in kept.get("holes_kept", [])) and \ + re.match(r"(?i)^\s*(?:match(?:ing|ed)?\s+(?:on|by)\s+|on\s+)[a-z_]", t): + return True + if other: + return False + if not BUILD.search(t): + return False + if ENTRY.search(t): + return True + has_table = bool(DATA.search(t)) + outcome = bool(_interaction_request(t) or SINK_FILE.search(t) or SINK_OBJ.search(t) or STORED.search(t) or re.search(r"(?i)\b(?:browser|web ?page|website|dashboard)\b", t) + or PRINTED.search(t)) + return has_table and outcome diff --git a/workbench/project_answer.py b/workbench/project_answer.py new file mode 100644 index 0000000000000000000000000000000000000000..68561ff48bea2811de78d6bc144af21c2d6a203d --- /dev/null +++ b/workbench/project_answer.py @@ -0,0 +1,92 @@ +"""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}}} diff --git a/workbench/project_context.py b/workbench/project_context.py new file mode 100644 index 0000000000000000000000000000000000000000..2d25dffcef6bacb0f67f839e8438c27f0edf437f --- /dev/null +++ b/workbench/project_context.py @@ -0,0 +1,49 @@ +"""Keep a received new project while the conversation chooses its workspace.""" +import copy +import 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 `; 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']) diff --git a/workbench/project_discussion.py b/workbench/project_discussion.py new file mode 100644 index 0000000000000000000000000000000000000000..e48292d28b9324f9bf7b63f289acf6d737aec8bc --- /dev/null +++ b/workbench/project_discussion.py @@ -0,0 +1,241 @@ +"""Discuss a received program from its saved meaning, without building or running it. + +State, events, conditions, examples and reasons are the vocabulary of the current +project. Questions bind to that record; a hypothetical state is never reported as +the live application's state. No application-specific templates or topic facts. +""" +import json +import re + + +def _value(value): + return json.dumps(value, ensure_ascii=False) + + +def _mentions(text, name): + return bool(name and re.search(r'(? 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}} diff --git a/workbench/project_intent.py b/workbench/project_intent.py new file mode 100644 index 0000000000000000000000000000000000000000..db1aeee00ebe9b0abcaa129d11fba973d2157460 --- /dev/null +++ b/workbench/project_intent.py @@ -0,0 +1,385 @@ +"""Receive a described program through the existing work ledger and compiler. + +Project nouns are kept verbatim. The existing parts decide which described +stages connect; missing destination/evidence/meaning is filled on later turns. +""" +import ast +import copy +import hashlib +import json +from pathlib import Path +import re +import sys +import 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 " (should|must)? give|return|produce|expect|=> " ("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'(? %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 + '' + return page.replace('', panel + '', 1) if '' 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 = '''

    Edit selected record

    +

    Select a table row or a 3D object.

    +
    + +

    +''' + + +_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_key +ProjectSourceError = PS.SourceError +exec(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 binding diff --git a/workbench/project_sources.py b/workbench/project_sources.py new file mode 100644 index 0000000000000000000000000000000000000000..476d16443de768fef5742a799770b5e2e0091668 --- /dev/null +++ b/workbench/project_sources.py @@ -0,0 +1,377 @@ +"""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"(?= 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 result diff --git a/workbench/prosefold/core.py b/workbench/prosefold/core.py index bcf1fdea311402e9ae40743481642110902f8cd7..46fe9afd4b7abc09dc8d1da0d2084eafd53f35bb 100644 --- a/workbench/prosefold/core.py +++ b/workbench/prosefold/core.py @@ -82,7 +82,10 @@ def page_sentences(topic): try: con = sqlite3.connect("file:%s?mode=ro" % PAGE_STORE, uri=True) key = re.sub(r"[^a-z0-9]+", "_", topic.lower()).strip("_") - row = con.execute("select page_id from title_alias where normalized_title = ?", (key,)).fetchone() + # 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 in (?, ?)", + (key, key.replace("_", " "))).fetchone() if not row: return [] out = [] diff --git a/workbench/prosefold/options.py b/workbench/prosefold/options.py index 4ed2fd7080c4f1fb83fd2968dd0904261286d16d..48dcb33a6ac0661c7c54c2ce30dc00db6c0eefd7 100644 --- a/workbench/prosefold/options.py +++ b/workbench/prosefold/options.py @@ -66,7 +66,10 @@ def page_records(topic): try: con = sqlite3.connect("file:%s?mode=ro" % store, uri=True) key = re.sub(r"[^a-z0-9]+", "_", topic.lower()).strip("_") - row = con.execute("select page_id from title_alias where normalized_title = ?", (key,)).fetchone() + # 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 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) diff --git a/workbench/question_obligation.py b/workbench/question_obligation.py new file mode 100644 index 0000000000000000000000000000000000000000..4eac2e498eb91de0ccbebc9267b1b3b5469c8840 --- /dev/null +++ b/workbench/question_obligation.py @@ -0,0 +1,364 @@ +"""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 list +of topics or answers. A match means the source says the answer, not that the +source is independently true. Unknown grammar remains a received hole. +""" +import hashlib +import json +import 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)]} diff --git a/workbench/reflect.py b/workbench/reflect.py new file mode 100644 index 0000000000000000000000000000000000000000..d4d2e5bb2d8827930e9d4b5bbc77a5551bc56d93 --- /dev/null +++ b/workbench/reflect.py @@ -0,0 +1,763 @@ +"""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 Oracle7 +handled it, the execution receipt: started, finished, exit, check, files, the change made, what was tried), its parts as +its own code describes them (each module's own first docstring line, read from the install, not written here), its frozen +identity, and the thread of ideas the conversation is developing (subjects, claims, deductions, interpretations, the +operator'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 theirs +A 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 json +import os +import re +import time +from pathlib import Path + +NL = chr(10) +WB = Path(__file__).resolve().parent +TREE = WB.parent +HOME = 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 thread +def _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 work +def 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 None diff --git a/workbench/registry.py b/workbench/registry.py index 998e38a90325d9e79fccf854939cd390d22fd82e..653035cb6517ecd9d986e6463433cadcb3dde17f 100644 --- a/workbench/registry.py +++ b/workbench/registry.py @@ -121,9 +121,11 @@ def read_tx(signature): 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) @@ -157,14 +159,27 @@ def records(d): 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"]}) @@ -180,16 +195,21 @@ def check(d): 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} diff --git a/workbench/relay.py b/workbench/relay.py new file mode 100644 index 0000000000000000000000000000000000000000..5c3b5a38ace7563dade70f4518d198ef39bf8b9b --- /dev/null +++ b/workbench/relay.py @@ -0,0 +1,91 @@ +"""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 if +nothing 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 a +long 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 """ +import base64 +import json +import os +import subprocess +import sys +import threading +import time +import urllib.error +import urllib.request + +PORT, TREE, STATE = int(sys.argv[1]), sys.argv[2], sys.argv[3] +BASE = "http://127.0.0.1:%d" % PORT +HOP = {"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 = None +if 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() diff --git a/workbench/repair.py b/workbench/repair.py new file mode 100644 index 0000000000000000000000000000000000000000..665a0d3a6ef96e3fd2c1b644b5fcea710b52611c --- /dev/null +++ b/workbench/repair.py @@ -0,0 +1,519 @@ +"""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 the +frames 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 ones +that turn an operation the description says is wrong into the one it says is wanted are tried first. The project's tests are +the judge: a change is kept only if they pass, and kept untested only when the description itself names both the wrong +and the wanted operation. Nothing is written by a language model; every change is a move on the code that is there.""" +import ast +import os +import re +import subprocess +import sys +from 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 most +SPAN_CAP = 14 # moves considered for pairs, at most +PAIR_CAP = 90 # pairs tried, at most +OPS = { # 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 at +should would could will can must not no do does did done fix fixes correct correction repair wrong instead make makes made +please function method code test tests run running rerun then also too so when what which there here into out up use uses +used 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 code +def _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 changes +def _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 + + +# ---------------------------------------------------------------- checks +def 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: + pass diff --git a/workbench/resolve.py b/workbench/resolve.py new file mode 100644 index 0000000000000000000000000000000000000000..61737d8b64325f86c367bf1b2250d6c8410d54a8 --- /dev/null +++ b/workbench/resolve.py @@ -0,0 +1,278 @@ +"""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 just +changed", "is anything broken", "pull up calc.py") is read here: its content words are compared, by the word meanings +Oracle7 derived from its own corpus with no training (converse/data/ladder/wordvec.npz), with the words that describe each +operation; the operation it reads is the one that clearly wins (a floor and a margin over the next). The things the request +names 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; an +operation that changes or runs anything is offered, and done only on go. Nothing is read when no operation clearly wins: the +reply names the two nearest and asks. No language model.""" +import os +import re +from pathlib import Path + +WB = Path(__file__).resolve().parent +OPS = [ # 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 shall +do 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 some +there here up out about into over once more yes no ok okay hey oracle oracle7 thing things stuff something +anything 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 it +QUESTION = 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.45 +USES = 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, sure diff --git a/workbench/runjail.py b/workbench/runjail.py new file mode 100644 index 0000000000000000000000000000000000000000..382d96feb7449df38e6c3b22f845c95662809d01 --- /dev/null +++ b/workbench/runjail.py @@ -0,0 +1,63 @@ +"""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 a +private home and temporary folder, and with the head's own listening port refused even on loopback (the network scope +guard in bench.GUARD reads O7_DENY_PORTS). Before this, a hostile repository's test could rewrite the hole record, the +writing 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 a +setting added later is covered without editing this file. Would not solve: a program not written in Python ignores the +port guard (bench.GUARD's own limit); a run with the head's operating-system user can still open files by absolute path. +""" +import hashlib +import os +from pathlib import Path + +OWN = ("ORACLE7_", "ORACLE_", "O7_") # Oracle7's own setting families +KEEP = {"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 e diff --git a/workbench/seal.py b/workbench/seal.py new file mode 100644 index 0000000000000000000000000000000000000000..7633bd6da054786fd7315b2d2b838bc6a1ea4b5a --- /dev/null +++ b/workbench/seal.py @@ -0,0 +1,155 @@ +"""seal - the judge at the one exit every reply leaves through (12.5, round-2 design section 1.1; organ 1 of 4). + +A reply is said only as far as its receipts read back. The seal splits the delivered text into sentences, each with the +receipts its producer attached, and reads every receipt back against its record with its own code: + [wd:Q P

    Q] the relation store holds (s, p, o) and the sentence says the object's name and the subject's (or a + pronoun standing for it); + [hole:] the hole record holds that id (a hole says what is not held; it is never an assertion). +Other receipt families (a page record [n], a proving path, a reading receipt) are counted by family; until the seal reads +a family back it is "not read by the seal" and changes nothing. Sentences with no receipt are counted. + +The seal only lowers: a reply's label is the lower of what its producer said and what its receipts bear. It never raises a +hole to an answer, never adds a sentence, and never rewrites one. No language model; no hand-written list about data. +This module is pure: it is given the stores and the reply and returns the verdict; wiring it at the one exit is step 3.""" +import json +import os +import re + +RECEIPT = re.compile(r"\[([^\[\]]{1,200})\]") +# a receipt has a shape: family:value (wd:, hole:, scene:, turn:, enwiki_...:) or page record numbers; a bracket holding code or +# a list ([x for x in xs], ['a', 'b']) is text, not a receipt +SHAPE = re.compile(r"^(?:[A-Za-z][\w-]{0,40}:\S.*|\d+(?:\s*,\s*\d+)*)$") +WD = re.compile(r"^wd:Q(\d+)\s+P(\d+)\s+Q(\d+)$") +HOLE = re.compile(r"^hole:([\w-]+)$") +PRONOUN = {"it", "he", "she", "they", "its", "his", "her", "their", "this", "these"} +ORDER = {"answered": 3, "offered": 2, "hole": 1} + + +def sentences(text): + """the body as [(sentence, [receipts])]: a sentence ends at . ! ? followed by its receipt group; sections a reply marks as + sources or how it was made are not sentences of the body""" + body, fence = [], False + for ln in str(text or "").splitlines(): + if ln.strip().startswith("```"): + fence = not fence # code shown in a reply is not a sentence of it + continue + if fence: + continue + s = ln.strip() + if re.match(r"^(?:#+\s*|\*\*|_)?(?:sources|how this was made)\b", s, re.I): + break + if s and not s.startswith(("#", "```")): + body.append(s) + text = re.sub(r"`[^`]*`", "", " ".join(body)) # inline code is not a sentence's content or a receipt + out, pos = [], 0 + for m in re.finditer(r"[.!?][\"')\]]*((?:\s*\[[^\[\]]{1,200}\])*)(?=\s+[A-Z0-9\"(]|\s*$)", text): + seg = text[pos:m.end()].strip() + pos = m.end() + if seg: + out.append((RECEIPT.sub("", seg).strip(), [x for x in RECEIPT.findall(seg) if SHAPE.match(x.strip())])) + tail = text[pos:].strip() + if tail: + out.append((RECEIPT.sub("", tail).strip(), [x for x in RECEIPT.findall(tail) if SHAPE.match(x.strip())])) + return [(s, rc) for s, rc in out if s or rc] + + +def _words(s): + return {w for w in re.findall(r"[a-z0-9]+", s.lower()) if len(w) > 2} + + +def read_back(sentence, receipts, store, holes): + """-> (family, ok or None). ok None = a family the seal does not read yet""" + if not receipts: + return "none", None + fams = [] + for rc in receipts: + rc = rc.strip() + m = WD.match(rc) + if m: + s, p, o = (int(x) for x in m.groups()) + ok = bool(store.holds(s, p, o)) + if ok: + ow, sw, ws = _words(store.label(o) or ""), _words(store.label(s) or ""), _words(sentence) + ok = (not ow or bool(ow & ws)) and (not sw or bool(sw & ws) or bool(PRONOUN & set(sentence.lower().split()))) + fams.append(("wd", ok)) + continue + m = HOLE.match(rc) + if m: + fams.append(("hole", m.group(1) in holes)) + continue + if re.fullmatch(r"\d+(?:\s*,\s*\d+)*", rc): + fams.append(("page", None)) + continue + fams.append(("other:" + rc.split(":")[0][:20].lower(), None)) + known = [ok for _f, ok in fams if ok is not None] + fam = fams[0][0] if len({f for f, _ in fams}) == 1 else "+".join(sorted({f for f, _ in fams})) + if not known: + return fam, None + return fam, all(known) + + +def holes_of(state_dir): + p = os.path.join(state_dir, "holes.jsonl") if state_dir else None + out = set() + if p and os.path.isfile(p): + for ln in open(p, encoding="utf-8", errors="replace"): + try: + out.add(str(json.loads(ln)["id"])) + except (ValueError, KeyError): + continue + return out + + +def registry(tree): + """the names of this release's verified parts (RELEASE_HASHES.json, the registry verify_install checks); empty when absent""" + try: + return set(json.load(open(os.path.join(tree, "RELEASE_HASHES.json"), encoding="utf-8")).get("parts") or {}) + except (OSError, ValueError): + return set() + + +def proof_reads(reply, parts): + """-> (ok, why) for a proving-path receipt: every part it names is a part of this release's registry""" + pr = reply.get("proof") or {} + names = list(pr.get("parts") or []) + if not names: + return None, None + missing = [n for n in names if n not in parts] + if missing: + return False, "its proof names %s, which %s not a part of this release" % (", ".join(missing), "is" if len(missing) == 1 else "are") + return True, "proved by %s" % ", ".join(names) + + +def executed(reply): + """a record of what ran: the bench's receipt (state) or the workspace tools' run receipt (started, returncode)""" + ex = reply.get("execution") or {} + return isinstance(ex, dict) and (bool(ex.get("state")) or (ex.get("started") is True and "returncode" in ex)) + + +def seal(reply, store, holes=frozenset(), parts=frozenset()): + """-> the verdict: each sentence's family and read-back, the label the receipts bear (never above the producer's), and + what would be lowered and why. Pure: the reply is not changed here.""" + status = reply.get("status") or "hole" + rows = [] + for s, rc in sentences(reply.get("response")): + fam, ok = read_back(s, rc, store, holes) + rows.append({"text": s, "receipts": rc, "family": fam, "ok": ok}) + asserted = [r for r in rows if r["family"] not in ("hole",)] + failed = [r for r in asserted if r["ok"] is False] + bare = [r for r in asserted if r["family"] == "none"] + unread = [r for r in asserted if r["ok"] is None and r["family"] != "none"] + label = status + why = [] + pok, pwhy = proof_reads(reply, parts) + if status == "answered": + if failed: + label, why = "offered", ["%d receipted sentence(s) do not read back" % len(failed)] + elif pok is False: + label, why = "offered", [pwhy] + elif (bare and not any(r["ok"] for r in asserted) and not unread and pok is None and not executed(reply)): + label, why = "offered", ["no sentence carries a receipt, a proof or a record of what ran"] + if ORDER.get(label, 0) > ORDER.get(status, 0): + label = status # the seal only lowers + return {"status": status, "label": label, "lowered": label != status, "why": why, "proof": pwhy, "rows": rows, + "counts": {"sentences": len(rows), "read_back": sum(1 for r in rows if r["ok"]), "failed": len(failed), + "bare": len(bare), "unread_family": len(unread)}} diff --git a/workbench/selfdev.py b/workbench/selfdev.py new file mode 100644 index 0000000000000000000000000000000000000000..2821d927217fe65125cc24428a4fabe209cf7e91 --- /dev/null +++ b/workbench/selfdev.py @@ -0,0 +1,374 @@ +"""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: " +(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]) diff --git a/workbench/server.py b/workbench/server.py index 0888a5542b424901d993c556ea6402406bd831a4..18b163e8acd5b0154241d29818b4f9b979de1d83 100644 --- a/workbench/server.py +++ b/workbench/server.py @@ -1,1251 +1,2134 @@ -#!/usr/bin/env python3 -"""Oracle7 Workbench - your own Oracle7, on your own machine, with the diagram of everything it is. - - python oracle7.py --workbench [port] (default 8177; opens on http://127.0.0.1:/) - -What it does - Ask talk to Oracle7; the diagram lights the path each answer took and shows why a decline happened - Specialists the 267 admitted specialists and the five systems built the same way, each with its card - Build scaffold a specialist, edit it here, run its dev exam as often as you like, its held-out exam once - Grow admitted specialists join your model and appear on the diagram; a changed file sends one back to the exam - Gaps (off until you turn it on) your declines, grouped into the specialists your model is missing - Code describe a function by examples; the code organ composes it and runs it on your examples - Film record any answer's path on the diagram as a video file, made in your browser - Share package a specialist (its folder, card, exam verdict and hashes) for the community registry - -Privacy: the server listens on 127.0.0.1 only. Nothing is sent anywhere. The gap journal is off by default, lives in -workbench/local/journal.jsonl when on, is never packaged, and the Gaps page deletes it in one click. -Your specialists can only ADD answers: one runs only when the core declined for lack of a reading, never when the core -answered and never when a check (false premise, private question, units...) stopped the answer. Stdlib only.""" -from __future__ import annotations - -import hashlib -import io -import json -import os -import re -import shutil -import subprocess -import sys -import tempfile -import threading -import time -import zipfile -from collections import Counter, defaultdict -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path -from urllib.parse import parse_qs, urlparse - -HERE = Path(__file__).resolve().parent -LOCAL = Path(os.environ.get("ORACLE7_WORKBENCH_LOCAL", str(HERE / "local"))) -SPECS = LOCAL / "specialists" -OUTBOX = LOCAL / "outbox" -JOURNAL = LOCAL / "journal.jsonl" -CONVS = LOCAL / "conversations" -SETTINGS = LOCAL / "settings.json" -STATIC = HERE / "static" -DATA = HERE / "data" -for d in (SPECS, OUTBOX, CONVS): - d.mkdir(parents=True, exist_ok=True) -sys.path.insert(0, str(HERE)) -import exam # noqa: E402 -import sources # noqa: E402 - -# build a specialist from example questions (swarm/run.py): one job at a time, in a thread; the page polls /api/build -BUILD = {"state": "idle"} -_BUILD_LOCK = threading.Lock() - - -def start_build(questions, sid, on_done=None, examples=None): - """examples (text) given: compose a formula specialist from worked examples instead of building from questions""" - with _BUILD_LOCK: - if BUILD.get("state") == "running": - return dict(BUILD) - BUILD.clear() - BUILD.update({"state": "running", "kind": "compose" if examples else "build", "questions": len(questions or []), - "started": time.time()}) - - def work(): - try: - sys.path.insert(0, str(HERE / "swarm")) - import run as swarm_run - r = swarm_run.compose(examples, sid) if examples else swarm_run.build(questions, sid) - r.pop("build", None) - out = {"state": "done", "result": r} - except Exception as e: # noqa: BLE001 - out = {"state": "done", "result": {"outcome": "error", "message": "the build stopped: %s" % str(e)[:200]}} - with _BUILD_LOCK: - BUILD.clear() - BUILD.update(out) - if on_done: - on_done() - threading.Thread(target=work, daemon=True).start() - return dict(BUILD) -# 5.0: point the swarm at a target from the page (swarm/point.py): one run at a time, in a thread; the page polls /api/swarm -SWARM = {"state": "idle", "log": []} -_SWARM_LOCK = threading.Lock() -PICTURE = re.compile(r"^[a-z0-9_]{1,80}\.(png|apng)$") - - -def start_point(target): - """write the target under local/swarm/targets// and run the swarm on it (learn, build, examine, work, report)""" - name = re.sub(r"[^a-z0-9]+", "-", str(target.get("name") or "target").lower()).strip("-")[:40] or "target" - with _SWARM_LOCK: - if SWARM.get("state") == "running": - return dict(SWARM, log=SWARM["log"][-40:]) - SWARM.clear() - SWARM.update({"state": "running", "target": name, "log": [], "started": time.time()}) - d = LOCAL / "swarm" / "targets" / name - d.mkdir(parents=True, exist_ok=True) - (d / "target.json").write_text(json.dumps(target, indent=1, ensure_ascii=False), encoding="utf-8") - - def say(line): - with _SWARM_LOCK: - SWARM["log"].append(str(line)[:300]) - - def work(): - try: - sys.path.insert(0, str(HERE / "swarm")) - import point - rep = point.point(d, WB.eng, say) - pics = sorted(f.name for f in (d / "out" / "pictures").glob("*") if PICTURE.match(f.name)) if (d / "out" / "pictures").exists() else [] - out = {"state": "done", "report": point.markdown(rep), "pictures": pics, "seconds": rep.get("seconds")} - except Exception as e: # noqa: BLE001 - out = {"state": "done", "report": "The swarm stopped: %s" % str(e)[:300], "pictures": []} - with _SWARM_LOCK: - SWARM.update(out) - if WB: - WB.reload() - threading.Thread(target=work, daemon=True).start() - return {"state": "running", "target": name} - - -import mcp # noqa: E402 -import verify # noqa: E402 -import sensors # noqa: E402 -import registry # noqa: E402 - -ID = re.compile(r"^[a-z][a-z0-9-]{1,40}$") -FNAME = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_.-]{0,60}\.(py|json|md|txt|csv)$") -READING_DECLINES = ("act:clarify", "unverified:", "corpus_query", "factoid", "deliberation", "capability:", "arb:", "compose", - "family_precedence:low_credit", "verified:", "cube:") -CHECK_DECLINES = ("precision_guard", "same_name_guard", "weight:", "chat:unresolved") -TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", - ".json": "application/json", ".svg": "image/svg+xml", ".png": "image/png", ".woff2": "font/woff2"} - - -def settings(): - try: - s = json.loads(SETTINGS.read_text(encoding="utf-8")) - except Exception: # noqa: BLE001 - s = {} - s.setdefault("journal", False) - s.setdefault("keep_conversations", True) - return s - - -# ---------------------------------------------------------------- conversations (kept on this computer; one switch turns it off) -CID = re.compile(r"^[a-z0-9]{6,40}$") - - -def conv_path(cid): - if not CID.match(cid or ""): - raise ValueError("bad conversation id") - return CONVS / ("%s.json" % cid) - - -def conv_load(cid): - p = conv_path(cid) - return json.loads(p.read_text(encoding="utf-8")) if p.exists() else {"id": cid, "title": "", "created": int(time.time()), "turns": []} - - -def conv_add(cid, turn): - c = conv_load(cid) - c["turns"].append(turn) - c["updated"] = int(time.time()) - if not c.get("title"): - c["title"] = turn["q"][:70] - conv_path(cid).write_text(json.dumps(c, indent=0), encoding="utf-8") - - -def conv_list(): - out = [] - for p in CONVS.glob("*.json"): - try: - c = json.loads(p.read_text(encoding="utf-8")) - out.append({"id": c["id"], "title": c.get("title") or "(untitled)", "updated": c.get("updated", c.get("created", 0)), - "turns": len(c.get("turns", [])), "answered": sum(1 for t in c.get("turns", []) if t.get("status") == "answered")}) - except Exception: # noqa: BLE001 - pass - return sorted(out, key=lambda x: -x["updated"]) - - -def save_settings(s): - SETTINGS.write_text(json.dumps(s, indent=1), encoding="utf-8") - - -# ---------------------------------------------------------------- the path an answer took (names from the diagram only) -SPEC_GROUP = { - "Physical science": "acoustics additive chemistry densities decay electrical electronics energy fluids fuels materials mechanisms optics " - "physics springs thermo units carbonmat carboncapture renewables hvac".split(), - "Earth & life": "agriculture airquality anatomy biology botany climate ecology entomology forestry genetics geology hydrology marinebio " - "medicine meteorology microbiology mycelial mycology ocean ornithology seismology soil water wildlife greenhouse geography".split(), - "Computing": "algorithms cyber dataformats embedded git iot javascript linux networking python sql logic statistics calculus geometry".split(), - "Space": "astronomy orbits planetary spacecomms spacecraft bodies".split(), - "Humanities": "architecture arthistory economics government grammar law library linguistics literature music mythology poetry " - "psychology sociology ushistory worldhistory".split(), -} - - -def spec_group(sid): - if sid.startswith("rel-"): - return "Relation readers" - base = re.sub(r"-(v\d+|r\d+)$", "", sid).split("-")[0] - for g, names in SPEC_GROUP.items(): - if base in names: - return g - return "Everyday" - - -def trace(path, response, status): - p, resp = str(path or ""), str(response or "") - s = [["L0", "Front door"], ["L1", None]] - if "chat:and_parts" in p or "chat:parts" in p: - s.append(["L3", "Two-part turns"]) - if re.search(r"(^|[>|])chat:(resolved|unresolved)", p): - s.append(["L3", "Follow-up resolver"]) - if p.startswith("workbench:history"): - return [["L0", "Front door"], ["L3", "Conversation engine"], ["L3", "Dialogue organ"], ["L4", "Speaker"], ["L0", "Front door"]] - if p.startswith("workbench:help"): - return [["L0", "Front door"], ["L5", "Self-explanation"], ["L4", "Speaker"], ["L0", "Front door"]] - if p.startswith(("act:", "organ:converse")) or "arb:act_" in p: - s.append(["L3", "Conversation acts"]) - if "family_precedence" in p or "specialist_precedence" in p: - s.append(["L2", "Family precedence"]) - m = re.search(r"specialist:([a-z0-9-]+)", p) - mine = re.match(r"yours:([a-z0-9-]+)", p) - net = re.match(r"network\d*>([a-z0-9 _-]+)", p) - if mine: - s += [["L2", "Specialist call"], ["S", "Yours: " + mine.group(1)]] - elif net and not m: - s.append(["L2", "Specialist call"]) - for tok in net.group(1).split(): - if tok not in ("core_math", "validity"): - s.append(["S", spec_group(tok)]) - s.append(["E", "Math organ"]) - elif m: - g = spec_group(m.group(1)) - s += [["L2", "Specialist call"], ["S", g]] - if g == "Relation readers": - s.append(["V", "Relation store"]) - elif "exact_router" in p: - s += [["L2", "Exact router"], ["V", "Relation store"]] - elif "general_reader" in p: - s += [["L2", "General reader"], ["V", "Relation store"]] - elif "organ:relation" in p: - s += [["L2", "Organ dispatch"], ["V", "Relation store"]] - elif re.search(r"organ:code|code_organ|graded_code", p): - s += [["L2", "Organ dispatch"], ["E", "Code organ"]] - elif re.search(r"organ:math|network>|core_math|agent:maths|algebra:", p): - s += [["L2", "Organ dispatch"], ["E", "Math organ"]] - elif re.search(r"(^|[>|])op:", p): - s += [["L2", "Organ dispatch"], ["E", "Calculator"]] - elif "deliberation" in p: - s += [["L2", "Deliberation"], ["V", "Deep store"]] - elif "compose" in p: - s += [["L2", "Compose"], ["V", "Deep store"]] - elif re.search(r"factoid|cube|corpus_query|verified:", p): - s += [["L2", "Factoid & reading"], ["V", "Deep store"]] - elif re.search(r"capability:|arb:", p) and "arb:act_" not in p: - s += [["L2", "Capability routes"], ["V", "Deep store"]] - elif status != "answered" and p.startswith("act:clarify"): - s.append(["L2", "Front parser"]) - if p.startswith("same_name_guard"): - s += [["L3", "Conversation engine"], ["L4", "Same-name check"], ["V", "Relation store"]] - if re.match(r"precision_guard:(N1|C1|D1|N2|G3)_", p): - s.append(["L4", "Answer checks"]) - elif p.startswith("precision_guard:") or "same_name_guard:withheld" in p: - s.append(["L4", "Final-answer checks" if re.match(r"precision_guard:(G\d|Q\d)", p) else "Precision guard"]) - elif status != "answered" and not p.startswith("act:"): - s.append(["L4", "Precision guard"]) - if status == "answered": - if "From the Wikidata relation store" in resp: - s.append(["L4", "Receipts"]) - s.append(["L4", "Speaker"]) - s.append(["L0", "Front door"]) - out = [] - for x in s: - if not out or out[-1] != x: - out.append(x) - return out - - -def why_declined(path): - p = str(path or "") - if exam.CHECK.search(p): - return "check", "A check stopped it: the answer would rest on a premise or value it could not verify." - if "precision_guard:P" in p: - return "reading", "It found a reply but could not verify it against a record, so it declined rather than guess." - if p.startswith("act:clarify") or "Front parser" in p: - return "parse", "It did not read the question's shape. Rephrasing as a direct question often works." - if any(k in p for k in READING_DECLINES): - return "reading", "Nothing it holds could verify an answer, so it declined rather than guess." - return "other", "It declined rather than guess." - - - -# ---------------------------------------------------------------- what it can do (answered by the Workbench itself) -HELP_TOPICS = [ - ("ask", r"\b(ask|question|answer|decline|why did it|path)\b", - "Ask anything in the box at the bottom left. Each answer lights the path it took on the diagram and shows its route. " - "When Oracle7 cannot verify an answer it declines and says why (a check stopped it, it did not parse the question, or " - "nothing it holds could verify it). 'show path' replays a path; 'route' writes the raw route to the log."), - ("scan", r"\b(scan|my (?:pc|computer|laptop|machine))\b", - "Start > Scan this computer (or type /scan). It reads this machine's system, CPU, memory, disks, uptime and the processes " - "using the most memory - figures and process names only, never your files - and shows them. 'Make it a specialist' adds a " - "reader, so 'how much disk space is free on my computer?' gets the value and the call it was read from."), - ("connect", r"\b(connect|server|ssh|remote)\b", - "Start > Connect a server (or /connect user@host). It uses your own SSH key and runs a fixed list of read-only commands " - "(hostname, uptime, load, memory, disks, top processes, failed services). Name the server, then ask 'how much memory is " - " using?'. A password is never asked for or stored."), - ("files", r"\b(files?|upload|documents?|csv|spreadsheet|notes|tables?)\b", - "Start > Add files (or /files): drop .csv, .tsv, .txt or .md files. Tables answer 'what is the of ?' with " - "the file, row and column; text answers 'what do my notes say about ...?' by quoting the sentence with its file and line. " - "The files are copied into the reader's own folder on this machine."), - ("build", r"\b(build|make|create|write|new)\b.*\bspecialists?\b|\bspecialist\b|\bexams?\b", - "Build: 'New specialist' scaffolds a folder (manifest, organ, panel of test items, scorer) that you edit here, or 'Add the " - "worked example'. Run the dev exam as often as you like and the held-out exam once. It joins your model only if it gets " - "more right than the core alone, adds no false yes, has few wrong answers, stays in its lane on 924 general questions, " - "leaves identity questions alone and is fast. Commands: /new [words], /exam dev, /exam heldout. " - "Or let it be built: 'Ask the swarm' with 3 to 6 example questions (a table of named things is built from Wikidata), or " - "'Compose' with 8 or more worked examples of a calculation (the code composer writes the program from typed moves, units " - "as types, and reads it back; half the examples become its held-out exam). An admitted built specialist joins your group's " - "shared memory (on the Tree of Life spine); a new build first recalls from your commons (yours plus imported memories) and " - "tells you if another group already built one for the same request. In a terminal: memory, memory export, memory import."), - ("grow", r"\b(grow|improve|self.improv|learn|diagram)\b", - "Your model grows only through exams: an admitted specialist appears on the diagram's Specialists ring and answers where " - "the core declined. Change one of its files and it leaves your model until it passes a new held-out set. With the gap " - "journal on (Gaps, or /gaps on) your declines are grouped into the specialists you are missing, and 'Start a specialist' " - "turns a group into a new specialist with your questions as its first dev items."), - ("code", r"\b(code|coding|program|function|python|script|tests?)\b", - "Code (or /code ): ask for a function, e.g. 'check whether a string is a palindrome'. The code organ " - "hands over only programs it has run: a small website, palindromes, factorials, vowel and word counts, word frequencies, " - "HTTP routes, regex extraction, memoisation, a bank-account class, matrix multiply, fizzbuzz, fibonacci, string reversal, " - "JSON round-trips, concurrent work, binary search, tower of hanoi, quicksort, list sums, prime tests and two small games. " - "Check what it hands over with tests of your own: Run tests runs them in a separate Python process with a 10 second limit."), - ("film", r"\b(film|video|record|movie|clip)\b", - "Film (or /film): record answers as a video of the diagram tracing each path beside the question, answer and path. It is " - "made in your browser as a .webm file; 'film this' under any answer records just that one."), - ("voice", r"\b(eleven ?labs|narrat\w*|voice|voiceover|music|sound|audio|image|images|picture|illustrat\w*)\b", - "Film > Narration, sound and images (optional): connect your own ElevenLabs account with its API key to narrate each filmed " - "answer in a voice you choose, lay an ambient sound you describe under it, and open each answer with an illustration " - "(Gemini 2.5 Flash Image or GPT Image, through ElevenLabs; image generation needs their Pro plan). Generated images are " - "labelled as generated in the film and saved in workbench/local/assets. This is the only feature that sends anything off " - "your computer: the narration text, the sound description and the image prompts go to ElevenLabs. The key stays in the page " - "unless you tick 'remember on this computer'."), - ("share", r"\b(share|registry|import|package|hugging ?face)\b", - "Share (or /share ): packages a specialist you built - its folder, exam verdict and the SHA-256 of every file - and shows " - "the command to upload it to the community registry with your own Hugging Face account. Import takes a shared .zip, which " - "must pass its held-out exam on your machine before it joins. Readers of your computer, servers and files are never packaged."), - ("specialists", r"\b(specialists?|systems?|deepspace|trafficcop|chameleon|vision|artist)\b", - "Specialists lists the 267 admitted specialists (106 by field plus 161 relation readers), each with its held-out score and " - "card; search it or type /specialists . Systems describes the five systems built the same way: DeepSpace, Trafficcop, " - "Chameleon (builds websites), Vision (sees and reads) and Artist (makes images by citation)."), - ("mcp", r"\b(mcp|tools?|model context protocol|plug ?in|integrat\w*)\b", - "Start > Connect an MCP server: give the command that starts it (for example npx -y @modelcontextprotocol/server-filesystem " - "with a folder) or its URL. The Workbench lists its tools; tick the ones to use, add a few example questions if you like, and " - "it builds an adaptive specialist. It routes each question to the tool it fits, fills the arguments from the question (or " - "says which one is missing), answers with the tool's result and the exact call it made, and learns from your right/wrong " - "marks under each answer. Questions routed to a server are sent to it, so connect servers you trust."), - ("history", r"\b(history|previous|past|earlier|old|saved) (?:conversations?|chats?)\b|\bconversations?\b|\bremember\w*\b|\bmemory of\b", - "Conversations (the panel on the left; the button at the top opens and collapses it): every conversation is kept on this " - "computer. Open one and carry on - the core picks up its context, so follow-ups still work. Rename, search or delete them, " - "or switch keeping off. 'Make specialist' turns a conversation into a temporary specialist (7 days unless you choose) that " - "answers 'what did we say earlier about...?' and repeated questions by quoting the earlier answer with its date and route. " - "It is checked like any reader before it joins, and leaves your model when it expires."), - ("verify", r"\b(verify|verified|hash\w*|blockchain|chain|solana|on.chain|tamper\w*|authentic\w*|merkle)\b", - "Specialists > Verify this install (or /verify): recomputes the SHA-256 of every shipped part - all 307 specialist folders, " - "the admitted fold chain, this workbench, the launcher and the store manifest - and rebuilds the Merkle root published in " - "RELEASE_HASHES.json. A changed or missing specialist shows by name. 'Check the anchor on Solana' then asks a public Solana " - "RPC (read-only; the only network call) for the release's anchor transaction and confirms its memo carries the same root, " - "so your copy is provably the one released. Stores are checked against PACK_MANIFEST.json by oracle7.py --setup."), - ("sensors", r"\b(sensors?|iot|esp32|arduino|mqtt|serial|usb|thermometer|probe|telemetry|readings?|home assistant|shelly)\b", - "Start > Connect a sensor, or the Sensors tab (or /sensors): an HTTP device or hub that serves JSON or Prometheus metrics " - "(ESP32, Shelly, Tasmota, Home Assistant, weather stations), an MQTT topic, a USB/serial device that prints readings, a log " - "file a logger appends to, or a simulated garden node to try it without hardware. Test shows the numbers it found and what " - "each one measures; Add starts polling it (every 30 s by default, 24 h kept on this computer) and makes a reader you can ask: " - "'what is the soil moisture on garden node?', 'temperature on my sensor today?'. Every answer gives the value, its age, its " - "source and whether it was measured or simulated; a value outside its physical range is rejected and said so. " - "Ask 'is the soil moisture on garden node normal?' and the baseline reader answers from 30 days of 15-minute history: " - "the distance from your ideal band (sensor-ideal), from the sensor's own normal, and any spike, step, drift, stuck run, " - "dropout or oscillation in the last 3 days; declare two coupled quantities (sensor-pair) and it says whether a change " - "is a probable sensor fault or a real one. It never acts on what it measures."), - ("terminal", r"\b(cli|terminal|command line|shell|script|json output)\b", - "Everything that makes sense in a terminal works there too, with the same code: python oracle7.py help lists it. " - "ask \"question\" (answer, status and path), chat, specialists [word], card , systems, verify [--chain], mine, new , " - "example, exam dev|heldout, build \"q1\" \"q2\" ..., compose --file examples.txt, scan, sensors, sensor-test

    , " - "history. Add --json for machine-readable output."), - ("registry", r"\b(oracle7 token|\$?oracle7 registry|registry|register|attest\w*|vouch\w*|on.chain|token|holders?)\b", - "Share > Register on Solana: one specialist, one $ORACLE7. The creator of an admitted specialist signs, in their own wallet (Phantom), one Solana transaction that burns exactly 1 $ORACLE7 and carries, in a memo, the " - "specialist's fingerprint - the SHA-256 of its files, its held-out verdict and its held-out set, and the release it was examined " - "on. Anyone who imports it and sees it pass its held-out exam on their machine can Attest the same way. Check reads every " - "registration and attestation back from the chain, confirms it matches the specialist's files now, and shows each signer's " - "wallet and how much $ORACLE7 it holds. The records travel with the specialist when it is shared. No key is ever seen or " - "stored here; the burn is the only token movement, approved in the creator's wallet. Attesting is free."), - ("privacy", r"\b(privacy|private|data|sent|stored|safe)\b", - "The Workbench answers on 127.0.0.1 only and sends nothing anywhere. The gap journal is off until you turn it on, stays in " - "workbench/local/journal.jsonl, and one click deletes it. Conversations are kept in workbench/local/conversations so you can " - "go back to them; switch that off or delete them in the Conversations panel."), -] -COMMANDS = ["/help - this guide", "/scan - read this computer", "/connect user@host [port] [key] - read a server", - "/files - add files", "/mcp - connect an MCP server", "/sensors - connect and watch sensors", "/new [words] - a new specialist", "/exam dev|heldout - run an exam", - "/specialists - find one", "/systems - the five systems", "/gaps on|off - the gap journal", - "/code - compose a function", "/film - film the answers", "/share - package one", - "/verify - check this install against the published hashes", "/registry - its on-chain registrations and attestations", "/history - open the conversations panel", "/new-chat - start a new conversation", - "/remember [days] - make this conversation a temporary specialist", "/clear - clear the conversation"] -HELP_Q = re.compile(r"^\s*(?:/help\b|help\b|what (?:can|do) (?:you|it|the workbench|oracle7) do|what (?:are|is) (?:your|the|its) " - r"(?:features|commands|abilities)|(?:list|show) (?:me )?(?:the |your |all )?(?:features|commands)|what commands|" - r"how do i (?:use|start)\b|how does (?:this|the workbench) work)", re.I) -HOWTO_Q = re.compile(r"^\s*(?:how (?:do|can|would) i|how to|can i|can you|is it possible to)\b", re.I) - - -SENSORS_ALL = re.compile(r"\b(?:my|our|the|all(?: the| my)?) sensors\b|\bsensor readings\b|\ball (?:my )?readings\b", re.I) -PRONOUN = re.compile(r"\b(it|its|that one|this one|them|they)\b", re.I) -HISTORY_Q = re.compile(r"^\s*(?:what|which) (?:did|was|were) (?:i|my) (?:just |first |last |previous |earlier )?(?:ask|asked|question|questions)\b|" - r"^\s*what (?:was|were) my (first|last|previous|earlier|latest) questions?\b|" - r"^\s*what did you (?:just )?(?:say|answer|tell me)\b|^\s*what (?:have|did) (?:i|we) (?:asked|ask|talk(?:ed)? about|discuss(?:ed)?)\b", re.I) - - -def history_reply(text, sid): - """the conversation itself is kept by the Workbench, so it answers questions about it: what was asked first or last, - what it just said, what we have covered""" - t = str(text or "") - if not HISTORY_Q.search(t): - return None - try: - c = conv_load(sid) - except ValueError: - return None - asked = [x for x in c.get("turns", []) if not str(x.get("path", "")).startswith("workbench:")] - topic = re.search(r"\babout (.+?)[?.!]*$", t, re.I) - if topic: - want = set(sources._words(topic.group(1))) - sources.RECALL_FILLER - hits = [x for x in asked if want & set(sources._words(x["q"] + " " + str(x.get("response", ""))))] - if not hits: - return None # not in this conversation: a saved conversation may recall it - return "\n\n".join("At %s you asked \"%s\". I %s: %s" % (time.strftime("%H:%M", time.localtime(x.get("t", 0))), x["q"], - "answered" if x.get("status") == "answered" else "declined", str(x.get("response", ""))[:400]) for x in hits[-3:]) - if not asked: - return "Nothing has been asked in this conversation yet." - when = lambda x: time.strftime("%H:%M", time.localtime(x.get("t", 0))) - if re.search(r"\bfirst\b", t, re.I): - x = asked[0] - return "Your first question in this conversation (%s) was: \"%s\"" % (when(x), x["q"]) - if re.search(r"\bwhat did you (?:just )?(?:say|answer|tell me)\b", t, re.I): - x = asked[-1] - return "I said (%s), to \"%s\": %s" % (when(x), x["q"], str(x.get("response", ""))[:600]) - if re.search(r"\b(just|last|previous|latest)\b", t, re.I): - x = asked[-1] - return "Your last question (%s) was: \"%s\"" % (when(x), x["q"]) - lines = ["%d. %s - %s" % (i, x["q"], "answered" if x.get("status") == "answered" else "declined") for i, x in enumerate(asked[-12:], max(1, len(asked) - 11))] - return "In this conversation you have asked %d question%s:\n%s" % (len(asked), "" if len(asked) == 1 else "s", "\n".join(lines)) - - -def help_reply(text): - t = str(text or "") - if HELP_Q.search(t): - body = "\n\n".join("%s. %s" % (k.capitalize(), v) for k, _, v in HELP_TOPICS) - return ("Here is everything the Workbench does. The core model answers questions from sourced records and declines what " - "it cannot verify. Around it you can read your computer, servers and files, build and examine specialists, find " - "your gaps, compose code, film answers and share what you build.\n\n" + body + "\n\nCommands:\n" + "\n".join(COMMANDS)) - if HOWTO_Q.search(t): - first = ("registry", "terminal", "sensors", "mcp", "voice", "film", "verify", "history", "files", "scan", "code", "share", "grow", "build", "connect", "specialists", "privacy", "ask") - topics = sorted(HELP_TOPICS, key=lambda x: first.index(x[0]) if x[0] in first else 99) - hits = [v for k, pat, v in topics if re.search(pat, t, re.I)] - if hits: - return "\n\n".join(hits[:2]) - return None - -# ---------------------------------------------------------------- the engine + your specialists (fill declines only) -class Workbench: - def __init__(self, engine): - self.eng = engine - self.lock = threading.Lock() - self.mine = {} # id -> exam.Loaded (admitted and unchanged since its exam) - self.last = {} # session -> (your specialist id, subject) of its last answer, for follow-ups - self.warm = set() # sessions whose context the core holds in this run - self.reload() - - def reload(self): - mine = {} - for d in sorted(SPECS.iterdir()) if SPECS.exists() else []: - st = exam.status(d) - if st["state"] == "admitted": - try: - mine[d.name] = exam.load_specialist(d) - except Exception as e: # noqa: BLE001 - print("workbench: %s did not load: %s" % (d.name, e), file=sys.stderr) - self.mine = mine - - def chat(self, text, sid): - h = help_reply(text) - if h: - return {"status": "answered", "response": h, "path": "workbench:help"} - h = history_reply(text, sid) - if h: - return {"status": "answered", "response": h, "path": "workbench:history"} - # a follow-up to an answer from one of your readers ("what shelf is it on?") is read against that answer's subject - prev = self.last.get(sid) - if prev and PRONOUN.search(text): - sp = self.mine.get(prev[0]) - if sp is not None: - a = sp.reply(PRONOUN.sub(prev[1], text, count=1), sid) - if a and a.get("status") == "answered": - a = dict(a) - a["path"] = "yours:%s>followup>%s" % (prev[0], a.get("path", "")) - return self.remember(text, sid, a) - # questions ADDRESSED to your own things (my computer, my notes, a named server, your table's rows) go to their - # readers first: the core cannot know them, and its general answer would not be about them. The readers' lane - # check bounds how often that can happen on general questions. - now = time.time() - live = {i: sp for i, sp in self.mine.items() if not sp.m.get("expires") or float(sp.m["expires"]) > now} - if SENSORS_ALL.search(text): # "my sensors": every connected sensor answers, one line each - lines = [] - for i, sp in live.items(): - if sp.m.get("organ", {}).get("module", "").startswith("organ_sensor"): - a = sp.organ.answer("%s readings %s" % (sp.organ.name, text), sid) - if a and a.get("status") == "answered": - lines.append(a["response"]) - if lines: - return self.remember(text, sid, {"status": "answered", "response": "\n".join(lines), "path": "yours:sensors>all"}) - for i, sp in live.items(): - if sp.m.get("source"): - a = sp.reply(text, sid) - if a and a.get("status") == "answered": - a = dict(a) - a["path"] = "yours:%s>%s" % (i, a.get("path", "")) - return self.remember(text, sid, a) - if sid not in self.warm: - self.warm.add(sid) - try: - prior = [x for x in conv_load(sid).get("turns", []) if x.get("status") == "answered" - and not str(x.get("path", "")).startswith(("workbench:", "yours:"))][-2:] - except ValueError: - prior = [] - for x in prior: # replies discarded: this only restores what the core remembers - try: - self.eng.chat(x["q"], session_id="wb-" + sid) - except Exception: # noqa: BLE001 - pass - r = self.eng.chat(text, session_id="wb-" + sid) - self.last.pop(sid, None) # the core answered (or declined): follow-ups are its own - path = str(r.get("path", "")) - if r.get("status") != "answered" and live and exam.fillable(path): - for i, sp in live.items(): - a = sp.reply(text, sid) - if a and a.get("status") == "answered": - a = dict(a) - a["path"] = "yours:%s>%s" % (i, a.get("path", "")) - a["declined_by"] = path - return self.remember(text, sid, a) - return r - - def remember(self, text, sid, a): - """hand an answer from your specialist back to the core's conversation memory, so a follow-up ("and in winter?", - "what did I just ask?") reads against it like any answer the core gave""" - m = re.match(r"^yours:([a-z0-9-]+)>", str(a.get("path", ""))) - if m and a.get("subject"): - self.last[sid] = (m.group(1), str(a["subject"])) - - def upd(): - try: - import chat_context_v2 as cc - cc.update("wb-" + sid, text, a) - except Exception: # noqa: BLE001 - pass - try: - self.eng._ex.submit(upd).result(timeout=5) - except Exception: # noqa: BLE001 - pass - return a - - -WB = None - - -def specialists_payload(): - base = json.loads((DATA / "specialists.json").read_text(encoding="utf-8")) if (DATA / "specialists.json").exists() else {"items": []} - yours = [] - for d in sorted(SPECS.iterdir()): - if d.is_dir(): - st = exam.status(d) - m = exam.read_manifest(d) or {} - yours.append({"id": d.name, "name": m.get("name", d.name), "state": st["state"], "note": st.get("note", ""), - "verdict": st.get("verdict")}) - base["yours"] = yours - return base - - -def gaps(): - """declines from the journal, grouped by what is missing: the decline kind, then the domain words the questions share""" - rows = [] - if JOURNAL.exists(): - for line in JOURNAL.read_text(encoding="utf-8").splitlines(): - try: - rows.append(json.loads(line)) - except Exception: # noqa: BLE001 - pass - dec = [r for r in rows if r.get("status") != "answered"] - stop = set("the a an of in on at to is was were are be by for with from and or what which who whom whose where when why how " - "did does do it its this that these those i you he she they we my your his her their our me him them as than then " - "there here can could would should will shall may might must much many most more about into over after before " - "name tell give find please".split()) - groups = defaultdict(list) - for r in dec: - words = [w for w in re.findall(r"[a-z][a-z-]{2,}", r["q"].lower()) if w not in stop] - groups[r.get("why", "other")].append((r["q"], words)) - out = [] - for kind, items in groups.items(): - c = Counter(w for _, ws in items for w in set(ws)) - themes = [] - for w, n in c.most_common(8): - if n < 2: - break - ex = [q for q, ws in items if w in ws][:4] - themes.append({"word": w, "count": n, "examples": ex}) - out.append({"kind": kind, "count": len(items), "themes": themes, "examples": [q for q, _ in items[:5]]}) - out.sort(key=lambda g: -g["count"]) - return {"on": settings().get("journal", False), "turns": len(rows), "declined": len(dec), "groups": out} - - -def scaffold(sid, name, words, examples=()): - d = SPECS / sid - if d.exists(): - raise ValueError("a specialist named %s already exists" % sid) - shutil.copytree(HERE / "template", d) - for f in d.iterdir(): - if f.is_file(): - cue = "|".join(w.replace("-", "[- ]") for w in words) or "(?!x)x" # words are [a-z0-9-] only: safe in JSON and regex - t = f.read_text(encoding="utf-8").replace("__ID__", sid).replace("__NAME__", name.replace('"', "'")).replace( - "__CUE__", cue).replace("__MODULE__", "organ_" + sid.replace("-", "_")) - f.write_text(t, encoding="utf-8") - (d / "organ.py").rename(d / ("organ_%s.py" % sid.replace("-", "_"))) - if examples: # questions from your Gaps page become dev items to answer - pf = d / "panel.json" - panel = json.loads(pf.read_text(encoding="utf-8")) - panel["dev"] = [{"q": q, "a": "", "valid": True, "kind": "fact"} for q in examples] + panel["dev"] - pf.write_text(json.dumps(panel, indent=1), encoding="utf-8") - return d - - -def package(sid): - d = SPECS / sid - st = exam.status(d) - if (exam.read_manifest(d) or {}).get("source"): - raise ValueError("source readers read your own computer, servers or files, so they are not packaged for sharing") - if st["state"] != "admitted": - raise ValueError("only an admitted specialist is packaged (this one is %s); pass its held-out exam first" % st["state"]) - files = sorted(p for p in d.rglob("*") if p.is_file() and "__pycache__" not in p.parts) - sums = {str(p.relative_to(d)).replace("\\", "/"): hashlib.sha256(p.read_bytes()).hexdigest() for p in files} - man = {"id": sid, "state": st["state"], "verdict": st.get("verdict"), "files": sums, - "packaged": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "format": "oracle7-specialist/1"} - h = hashlib.sha256(json.dumps(sums, sort_keys=True).encode()).hexdigest()[:12] - out = OUTBOX / ("%s-%s.zip" % (sid, h)) - with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z: - for p in files: - z.write(p, "%s/%s" % (sid, p.relative_to(d).as_posix())) - z.writestr("%s/SHARE_MANIFEST.json" % sid, json.dumps(man, indent=1)) - return {"zip": str(out), "sha12": h, "state": st["state"], - "command": "huggingface-cli upload Prometheus7/oracle7-specialists \"%s\" specialists/%s --repo-type dataset" % (out, out.name)} - - -def import_zip(path): - p = Path(path).expanduser() - if not p.is_file() or p.suffix != ".zip": - raise ValueError("give the path of a .zip made by Share") - with zipfile.ZipFile(p) as z: - names = z.namelist() - top = {n.split("/")[0] for n in names} - if len(top) != 1: - raise ValueError("a shared specialist is one folder") - sid = top.pop() - if not ID.match(sid) or (SPECS / sid).exists(): - raise ValueError("bad or existing specialist id: %s" % sid) - for n in names: - parts = n.split("/") - if ".." in parts or n.startswith("/") or (len(parts) > 1 and parts[-1] and not FNAME.match(parts[-1])): - raise ValueError("refused file in package: %s" % n) - man = json.loads(z.read("%s/SHARE_MANIFEST.json" % sid)) - tmp = Path(tempfile.mkdtemp(prefix="o7import-")) - z.extractall(tmp) - src = tmp / sid - for rel, h in man["files"].items(): - if hashlib.sha256((src / rel).read_bytes()).hexdigest() != h: - shutil.rmtree(tmp) - raise ValueError("%s does not match its published hash" % rel) - (src / "SHARE_MANIFEST.json").unlink() - for v in src.glob("verdict_*.json"): # their verdict is theirs: it takes the exam again here - v.rename(v.with_name("shared_" + v.name)) - shutil.move(str(src), str(SPECS / sid)) - shutil.rmtree(tmp, ignore_errors=True) - return {"id": sid, "note": "imported; it joins your model only after it passes its held-out exam on this machine"} - - -def slug(s): - return re.sub(r"-+", "-", re.sub(r"[^a-z0-9]+", "-", str(s).lower())).strip("-")[:30] or "x" - - -def machine_probes(rd, on): - """questions whose answers the readings already hold, in parts that do not change between two reads""" - by = {(r["entity"].split()[0], r["signal"]): r for r in rd} - P = [] - if ("cpu", "cores") in by: - P.append(("How many cores does %s have?" % on, str(by[("cpu", "cores")]["value"]))) - if ("system", "hostname") in by: - P.append(("What is the hostname of %s?" % on, str(by[("system", "hostname")]["value"]))) - if ("memory", "used") in by: - P.append(("How much memory is %s using?" % on, by[("memory", "used")]["text"].split(" used of ")[1].split(" (")[0])) - if ("disk", "free") in by: - P.append(("How much disk space is free on %s?" % on, " free of ")) - if ("system", "uptime") in by: - P.append(("How long has %s been up?" % on, "up ")) - if ("processes", "top_memory") in by: - P.append(("What is using the most memory on %s?" % on, "using the most memory")) - P += [("How much memory does a computer need?", None), ("What is the capital of France?", None), ("Who wrote Hamlet?", None)] - return P - - -def file_probes(d): - org = sources.FilesOrgan(folder=d.name + "/files") - org.load() - P = [] - for fname, hdr, rows in org.tables: - keys = [r[0].strip() for r in rows if r and r[0].strip()] - for r in rows[:: max(1, len(rows) // 6)][:6]: - if r and r[0].strip() and keys.count(r[0].strip()) == 1: - for j in range(1, min(len(hdr), len(r))): - if hdr[j].strip() and r[j].strip(): - P.append(("What is the %s of %s?" % (hdr[j].strip(), r[0].strip()), r[j].strip())) - break - for fname, i, sent in org.lines[:: max(1, len(org.lines) // 5)][:5]: - ws = [w for w in sources._words(sent) if len(w) > 4][:3] - if len(ws) >= 2: - P.append(("What do my notes say about %s?" % " ".join(ws), sent[:30])) - P += [("What is the capital of France?", None), ("Who wrote Hamlet?", None)] - return P - - -def run_code(code, tests, timeout=10): - """your function + your tests, in a separate Python process (isolated mode, a temp dir, a time limit)""" - with tempfile.TemporaryDirectory(prefix="o7code-") as t: - f = Path(t) / "run.py" - f.write_text(code + "\n\n" + tests + "\nprint('ALL TESTS PASSED')\n", encoding="utf-8") - try: - r = subprocess.run([sys.executable, "-I", str(f)], cwd=t, capture_output=True, text=True, timeout=timeout) - out = (r.stdout + r.stderr)[-4000:] - return {"ok": r.returncode == 0 and "ALL TESTS PASSED" in r.stdout, "output": out} - except subprocess.TimeoutExpired: - return {"ok": False, "output": "stopped after %d s" % timeout} - - - -# ---------------------------------------------------------------- optional: ElevenLabs for film narration and sound (your key) -# The ONLY feature that sends anything off this machine, and only when you connect it: the text of the narration (or the -# sound description) goes to api.elevenlabs.io with your key; the audio comes back into your film. The key is kept in this -# page's memory, or in workbench/local/settings.json if you tick "remember on this computer". Off by default. -EL_API = "https://api.elevenlabs.io/v1" - - -def el_key(b): - k = str(b.get("key") or settings().get("elevenlabs_key") or "").strip() - if not k: - raise ValueError("connect ElevenLabs first (Film tab): paste your API key") - if not re.match(r"^[A-Za-z0-9_\-]{20,128}$", k): - raise ValueError("that does not look like an ElevenLabs API key") - return k - - -def el_call(path, key, body=None, accept="application/json", timeout=90): - import urllib.error - import urllib.request - req = urllib.request.Request(EL_API + path, data=None if body is None else json.dumps(body).encode(), - headers={"xi-api-key": key, "Content-Type": "application/json", "Accept": accept}, - method="GET" if body is None else "POST") - try: - with urllib.request.urlopen(req, timeout=timeout) as r: - return r.read() - except urllib.error.HTTPError as e: - raw = e.read()[:2000].decode("utf-8", "replace") - try: - d = json.loads(raw).get("detail") - msg = d.get("message") if isinstance(d, dict) else str(d) - except Exception: # noqa: BLE001 - msg = raw[:200] - raise ValueError("ElevenLabs refused it (%d): %s" % (e.code, msg)) - except urllib.error.URLError as e: - raise ValueError("could not reach ElevenLabs: %s" % e.reason) - -# ---------------------------------------------------------------- http -class H(BaseHTTPRequestHandler): - server_version = "oracle7-workbench" - - def log_message(self, *a): - pass - - def _send(self, code, obj, ctype="application/json", raw=None): - b = raw if raw is not None else json.dumps(obj, default=str).encode() - self.send_response(code) - self.send_header("Content-Type", ctype) - self.send_header("Cache-Control", "no-store") - self.send_header("Content-Length", str(len(b))) - self.send_header("X-Content-Type-Options", "nosniff") - self.end_headers() - self.wfile.write(b) - - def _body(self): - n = int(self.headers.get("Content-Length") or 0) - return json.loads(self.rfile.read(min(n, 2_000_000)) or b"{}") - - def _local_only(self): - host = (self.headers.get("Host") or "").split(":")[0] - return host in ("127.0.0.1", "localhost", "[::1]") - - def do_GET(self): # noqa: N802 - if not self._local_only(): - return self._send(403, {"error": "the workbench answers on 127.0.0.1 only"}) - u = urlparse(self.path) - q = {k: v[0] for k, v in parse_qs(u.query).items()} - if u.path in ("/", "/index.html"): - return self._send(200, None, TYPES[".html"], (STATIC / "index.html").read_bytes()) - if u.path.startswith("/static/"): - f = (STATIC / u.path[len("/static/"):]).resolve() - if STATIC.resolve() in f.parents and f.is_file(): - return self._send(200, None, TYPES.get(f.suffix, "application/octet-stream"), f.read_bytes()) - return self._send(404, {"error": "not found"}) - if u.path == "/api/state": - return self._send(200, {"head": WB.eng.tip, "journal": settings().get("journal", False), "yours": sorted(WB.mine), - "elevenlabs_remembered": bool(settings().get("elevenlabs_key"))}) - if u.path == "/api/sensors": - out = [] - for sid, c in sorted(sensors.configs().items()): - h = sensors.history(sid) - latest = {} - for r in h: - if r["ok"]: - latest[r["q"]] = {"v": r["v"], "unit": r["unit"], "t": r["t"]} - out.append({"id": sid, "name": c["name"], "kind": c["kind"], "address": c.get("address", ""), "interval": c.get("interval", 30), - "status": sensors.STATUS.get(sid), "latest": latest, "rejected": sum(1 for r in h if not r["ok"]), - "state": exam.status(SPECS / sid)["state"] if (SPECS / sid).exists() else "none"}) - return self._send(200, {"items": out, "quantities": {k: v[0] for k, v in sensors.QUANTITIES.items()}}) - if u.path == "/api/sensor/series": - rows = [r for r in sensors.history(q.get("id", "")) if r["q"] == q.get("q") and r["ok"]] - step = max(1, len(rows) // 300) - return self._send(200, {"points": [[int(r["t"]), r["v"]] for r in rows[::step]]}) - if u.path == "/api/registry/memo": - sid, kind = q.get("id", ""), q.get("kind", "register") - if not ID.match(sid) or not (SPECS / sid).is_dir(): - return self._send(404, {"error": "no such specialist"}) - try: - return self._send(200, {"memo": registry.memo_for(SPECS / sid, kind), "mint": registry.ORACLE7_MINT, "rpc": registry.RPC, - "burn_raw": registry.BURN_RAW, "decimals": registry.DECIMALS}) - except ValueError as e: - return self._send(400, {"error": str(e)}) - if u.path == "/api/convs": - return self._send(200, {"keep": settings().get("keep_conversations"), "items": conv_list()}) - if u.path == "/api/conv": - return self._send(200, conv_load(q.get("id", ""))) - if u.path == "/api/help": - return self._send(200, {"topics": [{"topic": k, "text": v} for k, _, v in HELP_TOPICS], "commands": COMMANDS}) - if u.path == "/api/specialists": - return self._send(200, specialists_payload()) - if u.path == "/api/systems": - return self._send(200, json.loads((DATA / "systems.json").read_text(encoding="utf-8"))) - if u.path == "/api/gaps": - return self._send(200, gaps()) - if u.path == "/api/card": - sid = q.get("id", "") - f = DATA / "cards" / (sid + ".md") - if re.match(r"^[a-z0-9-]+$", sid) and f.exists(): - return self._send(200, {"id": sid, "md": f.read_text(encoding="utf-8")}) - return self._send(404, {"error": "no card"}) - if u.path == "/api/files": - d = SPECS / q.get("id", "") - if not ID.match(q.get("id", "")) or not d.is_dir(): - return self._send(404, {"error": "no such specialist"}) - return self._send(200, {"files": sorted(p.name for p in d.iterdir() if p.is_file()), "status": exam.status(d)}) - if u.path == "/api/file": - d, name = SPECS / q.get("id", ""), q.get("name", "") - if not ID.match(q.get("id", "")) or not FNAME.match(name) or not (d / name).is_file(): - return self._send(404, {"error": "no such file"}) - return self._send(200, {"name": name, "text": (d / name).read_text(encoding="utf-8")}) - if u.path == "/api/exam": - return self._send(200, exam.progress(q.get("id", ""))) - if u.path == "/api/build": - with _BUILD_LOCK: - return self._send(200, json.loads(json.dumps(BUILD, default=str))) - if u.path == "/api/swarm": - with _SWARM_LOCK: - return self._send(200, json.loads(json.dumps(dict(SWARM, log=SWARM.get("log", [])[-200:]), default=str))) - if u.path == "/api/swarm/picture": - f = q.get("f", "") - t = SWARM.get("target") or "" - path = LOCAL / "swarm" / "targets" / t / "out" / "pictures" / f - if not PICTURE.match(f) or not re.match(r"^[a-z0-9-]{1,40}$", t) or not path.is_file(): - return self._send(404, {"error": "no such picture"}) - return self._send(200, None, "image/png", path.read_bytes()) - return self._send(404, {"error": "not found"}) - - def do_POST(self): # noqa: N802 - if not self._local_only() or (self.headers.get("Origin") and not re.match(r"^https?://(127\.0\.0\.1|localhost)(:\d+)?$", - self.headers.get("Origin", ""))): - return self._send(403, {"error": "the workbench answers its own page on 127.0.0.1 only"}) - u = urlparse(self.path) - try: - b = self._body() - except Exception: # noqa: BLE001 - return self._send(400, {"error": "bad request"}) - try: - if u.path == "/api/chat": - text, sid = str(b.get("text", "")).strip()[:4000], re.sub(r"[^a-z0-9]", "", str(b.get("sid", "x")))[:40] or "x" - if not text: - return self._send(400, {"error": "ask something"}) - t = time.time() - r = WB.chat(text, sid) - status = r.get("status") - kind, why = (None, None) if status == "answered" else why_declined(r.get("path")) - if settings().get("keep_conversations") and not b.get("nokeep") and CID.match(sid): - conv_add(sid, {"t": int(time.time()), "q": text, "status": status, "response": str(r.get("response", "")), - "path": str(r.get("path", "")), "trace": trace(r.get("path"), r.get("response"), status), - "why": why, "ms": int((time.time() - t) * 1000)}) - if settings().get("journal"): - with open(JOURNAL, "a", encoding="utf-8") as fh: - fh.write(json.dumps({"t": int(time.time()), "q": text, "status": status, "why": kind, - "path": str(r.get("path"))[:120]}) + "\n") - return self._send(200, {"status": status, "response": str(r.get("response", "")), "path": str(r.get("path", "")), - "trace": trace(r.get("path"), r.get("response"), status), "why": why, "why_kind": kind, - "ms": int((time.time() - t) * 1000)}) - if u.path == "/api/essay": - # ProseFold v2: an essay composed from this model's own cited records, with the chosen length, reading level, - # technical depth and style (profiles measured from the release's corpora); no language model - import prosefold.options as PO - topic = re.sub(r"\s+", " ", str(b.get("topic", ""))).strip()[:80] - if not topic: - return self._send(400, {"error": "name a topic"}) - pick = lambda k, allowed, d: b.get(k) if b.get(k) in allowed else d # noqa: E731 - voice_path = None - vt = str(b.get("voice_text", "") or "") - if b.get("style") == "custom" and len(vt.split()) >= 150: - LOCAL.mkdir(parents=True, exist_ok=True) - voice_path = LOCAL / "essay_voice.txt" - voice_path.write_text(vt[:200000], encoding="utf-8") - elif b.get("style") == "custom": - return self._send(400, {"error": "paste at least 150 words of the writing whose voice you want"}) - t = time.time() - r = PO.write(WB.eng.chat, topic, length=pick("length", PO.LENGTHS, "medium"), level=pick("level", PO.LEVELS, "general"), - depth=pick("depth", PO.DEPTHS, "standard"), style=pick("style", PO.STYLES, "plain"), voice_path=voice_path, - rewrite=bool(b.get("rewrite"))) - r["ms"] = int((time.time() - t) * 1000) - return self._send(200, r) - if u.path == "/api/journal": - s = settings() - s["journal"] = bool(b.get("on")) - save_settings(s) - return self._send(200, {"on": s["journal"]}) - if u.path == "/api/journal/clear": - JOURNAL.unlink(missing_ok=True) - return self._send(200, {"cleared": True}) - if u.path == "/api/new": - sid = str(b.get("id", "")).strip().lower() - if not ID.match(sid): - return self._send(400, {"error": "an id of lower-case letters, digits and hyphens, 2-41 long"}) - words = [w for w in re.findall(r"[a-z][a-z0-9-]+", str(b.get("words", "")).lower())][:20] - scaffold(sid, str(b.get("name") or sid)[:80], words, [str(x)[:300] for x in (b.get("examples") or [])][:20]) - return self._send(200, {"id": sid}) - if u.path == "/api/scan": - rd = sources.scan_local() - return self._send(200, {"readings": rd}) - if u.path == "/api/scan/save": - d = exam.make_source(SPECS, "this-computer", "this computer", "MachineOrgan", {"target": "local", "name": "this computer"}, - ["computer", "pc", "laptop", "machine", "desktop"]) - exam.start_source(d, machine_probes(sources.scan_local(), "my computer"), on_done=WB.reload) - return self._send(200, {"id": d.name}) - if u.path in ("/api/server", "/api/server/save"): - name = re.sub(r"[^A-Za-z0-9 .-]", "", str(b.get("name") or b.get("host") or ""))[:40].strip() or "server" - host, user, port, key = str(b.get("host", "")).strip(), str(b.get("user", "")).strip(), int(b.get("port") or 22), str(b.get("key", "")).strip() - rd = sources.scan_server(host, user, port, key) - if u.path == "/api/server": - return self._send(200, {"readings": rd}) - d = exam.make_source(SPECS, "server-" + slug(name), name, "MachineOrgan", - {"target": "server", "name": name, "host": host, "user": user, "port": port, "key": key}, [w for w in slug(name).split("-") if w]) - exam.start_source(d, machine_probes(rd, name), on_done=WB.reload) - return self._send(200, {"id": d.name}) - if u.path == "/api/files/add": - name = re.sub(r"[^A-Za-z0-9 .-]", "", str(b.get("name") or "my files"))[:40].strip() or "my files" - sid = str(b.get("id") or "files-" + slug(name)) - if not ID.match(sid): - return self._send(400, {"error": "bad id"}) - d = SPECS / sid - if not d.exists(): - exam.make_source(SPECS, sid, name, "FilesOrgan", {"folder": sid + "/files", "name": name}, ["notes", "files", "documents"]) - saved = [] - for f in (b.get("files") or [])[:50]: - fn = re.sub(r"[^A-Za-z0-9_.-]", "_", Path(str(f.get("name", ""))).name)[:80] - if not re.search(r"\.(csv|tsv|txt|md)$", fn, re.I): - continue - text = str(f.get("text", "")) - if len(text) > 5_000_000: - continue - (d / "files" / fn).write_text(text, encoding="utf-8") - saved.append(fn) - if not saved: - return self._send(400, {"error": "add .csv, .tsv, .txt or .md files (save other documents as text or CSV first)"}) - exam.start_source(d, file_probes(d), on_done=WB.reload) - return self._send(200, {"id": sid, "saved": saved}) - if u.path == "/api/el/connect": - key = el_key(b) - voices = json.loads(el_call("/voices", key)).get("voices", []) - st = settings() - if b.get("remember"): - st["elevenlabs_key"] = key - else: - st.pop("elevenlabs_key", None) - save_settings(st) - return self._send(200, {"voices": [{"id": v["voice_id"], "name": v.get("name", "")} for v in voices][:80], - "remembered": bool(b.get("remember"))}) - if u.path == "/api/el/forget": - st = settings() - st.pop("elevenlabs_key", None) - save_settings(st) - return self._send(200, {"forgotten": True}) - if u.path == "/api/el/speech": - key, text = el_key(b), str(b.get("text", ""))[:2500] - vid = re.sub(r"[^A-Za-z0-9]", "", str(b.get("voice") or "JBFqnCBsd6RMkjVDRZzb")) - audio = el_call("/text-to-speech/%s?output_format=mp3_44100_128" % vid, key, - {"text": text, "model_id": "eleven_multilingual_v2"}, accept="audio/mpeg") - return self._send(200, None, "audio/mpeg", audio) - if u.path == "/api/el/image": - # ElevenLabs Image & Video API: create, poll until completed, download the signed content_url - key, prompt = el_key(b), str(b.get("prompt", ""))[:1500] - model = str(b.get("model") or "gemini-2.5-flash-image") - if model not in ("gemini-2.5-flash-image", "gpt-image-1"): - return self._send(400, {"error": "model must be gemini-2.5-flash-image or gpt-image-1"}) - body = {"model_id": model, "prompt": prompt, "aspect_ratio": "16:9" if model.startswith("gemini") else "3:2"} - gid = json.loads(el_call("/flows/image", key, body))["id"] - t0, g = time.time(), {} - while time.time() - t0 < 180: - g = json.loads(el_call("/flows/image/%s" % re.sub(r"[^A-Za-z0-9_-]", "", gid), key)) - if g.get("status") in ("completed", "failed"): - break - time.sleep(2) - if g.get("status") != "completed": - return self._send(502, {"error": "image not made: %s" % (g.get("failure_reason") or g.get("status") or "timed out")}) - import urllib.request - try: - data = urllib.request.urlopen(g["content_url"], timeout=60).read() - except Exception: # noqa: BLE001 - the signed URL normally needs no key; try once with it - data = urllib.request.urlopen(urllib.request.Request(g["content_url"], headers={"xi-api-key": key}), timeout=60).read() - assets = LOCAL / "assets" - assets.mkdir(exist_ok=True) - ext = ".png" if "png" in str(g.get("content_mime_type", "")) else ".jpg" if "jp" in str(g.get("content_mime_type", "")) else ".webp" - (assets / ("image-%s%s" % (time.strftime("%Y%m%d-%H%M%S"), ext))).write_bytes(data) - return self._send(200, None, g.get("content_mime_type") or "image/png", data) - if u.path == "/api/el/sound": - key, prompt = el_key(b), str(b.get("prompt", ""))[:400] - audio = el_call("/sound-generation", key, {"text": prompt, "duration_seconds": min(22.0, max(2.0, float(b.get("seconds") or 20))), - "prompt_influence": 0.4}, accept="audio/mpeg") - return self._send(200, None, "audio/mpeg", audio) - if u.path == "/api/mcp/connect": - tools = mcp.connect(str(b.get("name", "")).strip(), str(b.get("command", "")).strip(), str(b.get("url", "")).strip(), - str(b.get("token", "")).strip()) - return self._send(200, {"tools": tools}) - if u.path == "/api/mcp/save": - server, tools = str(b.get("name", "")).strip(), [str(t) for t in (b.get("tools") or [])][:40] - if server not in mcp.servers() or not tools: - return self._send(400, {"error": "connect the server and pick at least one tool"}) - sid = "mcp-" + slug(server) - ex = [(str(x.get("q", ""))[:300], (str(x.get("want")) if x.get("want") else None)) for x in (b.get("examples") or [])][:20] - probes = [p for p in ex if p[0]] + [("What is the capital of France?", None), ("Who wrote Hamlet?", None)] - d = exam.make_source(SPECS, sid, "%s tools" % server, "mcp.McpOrgan", {"server": server, "tools": tools, "name": server, "folder": sid}, - [w for w in mcp.words(server)] or ["mcp"]) - exam.start_source(d, probes, on_done=WB.reload) - return self._send(200, {"id": sid}) - if u.path == "/api/feedback": - m = re.match(r"^yours:([a-z0-9-]+)>", str(b.get("path", ""))) - right = bool(b.get("right")) - if not m or not (SPECS / m.group(1)).is_dir(): - return self._send(200, {"learned": False, "note": "marks teach your own specialists; this answer came from the core"}) - d = SPECS / m.group(1) - tool = re.search(r"tool ([\w.-]+)\(", str(b.get("response", ""))) - if (exam.read_manifest(d) or {}).get("organ", {}).get("module", "").startswith("organ_mcp") or tool: - e = mcp.learn(d / "credit.json", tool.group(1), str(b.get("q", "")), right) if tool else {} - exam.start_source(d, None, on_done=WB.reload) # the lane check runs again after learning - return self._send(200, {"learned": True, "tool": tool.group(1) if tool else None, "credit": e}) - return self._send(200, {"learned": False, "note": "noted; only tool specialists learn from marks"}) - if u.path == "/api/conv/rename": - c = conv_load(str(b.get("id", ""))) - c["title"] = str(b.get("title", ""))[:120] - conv_path(c["id"]).write_text(json.dumps(c, indent=0), encoding="utf-8") - return self._send(200, {"ok": True}) - if u.path == "/api/conv/delete": - conv_path(str(b.get("id", ""))).unlink(missing_ok=True) - return self._send(200, {"ok": True}) - if u.path == "/api/conv/delete_all": - for p in CONVS.glob("*.json"): - p.unlink() - return self._send(200, {"ok": True}) - if u.path == "/api/conv/keep": - st = settings() - st["keep_conversations"] = bool(b.get("on")) - save_settings(st) - return self._send(200, {"keep": st["keep_conversations"]}) - if u.path == "/api/conv/specialist": - cid, days = str(b.get("id", "")), max(1, min(365, int(b.get("days") or 7))) - c = conv_load(cid) - done = [t for t in c["turns"] if t.get("status") == "answered" and not str(t.get("path", "")).startswith("workbench:")] - if not done: - return self._send(400, {"error": "this conversation has no answers to remember yet"}) - sid = ("chat-" + slug(c.get("title") or cid))[:34].rstrip("-") + "-" + cid[:4] - d = exam.make_source(SPECS, sid, "conversation: " + (c.get("title") or cid)[:60], "ConversationOrgan", - {"conv": cid, "name": (c.get("title") or cid)[:60]}, ["conversation", "earlier"]) - m = exam.read_manifest(d) - m["expires"] = time.time() + days * 86400 - m["temporary"] = True - (d / "manifest.json").write_text(json.dumps(m, indent=1), encoding="utf-8") - probes = [] - for t in done[:8]: - ws = [w for w in sources._words(t["q"]) if w not in sources.RECALL_FILLER][:3] - if ws: - probes.append(("What did we say earlier about %s?" % " ".join(ws), t["q"][:40])) - probes += [("What is the capital of France?", None), ("Who wrote Hamlet?", None), ("Who directed Jaws?", None)] - exam.start_source(d, probes, on_done=WB.reload) - return self._send(200, {"id": sid, "expires": m["expires"]}) - if u.path == "/api/swarm/point": # 5.0: point the swarm at a target (swarm/point.py) - t = b.get("target") - if isinstance(t, str): - t = json.loads(t) - if not isinstance(t, dict) or not (t.get("learn") or t.get("work")): - return self._send(400, {"error": "a target is JSON with learn and/or work (see the example)"}) - return self._send(200, start_point(t)) - if u.path == "/api/update/check": # 4.9: the newest published release (update.py) - import update - return self._send(200, update.check()) - if u.path == "/api/update/apply": - import update - return self._send(200, update.start_apply()) - if u.path == "/api/update/status": - import update - return self._send(200, dict(update.STATUS)) - if u.path == "/api/verify": - return self._send(200, verify.verify_install()) - if u.path == "/api/verify/chain": - return self._send(200, verify.check_anchor(str(b.get("signature") or "") or None)) - if u.path == "/api/sensor/test": - cfg = {"kind": str(b.get("kind", "")), "address": str(b.get("address", "")).strip(), "user": str(b.get("user", "")), - "password": str(b.get("password", ""))} - if cfg["kind"] == "http" and not re.match(r"^https?://", cfg["address"]): - return self._send(400, {"error": "the address must start with http:// or https://"}) - vals, where = sensors.read_source(cfg) - return self._send(200, {"source": where, "fields": [{"path": k, "value": v, "guess": sensors.guess_quantity(k)} - for k, v in list(vals.items())[:60]]}) - if u.path == "/api/sensor/add": - name = re.sub(r"[^A-Za-z0-9 .-]", "", str(b.get("name") or "my sensor"))[:40].strip() or "my sensor" - fields = [{"path": str(f["path"])[:120], "quantity": str(f["quantity"])[:40], "unit": str(f.get("unit") or "")[:12]} - for f in (b.get("fields") or []) if f.get("path") and f.get("quantity")][:30] - if not fields: - return self._send(400, {"error": "pick at least one reading and say what it measures"}) - sid = "sensor-" + slug(name) - c = {"id": sid, "name": name, "kind": str(b.get("kind", "")), "address": str(b.get("address", "")).strip(), - "interval": max(5, min(3600, int(b.get("interval") or 30))), "fields": fields, - "user": str(b.get("user", "")), "password": str(b.get("password", "")), "added": int(time.time())} - sensors.save_config(c) - sensors.poll_once(c) - sensors.start_poller(sid) - d = exam.make_source(SPECS, sid, name, "sensors.SensorOrgan", {"sensor": sid, "name": name}, - [w for w in slug(name).split("-") if w] or ["sensor"]) - qs = sorted({f["quantity"] for f in fields}) - probes = [("What is the %s on %s?" % (qq, name), qq) for qq in qs] - probes += [("What is the temperature of the Sun?", None), ("How much does a litre of water weigh?", None)] - exam.start_source(d, probes, on_done=WB.reload) - return self._send(200, {"id": sid}) - if u.path == "/api/sensor/remove": - sid = str(b.get("id", "")) - if not ID.match(sid): - return self._send(400, {"error": "bad id"}) - for p in (sensors.DIR / ("%s.json" % sid), sensors.DIR / ("%s.jsonl" % sid)): - p.unlink(missing_ok=True) - shutil.rmtree(SPECS / sid, ignore_errors=True) - WB.reload() - return self._send(200, {"removed": sid}) - if u.path == "/api/solana/rpc": - raw = json.dumps(b).encode() - out = registry.relay(raw) - return self._send(200, None, "application/json", out) - if u.path == "/api/registry/record": - sid = str(b.get("id", "")) - if not ID.match(sid) or not (SPECS / sid).is_dir(): - return self._send(400, {"error": "no such specialist"}) - return self._send(200, {"records": registry.record(SPECS / sid, str(b.get("kind", "")), str(b.get("signature", "")).strip())}) - if u.path == "/api/registry/check": - sid = str(b.get("id", "")) - if not ID.match(sid) or not (SPECS / sid).is_dir(): - return self._send(400, {"error": "no such specialist"}) - return self._send(200, registry.check(SPECS / sid)) - if u.path == "/api/build": - qs = [str(x).strip() for x in (b.get("questions") or []) if str(x).strip()][:12] - sid = str(b.get("id", "")).strip() or None - if len(qs) < 3: - return self._send(400, {"error": "give at least 3 example questions, one per line"}) - if sid and (not ID.match(sid) or (SPECS / sid).exists()): - return self._send(400, {"error": "that id is taken or not valid (lower-case letters, digits, hyphens)"}) - return self._send(200, start_build(qs, sid, on_done=WB.reload)) - if u.path == "/api/compose": - text = str(b.get("examples", ""))[:200000] - sid = str(b.get("id", "")).strip() or None - if text.count("->") + text.count("=>") < 8: - return self._send(400, {"error": "give at least 8 worked examples, one per line: inputs -> answer"}) - if sid and (not ID.match(sid) or (SPECS / sid).exists()): - return self._send(400, {"error": "that id is taken or not valid (lower-case letters, digits, hyphens)"}) - return self._send(200, start_build(None, sid, on_done=WB.reload, examples=text)) - if u.path == "/api/example": - src = HERE / "examples" / "habitable-zone" - if (SPECS / src.name).exists(): - return self._send(400, {"error": "the example is already in your specialists"}) - shutil.copytree(src, SPECS / src.name, ignore=shutil.ignore_patterns("__pycache__", "verdict_*", "exam_log*")) - return self._send(200, {"id": src.name}) - if u.path == "/api/file": - d, name = SPECS / str(b.get("id", "")), str(b.get("name", "")) - if not ID.match(str(b.get("id", ""))) or not d.is_dir() or not FNAME.match(name) or name.startswith("verdict_"): - return self._send(400, {"error": "that file cannot be written here"}) - (d / name).write_text(str(b.get("text", "")), encoding="utf-8") - WB.reload() - return self._send(200, {"saved": name, "status": exam.status(d)}) - if u.path == "/api/exam": - sid, split = str(b.get("id", "")), str(b.get("split", "dev")) - if not ID.match(sid) or not (SPECS / sid).is_dir() or split not in ("dev", "heldout"): - return self._send(400, {"error": "which specialist, and dev or heldout?"}) - exam.start(SPECS / sid, split, WB.eng, on_done=WB.reload) - return self._send(200, exam.progress(sid)) - if u.path == "/api/package": - sid = str(b.get("id", "")) - if not ID.match(sid) or not (SPECS / sid).is_dir(): - return self._send(400, {"error": "no such specialist"}) - return self._send(200, package(sid)) - if u.path == "/api/import": - r = import_zip(str(b.get("path", ""))) - return self._send(200, r) - if u.path == "/api/code/run": - return self._send(200, run_code(str(b.get("code", ""))[:100_000], str(b.get("tests", ""))[:50_000])) - except ValueError as e: - return self._send(400, {"error": str(e)}) - except Exception as e: # noqa: BLE001 - return self._send(500, {"error": "%s: %s" % (type(e).__name__, e)}) - return self._send(404, {"error": "not found"}) - - -def serve(engine, port=8177): - global WB - WB = Workbench(engine) - sensors.start_all() - srv = ThreadingHTTPServer(("127.0.0.1", port), H) - print("Oracle7 Workbench (%s) on http://127.0.0.1:%d/" % (engine.tip, port), flush=True) - srv.serve_forever() +#!/usr/bin/env python3 +"""Oracle7 Workbench - your own Oracle7, on your own machine, with the diagram of everything it is. + + python oracle7.py --workbench [port] (default 8177; opens on http://127.0.0.1:/) + +What it does + Ask talk to Oracle7; the diagram lights the path each answer took and shows why a decline happened + Specialists the 267 admitted specialists and the five systems built the same way, each with its card + Build scaffold a specialist, edit it here, run its dev exam as often as you like, its held-out exam once + Grow admitted specialists join your model and appear on the diagram; a changed file sends one back to the exam + Gaps (off until you turn it on) your declines, grouped into the specialists your model is missing + Code describe a function by examples; the code organ composes it and runs it on your examples + Film record any answer's path on the diagram as a video file, made in your browser + Share package a specialist (its folder, card, exam verdict and hashes) for the community registry + +Privacy: the server listens on 127.0.0.1 only. Nothing is sent anywhere. The gap journal is off by default, lives in +workbench/local/journal.jsonl when on, is never packaged, and the Gaps page deletes it in one click. +Your specialists can only ADD answers: one runs only when the core declined for lack of a reading, never when the core +answered and never when a check (false premise, private question, units...) stopped the answer. Stdlib only.""" +from __future__ import annotations + +import hashlib +import io +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +import threading +import time +import zipfile +from collections import Counter, defaultdict +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import parse_qs, urlparse + +HERE = Path(__file__).resolve().parent +LOCAL = Path(os.environ.get("ORACLE7_WORKBENCH_LOCAL", str(HERE / "local"))) +SPECS = LOCAL / "specialists" +OUTBOX = LOCAL / "outbox" +JOURNAL = LOCAL / "journal.jsonl" +CONVS = LOCAL / "conversations" +SETTINGS = LOCAL / "settings.json" +STATIC = HERE / "static" +DATA = HERE / "data" +for d in (SPECS, OUTBOX, CONVS): + d.mkdir(parents=True, exist_ok=True) +sys.path.insert(0, str(HERE)) +import exam # noqa: E402 +import sources # noqa: E402 + +# 12.0 C11: what this process runs. The workbench part's hash (verify.py's recipe) when the process started, again on +# asking, and as the assembled release records it; the oracle7.py it started from; the modules it has imported whose +# files changed on disk since it started (the process holds the older code until restarted). Never a guess from a 200 at /. +MAX_TEXT = 1_000_000 # one message; a longer one is refused with this number, never cut + + +_WORK_VERB = re.compile( + r"(?i)^\s*(?:(?:ok(?:ay)?|now|then|also|and|so)[\s,]+)*(?:please\s+)?" + r"(?:build|make|create|write|add|fix|repair|run|rerun|stop|test|implement|change|edit|replace|rename|undo|redo|" + r"go|adopt|roll\s*back|propose|improve|drop|remove|delete|save|use|open|continue|resume|keep|cancel|allow|start|" + r"set\s+up|generate|update|revise|turn|put|join|merge|read|list|show\s+(?:me\s+)?(?:the\s+)?(?:diff|log|files?|tasks?|changes))\b") +_TALK_VERB = re.compile(r"(?i)^\s*(?:please\s+)?(?:explain|describe|discuss|compare|tell|talk|think|consider|imagine|" + r"suppose|what\s+if|why|how|what)\b") + + +def _told_outcome(native): + """12.5 step 11 (round-2 design 4.A): the clause of this turn that asks for something to be done, from the native reading + (a non-negative clause in request mood); None when the reading is not available (then `_commanded` is the fallback)""" + if not isinstance(native, dict) or not native.get("available", True) or str(native.get("basis", "")).startswith( + ("turn_reader:loading", "turn_reader:error")): + return None + for c in native.get("outcomes") or []: + if isinstance(c, dict) and not c.get("negative") and ((c.get("frame") or {}).get("mood") == "request"): + return c + return None + + +def _mood_bar(prop, native): + """the turn's own mood bars the claim receiver (4.A): a turn that asks for something done is never received as a claim + marked answered; the claim receiver's words stay, under a hole naming the clause nothing here carried out""" + if not isinstance(prop, dict) or prop.get("status") != "answered": + return prop + c = _told_outcome(native) + if c is None: + return prop + clause = " ".join(str(c.get("text") or "").split())[:200] + head = ("Not carried out: you asked “%s”, and no part here took it as work, so nothing was done for it." % clause) + return dict(prop, status="hole", path="claim:barred>" + str(prop.get("path") or ""), + response=head + "\n" + str(prop.get("response") or ""), + execution={"state": "not_run", "cause": "uncovered", "clause": c.get("id"), + "takes": ["say it as a request a part takes (run, read, edit, make, a function from examples, " + "a tool over a table)"]}) + + +def _commanded(text, reading=None): + """The turn is a command (imperative, or a request envelope around one), not a statement or a question about one. + Quoted or negated commands ("don't build it yet", "\"build x\" is what I said") stay with conversation.""" + t = str(text or "") + body = (reading or {}).get("reading") if (reading or {}).get("steps") else t + body = str(body or t) + if re.match(r"""(?i)^\s*(?:["'`]|(?:don'?t|do\s+not|never)\b)""", body): + return False + if _TALK_VERB.match(body): + return False + return bool(_WORK_VERB.match(body)) + + +def _wb_hash(): + import verify as _v + return _v.part_hash(HERE) + + +def _file_sha(p): + try: + return hashlib.sha256(Path(p).read_bytes()).hexdigest() + except OSError: + return None + + +BOOT = {"t": time.time(), "pid": os.getpid(), "workbench": _wb_hash(), "oracle7_py": _file_sha(HERE.parent / "oracle7.py"), + "mtimes": {}} + + +def _boot_mtimes(): + for m in list(sys.modules.values()): + f = getattr(m, "__file__", None) + if f and str(Path(f).resolve()).startswith(str(HERE.parent)): + try: + BOOT["mtimes"].setdefault(str(Path(f).resolve()), os.path.getmtime(f)) + except OSError: + pass + + +def head_proof(r, tip): + """12.5 step 4 (round-2 design 1.1, the proving-path receipt): an answer of the admitted head says which parts of this + release it rests on, by their names in RELEASE_HASHES.json: the admitted head (core/admitted, its tip named), and the + specialist its own path names (specialists/). The seal reads these names back against the registry.""" + parts = ["core/admitted"] + for m in re.finditer(r"specialist:([A-Za-z0-9_.-]+)", str(r.get("path", ""))): + parts.append("specialists/" + m.group(1)) + return {"by": "head", "tip": str(tip or ""), "parts": parts, "path": str(r.get("path", ""))} + + +def identity(): + _boot_mtimes() + now = _wb_hash() + rel = {} + try: + rel = json.loads((HERE.parent / "RELEASE_HASHES.json").read_text(encoding="utf-8")) + except Exception: # noqa: BLE001 + pass + rwb = ((rel.get("parts") or {}).get("workbench") or {}) + stale = [] + for f, mt in sorted(BOOT["mtimes"].items()): + try: + if os.path.getmtime(f) > max(mt, BOOT["t"]): + stale.append(os.path.relpath(f, HERE.parent)) + except OSError: + stale.append(os.path.relpath(f, HERE.parent) + " (gone)") + return {"tree": str(HERE.parent), "state": os.environ.get("ORACLE7_STATE"), "pid": BOOT["pid"], + "started": BOOT["t"], "uptime_s": int(time.time() - BOOT["t"]), "version": rel.get("version"), + "release": rel.get("release"), "release_merkle_root": rel.get("merkle_root"), + "workbench_at_start": {"sha256": BOOT["workbench"][0], "files": BOOT["workbench"][1]}, + "workbench_now": {"sha256": now[0], "files": now[1]}, + "workbench_in_release": {"sha256": rwb.get("sha256"), "files": rwb.get("files")}, + "running_is_on_disk": now[0] == BOOT["workbench"][0] and not stale, + "running_is_release": BOOT["workbench"][0] == rwb.get("sha256"), + "oracle7_py_sha256": BOOT["oracle7_py"], "loaded_but_changed_on_disk": stale, + "build": hashlib.sha256((BOOT["workbench"][0] + (BOOT["oracle7_py"] or "")).encode()).hexdigest()[:16], + "language": language_status()} + + +def language_status(): + """Cheap readiness evidence; does not start another reader or hash the pack.""" + if os.environ.get("ORACLE7_CONVERSE", "1") == "0": + return {"stage": "disabled", "reader": False, "conversation": False, "speaker": False, "error": None} + wb = globals().get("WB") + cv = getattr(wb, "_cv", None) + if cv and hasattr(cv, "status"): + return cv.status() + error = getattr(wb, "_cv_error", None) + return {"stage": "failed" if error else "not_started", "reader": False, "conversation": False, + "speaker": False, "error": error} + + +def identity_brief(): + """the build id every reply carries (cheap: the start hashes; /api/identity checks the disk again)""" + return {"build": hashlib.sha256((BOOT["workbench"][0] + (BOOT["oracle7_py"] or "")).encode()).hexdigest()[:16], + "workbench": BOOT["workbench"][0][:16], "pid": BOOT["pid"], "state": os.environ.get("ORACLE7_STATE")} + +# build a specialist from example questions (swarm/run.py): one job at a time, in a thread; the page polls /api/build +BUILD = {"state": "idle"} +_BUILD_LOCK = threading.Lock() + + +def start_build(questions, sid, on_done=None, examples=None): + """examples (text) given: compose a formula specialist from worked examples instead of building from questions""" + with _BUILD_LOCK: + if BUILD.get("state") == "running": + return dict(BUILD) + BUILD.clear() + BUILD.update({"state": "running", "kind": "compose" if examples else "build", "questions": len(questions or []), + "started": time.time()}) + + def work(): + try: + sys.path.insert(0, str(HERE / "swarm")) + import run as swarm_run + r = swarm_run.compose(examples, sid) if examples else swarm_run.build(questions, sid) + r.pop("build", None) + out = {"state": "done", "result": r} + except Exception as e: # noqa: BLE001 + out = {"state": "done", "result": {"outcome": "error", "message": "the build stopped: %s" % str(e)[:200]}} + with _BUILD_LOCK: + BUILD.clear() + BUILD.update(out) + if on_done: + on_done() + threading.Thread(target=work, daemon=True).start() + return dict(BUILD) +# 5.0: point the swarm at a target from the page (swarm/point.py): one run at a time, in a thread; the page polls /api/swarm +SWARM = {"state": "idle", "log": []} +_SWARM_LOCK = threading.Lock() +PICTURE = re.compile(r"^[a-z0-9_]{1,80}\.(png|apng)$") + + +def start_point(target): + """write the target under local/swarm/targets// and run the swarm on it (learn, build, examine, work, report)""" + name = re.sub(r"[^a-z0-9]+", "-", str(target.get("name") or "target").lower()).strip("-")[:40] or "target" + with _SWARM_LOCK: + if SWARM.get("state") == "running": + return dict(SWARM, log=SWARM["log"][-40:]) + SWARM.clear() + SWARM.update({"state": "running", "target": name, "log": [], "started": time.time()}) + d = LOCAL / "swarm" / "targets" / name + d.mkdir(parents=True, exist_ok=True) + (d / "target.json").write_text(json.dumps(target, indent=1, ensure_ascii=False), encoding="utf-8") + + def say(line): + with _SWARM_LOCK: + SWARM["log"].append(str(line)[:300]) + + def work(): + try: + sys.path.insert(0, str(HERE / "swarm")) + import point + rep = point.point(d, WB.eng, say) + pics = sorted(f.name for f in (d / "out" / "pictures").glob("*") if PICTURE.match(f.name)) if (d / "out" / "pictures").exists() else [] + out = {"state": "done", "report": point.markdown(rep), "pictures": pics, "seconds": rep.get("seconds")} + except Exception as e: # noqa: BLE001 + out = {"state": "done", "report": "The swarm stopped: %s" % str(e)[:300], "pictures": []} + with _SWARM_LOCK: + SWARM.update(out) + if WB: + WB.reload() + threading.Thread(target=work, daemon=True).start() + return {"state": "running", "target": name} + + +import mcp # noqa: E402 +import verify # noqa: E402 +import sensors # noqa: E402 +import registry # noqa: E402 + +ID = re.compile(r"^[a-z][a-z0-9-]{1,40}$") +FNAME = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_.-]{0,60}\.(py|json|md|txt|csv)$") +READING_DECLINES = ("act:clarify", "unverified:", "corpus_query", "factoid", "deliberation", "capability:", "arb:", "compose", + "family_precedence:low_credit", "verified:", "cube:") +CHECK_DECLINES = ("precision_guard", "same_name_guard", "weight:", "chat:unresolved") +TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", + ".json": "application/json", ".svg": "image/svg+xml", ".png": "image/png", ".woff2": "font/woff2"} + + +def settings(): + try: + s = json.loads(SETTINGS.read_text(encoding="utf-8")) + except Exception: # noqa: BLE001 + s = {} + s.setdefault("journal", False) + s.setdefault("keep_conversations", True) + return s + + +# ---------------------------------------------------------------- conversations (kept on this computer; one switch turns it off) +CID = re.compile(r"^[a-z0-9]{6,40}$") + + +def conv_path(cid): + if not CID.match(cid or ""): + raise ValueError("bad conversation id") + return CONVS / ("%s.json" % cid) + + +def conv_load(cid): + p = conv_path(cid) + return json.loads(p.read_text(encoding="utf-8")) if p.exists() else {"id": cid, "title": "", "created": int(time.time()), "turns": []} + + +def conv_add(cid, turn): + c = conv_load(cid) + c["turns"].append(turn) + c["updated"] = int(time.time()) + if not c.get("title"): + c["title"] = turn["q"][:70] + conv_path(cid).write_text(json.dumps(c, indent=0), encoding="utf-8") + + +def conv_list(): + out = [] + for p in CONVS.glob("*.json"): + try: + c = json.loads(p.read_text(encoding="utf-8")) + out.append({"id": c["id"], "title": c.get("title") or "(untitled)", "updated": c.get("updated", c.get("created", 0)), + "turns": len(c.get("turns", [])), "answered": sum(1 for t in c.get("turns", []) if t.get("status") == "answered")}) + except Exception: # noqa: BLE001 + pass + return sorted(out, key=lambda x: -x["updated"]) + + +def save_settings(s): + SETTINGS.write_text(json.dumps(s, indent=1), encoding="utf-8") + + +# ---------------------------------------------------------------- the path an answer took (names from the diagram only) +SPEC_GROUP = { + "Physical science": "acoustics additive chemistry densities decay electrical electronics energy fluids fuels materials mechanisms optics " + "physics springs thermo units carbonmat carboncapture renewables hvac".split(), + "Earth & life": "agriculture airquality anatomy biology botany climate ecology entomology forestry genetics geology hydrology marinebio " + "medicine meteorology microbiology mycelial mycology ocean ornithology seismology soil water wildlife greenhouse geography".split(), + "Computing": "algorithms cyber dataformats embedded git iot javascript linux networking python sql logic statistics calculus geometry".split(), + "Space": "astronomy orbits planetary spacecomms spacecraft bodies".split(), + "Humanities": "architecture arthistory economics government grammar law library linguistics literature music mythology poetry " + "psychology sociology ushistory worldhistory".split(), +} + + +def spec_group(sid): + if sid.startswith("rel-"): + return "Relation readers" + base = re.sub(r"-(v\d+|r\d+)$", "", sid).split("-")[0] + for g, names in SPEC_GROUP.items(): + if base in names: + return g + return "Everyday" + + +def trace(path, response, status): + p, resp = str(path or ""), str(response or "") + s = [["L0", "Front door"], ["L1", None]] + if "chat:and_parts" in p or "chat:parts" in p: + s.append(["L3", "Two-part turns"]) + if re.search(r"(^|[>|])chat:(resolved|unresolved)", p): + s.append(["L3", "Follow-up resolver"]) + if p.startswith("workbench:history"): + return [["L0", "Front door"], ["L3", "Conversation engine"], ["L3", "Dialogue organ"], ["L4", "Speaker"], ["L0", "Front door"]] + if p.startswith("workbench:help"): + return [["L0", "Front door"], ["L5", "Self-explanation"], ["L4", "Speaker"], ["L0", "Front door"]] + if p.startswith(("act:", "organ:converse")) or "arb:act_" in p: + s.append(["L3", "Conversation acts"]) + if "family_precedence" in p or "specialist_precedence" in p: + s.append(["L2", "Family precedence"]) + m = re.search(r"specialist:([a-z0-9-]+)", p) + mine = re.match(r"yours:([a-z0-9-]+)", p) + net = re.match(r"network\d*>([a-z0-9 _-]+)", p) + if mine: + s += [["L2", "Specialist call"], ["S", "Yours: " + mine.group(1)]] + elif net and not m: + s.append(["L2", "Specialist call"]) + for tok in net.group(1).split(): + if tok not in ("core_math", "validity"): + s.append(["S", spec_group(tok)]) + s.append(["E", "Math organ"]) + elif m: + g = spec_group(m.group(1)) + s += [["L2", "Specialist call"], ["S", g]] + if g == "Relation readers": + s.append(["V", "Relation store"]) + elif "exact_router" in p: + s += [["L2", "Exact router"], ["V", "Relation store"]] + elif "general_reader" in p: + s += [["L2", "General reader"], ["V", "Relation store"]] + elif "organ:relation" in p: + s += [["L2", "Organ dispatch"], ["V", "Relation store"]] + elif re.search(r"organ:code|code_organ|graded_code", p): + s += [["L2", "Organ dispatch"], ["E", "Code organ"]] + elif re.search(r"organ:math|network>|core_math|agent:maths|algebra:", p): + s += [["L2", "Organ dispatch"], ["E", "Math organ"]] + elif re.search(r"(^|[>|])op:", p): + s += [["L2", "Organ dispatch"], ["E", "Calculator"]] + elif "deliberation" in p: + s += [["L2", "Deliberation"], ["V", "Deep store"]] + elif "compose" in p: + s += [["L2", "Compose"], ["V", "Deep store"]] + elif re.search(r"factoid|cube|corpus_query|verified:", p): + s += [["L2", "Factoid & reading"], ["V", "Deep store"]] + elif re.search(r"capability:|arb:", p) and "arb:act_" not in p: + s += [["L2", "Capability routes"], ["V", "Deep store"]] + elif status != "answered" and p.startswith("act:clarify"): + s.append(["L2", "Front parser"]) + if p.startswith("same_name_guard"): + s += [["L3", "Conversation engine"], ["L4", "Same-name check"], ["V", "Relation store"]] + if re.match(r"precision_guard:(N1|C1|D1|N2|G3)_", p): + s.append(["L4", "Answer checks"]) + elif p.startswith("precision_guard:") or "same_name_guard:withheld" in p: + s.append(["L4", "Final-answer checks" if re.match(r"precision_guard:(G\d|Q\d)", p) else "Precision guard"]) + elif status != "answered" and not p.startswith("act:"): + s.append(["L4", "Precision guard"]) + if status == "answered": + if "From the Wikidata relation store" in resp: + s.append(["L4", "Receipts"]) + s.append(["L4", "Speaker"]) + s.append(["L0", "Front door"]) + out = [] + for x in s: + if not out or out[-1] != x: + out.append(x) + return out + + +def why_declined(path): + p = str(path or "") + if exam.CHECK.search(p): + return "check", "A check stopped it: the answer would rest on a premise or value it could not verify." + if "precision_guard:P" in p: + return "reading", "It found a reply but could not verify it against a record, so it declined rather than guess." + if p.startswith("act:clarify") or "Front parser" in p: + return "parse", "It did not read the question's shape. Rephrasing as a direct question often works." + if any(k in p for k in READING_DECLINES): + return "reading", "Nothing it holds could verify an answer, so it declined rather than guess." + return "other", "It declined rather than guess." + + + +# ---------------------------------------------------------------- what it can do (answered by the Workbench itself) +HELP_TOPICS = [ + ("ask", r"\b(ask|question|answer|decline|why did it|path)\b", + "Ask anything in the box at the bottom left. Each answer lights the path it took on the diagram and shows its route. " + "When Oracle7 cannot verify an answer it declines and says why (a check stopped it, it did not parse the question, or " + "nothing it holds could verify it). 'show path' replays a path; 'route' writes the raw route to the log."), + ("scan", r"\b(scan|my (?:pc|computer|laptop|machine))\b", + "Start > Scan this computer (or type /scan). It reads this machine's system, CPU, memory, disks, uptime and the processes " + "using the most memory - figures and process names only, never your files - and shows them. 'Make it a specialist' adds a " + "reader, so 'how much disk space is free on my computer?' gets the value and the call it was read from."), + ("connect", r"\b(connect|server|ssh|remote)\b", + "Start > Connect a server (or /connect user@host). It uses your own SSH key and runs a fixed list of read-only commands " + "(hostname, uptime, load, memory, disks, top processes, failed services). Name the server, then ask 'how much memory is " + " using?'. A password is never asked for or stored."), + ("files", r"\b(files?|upload|documents?|csv|spreadsheet|notes|tables?)\b", + "Start > Add files (or /files): drop .csv, .tsv, .txt or .md files. Tables answer 'what is the of ?' with " + "the file, row and column; text answers 'what do my notes say about ...?' by quoting the sentence with its file and line. " + "The files are copied into the reader's own folder on this machine."), + ("build", r"\b(build|make|create|write|new)\b.*\bspecialists?\b|\bspecialist\b|\bexams?\b", + "Build: 'New specialist' scaffolds a folder (manifest, organ, panel of test items, scorer) that you edit here, or 'Add the " + "worked example'. Run the dev exam as often as you like and the held-out exam once. It joins your model only if it gets " + "more right than the core alone, adds no false yes, has few wrong answers, stays in its lane on 924 general questions, " + "leaves identity questions alone and is fast. Commands: /new [words], /exam dev, /exam heldout. " + "Or let it be built: 'Ask the swarm' with 3 to 6 example questions (a table of named things is built from Wikidata), or " + "'Compose' with 8 or more worked examples of a calculation (the code composer writes the program from typed moves, units " + "as types, and reads it back; half the examples become its held-out exam). An admitted built specialist joins your group's " + "shared memory (on the Tree of Life spine); a new build first recalls from your commons (yours plus imported memories) and " + "tells you if another group already built one for the same request. In a terminal: memory, memory export, memory import."), + ("grow", r"\b(grow|improve|self.improv|learn|diagram)\b", + "Your model grows only through exams: an admitted specialist appears on the diagram's Specialists ring and answers where " + "the core declined. Change one of its files and it leaves your model until it passes a new held-out set. With the gap " + "journal on (Gaps, or /gaps on) your declines are grouped into the specialists you are missing, and 'Start a specialist' " + "turns a group into a new specialist with your questions as its first dev items."), + ("code", r"\b(code|coding|program|function|python|script|tests?)\b", + "Code (or /code ): ask for a function, e.g. 'check whether a string is a palindrome'. The code organ " + "hands over only programs it has run: a small website, palindromes, factorials, vowel and word counts, word frequencies, " + "HTTP routes, regex extraction, memoisation, a bank-account class, matrix multiply, fizzbuzz, fibonacci, string reversal, " + "JSON round-trips, concurrent work, binary search, tower of hanoi, quicksort, list sums, prime tests and two small games. " + "Check what it hands over with tests of your own: Run tests runs them in a separate Python process with a 10 second limit."), + ("film", r"\b(film|video|record|movie|clip)\b", + "Film (or /film): record answers as a video of the diagram tracing each path beside the question, answer and path. It is " + "made in your browser as a .webm file; 'film this' under any answer records just that one."), + ("voice", r"\b(eleven ?labs|narrat\w*|voice|voiceover|music|sound|audio|image|images|picture|illustrat\w*)\b", + "Film > Narration, sound and images (optional): connect your own ElevenLabs account with its API key to narrate each filmed " + "answer in a voice you choose, lay an ambient sound you describe under it, and open each answer with an illustration " + "(Gemini 2.5 Flash Image or GPT Image, through ElevenLabs; image generation needs their Pro plan). Generated images are " + "labelled as generated in the film and saved in workbench/local/assets. This is the only feature that sends anything off " + "your computer: the narration text, the sound description and the image prompts go to ElevenLabs. The key stays in the page " + "unless you tick 'remember on this computer'."), + ("share", r"\b(share|registry|import|package|hugging ?face)\b", + "Share (or /share ): packages a specialist you built - its folder, exam verdict and the SHA-256 of every file - and shows " + "the command to upload it to the community registry with your own Hugging Face account. Import takes a shared .zip, which " + "must pass its held-out exam on your machine before it joins. Readers of your computer, servers and files are never packaged."), + ("specialists", r"\b(specialists?|systems?|deepspace|trafficcop|chameleon|vision|artist)\b", + "Specialists lists the 267 admitted specialists (106 by field plus 161 relation readers), each with its held-out score and " + "card; search it or type /specialists . Systems describes the five systems built the same way: DeepSpace, Trafficcop, " + "Chameleon (builds websites), Vision (sees and reads) and Artist (makes images by citation)."), + ("mcp", r"\b(mcp|tools?|model context protocol|plug ?in|integrat\w*)\b", + "Start > Connect an MCP server: give the command that starts it (for example npx -y @modelcontextprotocol/server-filesystem " + "with a folder) or its URL. The Workbench lists its tools; tick the ones to use, add a few example questions if you like, and " + "it builds an adaptive specialist. It routes each question to the tool it fits, fills the arguments from the question (or " + "says which one is missing), answers with the tool's result and the exact call it made, and learns from your right/wrong " + "marks under each answer. Questions routed to a server are sent to it, so connect servers you trust."), + ("history", r"\b(history|previous|past|earlier|old|saved) (?:conversations?|chats?)\b|\bconversations?\b|\bremember\w*\b|\bmemory of\b", + "Conversations (the panel on the left; the button at the top opens and collapses it): every conversation is kept on this " + "computer. Open one and carry on - the core picks up its context, so follow-ups still work. Rename, search or delete them, " + "or switch keeping off. 'Make specialist' turns a conversation into a temporary specialist (7 days unless you choose) that " + "answers 'what did we say earlier about...?' and repeated questions by quoting the earlier answer with its date and route. " + "It is checked like any reader before it joins, and leaves your model when it expires."), + ("verify", r"\b(verify|verified|hash\w*|blockchain|chain|solana|on.chain|tamper\w*|authentic\w*|merkle)\b", + "Specialists > Verify this install (or /verify): recomputes the SHA-256 of every shipped part - all 307 specialist folders, " + "the admitted fold chain, this workbench, the launcher and the store manifest - and rebuilds the Merkle root published in " + "RELEASE_HASHES.json. A changed or missing specialist shows by name. 'Check the anchor on Solana' then asks a public Solana " + "RPC (read-only; the only network call) for the release's anchor transaction and confirms its memo carries the same root, " + "so your copy is provably the one released. Stores are checked against PACK_MANIFEST.json by oracle7.py --setup."), + ("sensors", r"\b(sensors?|iot|esp32|arduino|mqtt|serial|usb|thermometer|probe|telemetry|readings?|home assistant|shelly)\b", + "Start > Connect a sensor, or the Sensors tab (or /sensors): an HTTP device or hub that serves JSON or Prometheus metrics " + "(ESP32, Shelly, Tasmota, Home Assistant, weather stations), an MQTT topic, a USB/serial device that prints readings, a log " + "file a logger appends to, or a simulated garden node to try it without hardware. Test shows the numbers it found and what " + "each one measures; Add starts polling it (every 30 s by default, 24 h kept on this computer) and makes a reader you can ask: " + "'what is the soil moisture on garden node?', 'temperature on my sensor today?'. Every answer gives the value, its age, its " + "source and whether it was measured or simulated; a value outside its physical range is rejected and said so. " + "Ask 'is the soil moisture on garden node normal?' and the baseline reader answers from 30 days of 15-minute history: " + "the distance from your ideal band (sensor-ideal), from the sensor's own normal, and any spike, step, drift, stuck run, " + "dropout or oscillation in the last 3 days; declare two coupled quantities (sensor-pair) and it says whether a change " + "is a probable sensor fault or a real one. It never acts on what it measures."), + ("terminal", r"\b(cli|terminal|command line|shell|script|json output)\b", + "Everything that makes sense in a terminal works there too, with the same code: python oracle7.py help lists it. " + "ask \"question\" (answer, status and path), chat, specialists [word], card , systems, verify [--chain], mine, new , " + "example, exam dev|heldout, build \"q1\" \"q2\" ..., compose --file examples.txt, scan, sensors, sensor-test
    , " + "history. Add --json for machine-readable output."), + ("registry", r"\b(oracle7 token|\$?oracle7 registry|registry|register|attest\w*|vouch\w*|on.chain|token|holders?)\b", + "Share > Register on Solana: one specialist, one $ORACLE7. The creator of an admitted specialist signs, in their own wallet (Phantom), one Solana transaction that burns exactly 1 $ORACLE7 and carries, in a memo, the " + "specialist's fingerprint - the SHA-256 of its files, its held-out verdict and its held-out set, and the release it was examined " + "on. Anyone who imports it and sees it pass its held-out exam on their machine can Attest the same way. Check reads every " + "registration and attestation back from the chain, confirms it matches the specialist's files now, and shows each signer's " + "wallet and how much $ORACLE7 it holds. The records travel with the specialist when it is shared. No key is ever seen or " + "stored here; the burn is the only token movement, approved in the creator's wallet. Attesting is free."), + ("privacy", r"\b(privacy|private|data|sent|stored|safe)\b", + "The Workbench answers on 127.0.0.1 only and sends nothing anywhere. The gap journal is off until you turn it on, stays in " + "workbench/local/journal.jsonl, and one click deletes it. Conversations are kept in workbench/local/conversations so you can " + "go back to them; switch that off or delete them in the Conversations panel."), +] +COMMANDS = ["/help - this guide", "/scan - read this computer", "/connect user@host [port] [key] - read a server", + "/files - add files", "/mcp - connect an MCP server", "/sensors - connect and watch sensors", "/new [words] - a new specialist", "/exam dev|heldout - run an exam", + "/specialists - find one", "/systems - the five systems", "/gaps on|off - the gap journal", + "/code - compose a function", "/film - film the answers", "/share - package one", + "/verify - check this install against the published hashes", "/registry - its on-chain registrations and attestations", "/history - open the conversations panel", "/new-chat - start a new conversation", + "/remember [days] - make this conversation a temporary specialist", "/clear - clear the conversation"] +HELP_Q = re.compile(r"^\s*(?:/help\b|help\b|what (?:can|do) (?:you|it|the workbench|oracle7) do|what (?:are|is) (?:your|the|its) " + r"(?:features|commands|abilities)|(?:list|show) (?:me )?(?:the |your |all )?(?:features|commands)|what commands|" + r"how do i (?:use|start)\b|how does (?:this|the workbench) work)", re.I) +HOWTO_Q = re.compile(r"^\s*(?:how (?:do|can|would) i|how to|can i|can you|is it possible to)\b", re.I) + + +SENSORS_ALL = re.compile(r"\b(?:my|our|the|all(?: the| my)?) sensors\b|\bsensor readings\b|\ball (?:my )?readings\b", re.I) +PRONOUN = re.compile(r"\b(it|its|that one|this one|them|they)\b", re.I) +HISTORY_Q = re.compile(r"^\s*(?:what|which) (?:did|was|were) (?:i|my) (?:just |first |last |previous |earlier )?(?:ask|asked|question|questions)\b|" + r"^\s*what (?:was|were) my (first|last|previous|earlier|latest) questions?\b|" + r"^\s*what did you (?:just )?(?:say|answer|tell me)\b|^\s*what (?:have|did) (?:i|we) (?:asked|ask|talk(?:ed)? about|discuss(?:ed)?)\b", re.I) + + +def history_reply(text, sid): + """the conversation itself is kept by the Workbench, so it answers questions about it: what was asked first or last, + what it just said, what we have covered""" + t = str(text or "") + if not HISTORY_Q.search(t): + return None + try: + c = conv_load(sid) + except ValueError: + return None + asked = [x for x in c.get("turns", []) if not str(x.get("path", "")).startswith("workbench:")] + topic = re.search(r"\babout (.+?)[?.!]*$", t, re.I) + if topic: + want = set(sources._words(topic.group(1))) - sources.RECALL_FILLER + hits = [x for x in asked if want & set(sources._words(x["q"] + " " + str(x.get("response", ""))))] + if not hits: + return None # not in this conversation: a saved conversation may recall it + return "\n\n".join("At %s you asked \"%s\". I %s: %s" % (time.strftime("%H:%M", time.localtime(x.get("t", 0))), x["q"], + "answered" if x.get("status") == "answered" else "declined", str(x.get("response", ""))[:400]) for x in hits[-3:]) + if not asked: + return "Nothing has been asked in this conversation yet." + when = lambda x: time.strftime("%H:%M", time.localtime(x.get("t", 0))) + if re.search(r"\bfirst\b", t, re.I): + x = asked[0] + return "Your first question in this conversation (%s) was: \"%s\"" % (when(x), x["q"]) + if re.search(r"\bwhat did you (?:just )?(?:say|answer|tell me)\b", t, re.I): + x = asked[-1] + return "I said (%s), to \"%s\": %s" % (when(x), x["q"], str(x.get("response", ""))[:600]) + if re.search(r"\b(just|last|previous|latest)\b", t, re.I): + x = asked[-1] + return "Your last question (%s) was: \"%s\"" % (when(x), x["q"]) + lines = ["%d. %s - %s" % (i, x["q"], "answered" if x.get("status") == "answered" else "declined") for i, x in enumerate(asked[-12:], max(1, len(asked) - 11))] + return "In this conversation you have asked %d question%s:\n%s" % (len(asked), "" if len(asked) == 1 else "s", "\n".join(lines)) + + +def help_reply(text): + t = str(text or "") + if HELP_Q.search(t): + body = "\n\n".join("%s. %s" % (k.capitalize(), v) for k, _, v in HELP_TOPICS) + return ("Here is everything the Workbench does. The core model answers questions from sourced records and declines what " + "it cannot verify. Around it you can read your computer, servers and files, build and examine specialists, find " + "your gaps, compose code, film answers and share what you build.\n\n" + body + "\n\nCommands:\n" + "\n".join(COMMANDS)) + if HOWTO_Q.search(t): + first = ("registry", "terminal", "sensors", "mcp", "voice", "film", "verify", "history", "files", "scan", "code", "share", "grow", "build", "connect", "specialists", "privacy", "ask") + topics = sorted(HELP_TOPICS, key=lambda x: first.index(x[0]) if x[0] in first else 99) + hits = [v for k, pat, v in topics if re.search(pat, t, re.I)] + if hits: + return "\n\n".join(hits[:2]) + return None + +# ---------------------------------------------------------------- the engine + your specialists (fill declines only) +MACHINES_TURN = re.compile(r"(?i)^\s*(?:please\s+)?(?:(?:show|map|read|check|list)\s+(?:me\s+)?(?:my|the|all)?\s*" + r"(?:machines|servers|computers|boxes|homelab)|how\s+(?:are|is)\s+(?:my|the)\s+" + r"(?:machines|servers|boxes|homelab))\b[\s?.!]*$") + +class Workbench: + def __init__(self, engine): + self.eng = engine + self.lock = threading.Lock() + self.mine = {} # id -> exam.Loaded (admitted and unchanged since its exam) + self.last = {} # session -> (your specialist id, subject) of its last answer, for follow-ups + self.warm = set() # sessions whose context the core holds in this run + self.reload() + if os.environ.get("ORACLE7_CONVERSE", "1") != "0": + self._converse() # warm while the browser opens, not after its first request + + def reload(self): + mine = {} + for d in sorted(SPECS.iterdir()) if SPECS.exists() else []: + st = exam.status(d) + if st["state"] == "admitted": + try: + mine[d.name] = exam.load_specialist(d) + except Exception as e: # noqa: BLE001 + print("workbench: %s did not load: %s" % (d.name, e), file=sys.stderr) + self.mine = mine + + def chat(self, text, sid): + """12.5 step 3 (round-2 design 1.1, audit E1): the one exit. Every reply of a turn leaves through `_delivered` + (word receipt, then the seal, then the conversation's observation and the turn record), once""" + try: # 12.5 step 9: a turn binds its words to the project once + import resolve as _rv + _rv.new_turn() + except Exception: # noqa: BLE001 + pass + return self._delivered(text, sid, self._turn(text, sid)) + + def _new_project(self, sid, request): + """Work asked for with no project open: a new project folder in Oracle7's own workspace (workbench/local/projects, + or ORACLE7_WORKBENCH_LOCAL), named from the request, opened with change authority for this conversation. Nothing + outside that folder is touched; the reply names the folder so the user can see and keep the result.""" + import bench as _b + base = Path(os.environ.get("ORACLE7_WORKBENCH_LOCAL") or (HERE / "local")) / "projects" + words = [w for w in re.findall(r"[a-z0-9]+", request.lower()) if len(w) > 2][:5] or ["project"] + name = "-".join(words)[:48] + folder, n = base / name, 2 + while folder.exists() and any(folder.iterdir()): + folder, n = base / ("%s-%d" % (name, n)), n + 1 + folder.mkdir(parents=True, exist_ok=True) + _b.open_env(_b.Turn(sid), str(folder)) + return folder + + def _turn(self, text, sid): + """the raw reply of a turn, recorded nowhere (the one exit records it). 12.0 Amendment 13: the bench first (work on the conversation's environment; nothing when none is open); every + delivered action recorded once into the conversation organ's context""" + # Start the existing conversation parts for work turns too. Previously a + # successful bench turn returned before Converse was ever constructed. + if os.environ.get("ORACLE7_CONVERSE", "1") != "0": + self._converse() + self._observe_pending_work(sid) + native = None + cv = getattr(self, "_cv", None) + # A correction of the referent ("Actually I meant Jupiter, not Mars") is the previous request asked again with the + # new referent, through this whole door (writer, questions, work); never a claim to examine (11-17). + if cv and hasattr(cv, "repair") and not getattr(self, "_repairing", False): + try: + repaired = cv.repair(text, sid) + except Exception: # noqa: BLE001 + repaired = None + if repaired and repaired.strip() != text.strip(): + self._repairing = True + try: + r = self._turn(repaired, sid) + finally: + self._repairing = False + return dict(r, path="repair>" + str(r.get("path", "")), repaired=repaired) + # A turn that names a folder that exists on this machine is about that folder, however it is worded ("There's a + # recipe folder at . Have a look and tell me what's there", "open - it's our stock list. I want + # to ..."). The folder is opened for this conversation first; whatever else the turn says is then received + # with the folder open. Before this, only a turn that was exactly "open " opened anything, so a plainly + # worded start never reached the work receivers (acceptance run 2026-11-17: all ten building cases). + if not getattr(self, "_repairing", False): + try: + import bench as _bf + named = None + for m in re.finditer(r"(?:[A-Za-z]:[\\/]|~[\\/]|/)[^\s\"'`<>|*?]+", text or ""): + cand = m.group(0).rstrip(".,;:!)]\u2014\u2013-") + if len(cand) > 3 and os.path.isdir(os.path.expanduser(cand)): + named = (m.start(), m.start() + len(cand), cand) + break + turn0 = _bf.Turn(sid) if named else None + same = bool(named and turn0.env is not None and getattr(turn0.env, "kind", "") == "folder" and + os.path.normcase(os.path.realpath(str(turn0.env.root))) == + os.path.normcase(os.path.realpath(os.path.expanduser(named[2])))) + if named and not same: + before = re.sub(r"(?i)(?:\b(?:please|can you|could you)\b\s*)?\b(?:open|look (?:at|in)|work (?:on|in)|" + r"at|in|from|under|inside|called|named)\s*$", "", text[:named[0]]).strip() + rest = (before + " " + re.sub(r"^[\s.,;:!\u2014\u2013-]+", "", text[named[1]:])).strip() + # a turn that only opens the folder is the bench's own "open " (which also resumes a request + # that was waiting for a folder): left to it. Only a turn that says more is opened here. + opened = _bf.open_env(turn0, named[2]) if len(re.findall(r"[A-Za-z]{2,}", rest)) >= 3 else None + if opened: + self._repairing = True + try: + r = self._turn(rest, sid) + finally: + self._repairing = False + return dict(r, response=str(opened.get("response", "")) + "\n\n" + str(r.get("response", "")), + path="open>" + str(r.get("path", "")), opened=named[2]) + except Exception: # noqa: BLE001 + pass + # One decision per turn (turn_act, 11-17): the act the turn performs picks its owner, instead of the first + # receiver whose word rules match. "build it" after an idea carries the kept plan to the work receivers. With a + # project open, the work receivers below keep their order (their contracts come first there). + if cv and not getattr(self, "_repairing", False): + try: + built = cv.build_kept_idea(text, sid) if hasattr(cv, "build_kept_idea") else None + except Exception: # noqa: BLE001 + built = None + try: + import bench as _b0 + open_env = _b0.Turn(sid).env + except Exception: # noqa: BLE001 + open_env = None + act = None + if not open_env and not built: + # a turn about the draft this conversation keeps (a question about it, a revision, an added source) + try: + import compose_writing + part = cv._discussion_part() + revised = compose_writing.revise(text, sid, part.router.reader if part else None) + except Exception: # noqa: BLE001 + revised = None + if revised: + return dict(revised, act="writing") + try: + import turn_act + act = turn_act.read(built or text, sid, cv).get("act") + except Exception: # noqa: BLE001 + act = None + if (built or act == "work") and not open_env: + # work with no project open: a new project folder in Oracle7's own workspace carries it + try: + folder = self._new_project(sid, built or text) + except Exception: # noqa: BLE001 + folder = None + if folder is not None: + self._repairing = True + try: + r = self._turn(built or text, sid) + finally: + self._repairing = False + note = "Started a new project folder for this: %s" % folder + "\n\n" + return dict(r, response=note + str(r.get("response", "")), project_folder=str(folder), + path=("idea:build>" if built else "new-project>") + str(r.get("path", "")), carried=built) + if built and built.strip() != text.strip(): + self._repairing = True + try: + r = self._turn(built, sid) + finally: + self._repairing = False + return dict(r, path="idea:build>" + str(r.get("path", "")), carried=built) + if (open_env is not None and getattr(open_env, "kind", "") == "folder" and act == "question" + and text.rstrip().endswith("?") and not _commanded(text)): # q54 k13 T2: "X is wrong. fix it" is work + # a question asked with a project open is about the project first: answered from its own text + try: + import project_answer + part = cv._discussion_part() + found = project_answer.answer(text, open_env.root, part.router.reader if part else None) + except Exception: # noqa: BLE001 + found = None + if found: + return dict(found, act=act) + if not open_env: # with a project open the bench's receivers keep the turn first (q54: k35, k14 lost it) + owned = None + try: + if act == "writing": + # A writing request has one owner from every entry point: the writer that keeps its obligation + # (request, bounds, sources) through delivery and checks the delivered body (Codex's 12.0 + # HANDOFF, PANEL_DECISIONS 1). It is reached through the door below, unchanged; no second writer + # takes it here (a parallel composer lost Codex's checked delivery, 2026-11-18). + owned = None + elif act == "question": + # a question asked after a piece was written is about that piece's subject first + import compose_writing + part = cv._discussion_part() + owned = compose_writing.follow_up(text, sid, part.router.reader) if part is not None else None + elif act == "self" and hasattr(cv, "_own_record"): + owned = cv._own_record(text, sid) + elif act == "idea" and hasattr(cv, "idea_reply"): + owned = cv.idea_reply(text, sid) + except Exception: # noqa: BLE001 + owned = None + if owned: + return dict(owned, act=act) + try: + import bench as _bench + import language_bridge as _language + turn = _bench.Turn(sid) + kept, env = turn.s.get("project"), turn.env + work = turn.s.get("work") + focus = turn.s.get("focus") + active_work = bool(focus == "work" and work and env and work.get("env") == env.key) + active = bool(kept and env and kept.get("env") in (None, env.key) and focus not in ("self", "work")) + named_work = active_work and bool(re.search(r"\b(?:work|task|goal|project|program|app)\b", text, re.I)) + if active or active_work: + # The existing delivered-turn ledger supplies the referent. A + # correction after a world/self answer belongs to that answer, + # not to an older project that happens to remain open. + import reflect as _record + ledger = _record.load(sid).get("ledger") or [] + expected = "bench:work" if active_work else "bench:project" + # Starting/stopping the project's app does not introduce a new + # conversational subject. Look through lifecycle receipts to + # the last substantive owner, while honoring real topic changes. + context = next((item for item in reversed(ledger) if not str(item.get("path", "")).startswith( + ("bench:run", "bench:stop", "turn:running", "turn:stop"))), None) + if context and not str(context.get("path", "")).startswith(expected): + active = False + active_work = False + state_reply = _language.work_answer(text, work) if active_work or named_work else None + reading = _language.request_reading(text, active_project=active, active_work=active_work) + cv = getattr(self, "_cv", None) + try: + native = cv.read_request(text, sid) if cv and hasattr(cv, "read_request") else None + except Exception as error: + # A word-reader failure is evidence of an unavailable reading, + # not a failure to load or execute an otherwise explicit tool. + native = {"original": text, "available": False, "basis": "turn_reader:error", "error": repr(error)[:300], + "clauses": [], "outcomes": [], "constraints": [], "goals": [], "literals": [], + "unresolved": [{"kind": "reader", "text": "the native reading did not complete"}]} + if cv and env: + import writing_sources + source_fill = writing_sources.receive(text, sid, env, + reader=getattr(cv, 'reader', None) or getattr(getattr(cv, 'router', None), 'reader', None)) + if source_fill: + return source_fill + deferred_to_work = False + if not state_reply and cv and hasattr(cv, "proposition_reply"): + # Conversation must defer to every existing work receiver, + # including structured plans and repository part bindings. + # Otherwise a valid check can become a recorded assertion. + owns_work = False + try: + import project_intent as _intent + current_work = work if (active_work or named_work) else None + owns_work = _intent.owns_turn(text, current_work, reading=native) + if not owns_work and env and env.kind == "folder": + import work_tasks as _work + import work_bindings as _bindings + owns_work = (_work.accepts(text, env.root, kept=current_work, reading=native) + or _bindings.accepts(text, env.root, reading=native)) + if not owns_work: + import interactive_program as _programs + try: + owns_work = _programs.request_contract(text, env.root, reading=native) is not None + except _programs.ProgramError: + owns_work = True # the work owner must explain its named contract hole + except ImportError: + pass + if not owns_work and env and env.kind == "folder" and focus not in ("self", "work"): + # The folder's table project keeps its own turns: a build + # request with an entry command or a table and an outcome, + # and, while that project is the subject, its fills, drops, + # examples, revisions and questions about its record. + # (project_intent declines these "to their owner"; that + # owner is the bench, not the conversation.) + try: + import project as _table_project + bound = kept if active else None + if bound is not None and _language.project_answer(text, bound): + owns_work = True + elif not _language.asks_about(text): + owns_work = bool(_table_project.is_project(text, bound)) + except Exception: # noqa: BLE001 - the ownership check never blocks a turn + pass + if not owns_work and hasattr(cv, 'contribution_reply'): + contribution = cv.contribution_reply(text, sid) + if contribution: + return contribution + if not owns_work: + # A reply to Oracle7's own reasoning in this thread ("I + # disagree because ...", "what would make that wrong?") + # is reflection's: it weighs the turn against the premises + # it said. Bench and reflection run below in that order. + try: + import reflect as _reflection + if _reflection.claims(text, sid): + owns_work = True + except Exception: # noqa: BLE001 + pass + if not owns_work: + # an adopted capability of Oracle7 called by its own words + # (or the list of them) is the head's door to it (C11) + try: + import continuation as _continuation + if _continuation.LISTQ.search(text) or _continuation.capability_for(text) is not None: + owns_work = True + except Exception: # noqa: BLE001 + pass + # Existing concrete work receivers own their contracts first. + # A writer's dry take can then own a prose outcome before the + # generic command fallback, without stealing service actions. + if not owns_work and hasattr(cv, 'writing_reply'): + # in an open environment a turn reaches the writer only as a prose request asked outright, however + # it is worded (12.5, q50: "run the tests" read run -> cover -> discuss; "handle the empty case" + # read handle -> treat -> discuss; neither verb list decides it, the take's own reading does) + commanded_here = bool(env) + try: + written = cv.writing_reply(text, sid, direct_only=commanded_here) + except TypeError: + written = None if commanded_here else cv.writing_reply(text, sid) + if written: + return written + if not owns_work and env and _commanded(text, reading): + # Mood decides first ownership: a command in an open + # environment goes to the work receivers (edit, write, run, + # build into yourself, tests, ...); a statement or question + # goes to conversation. A command no receiver takes still + # reaches conversation below. + owns_work = True + deferred_to_work = True + if not owns_work and env: + # 12.0 C29: a question about the work held here ("how far along are we?") is the bench's, answered + # from that work's record + try: + if _bench.ours_question(_bench.Turn(sid), text): + owns_work = True + deferred_to_work = True + except Exception: # noqa: BLE001 + pass + if not owns_work and env: + # A wording Oracle7's own word meanings read as an operation + # of this environment ("what's in this folder", "verify the + # tests are passing", "did anything go wrong?") is the + # bench's: done if sure and only reading, offered otherwise. + try: + import resolve as _resolve + if _resolve.resolve(text, env, near_ok=True)[0]: + owns_work = True + deferred_to_work = True + except Exception: # noqa: BLE001 + pass + if not owns_work: + proposition = _mood_bar(cv.proposition_reply(text, sid), native) + if proposition: + return (dict(proposition, turn_reading=native) if native else proposition) + # A question about source must not enter the mutation/composition + # receiver just because it contains words such as "fails" or "fix". + import project_context as _project_context + bb = state_reply or _language.code_context(text, native, env, turn) or _project_context.receive(text, reading, native, turn) + if bb is None: + bb = _bench.handle(reading["reading"], sid, reading=native) + if bb and str(bb.get("path", "")).startswith("bench:open"): + import code_discussion as _code_discussion + resumed = _code_discussion.resume_after_open(sid) + if resumed: + resumed["response"] = bb["response"] + "\n\n" + resumed["response"] + resumed["resumed_after_open"] = True + bb = resumed + else: + resumed = _project_context.resume(sid) + if resumed: + resumed["response"] = bb["response"] + "\n\n" + resumed["response"] + resumed["resumed_after_open"] = True + bb = resumed + elif bb and str(bb.get("path", "")).startswith("bench:authority"): + resumed = _project_context.resume(sid) + if resumed: + bb = resumed + names_here = False + if bb is None and env and getattr(env, "kind", None) == "folder" and _commanded(text, reading): + try: # the command names a file of this folder + import resolve as _resolve_names + names_here = bool(_resolve_names.bind(text, env).get("file")) + except Exception: # noqa: BLE001 + names_here = False + if bb is None and (deferred_to_work or names_here): + # no work receiver took the command: conversation receives it + proposition = _mood_bar(cv.proposition_reply(text, sid), native) if deferred_to_work else None + if proposition: + return (dict(proposition, turn_reading=native) if native else proposition) + if names_here or _commanded(text, reading) and re.search( + r"(?i)\.\w{1,4}\b|\b\w+\([^)]*\)|\b(?:function|tool|program|script|module|class|tests?|file|folder|" + r"table|csv|code|app|repo)\b", text): + # 12.0 C28: a work command no receiver takes is a hole, said as one; it never falls through to open talk, + # which would answer an instruction with small talk and mark it checked + bb = {"status": "hole", "path": "bench:untaken", "response": ( + "No part here takes that request as written, so nothing was done. The ways a request reaches a part " + "here: a function from examples (`add a function NAME(args) to FILE.py: what it does. " + "NAME(1) == 2, ...`), a module from its tests (`make the tests in test_x.py pass`), a tool over a " + "table (`build `python3 tool.py cmd` that reads data.csv and saves ... to out.csv`), an edit " + "(`in FILE.py, change A to B`), or run, read, ls, grep, undo. Say it one of those ways, or tell me " + "what it should do and I'll name what is missing.")} + if bb and native: + bb = dict(bb, turn_reading=native) + if bb and reading["steps"]: + bb = dict(bb, language=reading) + # The receive part keeps its canonical clauses, and their exact + # original wording lives beside them for later correction. + if str(bb.get("path", "")).startswith("bench:project") and not str(bb.get("path", "")).startswith("bench:project:record"): + turn = _bench.Turn(sid) + shape = turn.s.get("project") + if shape is not None: + shape.setdefault("language_readings", []).append(reading) + try: + turn.save() + if turn.env and turn.env.kind == "folder": + import project as _project + _project.save_project(turn.env.root, shape) + except OSError as e: + bb["language"]["record_error"] = str(e)[:200] + except Exception as e: # noqa: BLE001 + bb = {"status": "hole", "path": "bench:error", "response": "The bench did not load: %s" % repr(e)[:200]} + if bb: + return (bb) + try: # Amendment 14: reflection on its work and on ideas, same chat + import reflect as _rf + rr = _rf.handle(text, sid) + except Exception: # noqa: BLE001 + _rf, rr = None, None + if rr: + return (dict(rr, turn_reading=native) if native else rr) + r = self._chat_inner(text, sid) + if native: + r = dict(r, turn_reading=native) + if _rf is not None and r.get("status") != "answered": + try: + rr = _rf.after_head(text, sid, r) + except Exception: # noqa: BLE001 + rr = None + if rr: + return (dict(rr, turn_reading=native) if native else rr) + if not str(r.get("path", "")).startswith(("tool:", "learn:")): + r = dict(r, _observed_by_door=True) # the open path's door (stands / Converse.reply) already observed it + return r + + def _observe_pending_work(self, sid): + """Replay work delivered while Converse warmed, from the existing ledger. + + A new ready Converse restores a bounded window of delivered context + from the ledger, without executing any work. Its returned sequence + advances this same cursor so warm-up turns are not observed twice. + The ready result is also used for the current turn: if warming finishes + just after this call, that turn waits in order with the older work. + """ + try: + import reflect as record + cv = getattr(self, "_cv", None) + identity = id(cv) + if self.__dict__.get("_work_cv_identity") != identity: + self._work_cv_identity = identity + self._work_observed = {} + st = record.load(sid) + ledger = st.get("ledger") or [] + seq = int(st.get("seq") or (ledger[-1]["n"] if ledger else 0)) + seen = self._work_observed + if sid not in seen: + seen[sid] = seq + ready = bool(cv and cv.ready() and os.environ.get("ORACLE7_CONVERSE", "1") != "0") + if not ready: + return False + if hasattr(cv, 'restore_context'): + restored_through = cv.restore_context(sid) + if isinstance(restored_through, int): + seen[sid] = max(seen[sid], restored_through) + for entry in ledger: + n = int(entry["n"]) + if n <= seen[sid]: + continue + # Advance before calling observe: that contract can record part + # of a turn before an error; retrying it would duplicate context. + seen[sid] = n + if str(entry.get("path", "")).startswith(("bench:", "reflect:", "tool:", "learn:")): + cv.observe(entry.get("you", ""), sid, + {"response": entry.get("said", ""), "status": entry.get("status"), + "path": entry.get("path"), "execution": entry.get("ex") or {}}) + seen[sid] = seq + return True + except Exception as e: # noqa: BLE001 + self._work_observe_error = repr(e)[:200] + return False + + def _delivered(self, text, sid, r): + """the one record of what was done for this turn, in the organ's live context (also when nothing is kept on disk)""" + try: + import language_bridge as _language + r = _language.word_receipt(r) + if str(r.get("path", "")).startswith("bench:project:gap"): + import bench as _bench + import project as _project + shape = _bench.Turn(sid).s.get("project") or {} + cv = getattr(self, "_cv", None) + reader = getattr(getattr(cv, "router", None), "reader", None) + owned = set(_project.ALL_PART_WORDS) + for context in (shape.get("source_contexts") or {}).values(): + owned.update((context.get("world") or {}).get("cols", ())) + suggestions = _language.spelling_suggestions(shape, reader, owned) + if suggestions: + r = dict(r, language=dict(r.get("language") or {}, suggestions=suggestions)) + r["response"] += "\n\n" + "\n".join( + "For `%s`, the word reader suggests `%s`. If that is what you mean, say `%s means %s`." % ( + s["word"], s["reading"], s["word"], s["reading"]) for s in suggestions) + except Exception: # noqa: BLE001 + pass + seen_by_door = r.pop("_observed_by_door", False) + try: # 12.5 step 5: every hole that leaves is one record, with its receipt + import holes as _holes + r = _holes.record_reply(r) + except Exception: # noqa: BLE001 + pass + r = self._seal(r) # 12.5: the seal, after the word receipt, before anything is recorded + cv = getattr(self, '_cv', None) + if cv and hasattr(cv, 'commit_writing'): + r = cv.commit_writing(sid, r) + try: + import context_record + reading = cv.read_request(text, sid) if cv and hasattr(cv, 'read_request') else None + r = context_record.record(text, sid, r, reading) + except Exception as error: + r = dict(r, context_record_error=repr(error)[:200]) + observed = False + try: + cv = getattr(self, "_cv", None) + if self._observe_pending_work(sid) and not seen_by_door: + cv.observe(text, sid, r) + observed = True + except Exception: # noqa: BLE001 + pass + try: + import reflect as _rf + _rf.record(text, sid, r) + if observed: + self._work_observed[sid] = int(_rf.load(sid).get("seq") or self._work_observed.get(sid, 0)) + except Exception: # noqa: BLE001 + pass + return r + + def _seal(self, r): + """12.5 step 4 (round-2 design 1.1): the seal at the one exit. Every receipt is read back with the seal's own code + (relations against the store, holes against the hole record, a proof's parts against this release's registry); a + reply is said only as far as its receipts bear. It only lowers, and a lowered reply says why. ORACLE7_SEAL=0 keeps it + as identity (the step-3 measure).""" + self.__dict__["_exits"] = self.__dict__.get("_exits", 0) + 1 + if os.environ.get("ORACLE7_SEAL", "1") == "0" or not isinstance(r, dict): + return r + try: + import seal as _sl + if self.__dict__.get("_seal_ctx") is None: + sys.path.insert(0, str(HERE / "converse")) + import parts as _pt + self._seal_ctx = (_pt.Store(str(HERE.parent)), _sl.registry(str(HERE.parent))) + store, reg = self._seal_ctx + v = _sl.seal(r, store, _sl.holes_of(os.environ.get("ORACLE7_STATE")), reg) + except Exception as e: # noqa: BLE001 + return dict(r, seal={"error": repr(e)[:200]}) # recorded, never silent; the producer's label stands + r = dict(r, seal={"label": v["label"], "why": v["why"], "proof": v.get("proof"), "counts": v["counts"]}) + if v["lowered"]: + r["status"] = v["label"] + r["response"] = str(r.get("response", "")) + "\n\n(Not counted as answered: %s.)" % "; ".join(v["why"]) + return r + + def _chat_inner(self, text, sid): + """12.0: the door (_chat_door) and the gap loop around it: a go after an offer runs the lookup; a question the door + could not answer is answered from what was learned before, or gets the offer to look it up (learn.py)""" + try: + import learn as _learn + except Exception: # noqa: BLE001 + return self._chat_door(text, sid) + pend = self.__dict__.setdefault("_learn_pending", {}) + if sid in pend and _learn.GO.match(text or ""): + q = pend.pop(sid) + try: + cv = getattr(self, '_cv', None) + reader = getattr(cv, 'reader', None) or getattr(getattr(cv, 'router', None), 'reader', None) + return _learn.lookup(q, reader=reader) + except Exception as e: # noqa: BLE001 + return {"status": "hole", "response": "The lookup did not complete: %s" % repr(e)[:160], "path": "learn:error"} + pend.pop(sid, None) + r = self._chat_door(text, sid) + if r.get("status") == "answered" or str(r.get("path", "")).startswith(("tool:", "workbench:", "yours:")): + return r + asks = text.rstrip().endswith("?") + cv = getattr(self, "_cv", None) + if not asks and cv and getattr(cv, "router", None) is not None: + try: + asks = cv.router.reader.read(text).get("mood") == "question" + except Exception: # noqa: BLE001 + asks = False + if not asks: + return r + reader = getattr(cv, 'reader', None) or getattr(getattr(cv, 'router', None), 'reader', None) + kept = _learn.recall(text, reader=reader) + if kept: + return kept + # The offer to look something up is made where a lookup could answer: a question about the world. A question + # about the person asking, this conversation, Oracle7 itself, a view, or the piece just written is not one an + # encyclopedia answers, so the offer is not hung on it; and it is not repeated on the turn straight after it + # was made and not taken (it stood as a fixed tail on most replies: acceptance run 2026-11-17). + offered = self.__dict__.setdefault("_learn_offered", {}) + about_us = re.search(r"(?i)\b(?:you|your|yours|i|me|my|mine|we|us|our|ours)\b", text or "") + again = offered.get(sid, -9) >= self.__dict__.setdefault("_learn_turns", {}).get(sid, 0) - 1 + self._learn_turns[sid] = self._learn_turns.get(sid, 0) + 1 + if about_us or again: + return r + offered[sid] = self._learn_turns[sid] + pend[sid] = text + said = str(r.get("response", "")).strip() + return dict(r, status="hole", path=str(r.get("path", "")) + ">learn:offer", + response=(said + "\n" if said else "") + _learn.offer_text()) + + def _chat_door(self, text, sid): + """11.5: the head first (chat_core); where it did not answer with an answer, the turn loop composes (converse)""" + try: # 12.0: a turn whose verb names a tool runs it (find/read/write/run/fetch) + import tools as _tools + t = _tools.dispatch(text) + if t: + return t + except Exception: # noqa: BLE001 + pass + if os.environ.get("ORACLE7_CONVERSE", "1") == "0": + return self.chat_core(text, sid) + cv = self._converse() + if cv is not None and not cv.ready() and hasattr(cv, "wait_ready"): + # The existing browser turn job keeps this request live while the + # native parts warm. Explicit bench tools already ran before here. + cv.wait_ready(120) + if cv is None or not cv.ready(): + state = cv.status() if cv and hasattr(cv, "status") else language_status() + reason = state.get("error") or "still loading at " + state.get("stage", "startup") + return {"status": "hole", "path": "converse:startup", "response": "The conversation parts are unavailable: " + reason + + ". I have not answered this request yet.", "language": state, + "execution": {"state": "waiting-language" if not state.get("error") else "failed", "started": False}} + r = self.chat_core(text, sid) + self._observe_pending_work(sid) # work precedes the question that refers back to it + context_refuses = getattr(cv, "context_refuses", None) + if cv.stands(r, text) and not (context_refuses and context_refuses(r, text, sid)): + cv.observe(text, sid, r) # Amendment 14 (2): the delivered exchange is the composer's context + return r + return cv.reply(text, sid, r) + + def _converse(self): + if getattr(self, "_cv", None) is None: + try: + import os as _os, sys as _sys + _sys.path.insert(0, _os.path.join(_os.path.dirname(_os.path.abspath(__file__)), "converse")) + from converse.session import Converse + self._cv = Converse(self.eng, self) + except Exception as e: # noqa: BLE001 + self._cv = False + self._cv_error = repr(e)[:300] + return self._cv or None + + def chat_core(self, text, sid): + h = help_reply(text) + if h: + return {"status": "answered", "response": h, "path": "workbench:help"} + if MACHINES_TURN.match(text or ""): # 12.0: the machines map, in words (the Machines tab draws it) + import machines as _mc + if not _mc.config(): + return {"status": "offered", "path": "workbench:machines", "response": + "No machines are listed yet. Open the Machines tab and add each one by its ssh alias or user@host; " + "I read this computer and every listed machine read-only over your own ssh keys."} + return {"status": "answered", "path": "workbench:machines", "response": _mc.summary(_mc.collect()) + + "\n\nThe Machines tab draws this as a map.", "execution": {"state": "read"}} + h = history_reply(text, sid) + if h: + return {"status": "answered", "response": h, "path": "workbench:history"} + # a follow-up to an answer from one of your readers ("what shelf is it on?") is read against that answer's subject + prev = self.last.get(sid) + if prev and PRONOUN.search(text): + sp = self.mine.get(prev[0]) + if sp is not None: + a = sp.reply(PRONOUN.sub(prev[1], text, count=1), sid) + if a and a.get("status") == "answered": + a = dict(a) + a["path"] = "yours:%s>followup>%s" % (prev[0], a.get("path", "")) + return self.remember(text, sid, a) + # questions ADDRESSED to your own things (my computer, my notes, a named server, your table's rows) go to their + # readers first: the core cannot know them, and its general answer would not be about them. The readers' lane + # check bounds how often that can happen on general questions. + now = time.time() + live = {i: sp for i, sp in self.mine.items() if not sp.m.get("expires") or float(sp.m["expires"]) > now} + if SENSORS_ALL.search(text): # "my sensors": every connected sensor answers, one line each + lines = [] + for i, sp in live.items(): + if sp.m.get("organ", {}).get("module", "").startswith("organ_sensor"): + a = sp.organ.answer("%s readings %s" % (sp.organ.name, text), sid) + if a and a.get("status") == "answered": + lines.append(a["response"]) + if lines: + return self.remember(text, sid, {"status": "answered", "response": "\n".join(lines), "path": "yours:sensors>all"}) + for i, sp in live.items(): + if sp.m.get("source"): + a = sp.reply(text, sid) + if a and a.get("status") == "answered": + a = dict(a) + a["path"] = "yours:%s>%s" % (i, a.get("path", "")) + return self.remember(text, sid, a) + if sid not in self.warm: + self.warm.add(sid) + try: + prior = [x for x in conv_load(sid).get("turns", []) if x.get("status") == "answered" + and not str(x.get("path", "")).startswith(("workbench:", "yours:"))][-2:] + except ValueError: + prior = [] + for x in prior: # replies discarded: this only restores what the core remembers + try: + self.eng.chat(x["q"], session_id="wb-" + sid) + except Exception: # noqa: BLE001 + pass + r = self.eng.chat(text, session_id="wb-" + sid) + self.last.pop(sid, None) # the core answered (or declined): follow-ups are its own + path = str(r.get("path", "")) + if r.get("status") != "answered" and live and exam.fillable(path): + for i, sp in live.items(): + a = sp.reply(text, sid) + if a and a.get("status") == "answered": + a = dict(a) + a["path"] = "yours:%s>%s" % (i, a.get("path", "")) + a["declined_by"] = path + return self.remember(text, sid, a) + if r.get("status") == "answered": + r = dict(r, proof=head_proof(r, getattr(self.eng, "tip", ""))) + return r + + def remember(self, text, sid, a): + """hand an answer from your specialist back to the core's conversation memory, so a follow-up ("and in winter?", + "what did I just ask?") reads against it like any answer the core gave""" + m = re.match(r"^yours:([a-z0-9-]+)>", str(a.get("path", ""))) + if m and a.get("subject"): + self.last[sid] = (m.group(1), str(a["subject"])) + + def upd(): + try: + import chat_context_v2 as cc + cc.update("wb-" + sid, text, a) + except Exception: # noqa: BLE001 + pass + try: + self.eng._ex.submit(upd).result(timeout=5) + except Exception: # noqa: BLE001 + pass + return a + + +WB = None + + +def specialists_payload(): + base = json.loads((DATA / "specialists.json").read_text(encoding="utf-8")) if (DATA / "specialists.json").exists() else {"items": []} + yours = [] + for d in sorted(SPECS.iterdir()): + if d.is_dir(): + st = exam.status(d) + m = exam.read_manifest(d) or {} + yours.append({"id": d.name, "name": m.get("name", d.name), "state": st["state"], "note": st.get("note", ""), + "verdict": st.get("verdict")}) + base["yours"] = yours + return base + + +def gaps(): + """declines from the journal, grouped by what is missing: the decline kind, then the domain words the questions share""" + rows = [] + if JOURNAL.exists(): + for line in JOURNAL.read_text(encoding="utf-8").splitlines(): + try: + rows.append(json.loads(line)) + except Exception: # noqa: BLE001 + pass + dec = [r for r in rows if r.get("status") != "answered"] + stop = set("the a an of in on at to is was were are be by for with from and or what which who whom whose where when why how " + "did does do it its this that these those i you he she they we my your his her their our me him them as than then " + "there here can could would should will shall may might must much many most more about into over after before " + "name tell give find please".split()) + groups = defaultdict(list) + for r in dec: + words = [w for w in re.findall(r"[a-z][a-z-]{2,}", r["q"].lower()) if w not in stop] + groups[r.get("why", "other")].append((r["q"], words)) + out = [] + for kind, items in groups.items(): + c = Counter(w for _, ws in items for w in set(ws)) + themes = [] + for w, n in c.most_common(8): + if n < 2: + break + ex = [q for q, ws in items if w in ws][:4] + themes.append({"word": w, "count": n, "examples": ex}) + out.append({"kind": kind, "count": len(items), "themes": themes, "examples": [q for q, _ in items[:5]]}) + out.sort(key=lambda g: -g["count"]) + return {"on": settings().get("journal", False), "turns": len(rows), "declined": len(dec), "groups": out} + + +def scaffold(sid, name, words, examples=()): + d = SPECS / sid + if d.exists(): + raise ValueError("a specialist named %s already exists" % sid) + shutil.copytree(HERE / "template", d) + for f in d.iterdir(): + if f.is_file(): + cue = "|".join(w.replace("-", "[- ]") for w in words) or "(?!x)x" # words are [a-z0-9-] only: safe in JSON and regex + t = f.read_text(encoding="utf-8").replace("__ID__", sid).replace("__NAME__", name.replace('"', "'")).replace( + "__CUE__", cue).replace("__MODULE__", "organ_" + sid.replace("-", "_")) + f.write_text(t, encoding="utf-8") + (d / "organ.py").rename(d / ("organ_%s.py" % sid.replace("-", "_"))) + if examples: # questions from your Gaps page become dev items to answer + pf = d / "panel.json" + panel = json.loads(pf.read_text(encoding="utf-8")) + panel["dev"] = [{"q": q, "a": "", "valid": True, "kind": "fact"} for q in examples] + panel["dev"] + pf.write_text(json.dumps(panel, indent=1), encoding="utf-8") + return d + + +def package(sid): + d = SPECS / sid + st = exam.status(d) + if (exam.read_manifest(d) or {}).get("source"): + raise ValueError("source readers read your own computer, servers or files, so they are not packaged for sharing") + if st["state"] != "admitted": + raise ValueError("only an admitted specialist is packaged (this one is %s); pass its held-out exam first" % st["state"]) + files = sorted(p for p in d.rglob("*") if p.is_file() and "__pycache__" not in p.parts) + sums = {str(p.relative_to(d)).replace("\\", "/"): hashlib.sha256(p.read_bytes()).hexdigest() for p in files} + man = {"id": sid, "state": st["state"], "verdict": st.get("verdict"), "files": sums, + "packaged": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "format": "oracle7-specialist/1"} + h = hashlib.sha256(json.dumps(sums, sort_keys=True).encode()).hexdigest()[:12] + out = OUTBOX / ("%s-%s.zip" % (sid, h)) + with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z: + for p in files: + z.write(p, "%s/%s" % (sid, p.relative_to(d).as_posix())) + z.writestr("%s/SHARE_MANIFEST.json" % sid, json.dumps(man, indent=1)) + return {"zip": str(out), "sha12": h, "state": st["state"], + "command": "huggingface-cli upload Prometheus7/oracle7-specialists \"%s\" specialists/%s --repo-type dataset" % (out, out.name)} + + +def import_zip(path): + p = Path(path).expanduser() + if not p.is_file() or p.suffix != ".zip": + raise ValueError("give the path of a .zip made by Share") + with zipfile.ZipFile(p) as z: + names = z.namelist() + top = {n.split("/")[0] for n in names} + if len(top) != 1: + raise ValueError("a shared specialist is one folder") + sid = top.pop() + if not ID.match(sid) or (SPECS / sid).exists(): + raise ValueError("bad or existing specialist id: %s" % sid) + for n in names: + parts = n.split("/") + if ".." in parts or n.startswith("/") or (len(parts) > 1 and parts[-1] and not FNAME.match(parts[-1])): + raise ValueError("refused file in package: %s" % n) + man = json.loads(z.read("%s/SHARE_MANIFEST.json" % sid)) + tmp = Path(tempfile.mkdtemp(prefix="o7import-")) + z.extractall(tmp) + src = tmp / sid + for rel, h in man["files"].items(): + if hashlib.sha256((src / rel).read_bytes()).hexdigest() != h: + shutil.rmtree(tmp) + raise ValueError("%s does not match its published hash" % rel) + (src / "SHARE_MANIFEST.json").unlink() + for v in src.glob("verdict_*.json"): # their verdict is theirs: it takes the exam again here + v.rename(v.with_name("shared_" + v.name)) + shutil.move(str(src), str(SPECS / sid)) + shutil.rmtree(tmp, ignore_errors=True) + return {"id": sid, "note": "imported; it joins your model only after it passes its held-out exam on this machine"} + + +def slug(s): + return re.sub(r"-+", "-", re.sub(r"[^a-z0-9]+", "-", str(s).lower())).strip("-")[:30] or "x" + + +def machine_probes(rd, on): + """questions whose answers the readings already hold, in parts that do not change between two reads""" + by = {(r["entity"].split()[0], r["signal"]): r for r in rd} + P = [] + if ("cpu", "cores") in by: + P.append(("How many cores does %s have?" % on, str(by[("cpu", "cores")]["value"]))) + if ("system", "hostname") in by: + P.append(("What is the hostname of %s?" % on, str(by[("system", "hostname")]["value"]))) + if ("memory", "used") in by: + P.append(("How much memory is %s using?" % on, by[("memory", "used")]["text"].split(" used of ")[1].split(" (")[0])) + if ("disk", "free") in by: + P.append(("How much disk space is free on %s?" % on, " free of ")) + if ("system", "uptime") in by: + P.append(("How long has %s been up?" % on, "up ")) + if ("processes", "top_memory") in by: + P.append(("What is using the most memory on %s?" % on, "using the most memory")) + P += [("How much memory does a computer need?", None), ("What is the capital of France?", None), ("Who wrote Hamlet?", None)] + return P + + +def file_probes(d): + org = sources.FilesOrgan(folder=d.name + "/files") + org.load() + P = [] + for fname, hdr, rows in org.tables: + keys = [r[0].strip() for r in rows if r and r[0].strip()] + for r in rows[:: max(1, len(rows) // 6)][:6]: + if r and r[0].strip() and keys.count(r[0].strip()) == 1: + for j in range(1, min(len(hdr), len(r))): + if hdr[j].strip() and r[j].strip(): + P.append(("What is the %s of %s?" % (hdr[j].strip(), r[0].strip()), r[j].strip())) + break + for fname, i, sent in org.lines[:: max(1, len(org.lines) // 5)][:5]: + ws = [w for w in sources._words(sent) if len(w) > 4][:3] + if len(ws) >= 2: + P.append(("What do my notes say about %s?" % " ".join(ws), sent[:30])) + P += [("What is the capital of France?", None), ("Who wrote Hamlet?", None)] + return P + + +def run_code(code, tests, timeout=10): + """your function + your tests, in a separate Python process (isolated mode, a temp dir, a time limit)""" + with tempfile.TemporaryDirectory(prefix="o7code-") as t: + f = Path(t) / "run.py" + f.write_text(code + "\n\n" + tests + "\nprint('ALL TESTS PASSED')\n", encoding="utf-8") + try: + r = subprocess.run([sys.executable, "-I", str(f)], cwd=t, capture_output=True, text=True, timeout=timeout) + out = (r.stdout + r.stderr)[-4000:] + return {"ok": r.returncode == 0 and "ALL TESTS PASSED" in r.stdout, "output": out} + except subprocess.TimeoutExpired: + return {"ok": False, "output": "stopped after %d s" % timeout} + + + +# ---------------------------------------------------------------- optional: ElevenLabs for film narration and sound (your key) +# The ONLY feature that sends anything off this machine, and only when you connect it: the text of the narration (or the +# sound description) goes to api.elevenlabs.io with your key; the audio comes back into your film. The key is kept in this +# page's memory, or in workbench/local/settings.json if you tick "remember on this computer". Off by default. +EL_API = "https://api.elevenlabs.io/v1" + + +def el_key(b): + k = str(b.get("key") or settings().get("elevenlabs_key") or "").strip() + if not k: + raise ValueError("connect ElevenLabs first (Film tab): paste your API key") + if not re.match(r"^[A-Za-z0-9_\-]{20,128}$", k): + raise ValueError("that does not look like an ElevenLabs API key") + return k + + +def el_call(path, key, body=None, accept="application/json", timeout=90): + import urllib.error + import urllib.request + req = urllib.request.Request(EL_API + path, data=None if body is None else json.dumps(body).encode(), + headers={"xi-api-key": key, "Content-Type": "application/json", "Accept": accept}, + method="GET" if body is None else "POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + return r.read() + except urllib.error.HTTPError as e: + raw = e.read()[:2000].decode("utf-8", "replace") + try: + d = json.loads(raw).get("detail") + msg = d.get("message") if isinstance(d, dict) else str(d) + except Exception: # noqa: BLE001 + msg = raw[:200] + raise ValueError("ElevenLabs refused it (%d): %s" % (e.code, msg)) + except urllib.error.URLError as e: + raise ValueError("could not reach ElevenLabs: %s" % e.reason) + +# ---------------------------------------------------------------- http +class H(BaseHTTPRequestHandler): + server_version = "oracle7-workbench" + + def log_message(self, *a): + pass + + def _send(self, code, obj, ctype="application/json", raw=None): + b = raw if raw is not None else json.dumps(obj, default=str).encode() + self.send_response(code) + self.send_header("Content-Type", ctype) + self.send_header("Cache-Control", "no-store") + self.send_header("Content-Length", str(len(b))) + self.send_header("X-Content-Type-Options", "nosniff") + self.end_headers() + self.wfile.write(b) + + def _body(self): + n = int(self.headers.get("Content-Length") or 0) + if n > 4 * MAX_TEXT + 65536: # C11: never read part of a body and go on as if it were all + raise ValueError("the request is %d bytes; one message may be up to %d characters" % (n, MAX_TEXT)) + return json.loads(self.rfile.read(n) or b"{}") + + def _local_only(self): + host = (self.headers.get("Host") or "").split(":")[0] + return host in ("127.0.0.1", "localhost", "[::1]") + + def do_GET(self): # noqa: N802 + if not self._local_only(): + return self._send(403, {"error": "the workbench answers on 127.0.0.1 only"}) + u = urlparse(self.path) + q = {k: v[0] for k, v in parse_qs(u.query).items()} + if u.path in ("/", "/chat") and (STATIC / "chat.html").is_file(): # 12.0: the chat page first + return self._send(200, None, TYPES[".html"], (STATIC / "chat.html").read_bytes()) + if u.path in ("/", "/index.html", "/full", "/workbench"): + return self._send(200, None, TYPES[".html"], (STATIC / "index.html").read_bytes()) + if u.path.startswith("/static/"): + f = (STATIC / u.path[len("/static/"):]).resolve() + if STATIC.resolve() in f.parents and f.is_file(): + return self._send(200, None, TYPES.get(f.suffix, "application/octet-stream"), f.read_bytes()) + return self._send(404, {"error": "not found"}) + if u.path == "/api/identity": # C11: the loaded build, the tree, the state root, checked now + return self._send(200, identity()) + if u.path == "/api/turn": # C11: a conversation's turn job, for the page to follow it + import continuation as _ct + sid = re.sub(r"[^a-z0-9]", "", q.get("sid", ""))[:40] + js = [j for j in _ct._tj_all() if j.get("sid") == sid] + j = max(js, key=lambda entry: entry.get("t", 0)) if js else None + if j and j["state"] != "running" and q.get("take", "").lower() in ("1", "true") and not j.get("shown"): + j["shown"] = True + _ct._tj_put(j) + return self._send(200, {"job": j}) + if u.path == "/api/state": + return self._send(200, {"head": WB.eng.tip, "journal": settings().get("journal", False), "yours": sorted(WB.mine), + "elevenlabs_remembered": bool(settings().get("elevenlabs_key")), "language": language_status()}) + if u.path == "/api/sensors": + out = [] + for sid, c in sorted(sensors.configs().items()): + h = sensors.history(sid) + latest = {} + for r in h: + if r["ok"]: + latest[r["q"]] = {"v": r["v"], "unit": r["unit"], "t": r["t"]} + out.append({"id": sid, "name": c["name"], "kind": c["kind"], "address": c.get("address", ""), "interval": c.get("interval", 30), + "status": sensors.STATUS.get(sid), "latest": latest, "rejected": sum(1 for r in h if not r["ok"]), + "state": exam.status(SPECS / sid)["state"] if (SPECS / sid).exists() else "none"}) + return self._send(200, {"items": out, "quantities": {k: v[0] for k, v in sensors.QUANTITIES.items()}}) + if u.path == "/api/sensor/series": + rows = [r for r in sensors.history(q.get("id", "")) if r["q"] == q.get("q") and r["ok"]] + step = max(1, len(rows) // 300) + return self._send(200, {"points": [[int(r["t"]), r["v"]] for r in rows[::step]]}) + if u.path == "/api/registry/memo": + sid, kind = q.get("id", ""), q.get("kind", "register") + if not ID.match(sid) or not (SPECS / sid).is_dir(): + return self._send(404, {"error": "no such specialist"}) + try: + return self._send(200, {"memo": registry.memo_for(SPECS / sid, kind), "mint": registry.ORACLE7_MINT, "rpc": registry.RPC, + "burn_raw": registry.BURN_RAW, "decimals": registry.DECIMALS}) + except ValueError as e: + return self._send(400, {"error": str(e)}) + if u.path == "/api/machines": # 12.0: the page's Machines tab: the last map kept and the user's list + import machines as _mc + return self._send(200, _mc.latest()) + if u.path == "/api/orbiters": # 12.0: the page's Satellites tab (orbiters.py, as the command line) + import orbiters as _orb + return self._send(200, {"items": [{"name": c.get("name"), "good_for": c.get("good_for"), "needs": _orb.missing(c)} + for c in _orb.cards()]}) + if u.path == "/api/convs": + return self._send(200, {"keep": settings().get("keep_conversations"), "items": conv_list()}) + if u.path == "/api/conv": + return self._send(200, conv_load(q.get("id", ""))) + if u.path == "/api/help": + return self._send(200, {"topics": [{"topic": k, "text": v} for k, _, v in HELP_TOPICS], "commands": COMMANDS}) + if u.path == "/api/specialists": + return self._send(200, specialists_payload()) + if u.path == "/api/systems": + return self._send(200, json.loads((DATA / "systems.json").read_text(encoding="utf-8"))) + if u.path == "/api/gaps": + return self._send(200, gaps()) + if u.path == "/api/card": + sid = q.get("id", "") + f = DATA / "cards" / (sid + ".md") + if re.match(r"^[a-z0-9-]+$", sid) and f.exists(): + return self._send(200, {"id": sid, "md": f.read_text(encoding="utf-8")}) + return self._send(404, {"error": "no card"}) + if u.path == "/api/files": + d = SPECS / q.get("id", "") + if not ID.match(q.get("id", "")) or not d.is_dir(): + return self._send(404, {"error": "no such specialist"}) + return self._send(200, {"files": sorted(p.name for p in d.iterdir() if p.is_file()), "status": exam.status(d)}) + if u.path == "/api/file": + d, name = SPECS / q.get("id", ""), q.get("name", "") + if not ID.match(q.get("id", "")) or not FNAME.match(name) or not (d / name).is_file(): + return self._send(404, {"error": "no such file"}) + return self._send(200, {"name": name, "text": (d / name).read_text(encoding="utf-8")}) + if u.path == "/api/exam": + return self._send(200, exam.progress(q.get("id", ""))) + if u.path == "/api/build": + with _BUILD_LOCK: + return self._send(200, json.loads(json.dumps(BUILD, default=str))) + if u.path == "/api/swarm": + with _SWARM_LOCK: + return self._send(200, json.loads(json.dumps(dict(SWARM, log=SWARM.get("log", [])[-200:]), default=str))) + if u.path == "/api/swarm/picture": + f = q.get("f", "") + t = SWARM.get("target") or "" + path = LOCAL / "swarm" / "targets" / t / "out" / "pictures" / f + if not PICTURE.match(f) or not re.match(r"^[a-z0-9-]{1,40}$", t) or not path.is_file(): + return self._send(404, {"error": "no such picture"}) + return self._send(200, None, "image/png", path.read_bytes()) + return self._send(404, {"error": "not found"}) + + def do_POST(self): # noqa: N802 + if not self._local_only() or (self.headers.get("Origin") and not re.match(r"^https?://(127\.0\.0\.1|localhost)(:\d+)?$", + self.headers.get("Origin", ""))): + return self._send(403, {"error": "the workbench answers its own page on 127.0.0.1 only"}) + u = urlparse(self.path) + try: + b = self._body() + except ValueError as e: + return self._send(413, {"error": str(e)}) + except Exception: # noqa: BLE001 + return self._send(400, {"error": "bad request"}) + try: + if u.path == "/api/chat": + text, sid = str(b.get("text", "")).strip(), re.sub(r"[^a-z0-9]", "", str(b.get("sid", "x")))[:40] or "x" + if not text: + return self._send(400, {"error": "ask something"}) + if len(text) > MAX_TEXT: # C11: refused with the limit, never cut silently + return self._send(413, {"error": "the message is %d characters; one message may be up to %d. Put the " + "specification in a file in the project folder and name the file." + % (len(text), MAX_TEXT)}) + t = time.time() + import continuation as _ct + ic = _ct.intercept(sid, text) # a turn job running here: status / stop answered from its record + note = "" + if ic and ic.get("resume"): + j = ic["resume"] + text = j["text"] + note = "Taking up again the request that was %s at %s (job %s): \"%s\"%s" % ( + "stopped" if j["state"] == "stopped" else "cut off", j.get("stage") or "its start", j["id"], + text[:200], chr(10)) + ic = None + if ic: + r = WB._delivered(text, sid, ic) # 12.5 step 3 (audit E2): a job's own reply leaves by the one exit too + elif b.get("deadline"): # the browser's turns: long work goes on as a job, kept and stoppable + r = _ct.run_turn(lambda: WB.chat(text, sid), sid, text, max(2.0, float(b["deadline"]))) + else: + r = WB.chat(text, sid) + if note: + r = dict(r, response=note + str(r.get("response", ""))) + status = r.get("status") + ex = r.get("execution") + try: + import bench as _bench + _env = _bench.Turn(sid).s.get("env") + except Exception: # noqa: BLE001 + _env = None + where = {"release": getattr(WB.eng, "tip", ""), "build": BOOT and identity_brief(), + "language": language_status(), + "host": os.uname().nodename if hasattr(os, "uname") else os.environ.get("COMPUTERNAME", ""), + "env": (("%s:%s" % (_env.get("host"), _env["root"])) if _env and _env.get("kind") == "host" else (_env or {}).get("root"))} + kind, why = (None, None) if status == "answered" else why_declined(r.get("path")) + details = {key: r[key] for key in ("turn_reading", "language", "reading", "claims", "subjects", "basis", "details", "wording", "missing_evidence", + "proposition", "proposition_plan", "proposition_check", "proposition_reading", + "code_reading", "resumed_after_open", "resumed_project_request", "meaning_graph", "meaning_check", "meaning_plan", "turn_receipt", "writing", "writing_source", "context_record_error", "contribution") if key in r} + if settings().get("keep_conversations") and not b.get("nokeep") and CID.match(sid): + conv_add(sid, {"t": int(time.time()), "q": text, "status": status, "response": str(r.get("response", "")), + "path": str(r.get("path", "")), "trace": trace(r.get("path"), r.get("response"), status), + "why": why, "ms": int((time.time() - t) * 1000), "execution": ex, "where": where, **details}) + if settings().get("journal"): + with open(JOURNAL, "a", encoding="utf-8") as fh: + fh.write(json.dumps({"t": int(time.time()), "q": text, "status": status, "why": kind, + "path": str(r.get("path"))[:120]}) + "\n") + return self._send(200, {"status": status, "response": str(r.get("response", "")), "path": str(r.get("path", "")), + "trace": trace(r.get("path"), r.get("response"), status), "why": why, "why_kind": kind, + "ms": int((time.time() - t) * 1000), "execution": ex, "where": where, **details}) + if u.path == "/api/machines/collect": # read this computer and every listed machine now (read-only) + import machines as _mc + return self._send(200, {"map": _mc.collect(), "meta": {m["id"]: m for m in _mc.config()}}) + if u.path == "/api/machines/save": # the user's own list, kept on this computer only + import machines as _mc + items = b.get("machines") if isinstance(b.get("machines"), list) else [] + return self._send(200, {"machines": _mc.save(items[:40])}) + if u.path == "/api/orbiters/exam": + import orbiters as _orb + card = next((c for c in _orb.cards() if c.get("name") == str(b.get("name", ""))), None) + if card is None: + return self._send(404, {"error": "no such orbiter"}) + r = _orb.run_exam(card, timeout=600) + return self._send(200, {k: (v if isinstance(v, (int, float, bool)) or v is None else str(v)[:1200]) for k, v in r.items()}) + if u.path == "/api/essay": + # ProseFold v2: an essay composed from this model's own cited records, with the chosen length, reading level, + # technical depth and style (profiles measured from the release's corpora); no language model + import prosefold.options as PO + topic = re.sub(r"\s+", " ", str(b.get("topic", ""))).strip()[:80] + if not topic: + return self._send(400, {"error": "name a topic"}) + pick = lambda k, allowed, d: b.get(k) if b.get(k) in allowed else d # noqa: E731 + voice_path = None + vt = str(b.get("voice_text", "") or "") + if b.get("style") == "custom" and len(vt.split()) >= 150: + LOCAL.mkdir(parents=True, exist_ok=True) + voice_path = LOCAL / "essay_voice.txt" + voice_path.write_text(vt[:200000], encoding="utf-8") + elif b.get("style") == "custom": + return self._send(400, {"error": "paste at least 150 words of the writing whose voice you want"}) + t = time.time() + # The plain essay entry uses the same durable writing owner as + # chat. Existing voice/level/depth profiles retain their own + # selector until they supply checked records to that owner. + length = pick('length', PO.LENGTHS, 'medium') + plain_profile = (pick('level', PO.LEVELS, 'general') == 'general' + and pick('depth', PO.DEPTHS, 'standard') == 'standard' + and pick('style', PO.STYLES, 'plain') == 'plain' + and not b.get('rewrite') and length != 'full') + cv = WB._converse() + discussion = cv._discussion_part() if cv and hasattr(cv, '_discussion_part') else None + if plain_profile and discussion is not None: + essay_sid = str(b.get('sid') or ('essay' + hashlib.sha256(topic.encode()).hexdigest()[:22])) + request = 'Write %d sentences about %s.' % (PO.LENGTHS[length], topic) + raw = discussion.write_account(request, essay_sid, subject=topic, + sizes=[{'n': PO.LENGTHS[length], 'unit': 'sentence', 'words': str(PO.LENGTHS[length])}]) + if raw is not None: + r = WB._delivered(request, essay_sid, raw) + draft = r.get('writing') or {} + counts = draft.get('delivered_counts') or draft.get('counts') or {} + grade = PO.fk_grade(draft.get('body', '')) + lo, hi = PO.LEVELS['general'] + r.update(essay_md=r.get('response', ''), topic=topic, sid=essay_sid, + sentences=counts.get('sentence', 0), records_used=len(draft.get('evidence', [])), + faithful=counts.get('sentence', 0) if draft.get('delivered_checked') else 0, + reading_grade=grade, level_band=[lo, hi], level_reached=lo <= grade <= hi, + options={'length': length, 'level': 'general', 'depth': 'standard', 'style': 'plain'}, + ms=int((time.time() - t) * 1000)) + return self._send(200, r) + r = PO.write(WB.eng.chat, topic, length=pick("length", PO.LENGTHS, "medium"), level=pick("level", PO.LEVELS, "general"), + depth=pick("depth", PO.DEPTHS, "standard"), style=pick("style", PO.STYLES, "plain"), voice_path=voice_path, + rewrite=bool(b.get("rewrite"))) + r["ms"] = int((time.time() - t) * 1000) + return self._send(200, r) + if u.path == "/api/journal": + s = settings() + s["journal"] = bool(b.get("on")) + save_settings(s) + return self._send(200, {"on": s["journal"]}) + if u.path == "/api/journal/clear": + JOURNAL.unlink(missing_ok=True) + return self._send(200, {"cleared": True}) + if u.path == "/api/new": + sid = str(b.get("id", "")).strip().lower() + if not ID.match(sid): + return self._send(400, {"error": "an id of lower-case letters, digits and hyphens, 2-41 long"}) + words = [w for w in re.findall(r"[a-z][a-z0-9-]+", str(b.get("words", "")).lower())][:20] + scaffold(sid, str(b.get("name") or sid)[:80], words, [str(x)[:300] for x in (b.get("examples") or [])][:20]) + return self._send(200, {"id": sid}) + if u.path == "/api/scan": + rd = sources.scan_local() + return self._send(200, {"readings": rd}) + if u.path == "/api/scan/save": + d = exam.make_source(SPECS, "this-computer", "this computer", "MachineOrgan", {"target": "local", "name": "this computer"}, + ["computer", "pc", "laptop", "machine", "desktop"]) + exam.start_source(d, machine_probes(sources.scan_local(), "my computer"), on_done=WB.reload) + return self._send(200, {"id": d.name}) + if u.path in ("/api/server", "/api/server/save"): + name = re.sub(r"[^A-Za-z0-9 .-]", "", str(b.get("name") or b.get("host") or ""))[:40].strip() or "server" + host, user, port, key = str(b.get("host", "")).strip(), str(b.get("user", "")).strip(), int(b.get("port") or 22), str(b.get("key", "")).strip() + rd = sources.scan_server(host, user, port, key) + if u.path == "/api/server": + return self._send(200, {"readings": rd}) + d = exam.make_source(SPECS, "server-" + slug(name), name, "MachineOrgan", + {"target": "server", "name": name, "host": host, "user": user, "port": port, "key": key}, [w for w in slug(name).split("-") if w]) + exam.start_source(d, machine_probes(rd, name), on_done=WB.reload) + return self._send(200, {"id": d.name}) + if u.path == "/api/files/add": + name = re.sub(r"[^A-Za-z0-9 .-]", "", str(b.get("name") or "my files"))[:40].strip() or "my files" + sid = str(b.get("id") or "files-" + slug(name)) + if not ID.match(sid): + return self._send(400, {"error": "bad id"}) + d = SPECS / sid + if not d.exists(): + exam.make_source(SPECS, sid, name, "FilesOrgan", {"folder": sid + "/files", "name": name}, ["notes", "files", "documents"]) + saved = [] + for f in (b.get("files") or [])[:50]: + fn = re.sub(r"[^A-Za-z0-9_.-]", "_", Path(str(f.get("name", ""))).name)[:80] + if not re.search(r"\.(csv|tsv|txt|md)$", fn, re.I): + continue + text = str(f.get("text", "")) + if len(text) > 5_000_000: + continue + (d / "files" / fn).write_text(text, encoding="utf-8") + saved.append(fn) + if not saved: + return self._send(400, {"error": "add .csv, .tsv, .txt or .md files (save other documents as text or CSV first)"}) + exam.start_source(d, file_probes(d), on_done=WB.reload) + return self._send(200, {"id": sid, "saved": saved}) + if u.path == "/api/el/connect": + key = el_key(b) + voices = json.loads(el_call("/voices", key)).get("voices", []) + st = settings() + if b.get("remember"): + st["elevenlabs_key"] = key + else: + st.pop("elevenlabs_key", None) + save_settings(st) + return self._send(200, {"voices": [{"id": v["voice_id"], "name": v.get("name", "")} for v in voices][:80], + "remembered": bool(b.get("remember"))}) + if u.path == "/api/el/forget": + st = settings() + st.pop("elevenlabs_key", None) + save_settings(st) + return self._send(200, {"forgotten": True}) + if u.path == "/api/el/speech": + key, text = el_key(b), str(b.get("text", ""))[:2500] + vid = re.sub(r"[^A-Za-z0-9]", "", str(b.get("voice") or "JBFqnCBsd6RMkjVDRZzb")) + audio = el_call("/text-to-speech/%s?output_format=mp3_44100_128" % vid, key, + {"text": text, "model_id": "eleven_multilingual_v2"}, accept="audio/mpeg") + return self._send(200, None, "audio/mpeg", audio) + if u.path == "/api/el/image": + # ElevenLabs Image & Video API: create, poll until completed, download the signed content_url + key, prompt = el_key(b), str(b.get("prompt", ""))[:1500] + model = str(b.get("model") or "gemini-2.5-flash-image") + if model not in ("gemini-2.5-flash-image", "gpt-image-1"): + return self._send(400, {"error": "model must be gemini-2.5-flash-image or gpt-image-1"}) + body = {"model_id": model, "prompt": prompt, "aspect_ratio": "16:9" if model.startswith("gemini") else "3:2"} + gid = json.loads(el_call("/flows/image", key, body))["id"] + t0, g = time.time(), {} + while time.time() - t0 < 180: + g = json.loads(el_call("/flows/image/%s" % re.sub(r"[^A-Za-z0-9_-]", "", gid), key)) + if g.get("status") in ("completed", "failed"): + break + time.sleep(2) + if g.get("status") != "completed": + return self._send(502, {"error": "image not made: %s" % (g.get("failure_reason") or g.get("status") or "timed out")}) + import urllib.request + try: + data = urllib.request.urlopen(g["content_url"], timeout=60).read() + except Exception: # noqa: BLE001 - the signed URL normally needs no key; try once with it + data = urllib.request.urlopen(urllib.request.Request(g["content_url"], headers={"xi-api-key": key}), timeout=60).read() + assets = LOCAL / "assets" + assets.mkdir(exist_ok=True) + ext = ".png" if "png" in str(g.get("content_mime_type", "")) else ".jpg" if "jp" in str(g.get("content_mime_type", "")) else ".webp" + (assets / ("image-%s%s" % (time.strftime("%Y%m%d-%H%M%S"), ext))).write_bytes(data) + return self._send(200, None, g.get("content_mime_type") or "image/png", data) + if u.path == "/api/el/sound": + key, prompt = el_key(b), str(b.get("prompt", ""))[:400] + audio = el_call("/sound-generation", key, {"text": prompt, "duration_seconds": min(22.0, max(2.0, float(b.get("seconds") or 20))), + "prompt_influence": 0.4}, accept="audio/mpeg") + return self._send(200, None, "audio/mpeg", audio) + if u.path == "/api/mcp/connect": + tools = mcp.connect(str(b.get("name", "")).strip(), str(b.get("command", "")).strip(), str(b.get("url", "")).strip(), + str(b.get("token", "")).strip()) + return self._send(200, {"tools": tools}) + if u.path == "/api/mcp/save": + server, tools = str(b.get("name", "")).strip(), [str(t) for t in (b.get("tools") or [])][:40] + if server not in mcp.servers() or not tools: + return self._send(400, {"error": "connect the server and pick at least one tool"}) + sid = "mcp-" + slug(server) + ex = [(str(x.get("q", ""))[:300], (str(x.get("want")) if x.get("want") else None)) for x in (b.get("examples") or [])][:20] + probes = [p for p in ex if p[0]] + [("What is the capital of France?", None), ("Who wrote Hamlet?", None)] + d = exam.make_source(SPECS, sid, "%s tools" % server, "mcp.McpOrgan", {"server": server, "tools": tools, "name": server, "folder": sid}, + [w for w in mcp.words(server)] or ["mcp"]) + exam.start_source(d, probes, on_done=WB.reload) + return self._send(200, {"id": sid}) + if u.path == "/api/feedback": + m = re.match(r"^yours:([a-z0-9-]+)>", str(b.get("path", ""))) + right = bool(b.get("right")) + if not m or not (SPECS / m.group(1)).is_dir(): + return self._send(200, {"learned": False, "note": "marks teach your own specialists; this answer came from the core"}) + d = SPECS / m.group(1) + tool = re.search(r"tool ([\w.-]+)\(", str(b.get("response", ""))) + if (exam.read_manifest(d) or {}).get("organ", {}).get("module", "").startswith("organ_mcp") or tool: + e = mcp.learn(d / "credit.json", tool.group(1), str(b.get("q", "")), right) if tool else {} + exam.start_source(d, None, on_done=WB.reload) # the lane check runs again after learning + return self._send(200, {"learned": True, "tool": tool.group(1) if tool else None, "credit": e}) + return self._send(200, {"learned": False, "note": "noted; only tool specialists learn from marks"}) + if u.path == "/api/conv/rename": + c = conv_load(str(b.get("id", ""))) + c["title"] = str(b.get("title", ""))[:120] + conv_path(c["id"]).write_text(json.dumps(c, indent=0), encoding="utf-8") + return self._send(200, {"ok": True}) + if u.path == "/api/conv/delete": + conv_path(str(b.get("id", ""))).unlink(missing_ok=True) + return self._send(200, {"ok": True}) + if u.path == "/api/conv/delete_all": + for p in CONVS.glob("*.json"): + p.unlink() + return self._send(200, {"ok": True}) + if u.path == "/api/conv/keep": + st = settings() + st["keep_conversations"] = bool(b.get("on")) + save_settings(st) + return self._send(200, {"keep": st["keep_conversations"]}) + if u.path == "/api/conv/specialist": + cid, days = str(b.get("id", "")), max(1, min(365, int(b.get("days") or 7))) + c = conv_load(cid) + done = [t for t in c["turns"] if t.get("status") == "answered" and not str(t.get("path", "")).startswith("workbench:")] + if not done: + return self._send(400, {"error": "this conversation has no answers to remember yet"}) + sid = ("chat-" + slug(c.get("title") or cid))[:34].rstrip("-") + "-" + cid[:4] + d = exam.make_source(SPECS, sid, "conversation: " + (c.get("title") or cid)[:60], "ConversationOrgan", + {"conv": cid, "name": (c.get("title") or cid)[:60]}, ["conversation", "earlier"]) + m = exam.read_manifest(d) + m["expires"] = time.time() + days * 86400 + m["temporary"] = True + (d / "manifest.json").write_text(json.dumps(m, indent=1), encoding="utf-8") + probes = [] + for t in done[:8]: + ws = [w for w in sources._words(t["q"]) if w not in sources.RECALL_FILLER][:3] + if ws: + probes.append(("What did we say earlier about %s?" % " ".join(ws), t["q"][:40])) + probes += [("What is the capital of France?", None), ("Who wrote Hamlet?", None), ("Who directed Jaws?", None)] + exam.start_source(d, probes, on_done=WB.reload) + return self._send(200, {"id": sid, "expires": m["expires"]}) + if u.path == "/api/swarm/point": # 5.0: point the swarm at a target (swarm/point.py) + t = b.get("target") + if isinstance(t, str): + t = json.loads(t) + if not isinstance(t, dict) or not (t.get("learn") or t.get("work")): + return self._send(400, {"error": "a target is JSON with learn and/or work (see the example)"}) + return self._send(200, start_point(t)) + if u.path == "/api/update/check": # 4.9: the newest published release (update.py) + import update + return self._send(200, update.check()) + if u.path == "/api/update/apply": + import update + return self._send(200, update.start_apply()) + if u.path == "/api/update/status": + import update + return self._send(200, dict(update.STATUS)) + if u.path == "/api/verify": + return self._send(200, verify.verify_install()) + if u.path == "/api/verify/chain": + return self._send(200, verify.check_anchor(str(b.get("signature") or "") or None)) + if u.path == "/api/sensor/test": + cfg = {"kind": str(b.get("kind", "")), "address": str(b.get("address", "")).strip(), "user": str(b.get("user", "")), + "password": str(b.get("password", ""))} + if cfg["kind"] == "http" and not re.match(r"^https?://", cfg["address"]): + return self._send(400, {"error": "the address must start with http:// or https://"}) + vals, where = sensors.read_source(cfg) + return self._send(200, {"source": where, "fields": [{"path": k, "value": v, "guess": sensors.guess_quantity(k)} + for k, v in list(vals.items())[:60]]}) + if u.path == "/api/sensor/add": + name = re.sub(r"[^A-Za-z0-9 .-]", "", str(b.get("name") or "my sensor"))[:40].strip() or "my sensor" + fields = [{"path": str(f["path"])[:120], "quantity": str(f["quantity"])[:40], "unit": str(f.get("unit") or "")[:12]} + for f in (b.get("fields") or []) if f.get("path") and f.get("quantity")][:30] + if not fields: + return self._send(400, {"error": "pick at least one reading and say what it measures"}) + sid = "sensor-" + slug(name) + c = {"id": sid, "name": name, "kind": str(b.get("kind", "")), "address": str(b.get("address", "")).strip(), + "interval": max(5, min(3600, int(b.get("interval") or 30))), "fields": fields, + "user": str(b.get("user", "")), "password": str(b.get("password", "")), "added": int(time.time())} + sensors.save_config(c) + sensors.poll_once(c) + sensors.start_poller(sid) + d = exam.make_source(SPECS, sid, name, "sensors.SensorOrgan", {"sensor": sid, "name": name}, + [w for w in slug(name).split("-") if w] or ["sensor"]) + qs = sorted({f["quantity"] for f in fields}) + probes = [("What is the %s on %s?" % (qq, name), qq) for qq in qs] + probes += [("What is the temperature of the Sun?", None), ("How much does a litre of water weigh?", None)] + exam.start_source(d, probes, on_done=WB.reload) + return self._send(200, {"id": sid}) + if u.path == "/api/sensor/remove": + sid = str(b.get("id", "")) + if not ID.match(sid): + return self._send(400, {"error": "bad id"}) + for p in (sensors.DIR / ("%s.json" % sid), sensors.DIR / ("%s.jsonl" % sid)): + p.unlink(missing_ok=True) + shutil.rmtree(SPECS / sid, ignore_errors=True) + WB.reload() + return self._send(200, {"removed": sid}) + if u.path == "/api/solana/rpc": + raw = json.dumps(b).encode() + out = registry.relay(raw) + return self._send(200, None, "application/json", out) + if u.path == "/api/registry/record": + sid = str(b.get("id", "")) + if not ID.match(sid) or not (SPECS / sid).is_dir(): + return self._send(400, {"error": "no such specialist"}) + return self._send(200, {"records": registry.record(SPECS / sid, str(b.get("kind", "")), str(b.get("signature", "")).strip())}) + if u.path == "/api/registry/check": + sid = str(b.get("id", "")) + if not ID.match(sid) or not (SPECS / sid).is_dir(): + return self._send(400, {"error": "no such specialist"}) + return self._send(200, registry.check(SPECS / sid)) + if u.path == "/api/build": + qs = [str(x).strip() for x in (b.get("questions") or []) if str(x).strip()][:12] + sid = str(b.get("id", "")).strip() or None + if len(qs) < 3: + return self._send(400, {"error": "give at least 3 example questions, one per line"}) + if sid and (not ID.match(sid) or (SPECS / sid).exists()): + return self._send(400, {"error": "that id is taken or not valid (lower-case letters, digits, hyphens)"}) + return self._send(200, start_build(qs, sid, on_done=WB.reload)) + if u.path == "/api/compose": + text = str(b.get("examples", ""))[:200000] + sid = str(b.get("id", "")).strip() or None + if text.count("->") + text.count("=>") < 8: + return self._send(400, {"error": "give at least 8 worked examples, one per line: inputs -> answer"}) + if sid and (not ID.match(sid) or (SPECS / sid).exists()): + return self._send(400, {"error": "that id is taken or not valid (lower-case letters, digits, hyphens)"}) + return self._send(200, start_build(None, sid, on_done=WB.reload, examples=text)) + if u.path == "/api/example": + src = HERE / "examples" / "habitable-zone" + if (SPECS / src.name).exists(): + return self._send(400, {"error": "the example is already in your specialists"}) + shutil.copytree(src, SPECS / src.name, ignore=shutil.ignore_patterns("__pycache__", "verdict_*", "exam_log*")) + return self._send(200, {"id": src.name}) + if u.path == "/api/file": + d, name = SPECS / str(b.get("id", "")), str(b.get("name", "")) + if not ID.match(str(b.get("id", ""))) or not d.is_dir() or not FNAME.match(name) or name.startswith("verdict_"): + return self._send(400, {"error": "that file cannot be written here"}) + (d / name).write_text(str(b.get("text", "")), encoding="utf-8") + WB.reload() + return self._send(200, {"saved": name, "status": exam.status(d)}) + if u.path == "/api/exam": + sid, split = str(b.get("id", "")), str(b.get("split", "dev")) + if not ID.match(sid) or not (SPECS / sid).is_dir() or split not in ("dev", "heldout"): + return self._send(400, {"error": "which specialist, and dev or heldout?"}) + exam.start(SPECS / sid, split, WB.eng, on_done=WB.reload) + return self._send(200, exam.progress(sid)) + if u.path == "/api/package": + sid = str(b.get("id", "")) + if not ID.match(sid) or not (SPECS / sid).is_dir(): + return self._send(400, {"error": "no such specialist"}) + return self._send(200, package(sid)) + if u.path == "/api/import": + r = import_zip(str(b.get("path", ""))) + return self._send(200, r) + if u.path == "/api/code/run": + return self._send(200, run_code(str(b.get("code", ""))[:100_000], str(b.get("tests", ""))[:50_000])) + except ValueError as e: + return self._send(400, {"error": str(e)}) + except Exception as e: # noqa: BLE001 + return self._send(500, {"error": "%s: %s" % (type(e).__name__, e)}) + return self._send(404, {"error": "not found"}) + + +def serve(engine, port=8177): + global WB + WB = Workbench(engine) + sensors.start_all() + os.environ["ORACLE7_HEAD_PORT"] = ",".join(filter(None, [os.environ.get("ORACLE7_HEAD_PORT"), str(port)])) # runjail refuses it + srv = ThreadingHTTPServer(("127.0.0.1", port), H) + print("Oracle7 Workbench (%s) on http://127.0.0.1:%d/" % (engine.tip, port), flush=True) + srv.serve_forever() diff --git a/workbench/service_parts.py b/workbench/service_parts.py new file mode 100644 index 0000000000000000000000000000000000000000..33af92698de26fe8e49f40ea46494d2b7f0c0ed4 --- /dev/null +++ b/workbench/service_parts.py @@ -0,0 +1,288 @@ +"""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 base64 +from contextlib import contextmanager +import hashlib +import json +import os +from pathlib import Path +import re +import tempfile +import threading +import time +import urllib.error +import urllib.parse +import urllib.request + + +class ServiceHole(ValueError): + def __init__(self, kind, text): + super().__init__(text) + self.kind = kind + + +_FILE_LOCKS = {} +_FILE_LOCKS_GUARD = threading.Lock() + + +@contextmanager +def _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 + + +@contextmanager +def _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)}} diff --git a/workbench/shadow.py b/workbench/shadow.py new file mode 100644 index 0000000000000000000000000000000000000000..5363fb63f122c9909b9c691b3d244144cfd320fc --- /dev/null +++ b/workbench/shadow.py @@ -0,0 +1,142 @@ +"""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 that +fits all examples within the size the examples evidence (`evidenced`), and for a decision list each guard or arm swapped +one 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, seeded +by 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's +answer is never changed here. Rival and probe counts are named guards; a cut is recorded.""" +import hashlib +import json +import os +import random +import 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 list +REDRAW = 40 # inputs re-drawn from the examples' parts +SECONDS = 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 rec diff --git a/workbench/static/chat.html b/workbench/static/chat.html new file mode 100644 index 0000000000000000000000000000000000000000..cf8b7393ff67e1230e36c8e7734fd109b2f6754a --- /dev/null +++ b/workbench/static/chat.html @@ -0,0 +1,380 @@ + + + + + +Oracle7 + + + +
    + +
    +
    Oracle7 +
    +
    +
    +
    +
    +

    What do you want to know or build?

    +

    Ask, talk, or say what you want made. Every reply shows whether it was checked and how it got there.

    +
    + + + + +
    +
    +
    +
    +
    +
    + + +
    +
    Runs on this computer. Tools: index, find, read, write, run, fetch, make, change, want.
    +
    +
    + + +
    +
    + + + diff --git a/workbench/static/machines.html b/workbench/static/machines.html new file mode 100644 index 0000000000000000000000000000000000000000..91a02c6f1ee09bb063ad9fb2058f5c36e9d7ef56 --- /dev/null +++ b/workbench/static/machines.html @@ -0,0 +1,572 @@ + + + + + +Machines + + + +
    + +
    +
    +
    +

    Machines

    +
    this computer and the machines it reaches over ssh · read-only
    +
    +
    + loading… + + + +
    +
    + +
    +
    + + Internet +
    +
    + +
    +
    +
    +
    +
    ⌂
    +
    +
    Home
    +
    the computer Oracle7 runs on · ssh out to every listed machine
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    S
    +
    +
    Servers
    +
    key-only ssh · read-only probe
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Watch list

    +

    Machines on this map

    +

    Legend

    +
    network link
    +
    SSH admin (laptop → servers)
    +
    offload / backup to the drive
    +
    server or machine · dashed = unreachable
    +
    public sites (nginx vhosts, checked every run)
    +
    2xx-3xx · 4xx · down/5xx
    +
    :8050 listening port · public bound to 0.0.0.0
    +
    Click any server for every site, service, port, cert and failed unit.
    +
    +
    +
    +
    + +
    + + + + + diff --git a/workbench/swarm/builder_v2.py b/workbench/swarm/builder_v2.py index d0386d8659b9e2974207702298225c36ece7ee64..199ca501fd221e357fdaecd4e2cda093899e721e 100644 --- a/workbench/swarm/builder_v2.py +++ b/workbench/swarm/builder_v2.py @@ -92,6 +92,12 @@ def build(brief, examples, task_id, out_root): cands[ph] = [] log.setdefault("errors", []).append("search %s: %s" % (ph, str(e)[:80])) ranked = choose_property(cands, examples) + ev = brief.get("evidence") or {} + if ev.get("pid"): + # 11.5 Amendment 14: the store's evidence names the relation every example's entity holds; it goes first, ahead of the + # word heuristics ("how long" never contains "length"); its table is fetched and examined exactly as any other + ranked = [(9.0, {"pid": ev["pid"], "label": ev.get("label", ev["pid"]), "datatype": "quantity", "aliases": []}, "store evidence")] + [r for r in ranked if r[1]["pid"] != ev["pid"]] + log["evidence"] = ev log["ranked"] = [(s, c["pid"], c["label"], ph) for s, c, ph in ranked[:6]] # the kind of thing the examples name: their proper names looked up, the classes two or more of them share names = [] diff --git a/workbench/swarm/part11.py b/workbench/swarm/part11.py index d22b3b489c640ca2e48ae37e499f9a3dfdd62fe3..3b7d4a009ca347e5f4d135ab37672ab2c1bd31b0 100644 --- a/workbench/swarm/part11.py +++ b/workbench/swarm/part11.py @@ -189,17 +189,57 @@ def _body_ok(kind, body, face, known): ex = body.get("examples") return isinstance(ex, list) and ex and all(isinstance(x, dict) and x.get("cite") for x in ex) if kind == "composite": - path = body.get("path") - if not (isinstance(path, list) and len(path) >= 2 and all(p in known for p in path)): - return False - for a, b in zip(path, path[1:]): - need = {x["unit"] for x in known[b]["interface"]["inputs"]} - if not {x["unit"] for x in known[a]["interface"]["outputs"]} & need: - return False - return True + return wiring(body, face, known)[0] is not None return False +def wiring(body, face, known): + """12.0 C13: every input of every step of a composite bound to a named value of the same unit - one of the composite's own + inputs, or an output of an earlier step - never only "the units of two neighbours meet". A step's binding is the body's + "bind" ({step: {input: "in:" | "."}}) where it is given; otherwise the one value of that input's unit + the step before outputs, else the composite input of that name and unit, else the one composite input of that unit. + -> (wiring: [{input: source}], None) or (None, why)""" + path = body.get("path") + if not (isinstance(path, list) and len(path) >= 2 and all(p in known for p in path)): + return None, "a path of known parts" + ins = {x["name"]: x["unit"] for x in face.get("inputs") or []} + given = body.get("bind") or {} + made = [] # per step: {output name: unit} + out = [] + for k, pid in enumerate(path): + step = {} + for x in known[pid]["interface"].get("inputs") or []: + src = (given.get(str(k)) or given.get(k) or {}).get(x["name"]) + if src: + if src.startswith("in:"): + u = ins.get(src[3:]) + else: + j, _, o = src.partition(".") + u = made[int(j)].get(o) if j.isdigit() and int(j) < k else None + if u != x["unit"]: + return None, "step %d: %s is bound to %s, not a value of unit %s" % (k, x["name"], src, x["unit"]) + else: + prev = [o for o, u in (made[k - 1].items() if k else []) if u == x["unit"]] + same = [n for n, u in ins.items() if u == x["unit"]] + alone = sum(1 for y in known[pid]["interface"].get("inputs") or [] if y["unit"] == x["unit"]) == 1 + if prev and x["name"] in prev: # the same name and unit, made just before + src = "%d.%s" % (k - 1, x["name"]) + elif ins.get(x["name"]) == x["unit"]: # the composite's own input of that name and unit + src = "in:" + x["name"] + elif len(prev) == 1 and alone: # by unit only when nothing else of the step shares it + src = "%d.%s" % (k - 1, prev[0]) + elif len(same) == 1 and alone: + src = "in:" + same[0] + else: + return None, "step %d: input %s (%s) is not bound to any value" % (k, x["name"], x["unit"]) + step[x["name"]] = src + if k and not any(not v.startswith("in:") for v in step.values()): + return None, "step %d takes nothing from the steps before it" % k + made.append({o["name"]: o["unit"] for o in known[pid]["interface"]["outputs"]}) + out.append(step) + return out, None + + def admit(part, known=None, trusted=None): """structure, hash, signature, least examiner -> (True, "admitted") or (False, why). known: {id: part} for composites""" if not isinstance(part, dict): @@ -252,16 +292,28 @@ def apply(part, inputs, known=None): lo, hi = part["body"]["range"] x = next(iter(inputs.values()), None) return x if isinstance(x, (int, float)) and lo <= x <= hi else None - if k == "composite": - v, cur = inputs, None - for pid in part["body"]["path"]: + if k == "composite": # C13: each step given exactly the values its inputs are bound to + wires, _why = wiring(part["body"], part["interface"], known) + if wires is None: + return None + made, cur = [], None + for pid, step in zip(part["body"]["path"], wires): p = known[pid] + v = {} + for name, src in step.items(): + if src.startswith("in:"): + if src[3:] not in inputs: + return None + v[name] = inputs[src[3:]] + else: + j, _, o = src.partition(".") + v[name] = made[int(j)][o] cur = apply(p, v, known) if cur is None: return None - cur = cur[0] if isinstance(cur, list) else cur - n = [x["name"] for x in (known[part["body"]["path"][min(part["body"]["path"].index(pid) + 1, len(part["body"]["path"]) - 1)]]["interface"].get("inputs") or [{"name": "x"}])][0] - v = {n: cur} + vals = cur if isinstance(cur, list) else [cur] + made.append({o["name"]: x for o, x in zip(p["interface"]["outputs"], vals)}) + cur = vals[0] return cur return None @@ -292,6 +344,23 @@ def _suite(): "easy examiner": seal(dict(ohm, examiner=dict(ex, n=5)), sk), "no must-decline": seal(dict(ohm, examiner=dict(ex, must_decline_share=0)), sk), "exam never run": seal(dict(ohm, examiner={k: v for k, v in ex.items() if k != "ran"}), sk), "exam failed": seal(dict(ohm, examiner=dict(ex, ran={"items": 149, "failed": 1})), sk), "exam smaller than declared": seal(dict(ohm, examiner=dict(ex, ran={"items": 20, "failed": 0})), sk), "author's own seed": seal(dict(ohm, examiner=dict(ex, seed_rule="mine")), sk), "no provenance": seal(dict(ohm, provenance={}), sk), "unit mismatch at a join": seal(dict(base, kind="composite", interface=comp["interface"], body={"path": [good["table"]["id"], good["formula2"]["id"]]}), sk), "example with no citation": seal(dict(base, kind="example-set", interface={"outputs": [{"name": "label", "unit": "class"}]}, body={"examples": [{"x": 1}]}), sk)} + # C13: a step with two inputs of one unit (the audit's probe: area from length and width) - unbound, refused; bound by + # name, admitted and computed + ft = dict(base, kind="formula", interface={"inputs": [{"name": "feet", "unit": "ft"}], "outputs": [{"name": "length", "unit": "m"}]}, + body={"expr": "feet * 0.3048", "source": "1 ft = 0.3048 m"}) + ar = dict(base, kind="formula", interface={"inputs": [{"name": "length", "unit": "m"}, {"name": "width", "unit": "m"}], + "outputs": [{"name": "area", "unit": "m2"}]}, body={"expr": "length * width", "source": "area"}) + good["ft"], good["ar"] = seal(ft, sk), seal(ar, sk) + known[good["ft"]["id"]], known[good["ar"]["id"]] = good["ft"], good["ar"] + face_ok = {"inputs": [{"name": "feet", "unit": "ft"}, {"name": "width", "unit": "m"}], "outputs": [{"name": "area", "unit": "m2"}]} + wired = seal(dict(base, kind="composite", interface=face_ok, body={"path": [good["ft"]["id"], good["ar"]["id"]]}), sk) + assert admit(wired, known)[0], admit(wired, known) + got = apply(wired, {"feet": 10, "width": 2}, known) + assert abs(got - 6.096) < 1e-9, got + bad["an input no value is bound to"] = seal(dict(base, kind="composite", interface={"inputs": [{"name": "feet", "unit": "ft"}], + "outputs": [{"name": "area", "unit": "m2"}]}, body={"path": [good["ft"]["id"], good["ar"]["id"]]}), sk) + bad["a binding of the wrong unit"] = seal(dict(base, kind="composite", interface=face_ok, body={"path": [good["ft"]["id"], good["ar"]["id"]], + "bind": {"1": {"width": "in:feet"}}}), sk) res["refused"] = {k: admit(v, known) for k, v in bad.items()} wrong = [k for k, v in res["refused"].items() if v[0]] tr = admit(good["table"], known, trusted={"someone else"}) diff --git a/workbench/swarm/run.py b/workbench/swarm/run.py index bbb59600bc3d7049911c0c8b7f8180d677255b86..a8b11b6ee1bd789efc0435fcf98b61ed98236683 100644 --- a/workbench/swarm/run.py +++ b/workbench/swarm/run.py @@ -1,282 +1,288 @@ -"""run - BUILD A SPECIALIST FROM EXAMPLE QUESTIONS, in the Workbench. No language model. - - 1. The swarm coordinator asks every installed specialist about your example questions and writes a brief: a typed - hole [givens |- ?u : asked], the neighbouring specialists, the named gap, its refusals and sources. It refuses - outright what lies outside the boundary (medical dosing, legal advice, a private person's details). - 2. compose the specialists you already have cover it: nothing is built, and you are told which ones - build/new with a table gap: the builder looks the property up on Wikidata (CC0; downloads are data only, hashed and - logged in local/swarm/sources), writes the specialist into local/specialists/ with an exam split by entity, and - checks it on the dev half - any other gap (a formula, a dated series): named, not built - this version builds tables only - 3. You run its exam: `exam dev`, then `exam heldout` (once). Only an admitted specialist joins your model. -The coordinator and builder are the versions tested in the pre-registered experiments (PREREG v2 and v3). - -COMPOSE A SPECIALIST FROM WORKED EXAMPLES (a formula gap): you give the inputs and output with their units and at least 8 -worked examples. Half go to the code composer (composer_v3 = composer_v2 + library learning, units as types; PREREG v5: 11 of 12 sealed tasks composed, -all 11 right on held-out); the other half become the held-out exam, which it never sees. It writes a Python program from -typed moves, runs it in a separate interpreter against the examples (read-back), and declines with the gap named when no -program within its bounds reproduces them or they are not a function of their inputs. The program is wrapped with the -formula reader organ_formula_v2 (the gate-examined v1 reader, changed so that it declines a question as missing an input -only when the question names one of the inputs).""" -from __future__ import annotations - -import json -import os -import re -import shutil -import sys -import tempfile -from pathlib import Path - -HERE = Path(__file__).resolve().parent -sys.path.insert(0, str(HERE)) -WB = HERE.parent -SPECS = Path(os.environ.get("ORACLE7_WORKBENCH_LOCAL", str(WB / "local"))) / "specialists" # the same folder as the server's -ID = re.compile(r"^[a-z0-9][a-z0-9-]{1,39}$") - - -def _family(): - import coordinator - organs, failed = coordinator.load_family() - srcs = [(o.id, s.get("name", ""), s.get("licence", "")) for o in organs for s in (o.m.get("sources") or [])] - return coordinator, organs, srcs - - -def brief(questions): - coordinator, organs, srcs = _family() - task = {"id": "yours", "title": "your task", "examples": list(questions)} - with open(os.devnull, "w") as log: - return coordinator.brief_for(task, organs, srcs, log) - - -def to_workbench(built_dir, sid, built_from=None): - """a gate-format folder from the builder -> a Workbench specialist (same organ, table and scorer; panel as dev/heldout). - built_from (the questions and the gap) is kept in the manifest: when the specialist passes its held-out exam it is - written to your group's memory under that request (4.2)""" - built_dir = Path(built_dir) - d = SPECS / sid - if d.exists(): - raise ValueError("a specialist named %s already exists" % sid) - d.mkdir(parents=True) - for f in ("organ_table_v2.py", "narrow_v1.py", "scorer_table_v1.py", "table.json"): - shutil.copy(built_dir / f, d / f) - m = json.loads((built_dir / "manifest.json").read_text(encoding="utf-8")) - panel = json.loads((built_dir / "panel_v1.json").read_text(encoding="utf-8")) - out = {"dev": [], "heldout": []} - for p in panel: - item = {"q": p["q"], "a": "" if p["expect"] is None else str(p["expect"]), "valid": p["valid"], "kind": p["kind"], - "expect": p["expect"], "dtype": p.get("dtype"), "unit": p.get("unit", ""), "why": p.get("why", "")} - out[p["split"]].append(item) - (d / "panel.json").write_text(json.dumps(out, indent=1, ensure_ascii=False), encoding="utf-8") - man = {"id": sid, "name": m["name"], "sources": m["sources"], - "organ": {"module": "organ_table_v2", "class": "TableOrgan", "init": {}}, - "accept": m["accept"], "panel": {"path": "panel.json", "scorer_module": "scorer_table_v1", "scorer_fn": "ok"}, - "budgets": {"latency_p50_ms": 200}, "notes": m.get("notes", "") + " Built in the Workbench from your example questions."} - if built_from: - man["built_from"] = built_from - (d / "manifest.json").write_text(json.dumps(man, indent=1, ensure_ascii=False), encoding="utf-8") - return d - - -def remembered(questions, gap="", node=None): - """4.2: has a group in your commons already built and examined a specialist for this request?""" - try: - import memory - r = memory.recall(questions, gap, node=node) - except Exception: # noqa: BLE001 - the memory never blocks a build - return None - if not r or (SPECS / r[0]).exists(): - return None - return {"specialist": r[0], "confidence": r[1], "from": r[2]} - - -def build(questions, sid=None, anyway=False): - """-> {"outcome", "message", "brief", "specialist" (folder or None), "build" (builder log or None), "memory"}""" - questions = [q.strip() for q in questions if q and q.strip()] - if len(questions) < 3: - return {"outcome": "error", "message": "give at least 3 example questions (6 is best)"} - b = brief(questions) - res = {"outcome": b["outcome"], "brief": b, "specialist": None, "build": None, "memory": None} - if b["outcome"] == "refuse": - res["message"] = "Refused: this is %s, which Oracle7 does not build specialists for." % " / ".join(b.get("refusals") or ["outside the boundary"]) - return res - if b["outcome"] == "compose": - res["message"] = "Already covered by your specialists: %s. Nothing to build." % ", ".join(b["neighbors"] or ["the core"]) - return res - mem = remembered(questions, b.get("gap", "")) - res["memory"] = mem - if mem and not anyway: - res["outcome"] = "recalled" - res["message"] = ("Your commons already holds %s for this request (from %s, recall confidence %.2f): %s built it and its " - "held-out exam admitted it. Import it from that group's share and run its exam here, or build anyway " - "(build ... --anyway)." % (mem["specialist"], mem["from"], mem["confidence"], mem["from"])) - return res - if b["type"] != "table": - res["message"] = ("Named, not built: %s. Tables of named things are built from Wikidata; for a formula, give worked " - "examples to compose (python oracle7.py compose --file examples.txt)." % b["gap"]) - return res - import builder_v2 - tmp = tempfile.mkdtemp(prefix="o7build-") - log = builder_v2.build(b, questions, "yours", tmp) - res["build"] = log - if not log.get("built"): - res["message"] = "No usable source found for: %s" % b["gap"] - return res - sid = sid or ("table-" + re.sub(r"[^a-z0-9]+", "-", log["property"].lower()).strip("-"))[:40] - if not ID.match(sid): - sid = "table-" + log["pid"].lower() - d = to_workbench(Path(tmp) / log["built"], sid, built_from={"questions": questions, "gap": b.get("gap", "")}) - shutil.rmtree(tmp, ignore_errors=True) - res["specialist"] = str(d) - res["message"] = ("Built %s: %s for %d things from Wikidata (%s). Dev check %d/%d. Next: exam %s dev, then exam %s heldout." - % (sid, log["property"], log["rows"], log["pid"], log["dev"]["correct"], log["dev"]["n"], sid, sid)) - return res - - -# ---- compose a formula specialist from worked examples ------------------------------------------------------------------- -ROW = re.compile(r"^(.*?)\s*(?:->|=>|→)\s*(.+?)\s*$") - - -def _value(s): - s = s.strip().strip('"').strip("'") - try: - return float(s.replace(",", "")) if re.fullmatch(r"-?[\d,]*\.?\d+(?:[eE][+-]?\d+)?", s) else s - except ValueError: - return s - - -def parse_examples(text): - """the examples file: title: / inputs: a (unit), b (unit) / output: y (unit) / source: (optional) / then one row per - line, inputs separated by commas or semicolons, then -> and the answer ("1.050, 1.010 -> 5.25"). Lines starting # are - notes. Numbers with thousands commas need the semicolon separator.""" - spec = {"title": "", "inputs": [], "output": "", "source": "your worked examples", "rows": []} - for ln in text.splitlines(): - ln = ln.strip() - if not ln or ln.startswith("#"): - continue - m = re.match(r"^(title|inputs|output|source)\s*:\s*(.*)$", ln, re.I) - if m: - k, v = m.group(1).lower(), m.group(2).strip() - if k == "inputs": - spec["inputs"] = [x.strip() for x in re.split(r"[;,](?![^(]*\))", v) if x.strip()] - else: - spec[k] = v - continue - m = ROW.match(ln) - if not m: - raise ValueError("not a row (inputs -> answer): %s" % ln) - ins = [x for x in re.split(r";" if ";" in m.group(1) else r",", m.group(1))] - spec["rows"].append({"in": [_value(x) for x in ins], "out": _value(m.group(2))}) - if not spec["inputs"] or not spec["output"]: - raise ValueError("the file needs an inputs: line and an output: line") - if any(len(r["in"]) != len(spec["inputs"]) for r in spec["rows"]): - raise ValueError("every row needs %d inputs" % len(spec["inputs"])) - return spec - - -RESERVED = {"math", "re", "seq", "pairs", "n", "b", "out", "digits", "compute", "code", "x", "v", "s"} - - -def arg_names(labels): - """readable argument names from the input labels ("original gravity (SG)" -> original_gravity), unique, never a keyword - or a name the emitted program already uses""" - import keyword - names = [] - for i, lab in enumerate(labels): - n = re.sub(r"[^a-z0-9]+", "_", re.sub(r"\s*\([^)]*\)", "", lab).lower()).strip("_")[:32] or "x%d" % (i + 1) - if n[0].isdigit() or keyword.iskeyword(n) or n in RESERVED or n.startswith("_") or n in names: - n = "%s_%d" % (n if n[0].isalpha() else "x", i + 1) - names.append(n) - return names - - -def rename_args(src, names): - """x1, x2, ... -> the readable names, as whole words only (the program is read back again afterwards)""" - for i in range(len(names), 0, -1): - src = re.sub(r"(? {"outcome": "composed"|"declined"|"recalled"|"error", "message", "specialist", "program", "memory"}""" - try: - spec = parse_examples(text) - except ValueError as e: - return {"outcome": "error", "message": str(e)} - if len(spec["rows"]) < 8: - return {"outcome": "error", "message": "give at least 8 worked examples: half are used to write the program, half to examine it"} - dev, held = _split(spec["rows"]) - title = spec["title"] or "%s from %s" % (spec["output"], ", ".join(spec["inputs"])) - request = ["What is the %s for %s?" % (re.sub(r"\s*\([^)]*\)", "", spec["output"]).strip(), - " and ".join(re.sub(r"\s*\([^)]*\)", "", x).strip() for x in spec["inputs"]))] - mem = remembered(request, "", node="hod") - if mem and not anyway: - return {"outcome": "recalled", "program": None, "specialist": None, "memory": mem, - "message": ("Your commons already holds %s for this calculation (from %s, recall confidence %.2f): it was composed " - "and admitted there. Import it from that group's share and run its exam here, or compose anyway " - "(compose ... --anyway)." % (mem["specialist"], mem["from"], mem["confidence"]))} - task = {"id": "yours", "title": title, "inputs": spec["inputs"], "output": spec["output"], "dev": dev, "held": held, - "source": spec["source"], "possible": True} - import composer_v3 # 4.5: library learning - admitted programs are moves - import library - composer_v3.LIBRARY.clear() - composer_v3.LIBRARY.extend(library.load(composer_v3.parse_unit)) - r = composer_v3.compose(task) - if r["status"] != "composed": - return {"outcome": "declined", "message": "Not composed: %s." % r.get("gap", "no program found"), "program": None, "specialist": None} - names = arg_names(spec["inputs"]) - py, js = rename_args(r["python"], names), rename_args(r["javascript"], names) - ok, note = composer_v3.read_back(py, [x["in"] for x in dev], [x["out"] for x in dev]) - if ok: # keep the readable names only if the program still reads back - r["python"], r["javascript"], r["read_back"] = py, js, note - base = re.sub(r"[^a-z0-9]+", "-", re.sub(r"\s*\([^)]*\)", "", spec["output"]).lower()).strip("-") - sid = sid or ("formula-" + base)[:40] - if not ID.match(sid): - return {"outcome": "error", "message": "an id is lower-case letters, digits and hyphens: %s" % sid} - d = SPECS / sid - if d.exists(): - return {"outcome": "error", "message": "a specialist named %s already exists" % sid} - import exam_formula_v2 - from organ_formula_v2 import sign_of - from domain_v3 import domain_v3 - d.mkdir(parents=True) - ret = [ln.strip() for ln in r["python"].splitlines() if ln.strip().startswith("return")] - expr = ret[-1][len("return "):] if r.get("kind") == "expr" and ret else r["derivation"] - kinds = ["code" if isinstance(v, str) else "number" for v in dev[0]["in"]] - sj = {"title": title, "inputs": spec["inputs"], "output": spec["output"], "input_kinds": kinds, - "expression": expr, "expression_x": r.get("expr_py"), "said": r["derivation"], "composer": "composer_v3 (frozen cf1a8a9a)", - "library": r.get("library", []), - "domain": {"inputs": [sign_of([x["in"][i] for x in dev]) for i in range(len(kinds))], "output": sign_of([x["out"] for x in dev])}} - sj["domain"]["order"], sj["domain"]["facts"] = domain_v3({"dev": dev, "title": title}, sj) - (d / "spec.json").write_text(json.dumps(sj, indent=1, ensure_ascii=False), encoding="utf-8") - (d / "program.py").write_text(r["python"], encoding="utf-8") - (d / "program.js").write_text(r["javascript"], encoding="utf-8") - for f in ("organ_formula_v2.py", "organ_formula_v3.py", "scorer_formula_v1.py", "narrow_v1.py"): - shutil.copy(HERE / f, d / f) - panel = {"dev": [], "heldout": []} - for p in exam_formula_v2.write(task): - panel[p["split"]].append({"q": p["q"], "a": "" if p["expect"] is None else str(p["expect"]), "valid": p["valid"], - "kind": p["kind"], "expect": p["expect"], "dtype": p.get("dtype"), "unit": p.get("unit", ""), - "why": p.get("why", "")}) - (d / "panel.json").write_text(json.dumps(panel, indent=1, ensure_ascii=False), encoding="utf-8") - out_label = re.sub(r"\s*\([^)]*\)", "", spec["output"]).strip() - man = {"id": sid, "name": "Composed: %s" % title, - "sources": [{"name": "a program composed by composer_v3 from %d of your worked examples; %s" % (len(dev), r["derivation"]), - "licence": "yours"}], - "organ": {"module": "organ_formula_v3", "class": "FormulaOrgan", "init": {}}, - "accept": {"kinds": ["compute"], "declines_in_domain": ["missing_input", "out_of_domain"], - "context_regex": r"\b%s\b" % re.escape(out_label.lower())}, - "panel": {"path": "panel.json", "scorer_module": "scorer_formula_v1", "scorer_fn": "ok"}, - "budgets": {"latency_p50_ms": 200}, - "notes": "Composed in the Workbench from your worked examples: %d used to write the program, %d held out for its exam. %s" - % (len(dev), len(held), r["read_back"]), - "built_from": {"questions": request, "gap": "", "node": "hod"}} - (d / "manifest.json").write_text(json.dumps(man, indent=1, ensure_ascii=False), encoding="utf-8") - return {"outcome": "composed", "specialist": str(d), "program": r["python"], - "message": "Composed %s: %s (%s; %s). Next: exam %s dev, then exam %s heldout." - % (sid, expr, r["derivation"], r["read_back"], sid, sid)} +"""run - BUILD A SPECIALIST FROM EXAMPLE QUESTIONS, in the Workbench. No language model. + + 1. The swarm coordinator asks every installed specialist about your example questions and writes a brief: a typed + hole [givens |- ?u : asked], the neighbouring specialists, the named gap, its refusals and sources. It refuses + outright what lies outside the boundary (medical dosing, legal advice, a private person's details). + 2. compose the specialists you already have cover it: nothing is built, and you are told which ones + build/new with a table gap: the builder looks the property up on Wikidata (CC0; downloads are data only, hashed and + logged in local/swarm/sources), writes the specialist into local/specialists/ with an exam split by entity, and + checks it on the dev half + any other gap (a formula, a dated series): named, not built - this version builds tables only + 3. You run its exam: `exam dev`, then `exam heldout` (once). Only an admitted specialist joins your model. +The coordinator and builder are the versions tested in the pre-registered experiments (PREREG v2 and v3). + +COMPOSE A SPECIALIST FROM WORKED EXAMPLES (a formula gap): you give the inputs and output with their units and at least 8 +worked examples. Half go to the code composer (composer_v3 = composer_v2 + library learning, units as types; PREREG v5: 11 of 12 sealed tasks composed, +all 11 right on held-out); the other half become the held-out exam, which it never sees. It writes a Python program from +typed moves, runs it in a separate interpreter against the examples (read-back), and declines with the gap named when no +program within its bounds reproduces them or they are not a function of their inputs. The program is wrapped with the +formula reader organ_formula_v2 (the gate-examined v1 reader, changed so that it declines a question as missing an input +only when the question names one of the inputs).""" +from __future__ import annotations + +import json +import os +import re +import shutil +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +WB = HERE.parent +SPECS = Path(os.environ.get("ORACLE7_WORKBENCH_LOCAL", str(WB / "local"))) / "specialists" # the same folder as the server's +ID = re.compile(r"^[a-z0-9][a-z0-9-]{1,39}$") + + +def _family(): + import coordinator + organs, failed = coordinator.load_family() + srcs = [(o.id, s.get("name", ""), s.get("licence", "")) for o in organs for s in (o.m.get("sources") or [])] + return coordinator, organs, srcs + + +def brief(questions): + coordinator, organs, srcs = _family() + task = {"id": "yours", "title": "your task", "examples": list(questions)} + with open(os.devnull, "w") as log: + return coordinator.brief_for(task, organs, srcs, log) + + +def to_workbench(built_dir, sid, built_from=None): + """a gate-format folder from the builder -> a Workbench specialist (same organ, table and scorer; panel as dev/heldout). + built_from (the questions and the gap) is kept in the manifest: when the specialist passes its held-out exam it is + written to your group's memory under that request (4.2)""" + built_dir = Path(built_dir) + d = SPECS / sid + if d.exists(): + raise ValueError("a specialist named %s already exists" % sid) + d.mkdir(parents=True) + for f in ("organ_table_v2.py", "narrow_v1.py", "scorer_table_v1.py", "table.json"): + shutil.copy(built_dir / f, d / f) + m = json.loads((built_dir / "manifest.json").read_text(encoding="utf-8")) + panel = json.loads((built_dir / "panel_v1.json").read_text(encoding="utf-8")) + out = {"dev": [], "heldout": []} + for p in panel: + item = {"q": p["q"], "a": "" if p["expect"] is None else str(p["expect"]), "valid": p["valid"], "kind": p["kind"], + "expect": p["expect"], "dtype": p.get("dtype"), "unit": p.get("unit", ""), "why": p.get("why", "")} + out[p["split"]].append(item) + (d / "panel.json").write_text(json.dumps(out, indent=1, ensure_ascii=False), encoding="utf-8") + man = {"id": sid, "name": m["name"], "sources": m["sources"], + "organ": {"module": "organ_table_v2", "class": "TableOrgan", "init": {}}, + "accept": m["accept"], "panel": {"path": "panel.json", "scorer_module": "scorer_table_v1", "scorer_fn": "ok"}, + "budgets": {"latency_p50_ms": 200}, "notes": m.get("notes", "") + " Built in the Workbench from your example questions."} + if built_from: + man["built_from"] = built_from + (d / "manifest.json").write_text(json.dumps(man, indent=1, ensure_ascii=False), encoding="utf-8") + return d + + +def remembered(questions, gap="", node=None): + """4.2: has a group in your commons already built and examined a specialist for this request?""" + try: + import memory + r = memory.recall(questions, gap, node=node) + except Exception: # noqa: BLE001 - the memory never blocks a build + return None + if not r or (SPECS / r[0]).exists(): + return None + return {"specialist": r[0], "confidence": r[1], "from": r[2]} + + +def build(questions, sid=None, anyway=False, evidence=None): + """-> {"outcome", "message", "brief", "specialist" (folder or None), "build" (builder log or None), "memory"} + evidence (11.5 Amendment 14): the store relation the answer path found every example's entity holding ({"pid", "label"}); + its name joins the brief as what is asked about, so the property search sees the quantity the questions ask for""" + questions = [q.strip() for q in questions if q and q.strip()] + if len(questions) < 3: + return {"outcome": "error", "message": "give at least 3 example questions (6 is best)"} + b = brief(questions) + if evidence and evidence.get("label"): + if "asked about:" not in b.get("gap", ""): + b["gap"] = b.get("gap", "") + "; asked about: " + evidence["label"] + b["evidence"] = evidence # always: the store's evidence leads the property choice + res = {"outcome": b["outcome"], "brief": b, "specialist": None, "build": None, "memory": None} + if b["outcome"] == "refuse": + res["message"] = "Refused: this is %s, which Oracle7 does not build specialists for." % " / ".join(b.get("refusals") or ["outside the boundary"]) + return res + if b["outcome"] == "compose": + res["message"] = "Already covered by your specialists: %s. Nothing to build." % ", ".join(b["neighbors"] or ["the core"]) + return res + mem = remembered(questions, b.get("gap", "")) + res["memory"] = mem + if mem and not anyway: + res["outcome"] = "recalled" + res["message"] = ("Your commons already holds %s for this request (from %s, recall confidence %.2f): %s built it and its " + "held-out exam admitted it. Import it from that group's share and run its exam here, or build anyway " + "(build ... --anyway)." % (mem["specialist"], mem["from"], mem["confidence"], mem["from"])) + return res + if b["type"] != "table": + res["message"] = ("Named, not built: %s. Tables of named things are built from Wikidata; for a formula, give worked " + "examples to compose (python oracle7.py compose --file examples.txt)." % b["gap"]) + return res + import builder_v2 + tmp = tempfile.mkdtemp(prefix="o7build-") + log = builder_v2.build(b, questions, "yours", tmp) + res["build"] = log + if not log.get("built"): + res["message"] = "No usable source found for: %s" % b["gap"] + return res + sid = sid or ("table-" + re.sub(r"[^a-z0-9]+", "-", log["property"].lower()).strip("-"))[:40] + if not ID.match(sid): + sid = "table-" + log["pid"].lower() + d = to_workbench(Path(tmp) / log["built"], sid, built_from={"questions": questions, "gap": b.get("gap", "")}) + shutil.rmtree(tmp, ignore_errors=True) + res["specialist"] = str(d) + res["message"] = ("Built %s: %s for %d things from Wikidata (%s). Dev check %d/%d. Next: exam %s dev, then exam %s heldout." + % (sid, log["property"], log["rows"], log["pid"], log["dev"]["correct"], log["dev"]["n"], sid, sid)) + return res + + +# ---- compose a formula specialist from worked examples ------------------------------------------------------------------- +ROW = re.compile(r"^(.*?)\s*(?:->|=>|→)\s*(.+?)\s*$") + + +def _value(s): + s = s.strip().strip('"').strip("'") + try: + return float(s.replace(",", "")) if re.fullmatch(r"-?[\d,]*\.?\d+(?:[eE][+-]?\d+)?", s) else s + except ValueError: + return s + + +def parse_examples(text): + """the examples file: title: / inputs: a (unit), b (unit) / output: y (unit) / source: (optional) / then one row per + line, inputs separated by commas or semicolons, then -> and the answer ("1.050, 1.010 -> 5.25"). Lines starting # are + notes. Numbers with thousands commas need the semicolon separator.""" + spec = {"title": "", "inputs": [], "output": "", "source": "your worked examples", "rows": []} + for ln in text.splitlines(): + ln = ln.strip() + if not ln or ln.startswith("#"): + continue + m = re.match(r"^(title|inputs|output|source)\s*:\s*(.*)$", ln, re.I) + if m: + k, v = m.group(1).lower(), m.group(2).strip() + if k == "inputs": + spec["inputs"] = [x.strip() for x in re.split(r"[;,](?![^(]*\))", v) if x.strip()] + else: + spec[k] = v + continue + m = ROW.match(ln) + if not m: + raise ValueError("not a row (inputs -> answer): %s" % ln) + ins = [x for x in re.split(r";" if ";" in m.group(1) else r",", m.group(1))] + spec["rows"].append({"in": [_value(x) for x in ins], "out": _value(m.group(2))}) + if not spec["inputs"] or not spec["output"]: + raise ValueError("the file needs an inputs: line and an output: line") + if any(len(r["in"]) != len(spec["inputs"]) for r in spec["rows"]): + raise ValueError("every row needs %d inputs" % len(spec["inputs"])) + return spec + + +RESERVED = {"math", "re", "seq", "pairs", "n", "b", "out", "digits", "compute", "code", "x", "v", "s"} + + +def arg_names(labels): + """readable argument names from the input labels ("original gravity (SG)" -> original_gravity), unique, never a keyword + or a name the emitted program already uses""" + import keyword + names = [] + for i, lab in enumerate(labels): + n = re.sub(r"[^a-z0-9]+", "_", re.sub(r"\s*\([^)]*\)", "", lab).lower()).strip("_")[:32] or "x%d" % (i + 1) + if n[0].isdigit() or keyword.iskeyword(n) or n in RESERVED or n.startswith("_") or n in names: + n = "%s_%d" % (n if n[0].isalpha() else "x", i + 1) + names.append(n) + return names + + +def rename_args(src, names): + """x1, x2, ... -> the readable names, as whole words only (the program is read back again afterwards)""" + for i in range(len(names), 0, -1): + src = re.sub(r"(? {"outcome": "composed"|"declined"|"recalled"|"error", "message", "specialist", "program", "memory"}""" + try: + spec = parse_examples(text) + except ValueError as e: + return {"outcome": "error", "message": str(e)} + if len(spec["rows"]) < 8: + return {"outcome": "error", "message": "give at least 8 worked examples: half are used to write the program, half to examine it"} + dev, held = _split(spec["rows"]) + title = spec["title"] or "%s from %s" % (spec["output"], ", ".join(spec["inputs"])) + request = ["What is the %s for %s?" % (re.sub(r"\s*\([^)]*\)", "", spec["output"]).strip(), + " and ".join(re.sub(r"\s*\([^)]*\)", "", x).strip() for x in spec["inputs"]))] + mem = remembered(request, "", node="hod") + if mem and not anyway: + return {"outcome": "recalled", "program": None, "specialist": None, "memory": mem, + "message": ("Your commons already holds %s for this calculation (from %s, recall confidence %.2f): it was composed " + "and admitted there. Import it from that group's share and run its exam here, or compose anyway " + "(compose ... --anyway)." % (mem["specialist"], mem["from"], mem["confidence"]))} + task = {"id": "yours", "title": title, "inputs": spec["inputs"], "output": spec["output"], "dev": dev, "held": held, + "source": spec["source"], "possible": True} + import composer_v3 # 4.5: library learning - admitted programs are moves + import library + composer_v3.LIBRARY.clear() + composer_v3.LIBRARY.extend(library.load(composer_v3.parse_unit)) + r = composer_v3.compose(task) + if r["status"] != "composed": + return {"outcome": "declined", "message": "Not composed: %s." % r.get("gap", "no program found"), "program": None, "specialist": None} + names = arg_names(spec["inputs"]) + py, js = rename_args(r["python"], names), rename_args(r["javascript"], names) + ok, note = composer_v3.read_back(py, [x["in"] for x in dev], [x["out"] for x in dev]) + if ok: # keep the readable names only if the program still reads back + r["python"], r["javascript"], r["read_back"] = py, js, note + base = re.sub(r"[^a-z0-9]+", "-", re.sub(r"\s*\([^)]*\)", "", spec["output"]).lower()).strip("-") + sid = sid or ("formula-" + base)[:40] + if not ID.match(sid): + return {"outcome": "error", "message": "an id is lower-case letters, digits and hyphens: %s" % sid} + d = SPECS / sid + if d.exists(): + return {"outcome": "error", "message": "a specialist named %s already exists" % sid} + import exam_formula_v2 + from organ_formula_v2 import sign_of + from domain_v3 import domain_v3 + d.mkdir(parents=True) + ret = [ln.strip() for ln in r["python"].splitlines() if ln.strip().startswith("return")] + expr = ret[-1][len("return "):] if r.get("kind") == "expr" and ret else r["derivation"] + kinds = ["code" if isinstance(v, str) else "number" for v in dev[0]["in"]] + sj = {"title": title, "inputs": spec["inputs"], "output": spec["output"], "input_kinds": kinds, + "expression": expr, "expression_x": r.get("expr_py"), "said": r["derivation"], "composer": "composer_v3 (frozen cf1a8a9a)", + "library": r.get("library", []), + "domain": {"inputs": [sign_of([x["in"][i] for x in dev]) for i in range(len(kinds))], "output": sign_of([x["out"] for x in dev])}} + sj["domain"]["order"], sj["domain"]["facts"] = domain_v3({"dev": dev, "title": title}, sj) + (d / "spec.json").write_text(json.dumps(sj, indent=1, ensure_ascii=False), encoding="utf-8") + (d / "program.py").write_text(r["python"], encoding="utf-8") + (d / "program.js").write_text(r["javascript"], encoding="utf-8") + for f in ("organ_formula_v2.py", "organ_formula_v3.py", "scorer_formula_v1.py", "narrow_v1.py"): + shutil.copy(HERE / f, d / f) + panel = {"dev": [], "heldout": []} + for p in exam_formula_v2.write(task): + panel[p["split"]].append({"q": p["q"], "a": "" if p["expect"] is None else str(p["expect"]), "valid": p["valid"], + "kind": p["kind"], "expect": p["expect"], "dtype": p.get("dtype"), "unit": p.get("unit", ""), + "why": p.get("why", "")}) + (d / "panel.json").write_text(json.dumps(panel, indent=1, ensure_ascii=False), encoding="utf-8") + out_label = re.sub(r"\s*\([^)]*\)", "", spec["output"]).strip() + man = {"id": sid, "name": "Composed: %s" % title, + "sources": [{"name": "a program composed by composer_v3 from %d of your worked examples; %s" % (len(dev), r["derivation"]), + "licence": "yours"}], + "organ": {"module": "organ_formula_v3", "class": "FormulaOrgan", "init": {}}, + "accept": {"kinds": ["compute"], "declines_in_domain": ["missing_input", "out_of_domain"], + "context_regex": r"\b%s\b" % re.escape(out_label.lower())}, + "panel": {"path": "panel.json", "scorer_module": "scorer_formula_v1", "scorer_fn": "ok"}, + "budgets": {"latency_p50_ms": 200}, + "notes": "Composed in the Workbench from your worked examples: %d used to write the program, %d held out for its exam. %s" + % (len(dev), len(held), r["read_back"]), + "built_from": {"questions": request, "gap": "", "node": "hod"}} + (d / "manifest.json").write_text(json.dumps(man, indent=1, ensure_ascii=False), encoding="utf-8") + return {"outcome": "composed", "specialist": str(d), "program": r["python"], + "message": "Composed %s: %s (%s; %s). Next: exam %s dev, then exam %s heldout." + % (sid, expr, r["derivation"], r["read_back"], sid, sid)} diff --git a/workbench/swarm/sleep105.py b/workbench/swarm/sleep105.py index 0cdf6c685157e66b1f2458a4ef8ae4982288ad94..4b693418cad7e3bbe7d5737d889ef217c87545cd 100644 --- a/workbench/swarm/sleep105.py +++ b/workbench/swarm/sleep105.py @@ -8,6 +8,8 @@ same door a person uses, and are written to a chained ledger. Then, each night: 3 DREAMING each hole is searched for across formulas (grow60: the library's chains, built by the swarm), stores (declines.resolve, and held-back readings a known answer confirms, which feed the learner) and specialists (swarm build: a table from Wikidata, through its own held-out exam). 4 FORGETTING unused or dominated parts are retired with a receipt. A retired part stays in the content-addressed store, so replay can still reach it. + The code store's night too (code_store.nightly): each kept function replayed on its evidence, retired with a receipt + when it no longer holds; the day's declined code goals dreamt over with the store as it is (recorded, never kept). 5 MORNING reach gained, holes filled, answers changed, parts retired, with no new wrong answer as the bar. Reports are chained. Days are Oracle7's own failures from v37 to v38 (failure_days.py) unless O7_DAYS names sealed days. Simulated nights: each day is a batch. usage: sleep105.py [nights] [turns per day]""" @@ -86,9 +88,9 @@ def phase(text, cur=None): def right(answer, want): if answer is None or want in (None, "", []): return False - # a labelled answer is a store record too: "1953-01-01" in the store is the year 1953, on both sides (11-05) - from handoff101 import date_of - return any(compare(str(answer), str(w))[0] == "CONFIRMED" or (date_of(str(w), record=True) is not None and + # a labelled answer is a store record too: "1953-01-01" in the store is the year 1953, on both sides (11-05) + from handoff101 import date_of + return any(compare(str(answer), str(w))[0] == "CONFIRMED" or (date_of(str(w), record=True) is not None and date_of(str(w), record=True) == date_of(str(answer), record=True)) for w in (want if isinstance(want, list) else [want])) @@ -436,6 +438,16 @@ for night in range(1, NIGHTS + 1): else: keep.append(p) parts = keep + # ---- 4b THE CODE STORE'S NIGHT (12.0 C9): kept functions replayed on their evidence, retired with a receipt when they no + # longer hold; the day's declined code goals dreamt over with the store as it now is (a dream is recorded, never kept) + try: + import code_store as _CS + phase("the code store: replay and dreams", rep) + cn = _CS.nightly(night=night, dream=not os.environ.get("O7_NO_CODE_DREAMS")) + rep["code_kept"], rep["code_retired"], rep["code_dreamt"] = cn["kept"], len(cn["retired"]), len(cn["dreamt"]) + retired += [{"id": "code:" + r["id"], "shape": r["name"], "night": night, "receipt": r["receipt"]} for r in cn["retired"]] + except Exception as e: # noqa: BLE001 + rep["code_store"] = "not run: %s" % repr(e)[:200] # ---- 5 MORNING rep["seconds"] = round(time.time() - t0) STATE["parts"] = [{k: p.get(k) for k in ("id", "kind", "shape", "steps", "source", "night", "reach")} for p in parts] diff --git a/workbench/tools.py b/workbench/tools.py new file mode 100644 index 0000000000000000000000000000000000000000..f1c14436619eefe13a5b1b0ed30f14b055e070db --- /dev/null +++ b/workbench/tools.py @@ -0,0 +1,683 @@ +"""tools - what the chat can do with your workspace (12.0): find, read, write, run, fetch. Each is a command of the chat's own +catalogue, so the door picks it when your turn's verb names it, exactly as it picks build or compose. + + find search your workspace's functions by meaning (the workspace index) + read show a file in the sandbox or workspace, or a function's source by name + write write the code that follows (the rest of the message) to a file in the sandbox + run [args] run a sandbox file (python), 60 s limit; the output comes back + fetch a page from the verified sources, saved in the sandbox, its text shown + make [name:] build the described algorithm: each step a code move, run in the sandbox, checked + against "expect " if given; a step nothing can build comes back as a named gap + +The sandbox (ORACLE7_SANDBOX, default workbench/local/sandbox) is the only place it writes or runs. Your workspace +(ORACLE7_WORKSPACE) is read only. Fetching is limited to the verified list; adding a source is yours to do (VERIFIED).""" +import json +import os +import re +import subprocess +import sys +import time +import urllib.parse +import urllib.request +from pathlib import Path + +WB = Path(__file__).resolve().parent +SANDBOX = Path(os.environ.get("ORACLE7_SANDBOX", WB / "local" / "sandbox")) +INDEX = Path(os.environ.get("ORACLE7_WS_INDEX", WB / "local" / "workspace" / "index")) +_WHERE = INDEX / "workspace_path.txt" +WORKSPACE = Path(os.environ.get("ORACLE7_WORKSPACE") or (_WHERE.read_text().strip() if _WHERE.is_file() else + str(WB / "local" / "workspace" / "src"))) +WORDVEC = Path(os.environ.get("ORACLE7_WORDVEC", WB / "converse" / "data" / "ladder" / "wordvec.npz")) +VERIFIED = ["arxiv.org", "export.arxiv.org", "www.ncbi.nlm.nih.gov", "pmc.ncbi.nlm.nih.gov", "api.semanticscholar.org", + "www.semanticscholar.org", "www.wikidata.org", "query.wikidata.org", "en.wikipedia.org", "simple.wikipedia.org", + "www.gutenberg.org", "catalog.data.gov", "api.data.gov", "www.data.gov"] +COMMANDS = ("find", "read", "write", "run", "fetch", "make", "index", "change", "want") +NL = chr(10) +_IX = {} + + +def _index(): + if not _IX: + import numpy as np + wv = np.load(WORDVEC, allow_pickle=True) + _IX["wv"], _IX["wvi"] = wv["vec"], {w: i for i, w in enumerate(wv["words"])} + _IX["recs"] = json.load(open(INDEX / "fn_index.json")) + _IX["vec"] = np.load(INDEX / "fn_vec.npy") + return _IX + + +def _inside(p, root): + try: + p.resolve().relative_to(root.resolve()) + return True + except ValueError: + return False + + +NO_INDEX = "There is no index of your code yet: type index and I read it in (secret-shaped files left out)." + + +def find(what, k=8): + import numpy as np + if not (INDEX / "fn_index.json").is_file(): + return NO_INDEX + ix = _index() + v = np.zeros(ix["wv"].shape[1], np.float32) + for w in re.findall(r"[a-z]{3,}", what.lower()): + if w in ix["wvi"]: + v += ix["wv"][ix["wvi"][w]] + if not v.any(): + return "I found nothing to search by in that; say what the code does." + s = ix["vec"] @ (v / np.linalg.norm(v)) + order = {} + VERBS = {"compute", "calculate", "find", "get", "make", "take", "run", "do", "use", "apply", "show", "list", "give", + "return", "the", "and", "with", "from", "into", "that", "which", "each", "every", "all"} + for w in re.findall(r"[a-z_][a-z0-9_]{2,}", what.lower()): + if w not in VERBS: # the verb of the request does not name a function + order.setdefault(w, len(order)) + named = [i for i, r in enumerate(ix["recs"]) if r["name"].lower() in order] # a function your words name comes first, + named.sort(key=lambda i: (order[ix["recs"][i]["name"].lower()], not ix["recs"][i]["doc"], -float(s[i]))) # the thing asked first + out, seen = [], set() + for i in named[:k] + [int(j) for j in np.argsort(-s)[:k * 4]]: + r = ix["recs"][i] + key = (r["name"], r["doc"][:80]) + if key in seen: + continue + seen.add(key) + doc = r["doc"].split("\n")[0][:90] + out.append("%s(%s) %s:%d%s" % (r["name"], ", ".join(r["args"][:6]), r["path"], r["line"], ("\n " + doc) if doc else "")) + if len(out) >= k: + break + return "\n".join(out) + + +def read(target, max_lines=120): + t = target.strip().strip("`'\"") + for root in (SANDBOX, WORKSPACE): + p = (root / t) + if p.is_file() and _inside(p, root): + lines = p.read_text(errors="ignore").splitlines() + more = "" if len(lines) <= max_lines else "\n... (%d more lines)" % (len(lines) - max_lines) + return "%s (%d lines)\n%s%s" % (t, len(lines), "\n".join(lines[:max_lines]), more) + hits = [r for r in _index()["recs"] if r["name"] == t] if (INDEX / "fn_index.json").is_file() else [] + if hits: + r = hits[0] + p = WORKSPACE / r["path"] + src = p.read_text(errors="ignore").splitlines()[r["line"] - 1: r["end"]] + also = "" if len(hits) == 1 else "\n(%d other definitions of %s: %s)" % ( + len(hits) - 1, t, ", ".join(h["path"] for h in hits[1:4])) + return "%s:%d\n%s%s" % (r["path"], r["line"], "\n".join(src[:max_lines]), also) + return "No file or function named %s in the sandbox or your workspace." % t + + +def write(name, code): + p = SANDBOX / name.strip() + if not _inside(p, SANDBOX): + return "I write only inside the sandbox (%s); %s is outside it." % (SANDBOX, name) + code = re.sub(r"^\s*```[a-z]*\n|\n```\s*$", "", code) + if not code.strip(): + return "Nothing to write: put the code after the file name." + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(code if code.endswith("\n") else code + "\n") + return "Wrote %s (%d lines) in the sandbox." % (name.strip(), code.count("\n") + 1) + + +def run_result(args): + """The run's receipt. Failure stays a hole through the chat and browser.""" + def result(status, response, **receipt): + return dict(status=status, response=response, path="tool:run", execution=receipt) + parts = args.split() + if not parts: + return result("hole", "Run what? Name a file in the sandbox.", started=False) + p = SANDBOX / parts[0] + if not (p.is_file() and _inside(p, SANDBOX)): + return result("hole", "There is no %s in the sandbox." % parts[0], started=False) + t0 = time.time() + try: + r = subprocess.run([sys.executable, p.name] + parts[1:], cwd=str(p.parent), capture_output=True, text=True, timeout=60, + env=__import__("runjail").env(root=p.parent, PYTHONPATH=str(WORKSPACE))) + except subprocess.TimeoutExpired: + return result("hole", "%s ran past the 60 s limit and was stopped." % parts[0], started=True, timed_out=True) + except OSError as e: + return result("hole", "Could not run %s: %s" % (parts[0], e), started=False) + out = (r.stdout or "")[-4000:] + err = (r.stderr or "")[-2500:] + head = "%s finished in %.1f s, exit %d." % (parts[0], time.time() - t0, r.returncode) + response = "\n".join(x for x in (head, out.rstrip(), ("errors:\n" + err.rstrip()) if err.strip() else "") if x) + return result("answered" if r.returncode == 0 else "hole", response, started=True, returncode=r.returncode) + + +def run(args): + """Keep the existing text interface for callers outside the chat.""" + return run_result(args)["response"] + + +def fetch(url): + u = url.strip().strip("<>") + host = urllib.parse.urlparse(u).netloc.lower() + if urllib.parse.urlparse(u).scheme != "https" or host not in VERIFIED: + return "%s is not on the verified list (%s). Adding a source is yours to do." % (host or u, ", ".join(VERIFIED[:6]) + ", ...") + req = urllib.request.Request(u, headers={"User-Agent": "Oracle7-fetch/12.0"}) + with urllib.request.urlopen(req, timeout=30) as r: + body = r.read(5_000_000) + ctype = r.headers.get("Content-Type", "") + d = SANDBOX / "fetched" + d.mkdir(parents=True, exist_ok=True) + name = re.sub(r"[^A-Za-z0-9._-]+", "_", host + urllib.parse.urlparse(u).path)[:120] or "page" + (d / name).write_bytes(body) + text = body.decode("utf-8", "ignore") + if "html" in ctype or text.lstrip().startswith("<"): + mm = re.search(r'(?s)id="mw-content-text".*', text) + text = mm.group(0) if mm else text + text = re.sub(r"(?is)<(script|style).*?", " ", text) + text = re.sub(r"(?s)<[^>]+>", " ", text) + text = re.sub(r"\s+", " ", text).strip() + return "Fetched %s (%d bytes) -> sandbox/fetched/%s\n%s" % (u, len(body), name, text[:1500]) + + +SECRET_NAME = re.compile(r"credential|secret|wallet|password|\.env|token|key_guard|(^|/)keys?\.py$|auth", re.I) +SECRET_TEXT = re.compile(r"hf_[A-Za-z0-9]{20,}|sk-[A-Za-z0-9_]{20,}|sk-ant-|BEGIN [A-Z ]*PRIVATE KEY|AKIA[0-9A-Z]{16}|" + r"ghp_[A-Za-z0-9]{30,}|xox[bp]-|(api_?key|apikey|secret|password|passwd|token|private_?key|mnemonic|" + r"seed_?phrase|auth)[a-z_]*['\"]?\s*[:=]\s*['\"][A-Za-z0-9_/+=.-]{16,}['\"]|" + r"\[[0-9]{1,3}(?:, ?[0-9]{1,3}){60,}\]|[1-9A-HJ-NP-Za-km-z]{86,88}|bearer [A-Za-z0-9._-]{20,}", re.I) + + +def index(folder): + """build the workspace index from your own folder: every .py file's functions and classes by Python's parser, each with a + meaning vector; files named for credentials, wallets, tokens, keys or auth, and files whose text holds anything shaped like + a secret, are never read into it (the list of skipped files is shown)""" + import ast as _ast + import numpy as np + root = Path(folder.strip().strip("'\"")).expanduser().resolve() + if not root.is_dir(): + return "There is no folder %s." % root + wv = np.load(WORDVEC, allow_pickle=True) + WV, WVI = wv["vec"], {w: i for i, w in enumerate(wv["words"])} + split = re.compile(r"[A-Z]?[a-z]+|[A-Z]+(?![a-z])|\d+") + recs, vecs, skipped, bad = [], [], [], 0 + for p in sorted(root.rglob("*.py")): + rel = str(p.relative_to(root)).replace("\\", "/") + if any(part.startswith(".") or part in ("node_modules", "__pycache__", "venv", ".venv") for part in p.parts): + continue + try: + text = p.read_text(encoding="utf-8", errors="ignore") + except Exception: # noqa: BLE001 + continue + if SECRET_NAME.search(rel) or SECRET_TEXT.search(text): + skipped.append(rel) + continue + try: + tree = _ast.parse(text) + except Exception: # noqa: BLE001 + bad += 1 + continue + for node in _ast.walk(tree): + if not isinstance(node, (_ast.FunctionDef, _ast.AsyncFunctionDef, _ast.ClassDef)): + continue + doc = _ast.get_docstring(node) or "" + args = [] if isinstance(node, _ast.ClassDef) else [a.arg for a in node.args.args] + ws = [w.lower() for w in split.findall(node.name)] + re.findall(r"[a-z]{3,}", doc.lower())[:60] + v = np.zeros(WV.shape[1], np.float32) + for w in ws: + if w in WVI: + v += WV[WVI[w]] + n = np.linalg.norm(v) + vecs.append(v / n if n > 0 else v) + recs.append({"path": rel, "name": node.name, "kind": "class" if isinstance(node, _ast.ClassDef) else "def", + "args": args, "doc": doc[:400], "line": node.lineno, "end": getattr(node, "end_lineno", node.lineno)}) + if not recs: + return "No Python functions found in %s." % root + INDEX.mkdir(parents=True, exist_ok=True) + np.save(INDEX / "fn_vec.npy", np.stack(vecs).astype(np.float32)) + json.dump(recs, open(INDEX / "fn_index.json", "w")) + _WHERE.write_text(str(root)) + global WORKSPACE + WORKSPACE = root + _IX.clear() + return ("Indexed %d functions and classes from %s (%d files unparsable). Left out as possible secrets: %d files%s" % ( + len(recs), root, bad, len(skipped), (": " + ", ".join(skipped[:12]) + (" ..." if len(skipped) > 12 else "")) if skipped else ".")) + + +def _find_recs(step, k=5): + import numpy as np + if not (INDEX / "fn_index.json").is_file(): + return [] # no workspace index yet: language moves only + ix = _index() + v = np.zeros(ix["wv"].shape[1], np.float32) + for w in re.findall(r"[a-z]{3,}", step.lower()): + if w in ix["wvi"]: + v += ix["wv"][ix["wvi"][w]] + if not v.any(): + return [] + sc = ix["vec"] @ (v / np.linalg.norm(v)) + return [(ix["recs"][i], float(sc[i])) for i in np.argsort(-sc)[:k]] + + +def _named(word): + """a workspace function named exactly by the step's word: one positional argument, its source readable; the shortest + documented definition first""" + if not (INDEX / "fn_index.json").is_file(): + return None + ix = _index() + cands = [r for r in ix["recs"] if r["name"].lower() == word and r["kind"] == "def" and "self" not in r["args"]] + cands = [r for r in cands if _required(r) == 1] # one input needed; the rest have defaults + cands.sort(key=lambda r: (not r["doc"], r["end"] - r["line"])) + return cands[0] if cands else None + + +_find_recs.named = _named + +_REQ = {} + + +def _required(rec): + """how many inputs the function needs (arguments without a default, self/cls not counted; -1 if unreadable)""" + key = (rec["path"], rec["line"]) + if key not in _REQ: + import ast as _ast + import textwrap + try: + lines = (WORKSPACE / rec["path"]).read_text(errors="ignore").splitlines()[rec["line"] - 1: rec["end"]] + node = _ast.parse(textwrap.dedent(NL.join(lines))).body[0] + a = node.args + pos = [x.arg for x in a.posonlyargs + a.args] + need = [x for x in pos[: len(pos) - len(a.defaults)] if x not in ("self", "cls")] + _REQ[key] = len(need) + sum(1 for d in a.kw_defaults if d is None) + except Exception: # noqa: BLE001 + _REQ[key] = -1 + return _REQ[key] + + +_find_recs.required = _required + + +def _read_rec(rec): + """the function's source, with the module-level functions and constants it uses from its own file (followed through), and + the file's plain imports""" + import ast as _ast + p = WORKSPACE / rec["path"] + try: + text = p.read_text(errors="ignore") + tree = _ast.parse(text) + except Exception: # noqa: BLE001 + return None, set() + lines = text.splitlines() + top = {} + for n in tree.body: + if isinstance(n, (_ast.FunctionDef, _ast.ClassDef)): + top[n.name] = n + elif isinstance(n, _ast.Assign) and len(n.targets) == 1 and isinstance(n.targets[0], _ast.Name): + top[n.targets[0].id] = n + want, order, todo = set(), [], [rec["name"]] + while todo: + nm = todo.pop() + if nm in want or nm not in top: + continue + want.add(nm) + order.append(top[nm]) + for sub in _ast.walk(top[nm]): + if isinstance(sub, _ast.Name) and sub.id in top and sub.id not in want: + todo.append(sub.id) + order.sort(key=lambda n: n.lineno) + src = (NL + NL).join(NL.join(lines[n.lineno - 1: n.end_lineno]) for n in order) + imps = set() + for n in tree.body: + if isinstance(n, _ast.Import): + imps.update(a.name for a in n.names if not a.asname) + return src, imps + + +COL_SRC = '''def _col(r, k): + """a column by its name as described, or the file's nearest header (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) + if near: + return r[near[0]] + raise KeyError(k)''' + +NUM_SRC = '''def _num(v): + """a number from text as people write it ($1,200.50, 45%, 3 kg), or None when there is none""" + import re as _re + if isinstance(v, (int, float)): + return float(v) + m = _re.search(r"-?\\d[\\d,]*(?:\\.\\d+)?|-?\\.\\d+", str(v)) + return float(m.group(0).replace(",", "")) if m else None''' + + +def _repair(src, out): + """one typed repair from the error the run printed: -> (new source, what was repaired) or (None, why not)""" + err = out.split(NL + "errors:", 1)[1] if NL + "errors:" in out else out + last = [ln for ln in err.strip().splitlines() if ln.strip()][-1:] or [""] + last = last[0] + m = re.match(r"KeyError: '(.+)'", last) + if m and "r[" in src: + new = re.sub(r"\br\[('(?:[^'\\]|\\.)*')\]", r"_col(r, \1)", src) + if "def _col(" not in new: + new = new.replace("\ndef run(", NL + COL_SRC + NL + NL + NL + "def run(", 1) + return new, "the column %r is not a header of the file; read it as the nearest header" % m.group(1) + if re.match(r"ValueError: could not convert string to float", last) and "float(i) for i in x" in src: + new = src.replace("float(i) for i in x", "v for v in (_num(i) for i in x) if v is not None") + if "def _num(" not in new: + new = new.replace("\ndef run(", NL + NUM_SRC + NL + NL + NL + "def run(", 1) + return new, "some values were not plain numbers; read them as people write numbers ($, commas, %, units) and skip blanks" + m = re.search(r"FileNotFoundError: .*No such file or directory: '([^']+)'", last) + if m: + want = Path(m.group(1)).name + cands = [p.name for p in SANDBOX.iterdir() if p.is_file() and (p.name.lower() == want.lower() or p.stem.lower() == Path(want).stem.lower())] + if cands: + return src.replace(repr(m.group(1)), repr(cands[0])), "there is no %s in the sandbox; used %s" % (want, cands[0]) + return None, "there is no file %s in the sandbox (write it there first)" % want + return None, last.strip()[:160] + + +def change(text): + """change : - a copy of your script in the sandbox, edited as described (replace A with B; rename A to B; + delete lines containing A; add at the end / after the line containing A), then run if it is Python. Your + original is never changed.""" + m = re.match(r"^\s*([^:]+?)\s*:\s*(.+)$", text, re.S) + if not m: + return "hole", "Say which file and what to change: change : replace A with B; rename A to B; ..." + name, edits = m.group(1).strip().strip("'\""), m.group(2) + src_p = next((p for p in (SANDBOX / name, WORKSPACE / name) if p.is_file()), None) + if not src_p: + return "hole", "There is no %s in the sandbox or your code." % name + s = src_p.read_text(errors="ignore") + dst = SANDBOX / Path(name).name + done, gaps = [], [] + Qx = r"""['"‘“`]?(.+?)['"’”`]?""" + for e in [x.strip(" .") for x in re.split(r";|\n|,\s*then\s+", edits) if x.strip(" .")]: + mm = re.match(r"^(?:replace|change)\s+" + Qx + r"\s+(?:with|to|into)\s+" + Qx + r"$", e, re.I) + if mm and not re.match(r"^rename\b", e, re.I): + n = s.count(mm.group(1)) + if n: + s = s.replace(mm.group(1), mm.group(2)) + done.append("replaced %r with %r (%d place%s)" % (mm.group(1), mm.group(2), n, "" if n == 1 else "s")) + else: + gaps.append("%r is not in %s" % (mm.group(1), name)) + continue + mm = re.match(r"^rename\s+(?:the\s+)?(?:function\s+|variable\s+)?" + Qx + r"\s+(?:to|as)\s+" + Qx + r"$", e, re.I) + if mm: + # the name itself: in Python, only name tokens (never text inside strings or comments) and never an attribute + # reached through a dot (hashlib.sha256 stays hashlib.sha256); in other files, the whole word not after a dot + if name.endswith(".py"): + import io as _io + import tokenize as _tk + try: + toks, n, prev = list(_tk.generate_tokens(_io.StringIO(s).readline)), 0, None + lines = s.splitlines(keepends=True) + edits = [] + for t in toks: + if t.type == _tk.NAME and t.string == mm.group(1) and not (prev and prev.type == _tk.OP and prev.string == "."): + edits.append(t.start) + if t.type not in (_tk.NL, _tk.NEWLINE, _tk.COMMENT, _tk.INDENT, _tk.DEDENT): + prev = t + for (r_, c_) in reversed(edits): + ln = lines[r_ - 1] + lines[r_ - 1] = ln[:c_] + mm.group(2) + ln[c_ + len(mm.group(1)):] + s2, n = "".join(lines), len(edits) + except (_tk.TokenError, IndentationError): + s2, n = re.subn(r"(? %s" % (exp, "PASS" if (ran and _matches(exp, got)) else "FAIL") + steps = NL.join(" " + re.sub(r"^(?:(\w+): )?step (\d+(?:-\d+)?): ", lambda m: ("%s %s. " % (m.group(1), m.group(2))) + if m.group(1) else "%s. " % m.group(2), t).split(" -> ")[0] for t in P.trace) + head, _, body = out.partition(NL) + MADE.clear() # 12.5 (seal live, q45): the run's own receipt goes out with the reply + MADE.update(dict(execution.get("execution") or {}, file=f.name, + state=("failed" if not ran else "passed" if (exp is not None and "PASS" in verdict) else + "failed" if exp is not None else "ran"), + check=(verdict.strip() or None))) + return ("answered" if ran and (exp is None or "PASS" in verdict) else "hole", + "Built %s (%d steps, %d lines; read %s to see it):" % (f.name, len(P.trace), src.count(NL), f.name) + NL + steps + + NL + NL + "Ran: " + head + (NL + body if body else "") + verdict) + + +def _matches(exp, got): + """12.0 Amendment 13: the check compares, it does not search. "expect 2" is the output 2, not any output with a 2 in it. + expect [within ] the output's last line is that number (default tolerance 1e-9, relative 1e-9) + expect contains the output contains the text (asked for by name) + expect the output's last line is the text, spaces trimmed + Before this, the check was a substring test ("2" passed an output of "12"); results made under it are kept as made.""" + lines = [ln.strip() for ln in str(got).strip().splitlines() if ln.strip()] + last = lines[-1] if lines else "" + e = exp.strip() + m = re.match(r"(?is)^contains\s+(.+)$", e) + if m: + return m.group(1).strip().strip("'\"") in str(got) + m = re.match(r"(?is)^(-?\d+(?:\.\d+)?(?:e-?\d+)?)\s*(?:within|\+-|±)?\s*(\d+(?:\.\d+)?(?:e-?\d+)?)?$", e) + if m: + try: + g = float(last.replace(",", "")) + except ValueError: + return False + v = float(m.group(1)) + tol = float(m.group(2)) if m.group(2) else max(1e-9, 1e-9 * abs(v)) + return abs(g - v) <= tol + return last == e.strip("'\"") or str(got).strip() == e.strip("'\"") + + +_POLITE = r"^(?:please\s+|can you\s+|could you\s+|will you\s+)?" +_ALIASES = ((_POLITE + r"(?:show|open|display|print|cat)\s+(?:me\s+)?(?:the\s+)?(?:file\s+|function\s+|source of\s+)?([\w./-]+)\s*[?.]?$", "read"), + (_POLITE + r"(?:search for|look for|locate|where is|where do we|where does it)\s+(.+?)\s*[?.]?$", "find"), + (_POLITE + r"(?:execute|start|launch)\s+([\w./-]+)\s*[?.]?$", "run"), + (_POLITE + r"(?:i\s+(?:want|need)|i'd like|i would like|give me|get me|show me|what is|what's|what are|how many|how much)\s+(.+?)\s*[?.]?$", "want")) + + +def _alias(t): + """the same tools said the way people say them ("show me report.py", "where is the merkle root computed", "how many players + are in Leeds"). Each is tried only where it can act: a file or function that exists, an indexed workspace, a goal the + planner can chain over the sandbox's tables with every word accounted for. Otherwise None, and the door goes on.""" + for rx, cmd in _ALIASES: + m = re.match(rx, t, re.I | re.S) + if not m: + continue + rest = m.group(1).strip() + try: + if cmd == "read": + out = read(rest) + if not out.startswith("No file or function"): + return {"status": "answered", "response": out, "path": "tool:read"} + elif cmd == "find" and (INDEX / "fn_index.json").is_file(): + return {"status": "answered", "response": find(rest), "path": "tool:find"} + elif cmd == "run" and (SANDBOX / rest).is_file(): + return run_result(rest) + elif cmd == "want": + import planner as _planner + if re.match(r"(?i)^\s*(?:what|how)\b", t): + rest = t.strip().rstrip("?. ") # "how many ..." / "what is ...": the planner reads the whole goal + steps, _why = _planner.plan(rest, SANDBOX) + if steps: + st, resp = want(rest) + return {"status": st, "response": resp, "path": "tool:want"} + except Exception: # noqa: BLE001 + return None + return None + + +def dispatch(text, verb=None): + """the turn names a tool when its verb is one of the commands (the door's own rule for build and compose: exact, no + threshold). verb: the reader's frame verb when the conversation organ is up; otherwise the turn's first word.""" + t = text.strip() + m = re.match(r"^(?:please\s+|can you\s+|could you\s+)?([A-Za-z]+)\b[\s:]*(.*)$", t, re.S | re.I) + if not m: + return None + first, rest = m.group(1).lower(), m.group(2) + v = (verb or first).lower() + if v not in COMMANDS or first != v: + return _alias(t) # 12.0 Amendment 10 + try: + if v == "find": + return {"status": "answered", "response": find(rest), "path": "tool:find"} + if v == "read": + return {"status": "answered", "response": read(rest), "path": "tool:read"} + if v == "write" and chr(10) not in rest and not re.match(r"^[\w./-]+\.\w{1,5}\s*:?\s*$", rest.strip()): + return _alias(t) # the file tool only when a file is named or code follows + if v == "write": + name, _, code = rest.partition("\n") + return {"status": "answered", "response": write(name.strip().rstrip(":"), code), "path": "tool:write"} + if v == "run": + return run_result(rest) + if v == "fetch": + return {"status": "answered", "response": fetch(rest), "path": "tool:fetch"} + if v == "index": + return {"status": "answered", "response": index(rest), "path": "tool:index"} + if v == "want": + st, resp = want(rest) + return {"status": st, "response": resp, "path": "tool:want"} + if v == "change": + st, resp = change(rest) + return {"status": st, "response": resp, "path": "tool:change"} + if v == "make": + MADE.clear() + st, resp = make(rest) + r = {"status": st, "response": resp, "path": "tool:make"} + if MADE: + r["execution"] = dict(MADE) + return r + except Exception as e: # noqa: BLE001 + return {"status": "hole", "response": "The %s did not complete: %s" % (v, repr(e)[:200]), "path": "tool:" + v} + return None diff --git a/workbench/turn_act.py b/workbench/turn_act.py new file mode 100644 index 0000000000000000000000000000000000000000..da814ae0b96dd0de7dee2814ced4199a0dd5ffd6 --- /dev/null +++ b/workbench/turn_act.py @@ -0,0 +1,97 @@ +"""turn_act - what a turn does, read once, so one part owns it (revised 12.0, 2026-11-17). + +Before this, each part took turns by its own word rules in a fixed order and the first to grab a turn owned it: a request +for writing without the verb "write" reached the claim receiver, a question put to Oracle7 about itself reached the page +discussion, an idea the user was weighing reached the refusal of opinions. Here the turn's act is read once from the +reader's own frame and the store's verb meanings, and the head gives the turn to the part that owns that act: + + work something described to be built, read by the work receivers' own reading (project_intent.accepts); with + no project open, the head opens a new project folder in Oracle7's own workspace for it + writing the writer's dry take holds (a text object or a size asked for, any wording) + self a question put to Oracle7 about itself, naming nothing else the store holds + idea the speaker weighing something they mean to do or make ("I'm thinking about building ..."), or asking what + Oracle7 makes of the idea already on the table + question any other question: the head and the held pages answer it, never the claim receiver + None everything else keeps the existing receivers, in their order (work, premises, corrections are read before) + +Nothing here is a list of user sentences: the act comes from mood, person and the class a verb's definitions reach. +Would not solve: a turn whose act the reader misreads (mood wrong) goes to the wrong owner; that is a reader defect. +""" +import re + +FIRST_PERSON = re.compile(r"(?i)\b(?:i|i'm|i've|i'd|we|we're|we've|my|our)\b") +SECOND_PERSON = re.compile(r"(?i)\b(?:you|your|yourself)\b") +INTENT = {"plan", "intend", "consider", "think", "want", "wish", "build", "make", "create", "start", "design", "develop"} +OPINION = re.compile(r"(?i)\b(?:what\s+do\s+you\s+think|your\s+(?:view|thoughts?|opinion|take)|good\s+idea|bad\s+idea|" + r"worth\s+(?:it|doing|building)|should\s+i)\b") + + +def _verbs(text, reader): + """every verb the turn uses, read by the store (a verb sense, its lemma)""" + out = [] + for w in re.findall(r"[A-Za-z]+", text.lower()): + if "verb" in reader.d.pos(w): + out.append(reader.d.lemma(w, "verb")) + return out + + +def _reaches(part, verb, words): + try: + return part._verb_class(verb, words, depth=1) + except Exception: # noqa: BLE001 + return verb in words + + +def read(text, sid, cv): + """-> {"act": writing|self|idea|question|None, "basis": why}; a dry reading, nothing is done""" + part = cv._discussion_part() if cv is not None and hasattr(cv, "_discussion_part") else None + if part is None: + return {"act": None, "basis": "no conversation parts loaded"} + reader = part.router.reader + frame = reader.read(text) + mood = frame.get("mood") + try: # a program or tool described to be made: the work receivers' own reading + import project_intent + if mood != "question" and project_intent.accepts(text): + return {"act": "work", "basis": "the work receivers' own reading takes it as something to build"} + except Exception: # noqa: BLE001 + pass + try: + if part.writing_take(text, sid) is not None: + return {"act": "writing", "basis": "the writer's dry take holds"} + # writing asked of a question or a structure ("Explain how ...", "Compare A and B ... sections with headings") + # is writing even where no single subject owns it: the question-led composer receives it + if mood != "question" and part._writing_reading(frame, text) is not None: + return {"act": "writing", "basis": "a writing act on a question or structure"} + # a question asked with a size or a structure ("Why do fjords form ...? Two paragraphs") asks for writing + if part._sizes(text) or re.search(r"(?i)\b(?:sections?|headings?|numbered steps|paragraphs?|essay)\b", text): + if len(text.split()) > 8: + return {"act": "writing", "basis": "a question asked with a size or structure is a writing request"} + except Exception: # noqa: BLE001 + pass + named = [] + try: + named = [qid for _span, qid, _w in part.router.link(text)] + except Exception: # noqa: BLE001 + pass + if mood == "question" and SECOND_PERSON.search(text) and not named and not OPINION.search(text): + return {"act": "self", "basis": "a question put to Oracle7, naming nothing else held"} + verbs = _verbs(text, reader) + weighing = FIRST_PERSON.search(text) and any(_reaches(part, v, INTENT) for v in verbs) + if weighing and mood != "question" or OPINION.search(text) and (weighing or idea_held(sid)): + return {"act": "idea", "basis": "the speaker weighs something they mean to do or make"} + if mood == "question": + return {"act": "question", "basis": "a question: the head and held pages answer it"} + return {"act": None, "basis": "left to the existing receivers"} + + +def idea_held(sid): + """a plan is on the table: one the speaker weighed, or work this conversation keeps""" + import reflect + if reflect.load(sid).get("ideas"): + return True + try: + import bench + return bool(bench.Turn(sid).s.get("work")) + except Exception: # noqa: BLE001 + return False diff --git a/workbench/work_bindings.py b/workbench/work_bindings.py new file mode 100644 index 0000000000000000000000000000000000000000..9a8c36d90eb0994fbc2c6b552c725832f7e32886 --- /dev/null +++ b/workbench/work_bindings.py @@ -0,0 +1,389 @@ +"""Executable value contracts connecting native clauses to existing work parts. + +Named repository functions and configured operations supply the vocabulary. +The binder does not invent implementations, inputs, recipients or credentials. +""" +import ast +import copy +import csv +import hashlib +import io +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + + +REGISTRY = { + 'inventory': {'required': {}, 'optional': set(), 'result': 'value', 'effect': 'read repository interfaces'}, + 'service_request': {'required': {'service': str, 'operation': str}, 'optional': {'params', 'payload', 'path_params'}, + 'result': 'value', 'effect': 'received HTTP operation'}, + 'invoke': {'required': {'file': str, 'function': str, 'source_sha256': str, 'inputs': list}, + 'optional': {'keywords', 'output_type', 'expected', 'timeout'}, 'result': 'value', 'effect': 'read-only repository value callable'}, + 'value_file': {'required': {'file': str, 'value': object}, 'optional': set(), + 'result': 'value', 'effect': 'one named value artifact'}, + 'email_draft': {'required': {'to': object, 'subject': str, 'body': str}, 'optional': {'sender'}, + 'result': 'draft', 'effect': 'kept email draft'}, + 'interactive_program': {'required': {'contract': dict}, 'optional': {'file'}, + 'result': 'file', 'effect': 'checked state/event program'}, + 'program_steps': {'required': {'description': str, 'file': str, 'check': object}, 'optional': {'source_files', 'postcondition'}, + 'result': 'file', 'effect': 'existing step compiler in the selected repository'}, +} + + +def _hole(kind, text): + from work_tasks import WorkHole + raise WorkHole(kind, text) + + +def _path(root, name): + from work_tasks import _path as checked_path + return checked_path(root, name) + + +def _sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def _named(name, text): + return bool(re.search(r'(? 1: + step['binding_hole'] = 'this clause refers to several results; name the input for each function parameter' + continue + kind = step.get('kind') + proposal = None + if kind in ('compose', 'make'): + if clause and clause.get('kind') != 'outcome': + step['binding_hole'] = 'this clause states context or a constraint; name the requested operation or its check' + continue + verb = frame.get('verb') or (re.findall(r'[A-Za-z]+', text.lower()) or [''])[0] + if _verb_family(verb, {'make', 'build', 'create', 'write', 'compose'}): + from work_tasks import inventory + descriptions = [name for name in inventory(root)['files'] + if name.endswith(('.steps', '.txt', '.md')) and _named(name, text)] + destinations = list(dict.fromkeys(re.findall(r'(? 1: + step['binding_hole'] = 'name one service operation for this clause' + if proposal is None and not options and _operation(verb, 'invoke'): + if available_functions is None: + available_functions = functions(root) + matches = [f for f in available_functions if _named(f['function'], text)] + named_files = [f for f in matches if _named(f['file'], text)] + matches = named_files or matches + if len(matches) == 1 and source: + function = matches[0] + if len(function['required']) == 1: + proposal = ('invoke', {k: function[k] for k in ('file', 'function', 'source_sha256')}) + proposal[1]['inputs'] = [{'$ref': source + '.value'}] + else: + step['binding_hole'] = 'name the inputs for %s(%s)' % (function['function'], ', '.join(function['required'])) + elif len(matches) > 1: + step['binding_hole'] = 'name the module for %s; several repository functions match' % matches[0]['function'] + paths = re.findall(r'(? 1_000_000: + continue + rel = path.relative_to(base).as_posix() + files.append(rel) + if len(files) >= limit: + clipped = True + break + if path.suffix == ".py": + try: + tree = ast.parse(path.read_text(encoding="utf-8")) + except (SyntaxError, UnicodeError): + continue + for node in ast.walk(tree): + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + functions.append({"file": rel, "name": node.name, "line": node.lineno, "kind": type(node).__name__}) + elif isinstance(node, (ast.Import, ast.ImportFrom)): + imports.append({"file": rel, "module": getattr(node, "module", None), "names": [a.name for a in node.names]}) + if clipped: + break + import repair + return {"files": files, "definitions": functions, "imports": imports, "check": repair.test_command(base), "clipped": clipped} + + +def _structured(text): + stripped = text.strip() + fenced = re.fullmatch(r"```(?:json|work)\s*\n(.*?)\n```", stripped, re.S | re.I) + if fenced: + stripped = fenced.group(1) + if stripped.startswith("{"): + try: + value = json.loads(stripped) + return value if isinstance(value, dict) and ("steps" in value or "edits" in value or "kind" in value) else None + except ValueError: + return None + return None + + +def is_status(text): + t = text.strip().lower().replace("\u2019", "'").rstrip(".?!") + return bool(re.fullmatch(r"(?:status|show (?:the )?(?:goal|work)|what(?:'s| is) (?:left|next|blocked)|what remains|what (?:have you|has been) (?:finished|completed)|where are we(?: now)?)", t)) + + +_CHECK_RUN = re.compile(r"(?i)^\s*(?:and\s+|then\s+)*(?:re)?run\s+(?:the\s+|its\s+|my\s+|all\s+)?(?:tests?|checks?|test\s+suite)\b") +_REPAIR_VERB = re.compile(r"(?i)^\s*(?:and\s+|then\s+|so\s+)*(?:please\s+)?(?:fix|correct|repair)\b") + + +def repair_owns(text, reading=None): + """Running the project's check is the last step of every repair, not a second outcome: "The addition function + subtracts. Correct it and run the tests." is one repair (bench.repair_turn runs the check itself), not a work plan. + New work with its check ("Add invoice validation; run its tests") is not a repair.""" + if _structured(text) is not None: + return False + frames = [c for c in (reading or {}).get("clauses", []) if c.get("kind") == "outcome"] + rest = [c for c in frames if not _CHECK_RUN.match(str(c.get("text") or ""))] + if frames: + return bool(rest and len(rest) < len(frames) and all(_REPAIR_VERB.match(str(c.get("text") or "")) for c in rest)) + parts = [p for p in re.split(r"(?i)[.;]\s+|\s+and\s+(?=(?:re)?run\b)", text.strip()) if p.strip()] + acts = [p for p in parts if re.match(r"(?i)^\s*(?:please\s+)?[a-z]+\b", p) and (_CHECK_RUN.match(p) or _REPAIR_VERB.match(p))] + return any(_CHECK_RUN.match(p) for p in acts) and any(_REPAIR_VERB.match(p) for p in acts) + + +def accepts(text, root, kept=None, reading=None): + """Ownership predicate: ordinary conversation and table projects retain their existing routes.""" + import project_intent + if project_intent.owns_turn(text, kept, reading): + return True + if _structured(text) is not None or text.lstrip().startswith(("--- ", "diff --git ")): + return True + if kept and is_status(text): + return True + if kept and re.fullmatch(r'(?i)\s*(?:continue|resume)(?:\s+(?:the\s+)?work)?\s*[.!]?\s*', text): + return True + if kept and kept.get("pending_revision") and re.fullmatch(r"(?i)\s*W\d+\s*[.!]?", text): + return True + if kept and (REVISE.match(text) or re.match(r"(?i)^\s*fill\s+W\d+\b", text)): + return True + if kept and kept.get("state") not in ("done", "cancelled") and re.match( + r"(?i)^\s*(?:continue|resume|retry|use (?:this|these)|send\s+draft-)", text): + return True + if re.search(r"(?i)\b(?:configure service|call service|draft (?:an? )?email|send draft-[0-9a-f]+|across (?:the )?(?:repository|repo|project)|work plan)\b", text): + return True + import project + if project.is_project(text, None, root) and (project.DATA.search(text) or project.ENTRY.search(text)): + return False # the table/project part owns its existing language, even with several native clauses + if repair_owns(text, reading): + return False # a correction of existing code plus its check: repair's turn + frames = [c for c in (reading or {}).get("clauses", []) if c.get("kind") == "outcome"] + code_words = re.search(r"(?i)\b(?:repository|repo|codebase|tests?|functions?|modules?)\b|\.(?:py|js|ts|tsx|jsx|rs|go|java)\b", text) + return bool(code_words and (len(frames) > 1 or len(re.findall(r"(?:;|\n)\s*(?:then\s+)?", text)) > 0)) + + +def _step(kind, request, args=None, **extra): + return dict(kind=kind, request=request, args=args or {}, **extra) + + +_INSTEAD = re.compile(r"(?i)(?:^|\s)(?P[^\s,;]+)\s+instead\s+of\s+(?P[^\s,;]+?)[.!]?(?=\s|$|,|;)") +_CHANGE_TO = re.compile(r"(?i)\b(?:change|replace|set)\s+(?P[^\s,;]+)\s+(?:to|into|with)\s+(?P[^\s,;]+?)[.!]?(?=\s|$|,|;)") +_FILLER = {"make", "change", "replace", "set", "the", "for", "from", "with", "into", "instead", "and", "then", "that", + "this", "it", "its", "in", "of", "to", "go", "up", "down", "use", "a", "an", "so", "should", "be"} + + +def _described_edit(text, root): + """A change described in words with a named file ("In size.py, make the range for few go up to 5 instead of 4", + "change 14 to 28 in repair.py"): the replaced value is found in that file, and the place is chosen by the request's + other words (the enclosing function's name, docstring, comments and the line itself). One place that fits best is + an exact edit, checked like any other; several equal places, or none, are a hole that names them. Nothing is + guessed beyond that file.""" + if root is None: + return None + m = _INSTEAD.search(text) or _CHANGE_TO.search(text) + if not m: + return None + old, new = m.group("old").strip("`'\""), m.group("new").strip("`'\"") + named = [f for f in re.findall(r"[\w./\\-]+\.\w+", text) if (Path(root) / f).is_file()] + if len(named) != 1 or old == new: + return None + rel = named[0].replace("\\", "/") + path = Path(root) / rel + try: + source = path.read_text(encoding="utf-8") + except (OSError, UnicodeError): + return None + lines = source.splitlines() + pattern = re.compile(r"(? 1 and (len(best) != 1 or places[0][0] == 0): + where = "; ".join("%s:%d `%s`" % (rel, n, l.strip()[:80]) for _s, n, l in (best if places[0][0] else places)[:6]) + return _step("unbound", text, {"error": "%s appears at several places in %s that fit the request equally: %s. " + "Name the line or the function." % (old, rel, where)}) + _score, number, line = places[0] + if lines.count(line) != 1: + return _step("unbound", text, {"error": "the line to change in %s is repeated; name the function: %s" % (rel, line.strip())}) + return _step("edits", text, {"edits": [{"path": rel, "before": line, "after": pattern.sub(new, line, count=1)}], + "described": {"file": rel, "line": number, "old": old, "new": new}}) + + + +def _read_clause(text, frame=None, root=None): + """Bind a received clause to a part contract; retain the complete clause for delegated composition.""" + t = text.strip().strip(";") + m = re.search(r"(?i)\brename\s+(?:(?:the\s+)?(?:symbol|function|identifier)\s+)?`?([A-Za-z_]\w*)`?\s+to\s+`?([A-Za-z_]\w*)`?", t) + if m: + return _step("rename", t, {"old": m.group(1), "new": m.group(2)}) + described = _described_edit(t, root) + if described is not None: + return described + if re.match(r"(?i)^(?:inspect|inventory|look (?:at|through)|read)\b", t): + return _step("inventory", t) + m = re.match(r"(?is)^(?:run|check with|test with)\s+`([^`]+)`\s*[.!]?$", t) + if m: + return _step("check", t, {"command": m.group(1)}) + if re.search(r"(?i)\b(?:run|check|test)\b.*\b(?:tests?|checks?|suite)\b|^run (?:its|the|their) tests", t): + # files the request names narrow the check to them ("run the size tests in tests/test_size_reading.py") + named = re.findall(r"[\w./\\-]+\.py\b", t) + return _step("check", t, {"targets": named} if named else None) + if re.match(r"(?i)^(?:synthesize|compose implementations)\b", t): + return _step("synthesize", t) + if re.search(r"(?i)^(?:make|implement|build|write|create)\b.*\btests?\b.*\b(?:pass|passing|green)\b", t): + if root is not None: + import compose_code as CC + named = re.findall(r"[\w./-]+\.py\b", t) + tests = [os.path.basename(name) for name in named if CC.is_test_path(name)] + if CC.read_class_tests(root, only=tests or None): + return _step("make", t) + return _step("synthesize", t) + if re.match(r"(?i)^(?:fix|repair|correct)\b", t): + return _step("repair_many", t) + m = re.match(r"(?is)^configure service\s+([A-Za-z][\w-]*)\s*:?\s*(\{.*\})$", t) + if m: + return _step("service_config", t, {"name": m.group(1), "contract": json.loads(m.group(2))}) + m = re.match(r"(?is)^call service\s+([A-Za-z][\w-]*)\s+([A-Za-z][\w-]*)(?:\s+(\{.*\}))?\s*$", t) + if m: + return _step("service_request", t, dict(service=m.group(1), operation=m.group(2), **(json.loads(m.group(3)) if m.group(3) else {}))) + m = re.match(r"(?is)^draft (?:an? )?email\s+to\s+(\S+)\s*\nsubject:\s*([^\n]*)\n(?:body:\s*)?(.*)$", t) + if m: + return _step("email_draft", t, {"to": m.group(1), "subject": m.group(2), "body": m.group(3)}) + m = re.match(r"(?i)^send\s+(draft-[0-9a-f]{20})(?:\s+(?:using|through)\s+([A-Za-z][\w-]*))?\s*[.!]?$", t) + if m: + return _step("email_send", t, {"draft_id": m.group(1), "service": m.group(2)}) + if re.match(r"(?i)^(?:write|create|save)\s+(?:file\s+)?[^\s]+\.[a-z0-9]+\s*:?\s*\n", t): + return _step("write", t) + if re.match(r"(?i)^(?:in\s+\S+\s*,?\s*(?:replace|change)|(?:replace|change)\s+[`\"])", t): + return _step("edit", t) + if re.search(r"(?i)\b(?:button|click|keyboard|keydown|interactive|event|canvas)\b", t): + return _step("interactive", t) + if re.match(r"(?i)^make\s+[\w-]+\s*:", t): + return _step("make", t) + return _step("compose", t, native_frame=frame or {}) + + +def _reference_owner(shape, item): + if item.get("step"): + return item["step"] + # Migrate older kept readings by their exact clause text, never by pronoun alone. + candidates = set() + for number, turn in enumerate(shape.get("turns", [])): + if item.get("turn") not in (None, number): + continue + for clause in (turn.get("reading") or {}).get("clauses", []): + if clause.get("id") == item.get("clause"): + candidates.update(step["id"] for step in shape["steps"] if step["request"] == clause["text"]) + return next(iter(candidates)) if len(candidates) == 1 else None + + +def _retire_references(shape, step): + kept, retired = [], [] + for item in shape.get("unresolved", []): + (retired if _reference_owner(shape, item) == step["id"] else kept).append(item) + shape["unresolved"] = kept + if retired: + shape.setdefault("retired_references", []).extend(dict(item, replaced_by=step["id"]) for item in retired) + + +def receive(text, root, kept=None, reading=None): + shape = copy.deepcopy(kept) if kept else {"v": 1, "id": _sha(text + str(time.time_ns()))[:16], "goal": text, "steps": [], "requirements": [], "receipts": [], "holes": [], "state": "received"} + if kept and is_status(text): + shape["_status_requested"] = True + return shape + import project_intent + if project_intent.owns_turn(text, kept, reading): + old = (kept or {}).get('build_intent') + intent = project_intent.receive(text, old, reading) + semantic = project_intent.semantic(intent) + previous = next((step for step in shape['steps'] if step['kind'] == 'described_program'), None) + if old and intent['original'] != old['original']: + shape.setdefault('previous_goals', []).append(copy.deepcopy({key: value for key, value in shape.items() if key != 'previous_goals'})) + shape.update(id=_sha(text + str(time.time_ns()))[:16], goal=text, steps=[], requirements=[], receipts=[], turns=[], + holes=[], state='received', check=None) + previous = None + shape['build_intent'] = intent + shape.setdefault('turns', []).append({'text': text, 'reading': copy.deepcopy(reading)}) + shape['constraints'] = copy.deepcopy(intent['constraints']) + if previous is None: + number = max([int(step['id'][1:]) for step in shape['steps']] or [0]) + 1 + previous = _step('described_program', intent['original'], {'intent': semantic}, id='W%d' % number, state='pending', attempts=[], after=[]) + shape['steps'].append(previous) + shape['requirements'].append({'id': previous['id'], 'text': intent['original'], 'status': 'open'}) + elif previous['args'].get('intent') != semantic: + previous.setdefault('superseded', []).append(copy.deepcopy({key: value for key, value in previous.items() if key != 'superseded'})) + previous.update(args={'intent': semantic}, state='pending', attempts=[]) + for requirement in shape['requirements']: + if requirement['id'] == previous['id']: + requirement['status'] = 'open' + shape['holes'], shape['state'] = [], 'received' + return shape + shape.setdefault("turns", []).append({"text": text, "reading": copy.deepcopy(reading) if reading else None}) + shape["retry_requested"] = bool(re.fullmatch(r"(?i)\s*retry\s*[.!]?", text)) + if kept and re.fullmatch(r"(?i)\s*(?:(?:continue|resume)(?:\s+(?:the\s+)?work)?|retry|status|show (?:the )?(?:goal|work))\s*[.!]?\s*", text): + return shape + correction = REVISE.match(text) + chosen = re.fullmatch(r"(?i)\s*(W\d+)\s*[.!]?", text) if shape.get("pending_revision") else None + if correction or chosen: + if chosen: + pending = shape["pending_revision"] + candidates, body, selected = pending["candidates"], pending["text"], chosen.group(1).upper() + target = next((s for s in shape["steps"] if s["id"] == selected and selected in candidates), None) + else: + body = correction.group(1) + possible = [s for s in shape["steps"] if s.get("state") != "done"] or list(shape["steps"]) + candidates = [s["id"] for s in possible] + target = possible[0] if len(possible) == 1 else None + if target is None: + shape["pending_revision"] = {"text": body, "candidates": candidates} + shape["holes"] = [{"kind": "scope", "text": "which work step does this correction belong to? Say %s; the correction is kept" % ", ".join(candidates), "candidates": candidates}] + shape["state"] = "blocked" + return shape + new_step = _read_clause(body, root=root) + _retire_references(shape, target) + prior = {key: copy.deepcopy(value) for key, value in target.items() if key != "superseded"} + history = target.setdefault("superseded", []) + history.append(prior) + target.update(new_step, state="pending", attempts=[]) + for requirement in shape["requirements"]: + if requirement["id"] == target["id"]: + requirement.setdefault("superseded", []).append(requirement["text"]) + requirement.update(text=body, status="open") + shape.pop("pending_revision", None) + shape["holes"], shape["state"] = [], "received" + return shape + fill = re.match(r"(?is)^\s*fill\s+(W\d+)\s*:\s*(.*)$", text) + data = _structured(fill.group(2) if fill else text) + steps = [] + new_references = [] + if data is not None: + if "steps" in data: + steps = data["steps"] + if not kept and data.get("goal"): + shape["goal"] = data["goal"] + elif "edits" in data: + steps = [_step("edits", text, data)] + else: + steps = [data] + if not isinstance(steps, list) or any(not isinstance(s, dict) for s in steps): + raise WorkHole("input", "a work shape needs a list of named part steps") + elif text.lstrip().startswith(("--- ", "diff --git ")): + steps = [_step("patch", text, {"diff": text})] + else: + complete = _read_clause(text, root=root) + if complete["kind"] in ("email_draft", "email_send", "service_config", "service_request", "write", "edit"): + steps = [complete] + elif reading and reading.get("available", True) and reading.get("clauses"): + for clause in reading["clauses"]: + if clause.get("kind") == "constraint": + shape.setdefault("constraints", []).append(copy.deepcopy(clause)) + elif clause.get("kind") == "outcome": + steps.append(dict(_read_clause(clause["text"], clause.get("frame"), root=root), + native_clause={"turn": len(shape["turns"]) - 1, "id": clause.get("id")})) + elif clause.get("text", "").strip(): + # A stated behavior can be an obligation without an imperative verb. + # Let a concrete part own it, or keep its named hole; history alone is insufficient. + steps.append(_step("compose", clause["text"], {"reading_kind": clause.get("kind", "context")}, native_frame=clause.get("frame") or {}, + native_clause={"turn": len(shape["turns"]) - 1, "id": clause.get("id")})) + new_references = [dict(copy.deepcopy(item), turn=len(shape["turns"]) - 1) for item in reading.get("unresolved", [])] + else: + chunks = [x.strip() for x in re.split(r";\s*(?:then\s+)?|\n\s*(?:\d+[.)]|[-*])\s+", text) if x.strip()] + steps = [_read_clause(chunk, root=root) for chunk in chunks] + if fill: + target = next((step for step in shape["steps"] if step["id"] == fill.group(1)), None) + if target is None or len(steps) != 1: + raise WorkHole("input", "a fill names one kept step and one replacement part contract") + _retire_references(shape, target) + replacement = dict(steps[0], id=target["id"], state="pending", attempts=[], replaces=target["request"], request=steps[0].get("request", fill.group(2))) + replacement.setdefault("after", list(target.get("after", []))) + shape["steps"][shape["steps"].index(target)] = replacement + for requirement in shape["requirements"]: + if requirement["id"] == target["id"]: + requirement.setdefault("superseded", []).append(requirement["text"]) + requirement.update(text=replacement["request"], status="open") + else: + # Steps of one request run in order; a new request is independent of earlier, unrelated work (an old blocked + # step must not hold it back) unless it opens by tying itself to that work ("then ...", "after that ..."). + previous_in_turn = None + tied = bool(re.match(r"(?i)^\s*(?:and\s+)?(?:then|after\s+that|next|afterwards|again)\b", text or "")) + for source in steps: + step = copy.deepcopy(source) + number = max([int(s["id"][1:]) for s in shape["steps"]] or [0]) + 1 + step.update(id="W%d" % number, state="pending", attempts=[]) + step.setdefault("request", text) + step.setdefault("args", {}) + if not isinstance(step.get("kind"), str) or not isinstance(step["args"], dict): + step.update(kind="unbound", args={"error": "each work step needs a part kind and an args object"}) + # A definition supplied to fill a caller's missing input precedes + # that caller. Arrival order must not put it behind the very work + # it enables. Explicit dependencies remain authoritative. + callers = [] + if step["kind"] == "service_config" and "after" not in source: + name = step["args"].get("name") + callers = [s for s in shape["steps"] if s.get("state") != "done" + and s.get("kind") in ("service_request", "email_send") + and (s.get("args") or {}).get("service") == name] + awaiting = [s["id"] for s in shape["steps"] if s.get("state") == "awaiting-check"] + default_after = ([previous_in_turn] if previous_in_turn + else ([shape["steps"][-1]["id"]] if (tied and shape["steps"]) + else (awaiting if step.get("kind") == "check" else []))) # a check covers changes awaiting one + step.setdefault("after", [] if callers else default_after) + previous_in_turn = step["id"] + if callers: + step["fills"] = [s["id"] for s in callers] + for caller in callers: + caller["after"] = list(dict.fromkeys(list(caller.get("after", [])) + [step["id"]])) + shape["steps"].append(step) + shape["requirements"].append({"id": step["id"], "text": step["request"], "status": "open"}) + for item in new_references: + matches = [step["id"] for step in shape["steps"] + if step.get("native_clause") == {"turn": item["turn"], "id": item.get("clause")}] + if len(matches) == 1: + item["step"] = matches[0] + shape.setdefault("unresolved", []).append(item) + shape["holes"], shape["state"] = [], "received" + return shape + + +def _check(command, root, runenv=None, timeout=90): + try: + if runenv is None: # round-3 R2: a project's check never runs with Oracle7's own settings + import runjail + runenv = runjail.env(root=root) + result = subprocess.run(command, shell=isinstance(command, str), cwd=str(root), env=runenv, + capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout) + return {"ok": result.returncode == 0, "exit": result.returncode, + "output": (result.stdout + result.stderr)[-12000:], "command": command} + except subprocess.TimeoutExpired: + return {"ok": False, "exit": None, "output": "the check exceeded %s seconds" % timeout, "command": command} + except OSError as exc: + return {"ok": False, "exit": None, "output": "the check could not start: %s" % exc, "command": command} + + +def _line_end(before): + """the file's own line ending: CRLF if it had them, LF if it had none; a new file takes the platform's""" + return "\r\n" if before and b"\r\n" in before else ("\n" if before is not None else os.linesep) + + +def _write_file(path, text): + guard_write(path) + before = path.read_bytes() if path.is_file() else None + path.parent.mkdir(parents=True, exist_ok=True) + if path.exists(): + path.unlink() # never mutate another tree through a hard link + after = text.replace("\n", _line_end(before)).encode("utf-8") # an edit never changes the file's line endings + path.write_bytes(after) + note_write(path, before, after) + import repair + repair.drop_bytecode(path) + return after + + +def edit_transaction(root, edits, check=None, runenv=None, postcondition=None, witness=False): + """Validate received contents and restore only this transaction's own writes. + + Round-3 R3 (the witness rule): when Oracle7 wrote the content (witness=True: composed or constructed code), a passing + check marks it checked only if that check, or the postcondition, failed on the files before the change. The baseline + already is the run with the change reverted. A check that passes either way does not tell the change apart, so the + state is 'changed-unwitnessed', which no step counts as done. Received exact edits (the user wrote the content) keep + 'checked', with the receipt saying whether the check told the change apart.""" + changes, originals = {}, {} + for edit in edits: + path = _path(root, edit["path"]) + if path not in changes: + guard_write(path) + originals[path] = path.read_bytes() if path.is_file() else None + before = originals[path].decode('utf-8').replace('\r\n', '\n').replace('\r', '\n') if originals[path] is not None else None + changes[path] = [before, before or ""] + old, current = changes[path] + if edit.get("sha256") and _sha(current) != edit["sha256"]: + raise WorkHole("conflict", "%s changed since the received edit; read it again" % edit["path"]) + if "content" in edit: + if old is not None and "before" not in edit and not edit.get("overwrite", False): + raise WorkHole("conflict", "%s already exists; include its before text/hash or explicit overwrite" % edit["path"]) + if "before" in edit and current != edit["before"]: + raise WorkHole("conflict", "%s no longer has the received before text" % edit["path"]) + new = edit["content"] + else: + before = edit.get("before") + if not isinstance(before, str) or not before: + raise WorkHole("edit", "an exact edit needs nonempty before text and its after text") + count = edit.get("count", 1) + if current.count(before) != count: + raise WorkHole("conflict", "%s contains the before text %d times, expected %s" % (edit["path"], current.count(before), count)) + new = current.replace(before, edit.get("after", "")) + if not isinstance(new, str): + raise WorkHole("edit", "file content must be text") + if path.suffix == ".py": + compile(new, str(path), "exec") + changes[path][1] = new + baseline = _check(check, root, runenv) if check else None + pre_post = _check(postcondition, root, runenv) if (postcondition and baseline and baseline["ok"]) else None + written = {} + try: + for path in changes: + if (path.read_bytes() if path.is_file() else None) != originals[path]: + raise WorkHole("conflict", "%s changed while the baseline check ran; no received outputs were written" % path.name) + for path, (before, after) in changes.items(): + if (path.read_bytes() if path.is_file() else None) != originals[path]: + raise WorkHole("conflict", "%s changed before publication; receive its current contents" % path.name) + written[path] = {"before": originals[path], "after": after.replace("\n", _line_end(originals[path])).encode("utf-8")} + _write_file(path, after) + checked = _check(check, root, runenv) if check else None + if checked and checked['ok'] and postcondition: + regression = checked + checked = _check(postcondition, root, runenv) + checked['regression'] = regression + if checked and not checked["ok"]: + tail = [line for line in str(checked.get("output") or "").splitlines() if line.strip()][-12:] + raise WorkHole("check", "the change failed its check, so the files were put back as they were:\n" + "\n".join(tail), + check=checked) + for path, change in written.items(): + if (path.read_bytes() if path.is_file() else None) != change['after']: + raise WorkHole("conflict", "%s changed during verification; receive its current contents" % path.name) + except Exception as exc: + preserved = [] + for path in reversed(written): + if not _rollback_owned(path, written[path]): + preserved.append(str(path.relative_to(Path(root).resolve())).replace(os.sep, "/")) + if preserved: + if isinstance(exc, WorkHole): + exc.hole['preserved'] = preserved + exc.hole['text'] += "; newer external contents were preserved in " + ", ".join(preserved) + else: + raise WorkHole("conflict", "the coordinated change failed; newer external contents were preserved", preserved=preserved, cause=str(exc)) from exc + raise + told_apart = bool(check) and ((baseline is not None and not baseline["ok"]) or (pre_post is not None and not pre_post["ok"])) + state = "changed-untested" if not check else "checked" if (told_apart or not witness) else "changed-unwitnessed" + return {"state": state, "witnessed": told_apart, "unwitnessed": None if told_apart or not check else + "the check passed before this change as well, so it does not tell this change apart", "files": [str(p.relative_to(Path(root).resolve())).replace(os.sep, "/") for p in changes], + "check": checked, "baseline": baseline, "changes": [{"file": str(p.relative_to(Path(root).resolve())).replace(os.sep, "/"), + "before": old, "after_sha256": _sha(new)} for p, (old, new) in changes.items()]} + + +def _rename_edits(root, old, new, paths=None): + if not old.isidentifier() or not new.isidentifier(): + raise WorkHole("name", "a code identifier must be a valid name") + paths = paths or [p for p in inventory(root)["files"] if p.endswith(".py")] + edits = [] + for name in paths: + path = _path(root, name) + before = path.read_text(encoding="utf-8") + tokens = list(tokenize.generate_tokens(io.StringIO(before).readline)) + if not any(t.type == tokenize.NAME and t.string == old for t in tokens): + continue + changed = [t._replace(string=new) if t.type == tokenize.NAME and t.string == old else t for t in tokens] + after = tokenize.untokenize(changed) + edits.append({"path": name, "before": before, "content": after}) + if not edits: + raise WorkHole("locate", "identifier %s is not in the received Python files; name the files or another part" % old) + return edits + + +def _patch_edits(root, patch): + lines = patch.splitlines(keepends=True) + edits, i = [], 0 + while i < len(lines): + if not lines[i].startswith("--- "): + i += 1 + continue + old_name = lines[i][4:].split("\t")[0].strip() + i += 1 + if i >= len(lines) or not lines[i].startswith("+++ "): + raise WorkHole("patch", "each patch file needs its +++ destination") + name = lines[i][4:].split("\t")[0].strip() + name = name[2:] if name.startswith("b/") else name + old_name = old_name[2:] if old_name.startswith("a/") else old_name + if name == "/dev/null" or old_name not in (name, "/dev/null"): + raise WorkHole("patch", "this part accepts file changes/additions; receive removals and moves as separate explicit parts") + path = _path(root, name) + before = path.read_text(encoding="utf-8") if path.is_file() else "" + source, output, cursor = before.splitlines(keepends=True), [], 0 + i += 1 + hunks = 0 + while i < len(lines) and not lines[i].startswith(("--- ", "diff --git ")): + match = re.match(r"@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", lines[i]) + if not match: + i += 1 + continue + hunks += 1 + start = max(0, int(match.group(1)) - 1) + if start < cursor or start > len(source): + raise WorkHole("patch", "%s has a stale or overlapping patch hunk" % name) + output.extend(source[cursor:start]) + cursor, i = start, i + 1 + while i < len(lines) and lines[i][:1] in (" ", "+", "-") and not lines[i].startswith(("--- ", "+++ ")): + sign, value = lines[i][0], lines[i][1:] + if sign in (" ", "-"): + if cursor >= len(source) or source[cursor] != value: + raise WorkHole("conflict", "%s patch context no longer matches; read the current file" % name) + cursor += 1 + if sign in (" ", "+"): + output.append(value) + i += 1 + if not hunks: + raise WorkHole("patch", "%s has no patch hunks" % name) + output.extend(source[cursor:]) + edits.append({"path": name, "before": before, "content": "".join(output)}) + if not edits: + raise WorkHole("patch", "receive a unified diff with named files and context lines") + return edits + + +def repair_many(root, request, command, runenv=None, limit=40, max_depth=3, postcondition=None, allowed_hosts=()): + """Compose existing repair moves across files; only a passing whole check publishes a change.""" + import repair as R + if not command: + raise WorkHole("check", "name the project's test/check command before repairing it") + baseline = _check(command, root, runenv) + tests_only = bool(re.fullmatch(r"(?i)\s*(?:(?:fix|repair)\s+(?:(?:the|all|its)\s+)?(?:failing\s+)?(?:tests?|checks?|test suite)|" + r"(?:make|get)\s+(?:(?:the|all|its)\s+)?(?:failing\s+)?(?:tests?|checks?|test suite)\s+(?:to\s+)?(?:pass|green))\s*[.!]?", request)) + if baseline["ok"] and not postcondition: + if tests_only: + return {"state": "checked", "files": [], "check": baseline, "witnessed": False, "no_change": True, + "response": "The requested tests already pass; no repair was needed, so nothing was changed."} + raise WorkHole("postcondition", "the existing tests already pass and do not demonstrate this newly requested behavior; receive a corresponding example or postcondition check before calling it finished", baseline=baseline) + + def verify(): + regression = _check(command, root, runenv) + if regression["ok"] and postcondition: + checked = _check(postcondition, root, runenv) + checked["regression"] = regression + return checked + return regression + + starting = verify() if postcondition else baseline + if starting["ok"]: + return {"state": "checked", "files": [], "check": starting, "baseline": baseline, "witnessed": False, "no_change": True, + "response": "The received behavior check and regression tests both pass; no repair was needed."} + req = R.read_request(request) + originals, owned, attempts, visited = {}, {}, [], set() + + def unchanged(): + for path, change in owned.items(): + if (path.read_bytes() if path.is_file() else None) != change['after']: + raise WorkHole('conflict', '%s changed during repair; its newer contents were preserved' % path.name) + + def restore_owned(): + preserved = [] + for path, change in reversed(list(owned.items())): + if not _rollback_owned(path, change): + preserved.append(str(path.relative_to(Path(root).resolve())).replace(os.sep, '/')) + owned.clear() + return preserved + + def search(log, depth): + if depth >= max_depth or len(attempts) >= limit: + return False + found = R.locate(root, req, log) + for _score, path, function, source in found[:4]: + path = _path(root, str(Path(path).resolve().relative_to(Path(root).resolve()))) + if R.is_test_file(path): + continue + unchanged() + if path.read_text(encoding='utf-8') != source: + raise WorkHole('conflict', '%s changed after the repair location was read' % path.name) + originals.setdefault(path, source) + if path not in owned: + before_bytes = path.read_bytes() + owned[path] = {'before': before_bytes, 'after': before_bytes} + for _priority, what, changed, _span in R.candidates(source, function, req)[:12]: + signature = (str(path), _sha(changed), tuple(sorted((str(other), _sha(other.read_text(encoding="utf-8"))) for other in originals if other != path))) + if signature in visited or len(attempts) >= limit: + continue + visited.add(signature) + try: + compile(changed, str(path), "exec") + except SyntaxError: + continue + unchanged() + trial_before = owned[path]['after'] + owned[path]['after'] = changed.replace('\n', _line_end(owned[path]['before'])).encode('utf-8') + _write_file(path, changed) + checked = verify() + unchanged() + attempts.append({"file": str(path.relative_to(Path(root).resolve())), "function": function.name, + "change": what, "exit": checked["exit"], "output": checked["output"][-1500:]}) + if checked["ok"]: + return True + # A new failing location is evidence to try the next part, never evidence of completion. + before_frames = {str(x) for x in R.frames_of(log, Path(root))} + after_frames = {str(x) for x in R.frames_of(checked["output"], Path(root))} + if after_frames != before_frames and search(checked["output"], depth + 1): + return True + unchanged() + if not _rollback_owned(path, {'before': trial_before, 'after': owned[path]['after']}): + raise WorkHole('conflict', '%s changed before its trial could be restored' % path.name) + owned[path]['after'] = trial_before + return False + + try: + success = search(starting["output"], 0) + if not success: + preserved = restore_owned() + if preserved: + raise WorkHole('conflict', 'newer contents appeared during repair; synthesis was not started', preserved=preserved) + originals.clear() + import work_synthesis + return work_synthesis.synthesize(root, request, check=command, postcondition=postcondition, + runenv=runenv, allowed_hosts=allowed_hosts, + prior={"baseline": baseline, "behavior_baseline": starting, "mutation_attempts": attempts, "limit": limit}) + final = verify() + unchanged() + if not final["ok"]: + raise WorkHole("check", "the final repair check did not repeat; originals were restored", check=final) + changes = [{"file": str(path.relative_to(Path(root).resolve())), "before": before, + "after_sha256": _sha(path.read_text(encoding="utf-8"))} for path, before in originals.items() + if path.read_text(encoding="utf-8") != before] + return {"state": "checked", "files": [c["file"] for c in changes], "changes": changes, + "check": final, "baseline": baseline, "attempts": attempts} + except Exception as exc: + preserved = restore_owned() + if preserved: + if isinstance(exc, WorkHole): + exc.hole['preserved'] = preserved + exc.hole['text'] += '; newer external contents were preserved in ' + ', '.join(preserved) + else: + raise WorkHole('conflict', 'repair failed; newer external contents were preserved', preserved=preserved, cause=str(exc)) from exc + raise + + +def _native(step, shape, root, dispatch, runenv, allowed_hosts): + import service_parts as S + kind, args = step["kind"], step.get("args") or {} + command = args.get("check") or shape.get("check") + if kind == "unbound": + raise WorkHole("input", args.get("error", "receive a named part and its inputs")) + for constraint in shape.get("constraints", []): + text = constraint.get("text", "") + negative = re.search(r"(?i)\b(?:do not|don't|never|without|must not)\b", text) + if negative and re.search(r"(?i)\bsend\b.*\b(?:email|mail|message)\b", text): + if kind == "email_send": + raise WorkHole("constraint", "the kept request says not to send email; this work remains a draft") + elif negative and re.search(r"(?i)\b(?:network|outside service|external service)\b", text): + if kind in ("service_request", "email_send"): + raise WorkHole("constraint", "the kept request rules out outside-service calls") + elif negative and re.search(r"(?i)\b(?:change|edit|modify)\b.*\btests?\b", text): + pass # checked against the concrete edit paths below + else: + raise WorkHole("constraint", "no connected check yet owns this constraint: %s. Name its check before continuing" % text) + if kind == "inventory": + value = inventory(root) + shape["inventory"] = value + if value["check"] and not shape.get("check"): + shape["check"] = value["check"] + return {"state": "checked", "value": value} + if kind in ("edits", "patch", "rename"): + edits = args.get("edits") if kind == "edits" else _patch_edits(root, args["diff"]) if kind == "patch" else _rename_edits(root, args["old"], args["new"], args.get("paths")) + if edits is None: + raise WorkHole("input", "receive the files' before/after edits") + import repair + if any(re.search(r"(?i)\b(?:do not|don't|never|must not)\b.*\b(?:change|edit|modify)\b.*\btests?\b", c.get("text", "")) for c in shape.get("constraints", [])) and any(repair.is_test_file(Path(edit["path"])) for edit in edits): + raise WorkHole("constraint", "the received edits include tests, but this goal says not to change tests") + return edit_transaction(root, edits, command, runenv) + if kind == "check": + command = args.get("command") or command or inventory(root)["check"] + if not command: + raise WorkHole("check", "the project has no discovered check; supply the command and expected outcome") + targets = args.get("targets") or [] + if targets and not args.get("command"): + missing = [t for t in targets if not (Path(root) / t).exists()] + if missing: + raise WorkHole("check", "the named test file is not in this project: " + ", ".join(missing)) + files = ['"%s"' % t.replace("\\", "/") for t in targets] + command = (str(command) + " " + " ".join(files) if "-m pytest" in str(command) + else " && ".join('"%s" %s' % (sys.executable, f) for f in files)) + shape["check"] = command + result = _check(command, root, runenv, args.get("timeout", 90)) + tail = [line for line in str(result.get("output") or "").splitlines() if line.strip()][-12:] + said = command if isinstance(command, str) else " ".join(command) + return {"state": "checked" if result["ok"] else "failed", "check": result, "command": command, + "hole": None if result["ok"] else {"kind": "check", "text": "the check failed (%s):\n%s" % (said, "\n".join(tail))}} + if kind == "repair_many": + return repair_many(root, step["request"], command or inventory(root)["check"], runenv, + limit=args.get("limit", 40), max_depth=args.get("max_depth", 3), postcondition=args.get("postcondition"), allowed_hosts=allowed_hosts) + if kind == "synthesize": + import work_synthesis + return work_synthesis.synthesize(root, step['request'], args.get('targets'), check=command, + postcondition=args.get('postcondition'), runenv=runenv, allowed_hosts=allowed_hosts) + if kind == 'described_program': + import project_intent + return project_intent.build(root, shape['build_intent'], runenv=runenv) + if kind == "service_config": + return S.configure(root, args["name"], args["contract"]) + if kind == "service_request": + return S.request(root, args["service"], args["operation"], args.get("params"), args.get("payload"), + path_params=args.get("path_params"), runenv=runenv, allowed_hosts=allowed_hosts) + if kind == "email_draft": + draft = S.draft_email(root, args["to"], args["subject"], args["body"], args.get("sender")) + shape["draft"] = draft + return {"state": "checked", "draft": draft, "response": "Email draft %s is kept for review; it has not been sent." % draft["id"]} + if kind == "email_send": + draft = shape.get("draft") + if not draft or draft["id"] != args.get("draft_id"): + raise WorkHole("draft", "receive and review the named draft in this work before authorizing its send") + if not args.get("service"): + raise WorkHole("configuration", "name the configured mail service: send %s using SERVICE" % draft["id"]) + if not re.fullmatch(r"(?i)send\s+" + re.escape(draft["id"]) + r"\s+(?:using|through)\s+" + re.escape(args["service"]) + r"\s*[.!]?", step["request"].strip()): + raise WorkHole("authority", "explicitly authorize sending this exact draft: send %s using %s" % (draft["id"], args["service"])) + return S.send_email(root, draft["id"], {"send": True, "draft_id": draft["id"], "sha256": draft["sha256"]}, + service=args["service"], operation=args.get("operation", "send"), runenv=runenv, allowed_hosts=allowed_hosts) + if dispatch: + result = dispatch(step, shape) + if result is not None: + return result + raise WorkHole("part", "no connected part completed %s: %s. Supply an edit contract, examples/tests, or connect the named existing part; the goal remains kept" % (kind, step["request"])) + + +def _fingerprint(root, step, shape, runenv): + digest = hashlib.sha256(json.dumps({key: step.get(key) for key in ("kind", "request", "args", "native_frame")}, sort_keys=True).encode()) + for name in shape.get("inventory", {}).get("files", []): + try: + path = _path(root, name) + digest.update(name.encode()) + digest.update(path.read_bytes() if path.is_file() else b"missing") + except (OSError, WorkHole): + digest.update(b"unreadable") + import service_parts + registered = service_parts.contracts(root) + digest.update(json.dumps(registered, sort_keys=True).encode()) + environment = dict(os.environ, **(runenv or {})) # as the service part reads credentials (round-3 R2) + # 12.0 C31: the network scope a step ran under is one of its inputs (a grant reopens what depended on it) + digest.update(("net_scope=" + str(environment.get("O7_NET_SCOPE", ""))).encode()) + for contract in registered.values(): + for key in ("env", "username_env"): + name = (contract.get("auth") or {}).get(key) + if name: + digest.update(str(environment.get(name, "")).encode()) # only the final digest is kept + return digest.hexdigest() + + +def _bound_inputs(value, shape, root=None, runenv=None): + """Connect outputs to later inputs by kept receipt identity, without evaluating code.""" + if isinstance(value, dict) and set(value) == {"$ref"}: + parts = str(value["$ref"]).split(".") + source = next((step for step in shape["steps"] if step["id"] == parts[0]), None) + if source is None or source.get("state") != "done" or not source.get("attempts"): + raise WorkHole("dependency", "input %s needs a checked result from %s" % (value["$ref"], parts[0])) + receipt = source["attempts"][-1] + if root is not None: + for name, expected in receipt["result"].get("source_files", {}).items(): + path = _path(root, name) + actual = hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None + if actual != expected: + raise WorkHole("stale", "%s changed after %s produced its checked value; receive a fresh result before reusing it" % (name, source["id"])) + for name, expected in receipt.get("artifacts", {}).items(): + path = _path(root, name) + actual = hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None + if actual != expected: + raise WorkHole("stale", "%s changed after %s was checked; receive a fresh check/result before reusing its output" % (name, source["id"])) + if source["kind"] in ("inventory", "check") and receipt.get("after_fingerprint") != _fingerprint(root, source, shape, runenv): + raise WorkHole("stale", "the project inputs changed after %s was checked; receive a fresh inventory/check before reusing that result" % source["id"]) + result = receipt["result"] + try: + for key in parts[1:]: + result = result[int(key)] if isinstance(result, list) else result[key] + except (KeyError, ValueError, IndexError, TypeError): + raise WorkHole("input", "the checked result has no input named %s; receive its actual result path" % value["$ref"]) + return copy.deepcopy(result) + if isinstance(value, dict): + return {key: _bound_inputs(child, shape, root, runenv) for key, child in value.items()} + if isinstance(value, list): + return [_bound_inputs(child, shape, root, runenv) for child in value] + return value + + +def _completed(step, result): + execution = result.get("execution") or {} + state = result.get("state") or execution.get("state") + if result.get("ok") is False or result.get("hole") or result.get("holes") or execution.get("holes"): + return False + for check in (result.get("check"), execution.get("check")): + if isinstance(check, dict) and check.get("ok") is not True: + return False + if isinstance(check, str) and check.lower() in ("failed", "not testing this", "unchecked"): + return False + if execution.get("exit") not in (None, 0) or result.get("exit") not in (None, 0): + return False + if state in ("checked", "changed-checked", "sent"): + return True + return step["kind"] == "inventory" and state in ("done", "read") + + +def _still_valid(step, shape, root, runenv): + """12.0 C31: a done step's receipt is history; it is valid now only if what it rested on is unchanged (its inputs and + authority, and the files it produced). Returns the reason it is no longer current, or None.""" + if root is None or not step.get("attempts"): + return None + last = step["attempts"][-1] + for name, expected in (last.get("artifacts") or {}).items(): + try: + path = _path(root, name) + actual = hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None + except (OSError, WorkHole): + actual = None + if actual != expected: + return "%s changed after it was checked" % name + if step["kind"] in ("inventory", "check") and last.get("after_fingerprint"): + try: + if _fingerprint(root, step, shape, runenv) != last["after_fingerprint"]: + return "its inputs or authority changed after it was checked" + except Exception: # noqa: BLE001 + return None + return None + + +def _status_result(shape, root=None, runenv=None): + done = sum(step.get("state") == "done" for step in shape.get("steps", [])) + pending = ["%s: %s (%s)" % (step["id"], step["request"], step.get("state", "pending")) + for step in shape.get("steps", []) if step.get("state") != "done"] + stale = [] + for step in shape.get("steps", []): + if step.get("state") == "done": + why = _still_valid(step, shape, root, runenv) + if why: + stale.append("%s was done, but %s; it needs a fresh check before it counts now" % (step["id"], why)) + response = "%d of %d work outcomes checked." % (done, len(shape.get("steps", []))) + response += " Still open: " + "; ".join(pending) if pending else " No work outcomes remain open." + if stale: + response += " Done then, not current: " + "; ".join(stale) + "." + if shape.get("holes"): + response += " " + " ".join(hole["text"] for hole in shape["holes"]) + return {"state": "read", "response": response, "files": [], "checks": [], "holes": copy.deepcopy(shape.get("holes", [])), "shape": shape} + + +def _dependencies(step): + found = set(step.get("after", [])) + def read(value): + if isinstance(value, dict): + if set(value) == {"$ref"}: + found.add(str(value["$ref"]).split(".")[0]) + else: + for child in value.values(): + read(child) + elif isinstance(value, list): + for child in value: + read(child) + read(step.get("args") or {}) + return found + + +def _ordered_steps(shape): + by_id = {step["id"]: step for step in shape["steps"]} + ordered, visiting, done = [], [], set() + def visit(sid): + if sid in done: + return + if sid not in by_id: + raise WorkHole("dependency", "work names missing predecessor %s" % sid) + if sid in visiting: + raise WorkHole("dependency", "work dependency cycle: %s" % " -> ".join(visiting[visiting.index(sid):] + [sid])) + visiting.append(sid) + for previous in sorted(_dependencies(by_id[sid])): + visit(previous) + visiting.pop() + done.add(sid) + ordered.append(by_id[sid]) + for step in shape["steps"]: + visit(step["id"]) + return ordered + + +def _ancestors(step, shape): + by_id, result = {item["id"]: item for item in shape["steps"]}, set() + def read(item): + for sid in _dependencies(item): + if sid not in result and sid in by_id: + result.add(sid) + read(by_id[sid]) + read(step) + return result + + +def advance(shape, root, dispatch=None, runenv=None, allowed_hosts=()): + shape = copy.deepcopy(shape) + if shape.pop("_status_requested", False): + return _status_result(shape, root, runenv) + if shape.get("pending_revision"): + save(root, shape) + result = _status_result(shape, root, runenv) + result["state"] = "waiting" + return result + shape["holes"] = [] + if shape.get("unresolved"): + shape["holes"] = [{"kind": "reference", "text": "name what the unresolved reference means", "reading": item} for item in shape["unresolved"]] + files, checks = [], [] + if any(s.get("kind") not in ("service_config", "service_request", "email_draft", "email_send") for s in shape["steps"]): + shape["inventory"] = inventory(root) + if not shape.get("check"): + shape["check"] = shape["inventory"]["check"] + try: + ordered = _ordered_steps(shape) + except WorkHole as exc: + shape["holes"].append(exc.hole) + ordered = [] + # 12.0 C31: a hole blocks the work that depends on it, not everything after it. A work-wide hole (an unresolved + # reference, a dependency cycle) still stops all, since what it affects is unknown. A check depends on every change + # made before it (a shared effect), so it waits while any of them is blocked. Independent work continues. + work_wide = bool(shape["holes"]) + blocked_ids = set() + for index, step in enumerate(ordered): + if work_wide or step.get("state") in ("done", "awaiting-check", "needs-repair"): + continue + # a check waits for earlier changes still to be made (one waiting for input will change the files later); a change + # that was tried, failed its own check and was put back has no effect left to wait for + def _restored(s): + last = (s.get("attempts") or [{}])[-1].get("result") or {} + return s.get("state") == "blocked" and ((last.get("hole") or {}).get("kind") == "check" or last.get("state") == "check") + hidden = {s["id"] for s in ordered[:index] if step["kind"] == "check" and s["kind"] not in ("check", "inventory") + and s.get("state") != "done" and not _restored(s)} + waits_on = sorted((_dependencies(step) | hidden) & blocked_ids) + if waits_on: + shape["holes"].append({"kind": "dependency", "step": step["id"], "text": "%s waits for %s, which is blocked" % (step["id"], ", ".join(waits_on))}) + blocked_ids.add(step["id"]) + continue + dependencies = [s for s in shape["steps"] if s["id"] in _dependencies(step)] + missing_dependencies = _dependencies(step) - {s["id"] for s in dependencies} + if missing_dependencies: + shape["holes"].append({"kind": "dependency", "step": step["id"], "text": "%s names missing predecessor %s" % (step["id"], ", ".join(sorted(missing_dependencies)))}) + blocked_ids.add(step["id"]) + continue + if any(s.get("state") not in ("done", "awaiting-check") and not (s.get("state") == "needs-repair" and step["kind"] in ("repair_many", "repair")) for s in dependencies): + shape["holes"].append({"kind": "dependency", "step": step["id"], "text": "%s is waiting for %s" % (step["id"], ", ".join(s["id"] for s in dependencies if s.get("state") != "done"))}) + blocked_ids.add(step["id"]) + continue + before = _fingerprint(root, step, shape, runenv) + if step.get("attempts") and before in {step["attempts"][-1].get("fingerprint"), step["attempts"][-1].get("after_fingerprint")} and step.get("state") == "blocked" and not shape.get("retry_requested"): + needed = copy.deepcopy(step['attempts'][-1]['result'].get('hole') or {}) + shape["holes"].append({"kind": "unchanged", "step": step["id"], "text": "%s still needs its kept hole filled; repeating unchanged work would not add evidence. %s" % (step["id"], needed.get('text', '')), + 'needed': needed}) + blocked_ids.add(step["id"]) + continue + try: + bound = dict(step, args=_bound_inputs(step.get("args") or {}, shape, root, runenv)) + with _MutationScope(root, shape): + result = _native(bound, shape, root, dispatch, runenv, allowed_hosts) + except (WorkHole, __import__("service_parts").ServiceHole) as exc: + result = {"state": "missing", "hole": getattr(exc, "hole", {"kind": getattr(exc, "kind", "part"), "text": str(exc)})} + except (ValueError, KeyError, TypeError, SyntaxError, OSError) as exc: + result = {"state": "failed", "hole": {"kind": "part", "text": "%s could not complete: %s" % (step["kind"], exc)}} + execution = result.get("execution") or {} + state = result.get("state") or execution.get("state") + complete = _completed(step, result) + awaiting = state == "changed-untested" + next_step = ordered[index + 1] if index + 1 < len(ordered) else None + repairing_next = not complete and step["kind"] == "check" and next_step and next_step["kind"] in ("repair_many", "repair") + step["state"] = "done" if complete else "awaiting-check" if awaiting else "needs-repair" if repairing_next else "blocked" + record = {"step": step["id"], "at": time.time(), "fingerprint": before, "result": result} + if 'inventory' in shape: + shape['inventory'] = inventory(root) # include files produced by this attempt, not only old names + record["after_fingerprint"] = _fingerprint(root, step, shape, runenv) + record["artifacts"] = {} + for name in result.get("files", execution.get("files", [])): + try: + path = _path(root, name) + if not path.is_file(): + raise WorkHole("artifact", "the part reports %s, but that file is not present" % name) + record["artifacts"][name] = hashlib.sha256(path.read_bytes()).hexdigest() + except (WorkHole, OSError) as exc: + complete, awaiting, repairing_next = False, False, False + step["state"] = "blocked" + result["hole"] = getattr(exc, "hole", {"kind": "artifact", "text": str(exc)}) + step.setdefault("attempts", []).append(record) + shape["receipts"].append(record) + for requirement in shape["requirements"]: + if requirement["id"] == step["id"]: + requirement["status"] = "passed" if complete else "open" + files.extend(result.get("files", execution.get("files", []))) + if result.get("check"): + checks.append(result["check"]) + if complete and step["kind"] in ("check", "repair_many", "repair"): + ancestors = _ancestors(step, shape) + for previous in shape["steps"]: + if previous["id"] in ancestors and previous.get("state") in ("awaiting-check", "needs-repair"): + previous["state"] = "done" + previous["checked_by"] = step["id"] + for requirement in shape["requirements"]: + if requirement["id"] == previous["id"]: + requirement["status"] = "passed" + if not complete and not awaiting and not repairing_next: + shape["holes"].append(dict(result.get("hole") or {"kind": "check", "text": result.get("response", "%s is not yet checked" % step["id"])}, step=step["id"])) + blocked_ids.add(step["id"]) + save(root, shape) + for step in shape["steps"]: + if step.get("state") == "awaiting-check": + shape["holes"].append({"kind": "check", "step": step["id"], "text": "%s changed files but has no passing check yet; add or run its check" % step["id"]}) + elif step.get("state") == "needs-repair" and not shape["holes"]: + shape["holes"].append({"kind": "check", "step": step["id"], "text": "%s has a failing check; receive a repair step with its kept evidence" % step["id"]}) + shape["state"] = "done" if shape["steps"] and all(s["state"] == "done" for s in shape["steps"]) and not shape["holes"] else "blocked" + save(root, shape) + # The reply is about this request: earlier items still open (unchanged since, so not re-run) are named once, briefly, + # not repeated in full each turn; "status" gives their detail. + earlier = {h.get("step") for h in shape["holes"] if h.get("kind") == "unchanged"} + by_id = {s["id"]: s for s in shape["steps"]} + for h in shape["holes"]: # a step waiting only on earlier open items belongs with them + if h.get("kind") == "dependency" and h.get("step") in by_id and _dependencies(by_id[h["step"]]) <= earlier: + earlier.add(h["step"]) + now = [s for s in shape["steps"] if s["id"] not in earlier] + finished = sum(s["state"] == "done" for s in now) + response = "%d of %d work outcomes checked." % (finished, len(now)) + current = [h for h in shape["holes"] if h.get("kind") != "unchanged" and h.get("step") not in earlier] + if current: + response += " " + " ".join(h["text"] for h in current) + if earlier: + response += " Still open from earlier: %s (say \"status\" for details)." % "; ".join( + "%s %s" % (i, by_id[i]["request"][:60]) for i in sorted(earlier) if i in by_id) + return {"state": "changed-checked" if shape["state"] == "done" else "waiting", "response": response, + "files": list(dict.fromkeys(files)), "checks": checks, "holes": shape["holes"], "shape": shape}