diff --git a/records/12/learn_sealed_run.py b/records/12/learn_sealed_run.py
new file mode 100644
index 0000000000000000000000000000000000000000..d271ee70f6cb4aa97753393c50de1416c395a6ab
--- /dev/null
+++ b/records/12/learn_sealed_run.py
@@ -0,0 +1,25 @@
+#!/usr/bin/env python3
+"""Run the sealed gap-loop set once. usage: learn_sealed_run.py
"""
+import json, os, sys, tempfile
+D, SEALED, OUT = sys.argv[1:4]
+os.environ["ORACLE7_LEARNED"] = os.path.join(tempfile.mkdtemp(), "learned.jsonl") # a fresh store: nothing known before
+sys.path.insert(0, D)
+import learn # noqa: E402
+S = json.load(open(SEALED))
+rows, tally = [], {"right-answered": 0, "right-offered": 0, "wrong-answered": 0, "miss": 0}
+for it in S["questions"]:
+ r = learn.lookup(it["q"])
+ hit = any(e.lower() in r["response"].lower() for e in it["expect"])
+ if r["status"] == "answered":
+ out = "right-answered" if hit else "wrong-answered"
+ elif r["status"] == "offered" and hit:
+ out = "right-offered"
+ else:
+ out = "miss"
+ tally[out] += 1
+ rows.append({"q": it["q"], "outcome": out, "status": r["status"], "response": r["response"][:600]})
+ print("%-15s %-50s %s" % (out, it["q"], r["response"][:150].replace("\n", " ")), flush=True)
+present = tally["right-answered"] + tally["right-offered"]
+ok = tally["wrong-answered"] == 0 and present >= 6
+print("TALLY", tally, "present", present, "BAR", "PASS" if ok else "FAIL")
+json.dump({"tally": tally, "present": present, "bar_pass": ok, "rows": rows}, open(OUT, "w"), indent=1)
diff --git a/records/12/learn_sealed_v1.json b/records/12/learn_sealed_v1.json
new file mode 100644
index 0000000000000000000000000000000000000000..fd6a227401c0562abc1b700eae4727d4ef63ab91
--- /dev/null
+++ b/records/12/learn_sealed_v1.json
@@ -0,0 +1,15 @@
+{
+ "about": "12.0 gap loop, sealed set v1 (2026-11-09). Questions never used while building learn.py; run once through learn.lookup (what a go after the offer runs). Outcomes: right-answered (status answered and one expected string in the response), right-offered (offered and expected present), wrong-answered (answered and no expected string: a breach of the law), miss (offered without the answer, or hole: honest). Bar: wrong-answered = 0 and expected present in >= 6 of 10. Live sources: the articles may change after the run; the response and URLs are recorded.",
+ "questions": [
+ {"q": "When did the Berlin Wall fall?", "expect": ["1989"]},
+ {"q": "Who wrote War and Peace?", "expect": ["Tolstoy"]},
+ {"q": "What is the capital of Mongolia?", "expect": ["Ulaanbaatar", "Ulan Bator"]},
+ {"q": "How many moons does Mars have?", "expect": ["two", "2 moons", "Phobos"]},
+ {"q": "Who discovered penicillin?", "expect": ["Fleming"]},
+ {"q": "When was the Eiffel Tower completed?", "expect": ["1889"]},
+ {"q": "What is the largest desert in the world?", "expect": ["Antarctic", "Sahara"]},
+ {"q": "Where is the Great Barrier Reef?", "expect": ["Australia", "Queensland", "Coral Sea"]},
+ {"q": "Who was the first person to walk on the Moon?", "expect": ["Armstrong"]},
+ {"q": "How long is the Nile River?", "expect": ["6,650", "6650", "6,695", "4,130", "4,160", "6,853", "4,258"]}
+ ]
+}
diff --git a/records/12/learn_sealed_v1_result.json b/records/12/learn_sealed_v1_result.json
new file mode 100644
index 0000000000000000000000000000000000000000..26cd2fbc0f4dfc025c3e596108d1067577a4dc1f
--- /dev/null
+++ b/records/12/learn_sealed_v1_result.json
@@ -0,0 +1,72 @@
+{
+ "tally": {
+ "right-answered": 1,
+ "right-offered": 5,
+ "wrong-answered": 0,
+ "miss": 4
+ },
+ "present": 6,
+ "bar_pass": true,
+ "rows": [
+ {
+ "q": "When did the Berlin Wall fall?",
+ "outcome": "miss",
+ "status": "offered",
+ "response": "From Wikipedia, one source, not yet checked against a second: The show was held in Berlin on 21 July 1990, to commemorate the fall of the Berlin Wall eight months earlier. [https://en.wikipedia.org/wiki/The_Wall_%E2%80%93_Live_in_Berlin]"
+ },
+ {
+ "q": "Who wrote War and Peace?",
+ "outcome": "right-offered",
+ "status": "offered",
+ "response": "From Wikipedia, one source, not yet checked against a second: Tolstoy wrote in a letter to Afanasy Fet that what he had written in War and Peace is also said by Schopenhauer in The World as Will and Representation. [https://en.wikipedia.org/wiki/War_and_Peace]"
+ },
+ {
+ "q": "What is the capital of Mongolia?",
+ "outcome": "miss",
+ "status": "offered",
+ "response": "From Wikipedia, one source, not yet checked against a second: Five-pagoda Temple is located in the capital of Inner Mongolia Hohhot. [https://en.wikipedia.org/wiki/Inner_Mongolia]"
+ },
+ {
+ "q": "How many moons does Mars have?",
+ "outcome": "right-offered",
+ "status": "offered",
+ "response": "From Wikipedia, one source, not yet checked against a second: Osiris-Rex 2 was a proposal to make OR a double mission, with the other one collecting samples from the two Mars moons. [https://en.wikipedia.org/wiki/List_of_missions_to_Mars]"
+ },
+ {
+ "q": "Who discovered penicillin?",
+ "outcome": "right-answered",
+ "status": "answered",
+ "response": "Penicillin was discovered in 1928 by the Scottish physician Alexander Fleming as a crude extract of P. rubens. [https://en.wikipedia.org/wiki/Penicillin] (two sources agree on fleming: Simple English Wikipedia [https://simple.wikipedia.org/wiki/Penicillin])"
+ },
+ {
+ "q": "When was the Eiffel Tower completed?",
+ "outcome": "right-offered",
+ "status": "offered",
+ "response": "From Wikipedia, one source, not yet checked against a second: As one of the most iconic and recognizable structures in the world, the Eiffel Tower, completed in 1889, has been the inspiration for the creation of over 50 similar towers around the world. [https://en.wikipedia.org/wiki/Eiffel_Tower_replicas_and_derivatives]"
+ },
+ {
+ "q": "What is the largest desert in the world?",
+ "outcome": "right-offered",
+ "status": "offered",
+ "response": "From Simple English Wikipedia, one source, not yet checked against a second: The largest hot desert in the world is the Sahara in North Africa. [https://simple.wikipedia.org/wiki/Desert]"
+ },
+ {
+ "q": "Where is the Great Barrier Reef?",
+ "outcome": "miss",
+ "status": "hole",
+ "response": "I looked in Wikipedia and Simple English Wikipedia and found nothing that answers it, so I still do not hold it."
+ },
+ {
+ "q": "Who was the first person to walk on the Moon?",
+ "outcome": "right-offered",
+ "status": "offered",
+ "response": "From Simple English Wikipedia, one source, not yet checked against a second: Neil Alden Armstrong (August 5, 1930 \u2013 August 25, 2012) was an American astronaut, and engineer, and is known as the first person to walk on the moon. [https://simple.wikipedia.org/wiki/Neil_Armstrong]"
+ },
+ {
+ "q": "How long is the Nile River?",
+ "outcome": "miss",
+ "status": "offered",
+ "response": "From Wikipedia, one source, not yet checked against a second: The stretch of the Nile between Cairo and Aswan has long been a popular destination for tourists: during celebrations surrounding the opening of the Suez Canal in 1870, a large group of tourists took a boat ride on that stretch of the river and visited Luxor, Dendera, Saqqara, Edfu, and Philae. [https://en.wikipedia.org/wiki/Nile]"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/records/12/make_sealed_run.py b/records/12/make_sealed_run.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3fec12782ffe735ce6315612d8aa1d191e26189
--- /dev/null
+++ b/records/12/make_sealed_run.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python3
+"""Run the sealed make set once. usage: make_sealed_run.py """
+import json, os, sys
+WB, SEALED, SBX, OUT = sys.argv[1:5]
+os.makedirs(SBX, exist_ok=True)
+assert not os.listdir(SBX), "the sandbox must start empty"
+os.environ["ORACLE7_SANDBOX"] = SBX
+os.environ.setdefault("ORACLE7_WORKSPACE", "/opt/o7ws/src")
+os.environ.setdefault("ORACLE7_WS_INDEX", "/opt/o7ws/index")
+os.environ.setdefault("ORACLE7_WORDVEC", WB + "/converse/data/ladder/wordvec.npz")
+sys.path.insert(0, WB)
+import tools # noqa: E402
+S = json.load(open(SEALED))
+for name, body in S["files"].items():
+ open(os.path.join(SBX, name), "w").write(body)
+rows, tally = [], {"correct": 0, "gap": 0, "wrong": 0}
+for t in S["tasks"]:
+ r = tools.dispatch("make %s: %s" % (t["id"], t["make"]))
+ resp = r["response"] if r else "(no tool)"
+ if r and r["status"] == "hole" and "nothing was written" in resp:
+ out = "gap"
+ else:
+ tail = resp.split("finished in", 1)[1] if "finished in" in resp else ""
+ ran = "exit 0." in tail
+ body = tail.split("exit 0.", 1)[1].split("\ncheck:", 1)[0].strip() if ran else ""
+ if not ran or not body:
+ out = "wrong"
+ elif t["expect"] is None:
+ out = "correct"
+ else:
+ out = "correct" if t["expect"] in body else "wrong"
+ tally[out] += 1
+ rows.append({"id": t["id"], "outcome": out, "response": resp[-1500:]})
+ print("%s %-8s %s" % (t["id"], out, t["make"][:90]), flush=True)
+ok = tally["correct"] >= 14 and tally["wrong"] <= 2
+print("TALLY", tally, "BAR", "PASS" if ok else "FAIL")
+json.dump({"tally": tally, "bar_pass": ok, "rows": rows}, open(OUT, "w"), indent=1)
diff --git a/records/12/make_sealed_run_v2.py b/records/12/make_sealed_run_v2.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c2579dba30e2214e0274f1f49cbf67b3b3ecb8f
--- /dev/null
+++ b/records/12/make_sealed_run_v2.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python3
+"""Run the sealed make set once. usage: make_sealed_run.py """
+import json, os, sys
+WB, SEALED, SBX, OUT = sys.argv[1:5]
+os.makedirs(SBX, exist_ok=True)
+assert not os.listdir(SBX), "the sandbox must start empty"
+os.environ["ORACLE7_SANDBOX"] = SBX
+os.environ.setdefault("ORACLE7_WORKSPACE", "/opt/o7ws/src")
+os.environ.setdefault("ORACLE7_WS_INDEX", "/opt/o7ws/index")
+os.environ.setdefault("ORACLE7_WORDVEC", WB + "/converse/data/ladder/wordvec.npz")
+sys.path.insert(0, WB)
+import tools # noqa: E402
+S = json.load(open(SEALED))
+for name, body in S["files"].items():
+ open(os.path.join(SBX, name), "w").write(body)
+rows, tally = [], {"correct": 0, "gap": 0, "wrong": 0}
+for t in S["tasks"]:
+ r = tools.dispatch("make %s: %s" % (t["id"], t["make"]))
+ resp = r["response"] if r else "(no tool)"
+ if r and r["status"] == "hole" and "nothing was written" in resp:
+ out = "gap"
+ else:
+ tail = resp.split("finished in", 1)[1] if "finished in" in resp else ""
+ ran = "exit 0." in tail
+ body = tail.split("exit 0.", 1)[1].split("\ncheck:", 1)[0].strip() if ran else ""
+ if not ran or not body:
+ out = "wrong"
+ elif t["expect"] is None:
+ out = "correct"
+ else:
+ out = "correct" if t["expect"] in body else "wrong"
+ tally[out] += 1
+ rows.append({"id": t["id"], "outcome": out, "response": resp[-1500:]})
+ print("%s %-8s %s" % (t["id"], out, t["make"][:90]), flush=True)
+ok = tally["correct"] >= 15 and tally["wrong"] <= 2
+print("TALLY", tally, "BAR", "PASS" if ok else "FAIL")
+json.dump({"tally": tally, "bar_pass": ok, "rows": rows}, open(OUT, "w"), indent=1)
diff --git a/records/12/make_sealed_run_v3.py b/records/12/make_sealed_run_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..5bf8fe3c88956b90171ec87274dcb0cc369c2537
--- /dev/null
+++ b/records/12/make_sealed_run_v3.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python3
+"""Run the sealed make set once. usage: make_sealed_run.py """
+import json, os, sys
+WB, SEALED, SBX, OUT = sys.argv[1:5]
+os.makedirs(SBX, exist_ok=True)
+assert not os.listdir(SBX), "the sandbox must start empty"
+os.environ["ORACLE7_SANDBOX"] = SBX
+os.environ.setdefault("ORACLE7_WORKSPACE", "/opt/o7ws/src")
+os.environ.setdefault("ORACLE7_WS_INDEX", "/opt/o7ws/index")
+os.environ.setdefault("ORACLE7_WORDVEC", WB + "/converse/data/ladder/wordvec.npz")
+sys.path.insert(0, WB)
+import tools # noqa: E402
+S = json.load(open(SEALED))
+for name, body in S["files"].items():
+ open(os.path.join(SBX, name), "w").write(body)
+rows, tally = [], {"correct": 0, "gap": 0, "wrong": 0}
+for t in S["tasks"]:
+ r = tools.dispatch("make %s: %s" % (t["id"], t["make"]))
+ resp = r["response"] if r else "(no tool)"
+ if r and r["status"] == "hole" and "nothing was written" in resp:
+ out = "gap"
+ else:
+ tail = resp.split("finished in", 1)[1] if "finished in" in resp else ""
+ ran = "exit 0." in tail
+ body = tail.split("exit 0.", 1)[1].split("\ncheck:", 1)[0].strip() if ran else ""
+ if not ran or not body:
+ out = "wrong"
+ elif t["expect"] is None:
+ out = "correct"
+ else:
+ out = "correct" if t["expect"] in body else "wrong"
+ tally[out] += 1
+ rows.append({"id": t["id"], "outcome": out, "response": resp[-1500:]})
+ print("%s %-8s %s" % (t["id"], out, t["make"][:90]), flush=True)
+ok = tally["correct"] >= 8 and tally["wrong"] <= 1
+print("TALLY", tally, "BAR", "PASS" if ok else "FAIL")
+json.dump({"tally": tally, "bar_pass": ok, "rows": rows}, open(OUT, "w"), indent=1)
diff --git a/records/12/make_sealed_run_v4.py b/records/12/make_sealed_run_v4.py
new file mode 100644
index 0000000000000000000000000000000000000000..ffb7db1b8a53f671d0b8771d71e0a2a7a12cd6e0
--- /dev/null
+++ b/records/12/make_sealed_run_v4.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python3
+"""Run the sealed make set once. usage: make_sealed_run.py """
+import json, os, sys
+WB, SEALED, SBX, OUT = sys.argv[1:5]
+os.makedirs(SBX, exist_ok=True)
+assert not os.listdir(SBX), "the sandbox must start empty"
+os.environ["ORACLE7_SANDBOX"] = SBX
+os.environ.setdefault("ORACLE7_WORKSPACE", "/opt/o7ws/src")
+os.environ.setdefault("ORACLE7_WS_INDEX", "/opt/o7ws/index")
+os.environ.setdefault("ORACLE7_WORDVEC", os.environ.get("ORACLE7_WORDVEC_SRC") or (WB + "/converse/data/ladder/wordvec.npz"))
+assert os.path.isfile(os.environ["ORACLE7_WORDVEC"]), "word vectors not found: " + os.environ["ORACLE7_WORDVEC"]
+sys.path.insert(0, WB)
+import tools # noqa: E402
+S = json.load(open(SEALED))
+for name, body in S["files"].items():
+ open(os.path.join(SBX, name), "w").write(body)
+rows, tally = [], {"correct": 0, "gap": 0, "wrong": 0}
+for t in S["tasks"]:
+ r = tools.dispatch("make %s: %s" % (t["id"], t["make"]))
+ resp = r["response"] if r else "(no tool)"
+ if r and r["status"] == "hole" and "nothing was written" in resp:
+ out = "gap"
+ else:
+ tail = resp.split("finished in", 1)[1] if "finished in" in resp else ""
+ ran = "exit 0." in tail
+ body = tail.split("exit 0.", 1)[1].split("\ncheck:", 1)[0].strip() if ran else ""
+ if not ran or not body:
+ out = "wrong"
+ elif t["expect"] is None:
+ out = "correct"
+ else:
+ out = "correct" if t["expect"] in body else "wrong"
+ tally[out] += 1
+ rows.append({"id": t["id"], "outcome": out, "response": resp[-1500:]})
+ print("%s %-8s %s" % (t["id"], out, t["make"][:90]), flush=True)
+ok = tally["correct"] >= 8 and tally["wrong"] <= 1
+print("TALLY", tally, "BAR", "PASS" if ok else "FAIL")
+json.dump({"tally": tally, "bar_pass": ok, "rows": rows}, open(OUT, "w"), indent=1)
diff --git a/records/12/make_sealed_run_v5.py b/records/12/make_sealed_run_v5.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c533e3b9cd7c75c641fe49666ab1d54d103a9d6
--- /dev/null
+++ b/records/12/make_sealed_run_v5.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python3
+"""Run sealed set v5 once (make and change commands). usage: make_sealed_run_v5.py
+env: ORACLE7_WORDVEC_SRC (checked before any task), ORACLE7_WORKSPACE, ORACLE7_WS_INDEX"""
+import json, os, sys
+WB, SEALED, SBX, OUT = sys.argv[1:5]
+os.makedirs(SBX, exist_ok=True)
+assert not os.listdir(SBX), "the sandbox must start empty"
+os.environ["ORACLE7_SANDBOX"] = SBX
+os.environ["ORACLE7_WORDVEC"] = os.environ.get("ORACLE7_WORDVEC_SRC") or (WB + "/converse/data/ladder/wordvec.npz")
+assert os.path.isfile(os.environ["ORACLE7_WORDVEC"]), "word vectors not found: " + os.environ["ORACLE7_WORDVEC"]
+sys.path.insert(0, WB)
+import tools # noqa: E402
+S = json.load(open(SEALED))
+for name, body in S["files"].items():
+ open(os.path.join(SBX, name), "w").write(body)
+rows, tally = [], {"correct": 0, "gap": 0, "wrong": 0}
+for t in S["tasks"]:
+ r = tools.dispatch(t["cmd"])
+ resp = r["response"] if r else "(no tool)"
+ is_gap = bool(r) and r["status"] == "hole" and ("nothing was written" in resp or "changed nothing" in resp)
+ if t.get("gap"):
+ out = "correct" if is_gap else "wrong"
+ elif t.get("in_response"):
+ out = "correct" if t["expect"] in resp else ("gap" if is_gap else "wrong")
+ elif is_gap:
+ out = "gap"
+ else:
+ tail = resp.split("finished in", 1)[1] if "finished in" in resp else ""
+ ran = "exit 0." in tail
+ body = tail.split("exit 0.", 1)[1].split("\ncheck:", 1)[0].strip() if ran else ""
+ out = "correct" if (ran and body and (t["expect"] is None or t["expect"] in body)) else "wrong"
+ tally[out] += 1
+ rows.append({"id": t["id"], "outcome": out, "response": resp[-1500:]})
+ print("%s %-8s %s" % (t["id"], out, t["cmd"][:100]), flush=True)
+ok = tally["correct"] >= 9 and tally["wrong"] <= 1
+print("TALLY", tally, "BAR", "PASS" if ok else "FAIL")
+json.dump({"tally": tally, "bar_pass": ok, "rows": rows}, open(OUT, "w"), indent=1)
diff --git a/records/12/make_sealed_v1.json b/records/12/make_sealed_v1.json
new file mode 100644
index 0000000000000000000000000000000000000000..ad3998173a8f24797673b596c6db678a615c441f
--- /dev/null
+++ b/records/12/make_sealed_v1.json
@@ -0,0 +1,33 @@
+{
+ "about": "12.0 make, sealed set v1 (2026-11-08). Written before any run of make on these descriptions; run once. Outcome per task: correct (exit 0 and expect found in the output; tasks without expect: exit 0 and non-empty output), gap (make named a step it could not build and wrote nothing), wrong (ran but expect not found, empty output, or a crash). Bar: correct >= 14 of 20 and wrong <= 2.",
+ "files": {
+ "log.txt": "2026-11-07 09:00 INFO start\n2026-11-08 10:02 ERROR db timeout\n\n2026-11-08 10:05 WARN disk 91%\n2026-11-09 11:00 ERROR disk full\n2026-11-09 11:30 INFO retry\n2026-11-09 12:00 ERROR gave up\n",
+ "words.txt": "the apple and the banana and the cherry apple\n",
+ "prices.csv": "item,amount\na,10.0\nb,20.5\nc,30.0\n",
+ "people.json": "[{\"name\": \"Grace\", \"age\": 46}, {\"name\": \"Ada\", \"age\": 36}]\n",
+ "text.txt": "Contact bob@example.org or amy@example.org, bob@example.org again. See https://example.org/a and https://example.org/b. Costs 300 and 1000 for 5 days.\n",
+ "numbers.txt": "5\n1\n9\n3\n7\n"
+ },
+ "tasks": [
+ {"id": "s01", "make": "read log.txt, split into lines, keep lines containing ERROR, count them, print it", "expect": "3"},
+ {"id": "s02", "make": "read log.txt, split into lines, keep lines containing WARN, print them", "expect": "WARN disk 91%"},
+ {"id": "s03", "make": "read words.txt, split into words, make them lowercase, remove duplicates, sort them, print them", "expect": "banana"},
+ {"id": "s04", "make": "read prices.csv, parse it as csv, take the amount column, convert to numbers, sum them, print it", "expect": "60.5"},
+ {"id": "s05", "make": "read prices.csv, parse it as csv, take the amount column, convert to numbers, find the maximum, print it", "expect": "30.0"},
+ {"id": "s06", "make": "read people.json, take the name field, sort them, print them", "expect": "Ada"},
+ {"id": "s07", "make": "read people.json, take the age field, average them, print it", "expect": "41.0"},
+ {"id": "s08", "make": "read text.txt, extract the emails, remove duplicates, print them", "expect": "amy@example.org"},
+ {"id": "s09", "make": "read text.txt, extract the urls, count them, print it", "expect": "2"},
+ {"id": "s10", "make": "read text.txt, extract the numbers, keep those greater than 100, sum them, print it", "expect": "1300"},
+ {"id": "s11", "make": "read words.txt, split into words, keep words longer than 5, print them", "expect": "cherry"},
+ {"id": "s12", "make": "read log.txt, split into lines, remove empty lines, count them, print it", "expect": "6"},
+ {"id": "s13", "make": "read words.txt, split into words, count each word, sort by count descending, take the top 1, print them", "expect": "the"},
+ {"id": "s14", "make": "read text.txt, replace example with sample, write it to out.txt, print it", "expect": "sample.org"},
+ {"id": "s15", "make": "hash words.txt with sha256 and print it", "expect": null},
+ {"id": "s16", "make": "fetch https://simple.wikipedia.org/wiki/Moon, extract the numbers, count them, print it", "expect": null},
+ {"id": "s17", "make": "read log.txt, split into lines, keep lines starting with 2026-11-08, print them", "expect": "2026-11-08 10:02 ERROR db timeout"},
+ {"id": "s18", "make": "read prices.csv, parse it as csv, sort by amount descending, take the first 2, print them", "expect": "30.0"},
+ {"id": "s19", "make": "read log.txt, split into lines, take the last word of each line, count each word, print them", "expect": "up"},
+ {"id": "s20", "make": "read numbers.txt, split into lines, convert to numbers, compute the median, print it", "expect": "5"}
+ ]
+}
diff --git a/records/12/make_sealed_v1_result.json b/records/12/make_sealed_v1_result.json
new file mode 100644
index 0000000000000000000000000000000000000000..c081e9abb79ea17e863f103f0a2eba2b49224bd9
--- /dev/null
+++ b/records/12/make_sealed_v1_result.json
@@ -0,0 +1,110 @@
+{
+ "tally": {
+ "correct": 18,
+ "gap": 2,
+ "wrong": 0
+ },
+ "bar_pass": true,
+ "rows": [
+ {
+ "id": "s01",
+ "outcome": "correct",
+ "response": "Built s01.py from 5 steps:\n step 1: read log.txt -> x = open('log.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: keep lines containing ERROR -> x = [i for i in x if 'ERROR' in str(i)]\n step 4: count them -> x = len(x)\n step 5: print it -> print(x)\n\ndef main():\n x = None\n x = open('log.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [i for i in x if 'ERROR' in str(i)]\n x = len(x)\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns01.py finished in 0.0 s, exit 0.\n3"
+ },
+ {
+ "id": "s02",
+ "outcome": "correct",
+ "response": "Built s02.py from 4 steps:\n step 1: read log.txt -> x = open('log.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: keep lines containing WARN -> x = [i for i in x if 'WARN' in str(i)]\n step 4: print them -> print(\"\\n\".join(map(str, x)))\n\ndef main():\n x = None\n x = open('log.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [i for i in x if 'WARN' in str(i)]\n print(\"\\n\".join(map(str, x)))\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns02.py finished in 0.0 s, exit 0.\n2026-11-08 10:05 WARN disk 91%"
+ },
+ {
+ "id": "s03",
+ "outcome": "correct",
+ "response": "Built s03.py from 6 steps:\n step 1: read words.txt -> x = open('words.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into words -> x = re.findall(r\"[A-Za-z']+\", str(x))\n step 3: make them lowercase -> x = [str(i).lower() for i in x]\n step 4: remove duplicates -> x = list(dict.fromkeys(x))\n step 5: sort them -> x = sorted(x)\n step 6: print them -> print(\"\\n\".join(map(str, x)))\n\nimport re\n\n\n\ndef main():\n x = None\n x = open('words.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = re.findall(r\"[A-Za-z']+\", str(x))\n x = [str(i).lower() for i in x]\n x = list(dict.fromkeys(x))\n x = sorted(x)\n print(\"\\n\".join(map(str, x)))\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns03.py finished in 0.0 s, exit 0.\nand\napple\nbanana\ncherry\nthe"
+ },
+ {
+ "id": "s04",
+ "outcome": "correct",
+ "response": "Built s04.py from 6 steps:\n step 1: read prices.csv -> x = open('prices.csv', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: parse it as csv -> x = list(csv.DictReader(io.StringIO(str(x))))\n step 3: take the amount column -> x = [r['amount'] for r in x]\n step 4: convert to numbers -> x = [float(i) for i in x]\n step 5: sum them -> x = sum(float(i) for i in x)\n step 6: print it -> print(x)\n\nimport csv\nimport io\n\n\n\ndef main():\n x = None\n x = open('prices.csv', encoding=\"utf-8\", errors=\"ignore\").read()\n x = list(csv.DictReader(io.StringIO(str(x))))\n x = [r['amount'] for r in x]\n x = [float(i) for i in x]\n x = sum(float(i) for i in x)\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns04.py finished in 0.0 s, exit 0.\n60.5"
+ },
+ {
+ "id": "s05",
+ "outcome": "correct",
+ "response": "Built s05.py from 6 steps:\n step 1: read prices.csv -> x = open('prices.csv', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: parse it as csv -> x = list(csv.DictReader(io.StringIO(str(x))))\n step 3: take the amount column -> x = [r['amount'] for r in x]\n step 4: convert to numbers -> x = [float(i) for i in x]\n step 5: find the maximum -> x = max(x, key=lambda p: p[1]) if x and isinstance(x[0], tuple) else max(x)\n step 6: print it -> print(x)\n\nimport csv\nimport io\n\n\n\ndef main():\n x = None\n x = open('prices.csv', encoding=\"utf-8\", errors=\"ignore\").read()\n x = list(csv.DictReader(io.StringIO(str(x))))\n x = [r['amount'] for r in x]\n x = [float(i) for i in x]\n x = max(x, key=lambda p: p[1]) if x and isinstance(x[0], tuple) else max(x)\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns05.py finished in 0.0 s, exit 0.\n30.0"
+ },
+ {
+ "id": "s06",
+ "outcome": "correct",
+ "response": "Built s06.py from 4 steps:\n step 1: read people.json -> x = json.load(open('people.json'))\n step 2: take the name field -> x = [r['name'] for r in x]\n step 3: sort them -> x = sorted(x)\n step 4: print them -> print(\"\\n\".join(map(str, x)))\n\nimport json\n\n\n\ndef main():\n x = None\n x = json.load(open('people.json'))\n x = [r['name'] for r in x]\n x = sorted(x)\n print(\"\\n\".join(map(str, x)))\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns06.py finished in 0.0 s, exit 0.\nAda\nGrace"
+ },
+ {
+ "id": "s07",
+ "outcome": "correct",
+ "response": "Built s07.py from 4 steps:\n step 1: read people.json -> x = json.load(open('people.json'))\n step 2: take the age field -> x = [r['age'] for r in x]\n step 3: average them -> x = sum(float(i) for i in x) / len(x) if x else 0.0\n step 4: print it -> print(x)\n\nimport json\n\n\n\ndef main():\n x = None\n x = json.load(open('people.json'))\n x = [r['age'] for r in x]\n x = sum(float(i) for i in x) / len(x) if x else 0.0\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns07.py finished in 0.0 s, exit 0.\n41.0"
+ },
+ {
+ "id": "s08",
+ "outcome": "correct",
+ "response": "Built s08.py from 4 steps:\n step 1: read text.txt -> x = open('text.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: extract the emails -> x = [n for n in re.findall('[\\\\w.+-]+@[\\\\w-]+\\\\.[\\\\w.]+', str(x))]\n step 3: remove duplicates -> x = list(dict.fromkeys(x))\n step 4: print them -> print(\"\\n\".join(map(str, x)))\n\nimport re\n\n\n\ndef main():\n x = None\n x = open('text.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [n for n in re.findall('[\\\\w.+-]+@[\\\\w-]+\\\\.[\\\\w.]+', str(x))]\n x = list(dict.fromkeys(x))\n print(\"\\n\".join(map(str, x)))\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns08.py finished in 0.0 s, exit 0.\nbob@example.org\namy@example.org"
+ },
+ {
+ "id": "s09",
+ "outcome": "correct",
+ "response": "Built s09.py from 4 steps:\n step 1: read text.txt -> x = open('text.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: extract the urls -> x = [n for n in re.findall('https?://[^\\\\s\\\\\"\\'<>]+', str(x))]\n step 3: count them -> x = len(x)\n step 4: print it -> print(x)\n\nimport re\n\n\n\ndef main():\n x = None\n x = open('text.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [n for n in re.findall('https?://[^\\\\s\\\\\"\\'<>]+', str(x))]\n x = len(x)\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns09.py finished in 0.0 s, exit 0.\n2"
+ },
+ {
+ "id": "s10",
+ "outcome": "correct",
+ "response": "Built s10.py from 5 steps:\n step 1: read text.txt -> x = open('text.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: extract the numbers -> x = [float(n) for n in re.findall('(-?\\\\d+(?:\\\\.\\\\d+)?)', str(x))]\n step 3: keep those greater than 100 -> x = [i for i in x if float(i) > 100]\n step 4: sum them -> x = sum(float(i) for i in x)\n step 5: print it -> print(x)\n\nimport re\n\n\n\ndef main():\n x = None\n x = open('text.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [float(n) for n in re.findall('(-?\\\\d+(?:\\\\.\\\\d+)?)', str(x))]\n x = [i for i in x if float(i) > 100]\n x = sum(float(i) for i in x)\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns10.py finished in 0.0 s, exit 0.\n1300.0"
+ },
+ {
+ "id": "s11",
+ "outcome": "correct",
+ "response": "Built s11.py from 4 steps:\n step 1: read words.txt -> x = open('words.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into words -> x = re.findall(r\"[A-Za-z']+\", str(x))\n step 3: keep words longer than 5 -> x = [i for i in x if len(str(i)) > 5]\n step 4: print them -> print(\"\\n\".join(map(str, x)))\n\nimport re\n\n\n\ndef main():\n x = None\n x = open('words.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = re.findall(r\"[A-Za-z']+\", str(x))\n x = [i for i in x if len(str(i)) > 5]\n print(\"\\n\".join(map(str, x)))\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns11.py finished in 0.0 s, exit 0.\nbanana\ncherry"
+ },
+ {
+ "id": "s12",
+ "outcome": "correct",
+ "response": "Built s12.py from 5 steps:\n step 1: read log.txt -> x = open('log.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: remove empty lines -> x = [i for i in x if not (not str(i).strip())]\n step 4: count them -> x = len(x)\n step 5: print it -> print(x)\n\ndef main():\n x = None\n x = open('log.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [i for i in x if not (not str(i).strip())]\n x = len(x)\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns12.py finished in 0.0 s, exit 0.\n6"
+ },
+ {
+ "id": "s13",
+ "outcome": "correct",
+ "response": "Built s13.py from 6 steps:\n step 1: read words.txt -> x = open('words.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into words -> x = re.findall(r\"[A-Za-z']+\", str(x))\n step 3: count each word -> x = collections.Counter(x).most_common()\n step 4: sort by count descending -> x = sorted(x, key=lambda p: p[1], reverse=True)\n step 5: take the top 1 -> x = x[:1]\n step 6: print them -> print(\"\\n\".join(\"%s\\t%s\" % p for p in x))\n\nimport collections\nimport re\n\n\n\ndef main():\n x = None\n x = open('words.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = re.findall(r\"[A-Za-z']+\", str(x))\n x = collections.Counter(x).most_common()\n x = sorted(x, key=lambda p: p[1], reverse=True)\n x = x[:1]\n print(\"\\n\".join(\"%s\\t%s\" % p for p in x))\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns13.py finished in 0.0 s, exit 0.\nthe\t3"
+ },
+ {
+ "id": "s14",
+ "outcome": "correct",
+ "response": "Built s14.py from 4 steps:\n step 1: read text.txt -> x = open('text.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: replace example with sample -> x = str(x).replace('example', 'sample')\n step 3: write it to out.txt -> open('out.txt', \"w\").write(x if isinstance(x, str) else \"\\n\".join(map(str, x)))\n step 4: print it -> print(x)\n\ndef main():\n x = None\n x = open('text.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = str(x).replace('example', 'sample')\n open('out.txt', \"w\").write(x if isinstance(x, str) else \"\\n\".join(map(str, x)))\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns14.py finished in 0.0 s, exit 0.\nContact bob@sample.org or amy@sample.org, bob@sample.org again. See https://sample.org/a and https://sample.org/b. Costs 300 and 1000 for 5 days."
+ },
+ {
+ "id": "s15",
+ "outcome": "correct",
+ "response": "Built s15.py from 1 steps:\n step 1: hash words.txt with sha256 and print it -> x = hashlib.sha256(x if isinstance(x, bytes) else str(x).encode()).hexdigest()\n\nimport hashlib\n\n\n\ndef main():\n x = None\n x = open('words.txt', \"rb\").read()\n x = hashlib.sha256(x if isinstance(x, bytes) else str(x).encode()).hexdigest()\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns15.py finished in 0.0 s, exit 0.\n45a0deb5b5ff7a866d14b5367880913aa0b4fc51b1ff905f03d3e8c60abedacb"
+ },
+ {
+ "id": "s16",
+ "outcome": "correct",
+ "response": "s://simple.wikipedia.org/wiki/Moon -> x = fetch_text('https://simple.wikipedia.org/wiki/Moon')\n step 2: extract the numbers -> x = [float(n) for n in re.findall('(-?\\\\d+(?:\\\\.\\\\d+)?)', str(x))]\n step 3: count them -> x = len(x)\n step 4: print it -> print(x)\n\nimport re\nimport urllib.parse\nimport urllib.request\n\nVERIFIED = ['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']\n\ndef fetch_text(url):\n \"\"\"a page from the verified sources, as text\"\"\"\n host = urllib.parse.urlparse(url).netloc.lower()\n if host not in VERIFIED:\n raise ValueError(host + \" is not on the verified list\")\n req = urllib.request.Request(url, headers={\"User-Agent\": \"Oracle7-make/12.0\"})\n t = urllib.request.urlopen(req, timeout=30).read(5_000_000).decode(\"utf-8\", \"ignore\")\n m = re.search(r'(?s)id=\"mw-content-text\".*', t)\n t = m.group(0) if m else t\n t = re.sub(r\"(?is)<(script|style).*?\\1>\", \" \", t)\n return re.sub(r\"\\s+\", \" \", re.sub(r\"(?s)<[^>]+>\", \" \", t)).strip()\n\ndef main():\n x = None\n x = fetch_text('https://simple.wikipedia.org/wiki/Moon')\n x = [float(n) for n in re.findall('(-?\\\\d+(?:\\\\.\\\\d+)?)', str(x))]\n x = len(x)\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns16.py finished in 0.9 s, exit 0.\n540"
+ },
+ {
+ "id": "s17",
+ "outcome": "correct",
+ "response": "Built s17.py from 4 steps:\n step 1: read log.txt -> x = open('log.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: keep lines starting with 2026-11-08 -> x = [i for i in x if '2026-11-08' in str(i)]\n step 4: print them -> print(\"\\n\".join(map(str, x)))\n\ndef main():\n x = None\n x = open('log.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [i for i in x if '2026-11-08' in str(i)]\n print(\"\\n\".join(map(str, x)))\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns17.py finished in 0.0 s, exit 0.\n2026-11-08 10:02 ERROR db timeout\n2026-11-08 10:05 WARN disk 91%"
+ },
+ {
+ "id": "s18",
+ "outcome": "correct",
+ "response": "Built s18.py from 5 steps:\n step 1: read prices.csv -> x = open('prices.csv', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: parse it as csv -> x = list(csv.DictReader(io.StringIO(str(x))))\n step 3: sort by amount descending -> x = sorted(x, key=lambda r: r['amount'], reverse=True)\n step 4: take the first 2 -> x = x[:2]\n step 5: print them -> print(x)\n\nimport csv\nimport io\n\n\n\ndef main():\n x = None\n x = open('prices.csv', encoding=\"utf-8\", errors=\"ignore\").read()\n x = list(csv.DictReader(io.StringIO(str(x))))\n x = sorted(x, key=lambda r: r['amount'], reverse=True)\n x = x[:2]\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\ns18.py finished in 0.0 s, exit 0.\n[{'item': 'c', 'amount': '30.0'}, {'item': 'b', 'amount': '20.5'}]"
+ },
+ {
+ "id": "s19",
+ "outcome": "gap",
+ "response": "I could not build every step, so nothing was written:\n - step 3 (take the last word of each line): no move of the language does this and no workspace function fits it; nearest: hyphae (oracle7-release/release102/coverage102.py, 0.77); lower_first (oracle7-release/workbench/prosefold/core.py, 0.76); lower_first (oracle7-release/prosefold/prosefold_v1.py, 0.76)"
+ },
+ {
+ "id": "s20",
+ "outcome": "gap",
+ "response": "I could not build every step, so nothing was written:\n - step 4 (compute the median): no move of the language does this and no workspace function fits it; nearest: median (oracle7-release/specialists/statistics/stats_panel_v2.py, 0.63); median (oracle7-release/specialists/statistics/stats_panel_v3.py, 0.63); median (oracle7-release/specialists/statistics/stats_panel_v1.py, 0.63)"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/records/12/make_sealed_v2.json b/records/12/make_sealed_v2.json
new file mode 100644
index 0000000000000000000000000000000000000000..0b1b751dab7eee0e459753c8f12282cdca44b3bc
--- /dev/null
+++ b/records/12/make_sealed_v2.json
@@ -0,0 +1,33 @@
+{
+ "about": "12.0 make, sealed set v2 (2026-11-09). Written after make v2 and before any run of make on these descriptions; run once on the shipping code. Outcomes as v1: correct (exit 0 and expect found in the output; no expect: exit 0 and non-empty output), gap (a named step make could not build, nothing written), wrong (ran but expect not found, empty output, or a crash). Bar: correct >= 15 of 20 and wrong <= 2. Same hand wrote moves and set (stated weakness carried from v1).",
+ "files": {
+ "orders.csv": "id,customer,total,city\n1,ann,12.50,leeds\n2,bo,40.00,york\n3,ann,7.25,leeds\n4,cy,19.75,hull\n5,bo,3.00,york\n",
+ "events.log": "09:01 login ann\n09:05 upload bo\n09:07 login cy\n\n09:12 logout ann\n09:15 login bo\n09:20 error disk\n",
+ "poem.txt": "Shall I compare thee to a summer's day?\nThou art more lovely and more temperate.\nRough winds do shake the darling buds of May,\n",
+ "scores.json": "[{\"team\": \"red\", \"points\": 14}, {\"team\": \"blue\", \"points\": 9}, {\"team\": \"green\", \"points\": 21}]\n",
+ "mixed.txt": "Order 66 shipped on 2026-03-14, order 67 on 2026-04-02. Call 555 0101. Mail ops@shop.test or help@shop.test.\n",
+ "vals.txt": "12\n7\n3\n19\n8\n10\n"
+ },
+ "tasks": [
+ {"id": "v01", "make": "read orders.csv, parse it as csv, take the total column, convert to numbers, sum them, print it", "expect": "82.5"},
+ {"id": "v02", "make": "read orders.csv, parse it as csv, take the customer column, remove duplicates, count them, print it", "expect": "3"},
+ {"id": "v03", "make": "read orders.csv, parse it as csv, take the city column, count each word, print them", "expect": "leeds\t2"},
+ {"id": "v04", "make": "read events.log, split into lines, keep lines containing login, count them, print it", "expect": "3"},
+ {"id": "v05", "make": "read events.log, split into lines, take the last word of each line, remove duplicates, print them", "expect": "disk"},
+ {"id": "v06", "make": "read events.log, split into lines, for each line, take the first word, print them", "expect": "09:20"},
+ {"id": "v07", "make": "read poem.txt, split into lines, take the length of each line, find the maximum, print it", "expect": "45"},
+ {"id": "v08", "make": "read poem.txt, split it into words, make them lowercase, keep words longer than 6, remove duplicates, print them", "expect": "temperate"},
+ {"id": "v09", "make": "read poem.txt, split it into words, count them, print it", "expect": "24"},
+ {"id": "v10", "make": "read scores.json, take the points field, sum them, print it", "expect": "44"},
+ {"id": "v11", "make": "read scores.json, take the team field, sort them, print them", "expect": "blue"},
+ {"id": "v12", "make": "read mixed.txt, extract the emails, print them", "expect": "help@shop.test"},
+ {"id": "v13", "make": "read mixed.txt, extract the dates, count them, print it", "expect": "2"},
+ {"id": "v14", "make": "read mixed.txt, extract the numbers, keep those greater than 100, print them", "expect": "555"},
+ {"id": "v15", "make": "read vals.txt, split into lines, convert to numbers, compute the median, print it", "expect": "9"},
+ {"id": "v16", "make": "read vals.txt, split into lines, convert to numbers, sort them descending, take the top 2, print them", "expect": "19.0"},
+ {"id": "v17", "make": "read vals.txt, split into lines, convert to numbers, keep those less than 10, average them, print it", "expect": "6"},
+ {"id": "v18", "make": "read poem.txt, replace thee with you, write it to poem2.txt, print it", "expect": "compare you"},
+ {"id": "v19", "make": "read events.log, split into lines, remove empty lines, reverse them, take the first 1, print them", "expect": "error disk"},
+ {"id": "v20", "make": "read vals.txt, split into lines, convert to numbers, compute the standard deviation, print it", "expect": null}
+ ]
+}
diff --git a/records/12/make_sealed_v2_result.json b/records/12/make_sealed_v2_result.json
new file mode 100644
index 0000000000000000000000000000000000000000..bc5fa6bcaf6fe9b59d77fb632157112970456089
--- /dev/null
+++ b/records/12/make_sealed_v2_result.json
@@ -0,0 +1,110 @@
+{
+ "tally": {
+ "correct": 18,
+ "gap": 1,
+ "wrong": 1
+ },
+ "bar_pass": true,
+ "rows": [
+ {
+ "id": "v01",
+ "outcome": "correct",
+ "response": "Built v01.py from 6 steps:\n step 1: read orders.csv -> x = open('orders.csv', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: parse it as csv -> x = list(csv.DictReader(io.StringIO(str(x))))\n step 3: take the total column -> x = [r['total'] for r in x]\n step 4: convert to numbers -> x = [float(i) for i in x]\n step 5: sum them -> x = sum(float(i) for i in x)\n step 6: print it -> print(x)\n\nimport csv\nimport io\n\n\n\ndef main():\n x = None\n x = open('orders.csv', encoding=\"utf-8\", errors=\"ignore\").read()\n x = list(csv.DictReader(io.StringIO(str(x))))\n x = [r['total'] for r in x]\n x = [float(i) for i in x]\n x = sum(float(i) for i in x)\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv01.py finished in 0.0 s, exit 0.\n82.5"
+ },
+ {
+ "id": "v02",
+ "outcome": "correct",
+ "response": "Built v02.py from 6 steps:\n step 1: read orders.csv -> x = open('orders.csv', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: parse it as csv -> x = list(csv.DictReader(io.StringIO(str(x))))\n step 3: take the customer column -> x = [r['customer'] for r in x]\n step 4: remove duplicates -> x = list(dict.fromkeys(x))\n step 5: count them -> x = len(x)\n step 6: print it -> print(x)\n\nimport csv\nimport io\n\n\n\ndef main():\n x = None\n x = open('orders.csv', encoding=\"utf-8\", errors=\"ignore\").read()\n x = list(csv.DictReader(io.StringIO(str(x))))\n x = [r['customer'] for r in x]\n x = list(dict.fromkeys(x))\n x = len(x)\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv02.py finished in 0.0 s, exit 0.\n3"
+ },
+ {
+ "id": "v03",
+ "outcome": "correct",
+ "response": "Built v03.py from 5 steps:\n step 1: read orders.csv -> x = open('orders.csv', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: parse it as csv -> x = list(csv.DictReader(io.StringIO(str(x))))\n step 3: take the city column -> x = [r['city'] for r in x]\n step 4: count each word -> x = collections.Counter(x).most_common()\n step 5: print them -> print(\"\\n\".join(\"%s\\t%s\" % p for p in x))\n\nimport collections\nimport csv\nimport io\n\n\n\ndef main():\n x = None\n x = open('orders.csv', encoding=\"utf-8\", errors=\"ignore\").read()\n x = list(csv.DictReader(io.StringIO(str(x))))\n x = [r['city'] for r in x]\n x = collections.Counter(x).most_common()\n print(\"\\n\".join(\"%s\\t%s\" % p for p in x))\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv03.py finished in 0.0 s, exit 0.\nleeds\t2\nyork\t2\nhull\t1"
+ },
+ {
+ "id": "v04",
+ "outcome": "correct",
+ "response": "Built v04.py from 5 steps:\n step 1: read events.log -> x = open('events.log', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: keep lines containing login -> x = [i for i in x if 'login' in str(i)]\n step 4: count them -> x = len(x)\n step 5: print it -> print(x)\n\ndef main():\n x = None\n x = open('events.log', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [i for i in x if 'login' in str(i)]\n x = len(x)\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv04.py finished in 0.0 s, exit 0.\n3"
+ },
+ {
+ "id": "v05",
+ "outcome": "correct",
+ "response": "Built v05.py from 5 steps:\n step 1: read events.log -> x = open('events.log', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: take the last word of each line -> x = [each_1(i) for i in x]\n step 4: remove duplicates -> x = list(dict.fromkeys(x))\n step 5: print them -> print(\"\\n\".join(map(str, x)))\n\ndef each_1(x):\n x = (str(x).split() or [''])[-1]\n return x\n\ndef main():\n x = None\n x = open('events.log', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [each_1(i) for i in x]\n x = list(dict.fromkeys(x))\n print(\"\\n\".join(map(str, x)))\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv05.py finished in 0.0 s, exit 0.\nann\nbo\ncy\ndisk"
+ },
+ {
+ "id": "v06",
+ "outcome": "correct",
+ "response": "Built v06.py from 4 steps:\n step 1: read events.log -> x = open('events.log', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: for each line, take the first word -> x = [each_1(i) for i in x]\n step 4: print them -> print(\"\\n\".join(map(str, x)))\n\ndef each_1(x):\n x = (str(x).split() or [''])[0]\n return x\n\ndef main():\n x = None\n x = open('events.log', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [each_1(i) for i in x]\n print(\"\\n\".join(map(str, x)))\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv06.py finished in 0.0 s, exit 0.\n09:01\n09:05\n09:07\n09:12\n09:15\n09:20"
+ },
+ {
+ "id": "v07",
+ "outcome": "correct",
+ "response": "Built v07.py from 5 steps:\n step 1: read poem.txt -> x = open('poem.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: take the length of each line -> x = [each_1(i) for i in x]\n step 4: find the maximum -> x = max(x, key=lambda p: p[1]) if x and isinstance(x[0], tuple) else max(x)\n step 5: print it -> print(x)\n\ndef each_1(x):\n x = len(x)\n return x\n\ndef main():\n x = None\n x = open('poem.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [each_1(i) for i in x]\n x = max(x, key=lambda p: p[1]) if x and isinstance(x[0], tuple) else max(x)\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv07.py finished in 0.0 s, exit 0.\n45"
+ },
+ {
+ "id": "v08",
+ "outcome": "correct",
+ "response": "Built v08.py from 6 steps:\n step 1: read poem.txt -> x = open('poem.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split it into words -> x = re.findall(r\"[A-Za-z']+\", str(x))\n step 3: make them lowercase -> x = [str(i).lower() for i in x]\n step 4: keep words longer than 6 -> x = [i for i in x if len(str(i)) > 6]\n step 5: remove duplicates -> x = list(dict.fromkeys(x))\n step 6: print them -> print(\"\\n\".join(map(str, x)))\n\nimport re\n\n\n\ndef main():\n x = None\n x = open('poem.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = re.findall(r\"[A-Za-z']+\", str(x))\n x = [str(i).lower() for i in x]\n x = [i for i in x if len(str(i)) > 6]\n x = list(dict.fromkeys(x))\n print(\"\\n\".join(map(str, x)))\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv08.py finished in 0.0 s, exit 0.\ncompare\nsummer's\ntemperate\ndarling"
+ },
+ {
+ "id": "v09",
+ "outcome": "correct",
+ "response": "Built v09.py from 4 steps:\n step 1: read poem.txt -> x = open('poem.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split it into words -> x = re.findall(r\"[A-Za-z']+\", str(x))\n step 3: count them -> x = len(x)\n step 4: print it -> print(x)\n\nimport re\n\n\n\ndef main():\n x = None\n x = open('poem.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = re.findall(r\"[A-Za-z']+\", str(x))\n x = len(x)\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv09.py finished in 0.0 s, exit 0.\n24"
+ },
+ {
+ "id": "v10",
+ "outcome": "correct",
+ "response": "Built v10.py from 4 steps:\n step 1: read scores.json -> x = json.load(open('scores.json'))\n step 2: take the points field -> x = [r['points'] for r in x]\n step 3: sum them -> x = sum(float(i) for i in x)\n step 4: print it -> print(x)\n\nimport json\n\n\n\ndef main():\n x = None\n x = json.load(open('scores.json'))\n x = [r['points'] for r in x]\n x = sum(float(i) for i in x)\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv10.py finished in 0.0 s, exit 0.\n44.0"
+ },
+ {
+ "id": "v11",
+ "outcome": "correct",
+ "response": "Built v11.py from 4 steps:\n step 1: read scores.json -> x = json.load(open('scores.json'))\n step 2: take the team field -> x = [r['team'] for r in x]\n step 3: sort them -> x = sorted(x)\n step 4: print them -> print(\"\\n\".join(map(str, x)))\n\nimport json\n\n\n\ndef main():\n x = None\n x = json.load(open('scores.json'))\n x = [r['team'] for r in x]\n x = sorted(x)\n print(\"\\n\".join(map(str, x)))\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv11.py finished in 0.0 s, exit 0.\nblue\ngreen\nred"
+ },
+ {
+ "id": "v12",
+ "outcome": "correct",
+ "response": "Built v12.py from 3 steps:\n step 1: read mixed.txt -> x = open('mixed.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: extract the emails -> x = [n for n in re.findall('[\\\\w.+-]+@[\\\\w-]+\\\\.[\\\\w.]+', str(x))]\n step 3: print them -> print(\"\\n\".join(map(str, x)))\n\nimport re\n\n\n\ndef main():\n x = None\n x = open('mixed.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [n for n in re.findall('[\\\\w.+-]+@[\\\\w-]+\\\\.[\\\\w.]+', str(x))]\n print(\"\\n\".join(map(str, x)))\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv12.py finished in 0.0 s, exit 0.\nops@shop.test\nhelp@shop.test."
+ },
+ {
+ "id": "v13",
+ "outcome": "correct",
+ "response": "Built v13.py from 4 steps:\n step 1: read mixed.txt -> x = open('mixed.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: extract the dates -> x = [n for n in re.findall('\\\\d{4}-\\\\d{2}-\\\\d{2}', str(x))]\n step 3: count them -> x = len(x)\n step 4: print it -> print(x)\n\nimport re\n\n\n\ndef main():\n x = None\n x = open('mixed.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [n for n in re.findall('\\\\d{4}-\\\\d{2}-\\\\d{2}', str(x))]\n x = len(x)\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv13.py finished in 0.0 s, exit 0.\n2"
+ },
+ {
+ "id": "v14",
+ "outcome": "correct",
+ "response": "Built v14.py from 4 steps:\n step 1: read mixed.txt -> x = open('mixed.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: extract the numbers -> x = [float(n) for n in re.findall('(-?\\\\d+(?:\\\\.\\\\d+)?)', str(x))]\n step 3: keep those greater than 100 -> x = [i for i in x if float(i) > 100]\n step 4: print them -> print(\"\\n\".join(map(str, x)))\n\nimport re\n\n\n\ndef main():\n x = None\n x = open('mixed.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [float(n) for n in re.findall('(-?\\\\d+(?:\\\\.\\\\d+)?)', str(x))]\n x = [i for i in x if float(i) > 100]\n print(\"\\n\".join(map(str, x)))\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv14.py finished in 0.0 s, exit 0.\n2026.0\n2026.0\n555.0\n101.0"
+ },
+ {
+ "id": "v15",
+ "outcome": "correct",
+ "response": "Built v15.py from 5 steps:\n step 1: read vals.txt -> x = open('vals.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: convert to numbers -> x = [float(i) for i in x]\n workspace: median from oracle7-release/specialists/statistics/stats_panel_v1.py\n step 5: print it -> print(x)\n\nimport json\nimport math\nimport random\nimport sys\n\ndef median(a):\n b = sorted(a); n = len(b)\n return b[n // 2] if n % 2 else (b[n // 2 - 1] + b[n // 2]) / 2\n\ndef main():\n x = None\n x = open('vals.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [float(i) for i in x]\n x = median(x)\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv15.py finished in 0.0 s, exit 0.\n9.0"
+ },
+ {
+ "id": "v16",
+ "outcome": "correct",
+ "response": "Built v16.py from 6 steps:\n step 1: read vals.txt -> x = open('vals.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: convert to numbers -> x = [float(i) for i in x]\n step 4: sort them descending -> x = sorted(x, reverse=True)\n step 5: take the top 2 -> x = x[:2]\n step 6: print them -> print(\"\\n\".join(map(str, x)))\n\ndef main():\n x = None\n x = open('vals.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [float(i) for i in x]\n x = sorted(x, reverse=True)\n x = x[:2]\n print(\"\\n\".join(map(str, x)))\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv16.py finished in 0.0 s, exit 0.\n19.0\n12.0"
+ },
+ {
+ "id": "v17",
+ "outcome": "correct",
+ "response": "Built v17.py from 6 steps:\n step 1: read vals.txt -> x = open('vals.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: convert to numbers -> x = [float(i) for i in x]\n step 4: keep those less than 10 -> x = [i for i in x if float(i) < 10]\n step 5: average them -> x = sum(float(i) for i in x) / len(x) if x else 0.0\n step 6: print it -> print(x)\n\ndef main():\n x = None\n x = open('vals.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [float(i) for i in x]\n x = [i for i in x if float(i) < 10]\n x = sum(float(i) for i in x) / len(x) if x else 0.0\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv17.py finished in 0.0 s, exit 0.\n6.0"
+ },
+ {
+ "id": "v18",
+ "outcome": "correct",
+ "response": "Built v18.py from 4 steps:\n step 1: read poem.txt -> x = open('poem.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: replace thee with you -> x = str(x).replace('thee', 'you')\n step 3: write it to poem2.txt -> open('poem2.txt', \"w\").write(x if isinstance(x, str) else \"\\n\".join(map(str, x)))\n step 4: print it -> print(x)\n\ndef main():\n x = None\n x = open('poem.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = str(x).replace('thee', 'you')\n open('poem2.txt', \"w\").write(x if isinstance(x, str) else \"\\n\".join(map(str, x)))\n print(x)\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv18.py finished in 0.0 s, exit 0.\nShall I compare you to a summer's day?\nThou art more lovely and more temperate.\nRough winds do shake the darling buds of May,"
+ },
+ {
+ "id": "v19",
+ "outcome": "wrong",
+ "response": "Built v19.py from 5 steps:\n step 1: read events.log -> x = open('events.log', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: remove empty lines, reverse them -> x = [i for i in x if not (not str(i).strip())]\n step 4: take the first 1 -> x = x[:1]\n step 5: print them -> print(\"\\n\".join(map(str, x)))\n\ndef main():\n x = None\n x = open('events.log', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [i for i in x if not (not str(i).strip())]\n x = x[:1]\n print(\"\\n\".join(map(str, x)))\n return x\n\n\nif __name__ == \"__main__\":\n main()\nv19.py finished in 0.0 s, exit 0.\n09:01 login ann"
+ },
+ {
+ "id": "v20",
+ "outcome": "gap",
+ "response": "I could not build every step, so nothing was written:\n - step 4 (compute the standard deviation): no move of the language does this and no workspace function fits it; nearest: _compute_interaction_gradient (ensouled/protein/fold.py, 0.64); _c546_dims (oracle7-release/network4/oracle_release_runtime_w550.py, 0.58); _c546_dims (oracle7-release/network4/oracle_release_runtime_w549.py, 0.58)"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/records/12/make_sealed_v3.json b/records/12/make_sealed_v3.json
new file mode 100644
index 0000000000000000000000000000000000000000..26f05159aefcc1260f4f93bca4693fe84c23f202
--- /dev/null
+++ b/records/12/make_sealed_v3.json
@@ -0,0 +1,19 @@
+{
+ "about": "12.0 make, sealed set v3 (2026-11-09): branching, programs used by later programs, statistics moves, a workspace function with one required input and defaults. Written after make v3 and before any run on these descriptions; run once, in order, in one sandbox (w02 is used by w03 and w04). Expected values worked by hand: nums 2,4,4,4,5,5,7,9 -> sample stdev sqrt(32/7)=2.138, mode 4, population variance 32/8=4.0. Outcomes as v1. Bar: correct >= 8 of 10 and wrong <= 1.",
+ "files": {
+ "sys.log": "08:00 boot ok\n08:10 WARN temp high\n08:20 check ok\n08:30 WARN fan slow\n",
+ "nums.txt": "2\n4\n4\n4\n5\n5\n7\n9\n"
+ },
+ "tasks": [
+ {"id": "w01", "make": "read sys.log, split into lines, for each line, if it contains WARN, take the last word, otherwise take the first word, print them", "expect": "slow"},
+ {"id": "w02", "make": "read sys.log, split into lines, keep lines containing WARN, print them", "expect": "fan slow"},
+ {"id": "w03", "make": "use w02, count them, print it", "expect": "2"},
+ {"id": "w04", "make": "use w02, take the last word of each line, print them", "expect": "high"},
+ {"id": "w05", "make": "read nums.txt, split into lines, convert to numbers, compute the standard deviation, print it", "expect": "2.13"},
+ {"id": "w06", "make": "read nums.txt, split into lines, convert to numbers, find the mode, print it", "expect": "4"},
+ {"id": "w07", "make": "read nums.txt, split into lines, convert to numbers, compute the population variance, print it", "expect": "4.0"},
+ {"id": "w08", "make": "read nums.txt, split into lines, count them, compute the bound, print it", "expect": null},
+ {"id": "w09", "make": "read sys.log, split into lines, if it contains ok, take the first word, otherwise take the last word, print them", "expect": "08:20"},
+ {"id": "w10", "make": "read sys.log, split into words, keep words longer than 4, remove duplicates, sort them, print them", "expect": "check"}
+ ]
+}
diff --git a/records/12/make_sealed_v3_result.json b/records/12/make_sealed_v3_result.json
new file mode 100644
index 0000000000000000000000000000000000000000..87b73961d481372582a975d1a4fd90fd586e2a52
--- /dev/null
+++ b/records/12/make_sealed_v3_result.json
@@ -0,0 +1,60 @@
+{
+ "tally": {
+ "correct": 8,
+ "gap": 0,
+ "wrong": 2
+ },
+ "bar_pass": false,
+ "rows": [
+ {
+ "id": "w01",
+ "outcome": "correct",
+ "response": "Built w01.py from 4 steps:\n step 1: read sys.log -> x = open('sys.log', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3-5: for each line, if it contains WARN / take the last word / otherwise take the first word -> x = [branch_1(i) for i in x]\n step 6: print them -> print(\"\\n\".join(map(str, x)))\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\ndef branch_1(x):\n i = x\n if 'WARN' in str(i):\n x = (str(x).split() or [''])[-1]\n else:\n x = (str(x).split() or [''])[0]\n return x\n\n\ndef run(x=None):\n x = open('sys.log', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [branch_1(i) for i in x]\n _show(\"\\n\".join(map(str, x)))\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nw01.py finished in 0.0 s, exit 0.\n08:00\nhigh\n08:20\nslow"
+ },
+ {
+ "id": "w02",
+ "outcome": "correct",
+ "response": "Built w02.py from 4 steps:\n step 1: read sys.log -> x = open('sys.log', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: keep lines containing WARN -> x = [i for i in x if 'WARN' in str(i)]\n step 4: print them -> print(\"\\n\".join(map(str, x)))\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\n\n\n\ndef run(x=None):\n x = open('sys.log', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [i for i in x if 'WARN' in str(i)]\n _show(\"\\n\".join(map(str, x)))\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nw02.py finished in 0.0 s, exit 0.\n08:10 WARN temp high\n08:30 WARN fan slow"
+ },
+ {
+ "id": "w03",
+ "outcome": "correct",
+ "response": "Built w03.py from 3 steps:\n step 1: use w02 -> x = _use('w02', None)\n step 2: count them -> x = len(x)\n step 3: print it -> print(x)\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\ndef _use(name, x):\n \"\"\"another program made here, used as a step: its run() on this value, its own printing off\"\"\"\n import importlib, os, sys\n here = os.path.dirname(os.path.abspath(__file__))\n if here not in sys.path:\n sys.path.insert(0, here)\n m = importlib.import_module(name)\n m._SHOW = False\n return m.run(x)\n\n\ndef run(x=None):\n x = _use('w02', None)\n x = len(x)\n _show(x)\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nw03.py finished in 0.0 s, exit 0.\n2"
+ },
+ {
+ "id": "w04",
+ "outcome": "wrong",
+ "response": "The make did not complete: FileNotFoundError(2, 'No such file or directory')"
+ },
+ {
+ "id": "w05",
+ "outcome": "correct",
+ "response": "Built w05.py from 5 steps:\n step 1: read nums.txt -> x = open('nums.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: convert to numbers -> x = [float(i) for i in x]\n step 4: compute the standard deviation -> x = statistics.stdev([float(i) for i in x]) if len(x) > 1 else None\n step 5: print it -> print(x)\n\nimport statistics\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\n\n\n\ndef run(x=None):\n x = open('nums.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [float(i) for i in x]\n x = statistics.stdev([float(i) for i in x]) if len(x) > 1 else None\n _show(x)\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nw05.py finished in 0.0 s, exit 0.\n2.138089935299395"
+ },
+ {
+ "id": "w06",
+ "outcome": "correct",
+ "response": "Built w06.py from 5 steps:\n step 1: read nums.txt -> x = open('nums.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: convert to numbers -> x = [float(i) for i in x]\n step 4: find the mode -> x = statistics.mode([float(i) for i in x]) if x else None\n step 5: print it -> print(x)\n\nimport statistics\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\n\n\n\ndef run(x=None):\n x = open('nums.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [float(i) for i in x]\n x = statistics.mode([float(i) for i in x]) if x else None\n _show(x)\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nw06.py finished in 0.0 s, exit 0.\n4.0"
+ },
+ {
+ "id": "w07",
+ "outcome": "correct",
+ "response": "Built w07.py from 5 steps:\n step 1: read nums.txt -> x = open('nums.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: convert to numbers -> x = [float(i) for i in x]\n step 4: compute the population variance -> x = statistics.pvariance([float(i) for i in x]) if x else None\n step 5: print it -> print(x)\n\nimport statistics\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\n\n\n\ndef run(x=None):\n x = open('nums.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [float(i) for i in x]\n x = statistics.pvariance([float(i) for i in x]) if x else None\n _show(x)\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nw07.py finished in 0.0 s, exit 0.\n4.0"
+ },
+ {
+ "id": "w08",
+ "outcome": "wrong",
+ "response": "The make did not complete: FileNotFoundError(2, 'No such file or directory')"
+ },
+ {
+ "id": "w09",
+ "outcome": "correct",
+ "response": "Built w09.py from 4 steps:\n step 1: read sys.log -> x = open('sys.log', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3-5: if it contains ok / take the first word / otherwise take the last word -> x = [branch_1(i) for i in x]\n step 6: print them -> print(\"\\n\".join(map(str, x)))\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\ndef branch_1(x):\n i = x\n if 'ok' in str(i):\n x = (str(x).split() or [''])[0]\n else:\n x = (str(x).split() or [''])[-1]\n return x\n\n\ndef run(x=None):\n x = open('sys.log', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [branch_1(i) for i in x]\n _show(\"\\n\".join(map(str, x)))\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nw09.py finished in 0.0 s, exit 0.\n08:00\nhigh\n08:20\nslow"
+ },
+ {
+ "id": "w10",
+ "outcome": "correct",
+ "response": "Built w10.py from 6 steps:\n step 1: read sys.log -> x = open('sys.log', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into words -> x = re.findall(r\"[A-Za-z']+\", str(x))\n step 3: keep words longer than 4 -> x = [i for i in x if len(str(i)) > 4]\n step 4: remove duplicates -> x = list(dict.fromkeys(x))\n step 5: sort them -> x = sorted(x)\n step 6: print them -> print(\"\\n\".join(map(str, x)))\n\nimport re\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\n\n\n\ndef run(x=None):\n x = open('sys.log', encoding=\"utf-8\", errors=\"ignore\").read()\n x = re.findall(r\"[A-Za-z']+\", str(x))\n x = [i for i in x if len(str(i)) > 4]\n x = list(dict.fromkeys(x))\n x = sorted(x)\n _show(\"\\n\".join(map(str, x)))\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nw10.py finished in 0.0 s, exit 0.\ncheck"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/records/12/make_sealed_v4.json b/records/12/make_sealed_v4.json
new file mode 100644
index 0000000000000000000000000000000000000000..70580c1b190b2371699852f0a1a209465f5b8cad
--- /dev/null
+++ b/records/12/make_sealed_v4.json
@@ -0,0 +1,20 @@
+{
+ "about": "12.0 make, sealed set v4 (2026-11-09), after the v3 failure and its two fixes; new files and descriptions, never run before this. Run once, in order, in one sandbox (x03 is used by x04 and x05). Expected values worked by hand: qty 3+0+12+5=20; temps 12,18,15,21,9 -> median 15, sample variance 90/4=22.5; sku branch A1->1, B2->2, C3->c3, D4->4. Outcomes as v1. Bar: correct >= 8 of 10 and wrong <= 1.",
+ "files": {
+ "inv.csv": "sku,qty,price\nA1,3,2.50\nB2,0,9.99\nC3,12,1.25\nD4,5,4.00\n",
+ "notes.log": "mon fix login bug\ntue DONE deploy api\nwed review docs\nthu DONE fix cache\n",
+ "temps.txt": "12\n18\n15\n21\n9\n"
+ },
+ "tasks": [
+ {"id": "x01", "make": "read inv.csv, parse it as csv, take the qty column, convert to numbers, sum them, print it", "expect": "20"},
+ {"id": "x02", "make": "read inv.csv, parse it as csv, take the sku column, for each item, if it starts with C, make it lowercase, otherwise take the last 1 characters, print them", "expect": "c3"},
+ {"id": "x03", "make": "read notes.log, split into lines, keep lines containing DONE, print them", "expect": "DONE fix cache"},
+ {"id": "x04", "make": "use x03, count them, print it", "expect": "2"},
+ {"id": "x05", "make": "use x03, take the first word of each line, print them", "expect": "thu"},
+ {"id": "x06", "make": "read temps.txt, split into lines, convert to numbers, compute the median, print it", "expect": "15"},
+ {"id": "x07", "make": "read temps.txt, split into lines, convert to numbers, compute the variance, print it", "expect": "22.5"},
+ {"id": "x08", "make": "read temps.txt, split into lines, convert to numbers, for each number, if it is less than 13, replace 9 with nine, print them", "expect": "nine.0"},
+ {"id": "x09", "make": "read notes.log, split into words, keep words longer than 5, remove duplicates, print them", "expect": "review"},
+ {"id": "x10", "make": "read notes.log, split into lines, count them, compute the bound, print it", "expect": null}
+ ]
+}
diff --git a/records/12/make_sealed_v4_result.json b/records/12/make_sealed_v4_result.json
new file mode 100644
index 0000000000000000000000000000000000000000..2a95d5d7eb041016dd01e0c7acd6f417a70149fd
--- /dev/null
+++ b/records/12/make_sealed_v4_result.json
@@ -0,0 +1,60 @@
+{
+ "tally": {
+ "correct": 10,
+ "gap": 0,
+ "wrong": 0
+ },
+ "bar_pass": true,
+ "rows": [
+ {
+ "id": "x01",
+ "outcome": "correct",
+ "response": "Built x01.py from 6 steps:\n step 1: read inv.csv -> x = open('inv.csv', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: parse it as csv -> x = list(csv.DictReader(io.StringIO(str(x))))\n step 3: take the qty column -> x = [r['qty'] for r in x]\n step 4: convert to numbers -> x = [float(i) for i in x]\n step 5: sum them -> x = sum(float(i) for i in x)\n step 6: print it -> print(x)\n\nimport csv\nimport io\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\n\n\n\ndef run(x=None):\n x = open('inv.csv', encoding=\"utf-8\", errors=\"ignore\").read()\n x = list(csv.DictReader(io.StringIO(str(x))))\n x = [r['qty'] for r in x]\n x = [float(i) for i in x]\n x = sum(float(i) for i in x)\n _show(x)\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nx01.py finished in 0.0 s, exit 0.\n20.0"
+ },
+ {
+ "id": "x02",
+ "outcome": "correct",
+ "response": "Built x02.py from 5 steps:\n step 1: read inv.csv -> x = open('inv.csv', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: parse it as csv -> x = list(csv.DictReader(io.StringIO(str(x))))\n step 3: take the sku column -> x = [r['sku'] for r in x]\n step 4-6: for each item, if it starts with C / make it lowercase / otherwise take the last 1 characters -> x = [branch_1(i) for i in x]\n step 7: print them -> print(\"\\n\".join(map(str, x)))\n\nimport csv\nimport io\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\ndef branch_1(x):\n i = x\n if str(i).startswith('C'):\n x = str(x).lower()\n else:\n x = str(x)[-1:]\n return x\n\n\ndef run(x=None):\n x = open('inv.csv', encoding=\"utf-8\", errors=\"ignore\").read()\n x = list(csv.DictReader(io.StringIO(str(x))))\n x = [r['sku'] for r in x]\n x = [branch_1(i) for i in x]\n _show(\"\\n\".join(map(str, x)))\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nx02.py finished in 0.0 s, exit 0.\n1\n2\nc3\n4"
+ },
+ {
+ "id": "x03",
+ "outcome": "correct",
+ "response": "Built x03.py from 4 steps:\n step 1: read notes.log -> x = open('notes.log', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: keep lines containing DONE -> x = [i for i in x if 'DONE' in str(i)]\n step 4: print them -> print(\"\\n\".join(map(str, x)))\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\n\n\n\ndef run(x=None):\n x = open('notes.log', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [i for i in x if 'DONE' in str(i)]\n _show(\"\\n\".join(map(str, x)))\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nx03.py finished in 0.0 s, exit 0.\ntue DONE deploy api\nthu DONE fix cache"
+ },
+ {
+ "id": "x04",
+ "outcome": "correct",
+ "response": "Built x04.py from 3 steps:\n step 1: use x03 -> x = _use('x03', None)\n step 2: count them -> x = len(x)\n step 3: print it -> print(x)\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\ndef _use(name, x):\n \"\"\"another program made here, used as a step: its run() on this value, its own printing off\"\"\"\n import importlib, os, sys\n here = os.path.dirname(os.path.abspath(__file__))\n if here not in sys.path:\n sys.path.insert(0, here)\n m = importlib.import_module(name)\n m._SHOW = False\n return m.run(x)\n\n\ndef run(x=None):\n x = _use('x03', None)\n x = len(x)\n _show(x)\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nx04.py finished in 0.0 s, exit 0.\n2"
+ },
+ {
+ "id": "x05",
+ "outcome": "correct",
+ "response": "Built x05.py from 3 steps:\n step 1: use x03 -> x = _use('x03', None)\n step 2: take the first word of each line -> x = [each_2(i) for i in x]\n step 3: print them -> print(\"\\n\".join(map(str, x)))\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\ndef _use(name, x):\n \"\"\"another program made here, used as a step: its run() on this value, its own printing off\"\"\"\n import importlib, os, sys\n here = os.path.dirname(os.path.abspath(__file__))\n if here not in sys.path:\n sys.path.insert(0, here)\n m = importlib.import_module(name)\n m._SHOW = False\n return m.run(x)\n\ndef each_2(x):\n x = (str(x).split() or [''])[0]\n return x\n\n\ndef run(x=None):\n x = _use('x03', None)\n x = [each_2(i) for i in x]\n _show(\"\\n\".join(map(str, x)))\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nx05.py finished in 0.0 s, exit 0.\ntue\nthu"
+ },
+ {
+ "id": "x06",
+ "outcome": "correct",
+ "response": "Built x06.py from 5 steps:\n step 1: read temps.txt -> x = open('temps.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: convert to numbers -> x = [float(i) for i in x]\n step 4: compute the median -> x = statistics.median([float(i) for i in x]) if x else None\n step 5: print it -> print(x)\n\nimport statistics\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\n\n\n\ndef run(x=None):\n x = open('temps.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [float(i) for i in x]\n x = statistics.median([float(i) for i in x]) if x else None\n _show(x)\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nx06.py finished in 0.0 s, exit 0.\n15.0"
+ },
+ {
+ "id": "x07",
+ "outcome": "correct",
+ "response": "Built x07.py from 5 steps:\n step 1: read temps.txt -> x = open('temps.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: convert to numbers -> x = [float(i) for i in x]\n step 4: compute the variance -> x = statistics.variance([float(i) for i in x]) if len(x) > 1 else None\n step 5: print it -> print(x)\n\nimport statistics\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\n\n\n\ndef run(x=None):\n x = open('temps.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [float(i) for i in x]\n x = statistics.variance([float(i) for i in x]) if len(x) > 1 else None\n _show(x)\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nx07.py finished in 0.0 s, exit 0.\n22.5"
+ },
+ {
+ "id": "x08",
+ "outcome": "correct",
+ "response": "Built x08.py from 5 steps:\n step 1: read temps.txt -> x = open('temps.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: convert to numbers -> x = [float(i) for i in x]\n step 4-5: for each number, if it is less than 13 / replace 9 with nine -> x = [branch_1(i) for i in x]\n step 6: print them -> print(\"\\n\".join(map(str, x)))\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\ndef branch_1(x):\n i = x\n if float(i) < 13:\n x = str(x).replace('9', 'nine')\n return x\n\n\ndef run(x=None):\n x = open('temps.txt', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = [float(i) for i in x]\n x = [branch_1(i) for i in x]\n _show(\"\\n\".join(map(str, x)))\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nx08.py finished in 0.0 s, exit 0.\n12.0\n18.0\n15.0\n21.0\nnine.0"
+ },
+ {
+ "id": "x09",
+ "outcome": "correct",
+ "response": "Built x09.py from 5 steps:\n step 1: read notes.log -> x = open('notes.log', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into words -> x = re.findall(r\"[A-Za-z']+\", str(x))\n step 3: keep words longer than 5 -> x = [i for i in x if len(str(i)) > 5]\n step 4: remove duplicates -> x = list(dict.fromkeys(x))\n step 5: print them -> print(\"\\n\".join(map(str, x)))\n\nimport re\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\n\n\n\ndef run(x=None):\n x = open('notes.log', encoding=\"utf-8\", errors=\"ignore\").read()\n x = re.findall(r\"[A-Za-z']+\", str(x))\n x = [i for i in x if len(str(i)) > 5]\n x = list(dict.fromkeys(x))\n _show(\"\\n\".join(map(str, x)))\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nx09.py finished in 0.0 s, exit 0.\ndeploy\nreview"
+ },
+ {
+ "id": "x10",
+ "outcome": "correct",
+ "response": "Built x10.py from 5 steps:\n step 1: read notes.log -> x = open('notes.log', encoding=\"utf-8\", errors=\"ignore\").read()\n step 2: split into lines -> x = [l for l in str(x).splitlines() if l.strip()]\n step 3: count them -> x = len(x)\n workspace: bound from oracle7-release/release105/examiner105.py\n step 5: print it -> print(x)\n\nimport hashlib\nimport json\nimport math\nimport sys\n\n_SHOW = True\n\n\ndef _show(v):\n if _SHOW:\n print(v)\n\n\ndef bound(n, k=0):\n \"\"\"the 95% upper bound on the error rate, from k failures in n (exact, by bisection)\"\"\"\n lo, hi = 0.0, 1.0\n for _ in range(60):\n m = (lo + hi) / 2\n tail = sum(math.comb(n, i) * m ** i * (1 - m) ** (n - i) for i in range(k + 1))\n lo, hi = (m, hi) if tail > 0.05 else (lo, m)\n return hi\n\n\ndef run(x=None):\n x = open('notes.log', encoding=\"utf-8\", errors=\"ignore\").read()\n x = [l for l in str(x).splitlines() if l.strip()]\n x = len(x)\n x = bound(x)\n _show(x)\n return x\n\n\ndef main():\n return run(None)\n\n\nif __name__ == \"__main__\":\n main()\nx10.py finished in 0.0 s, exit 0.\n0.5271291954984121"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/records/12/make_sealed_v5.json b/records/12/make_sealed_v5.json
new file mode 100644
index 0000000000000000000000000000000000000000..8512bdd962628d9cc521a619cfc053a40fdfa1cd
--- /dev/null
+++ b/records/12/make_sealed_v5.json
@@ -0,0 +1,20 @@
+{
+ "about": "12.0 make, sealed set v5 (2026-11-09): programs of several functions, the repair loop, pages, servers, change. Written after these were built and before any run on these commands; run once, in order, in one sandbox (z07 changes script.py, z08 changes it again). Expected values worked by hand: amounts 10,25,5,40 -> max 40, sample stdev sqrt(750/3)=15.81, mean 20; sales2 $1,000+$250+$5 = 1255 (needs three repairs: file name case, column name, written numbers). Outcomes: correct (exit 0 and expect found after the run line; tasks marked in_response: expect anywhere in the reply; tasks marked gap: the reply names a gap and writes nothing), gap (an unexpected gap), wrong (anything else). Bar: correct >= 9 of 10 and wrong <= 1.",
+ "files": {
+ "sales.csv": "region,amount\nnorth,10\nsouth,25\neast,5\nwest,40\n",
+ "sales2.csv": "Region,Total Amount\nnorth,\"$1,000\"\nsouth,$250\n\neast,$5\n",
+ "script.py": "total = 0\nfor n in [1, 2, 3]:\n total += n\nprint('total', total)\nprint('debug line')\n"
+ },
+ "tasks": [
+ {"id": "z01", "cmd": "make z01: function biggest: parse it as csv, take the amount column, convert to numbers, find the maximum; function smallest: parse it as csv, take the amount column, convert to numbers, find the minimum; main: read sales.csv, biggest it, print it", "expect": "40.0"},
+ {"id": "z02", "cmd": "make z02: function amounts: parse it as csv, take the amount column, convert to numbers; function spread: compute the standard deviation; main: read sales.csv, amounts it, spread it, print it", "expect": "15.81"},
+ {"id": "z03", "cmd": "make z03: read Sales2.csv, parse it as csv, take the amount column, convert to numbers, sum them, print it", "expect": "1255"},
+ {"id": "z04", "cmd": "make z04: read sales.csv, parse it as csv, take the Amount column, convert to numbers, average them, print it", "expect": "20.0"},
+ {"id": "z05", "cmd": "make z05: read sales.csv, parse it as csv, make a page called report", "expect": "page written: report.html"},
+ {"id": "z06", "cmd": "make z06: read sales.csv, parse it as csv, take the region column, serve it on port 8781", "expect": "west"},
+ {"id": "z07", "cmd": "change script.py: replace [1, 2, 3] with [1, 2, 3, 4]; delete lines containing debug", "expect": "total 10"},
+ {"id": "z08", "cmd": "change script.py: rename total to grand; add print('ok') at the end", "expect": "total 10\nok"},
+ {"id": "z09", "cmd": "change tools/build_oracle_paper.py: rename sha256 to digest", "expect": "Not run", "in_response": true},
+ {"id": "z10", "cmd": "make z10: read sales.csv, train a neural network on it, print it", "expect": null, "gap": true}
+ ]
+}
diff --git a/records/12/make_sealed_v5_result.json b/records/12/make_sealed_v5_result.json
new file mode 100644
index 0000000000000000000000000000000000000000..8e91ae71634848e88a5dd4a0c4b0fdc9d36abf60
--- /dev/null
+++ b/records/12/make_sealed_v5_result.json
@@ -0,0 +1,60 @@
+{
+ "tally": {
+ "correct": 9,
+ "gap": 0,
+ "wrong": 1
+ },
+ "bar_pass": true,
+ "rows": [
+ {
+ "id": "z01",
+ "outcome": "correct",
+ "response": "Built z01.py (11 steps, 39 lines; read z01.py to see it):\n biggest 1. parse it as csv\n biggest 2. take the amount column\n biggest 3. convert to numbers\n biggest 4. find the maximum\n smallest 1. parse it as csv\n smallest 2. take the amount column\n smallest 3. convert to numbers\n smallest 4. find the minimum\n 1. read sales.csv\n 2. biggest it\n 3. print it\n\nRan: z01.py finished in 0.0 s, exit 0.\n40.0"
+ },
+ {
+ "id": "z02",
+ "outcome": "correct",
+ "response": "Built z02.py (8 steps, 37 lines; read z02.py to see it):\n amounts 1. parse it as csv\n amounts 2. take the amount column\n amounts 3. convert to numbers\n spread 1. compute the standard deviation\n 1. read sales.csv\n 2. amounts it\n 3. spread it\n 4. print it\n\nRan: z02.py finished in 0.0 s, exit 0.\n15.811388300841896"
+ },
+ {
+ "id": "z03",
+ "outcome": "correct",
+ "response": "Built z03.py (7 steps, 54 lines; read z03.py to see it):\n 1. read Sales2.csv\n 2. parse it as csv\n 3. take the amount column\n 4. convert to numbers\n 5. sum them\n 6. print it\n repaired: there is no Sales2.csv in the sandbox; used sales2.csv | the column 'amount' is not a header of the file; read it as the nearest header | some values were not plain numbers; read them as people write numbers ($, commas, %, units) and skip blanks\n\nRan: z03.py finished in 0.0 s, exit 0.\n1255.0"
+ },
+ {
+ "id": "z04",
+ "outcome": "correct",
+ "response": "Built z04.py (7 steps, 45 lines; read z04.py to see it):\n 1. read sales.csv\n 2. parse it as csv\n 3. take the Amount column\n 4. convert to numbers\n 5. average them\n 6. print it\n repaired: the column 'Amount' is not a header of the file; read it as the nearest header\n\nRan: z04.py finished in 0.0 s, exit 0.\n20.0"
+ },
+ {
+ "id": "z05",
+ "outcome": "correct",
+ "response": "Built z05.py (3 steps, 45 lines; read z05.py to see it):\n 1. read sales.csv\n 2. parse it as csv\n 3. make a page called report\n\nRan: z05.py finished in 0.0 s, exit 0.\npage written: report.html\n[{'region': 'north', 'amount': '10'}, {'region': 'south', 'amount': '25'}, {'region': 'east', 'amount': '5'}, {'region': 'west', 'amount': '40'}]"
+ },
+ {
+ "id": "z06",
+ "outcome": "correct",
+ "response": "Built z06.py (4 steps, 64 lines; read z06.py to see it):\n 1. read sales.csv\n 2. parse it as csv\n 3. take the region column\n 4. serve it on port 8781\n\nRan: z06.py finished in 0.6 s, exit 0.\nserved on http://127.0.0.1:8781/ and answered itself: [\n \"north\",\n \"south\",\n \"east\",\n \"west\"\n]\n(run it with --serve to keep it up)"
+ },
+ {
+ "id": "z07",
+ "outcome": "correct",
+ "response": "Changed script.py in the sandbox:\n - replaced '[1, 2, 3]' with '[1, 2, 3, 4]' (1 place)\n - deleted 1 line containing 'debug'\n\nRan: script.py finished in 0.0 s, exit 0.\ntotal 10"
+ },
+ {
+ "id": "z08",
+ "outcome": "correct",
+ "response": "Changed script.py in the sandbox:\n - renamed total to grand (3 places)\n - added print('ok') at the end\n\nRan: script.py finished in 0.0 s, exit 0.\ntotal 10\nok"
+ },
+ {
+ "id": "z09",
+ "outcome": "correct",
+ "response": "Changed build_oracle_paper.py in the sandbox (a copy; your original is untouched):\n - renamed sha256 to digest (6 places)\n\nNot run (it came from your code). Type run build_oracle_paper.py to run it in the sandbox."
+ },
+ {
+ "id": "z10",
+ "outcome": "wrong",
+ "response": "Built z10.py (4 steps, 102 lines; read z10.py to see it):\n 1. read sales.csv\n workspace: train from wander-train/foldedforms_learn_hom_verify.py\n 3. print it\n repaired: could not repair: ModuleNotFoundError: No module named 'torch'\n\nRan: z10.py finished in 0.0 s, exit 1.\nerrors:\nTraceback (most recent call last):\n File \"/opt/o7conv/sbx_sealed5/z10.py\", line 1, in \n import torch\nModuleNotFoundError: No module named 'torch'\nit did not run cleanly; the error is above, and the program stays in the sandbox to fix"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/records/12/parts_heldout.txt b/records/12/parts_heldout.txt
new file mode 100644
index 0000000000000000000000000000000000000000..4c5d47189f6ef2e48b8691f0944ddd67d2bd308b
--- /dev/null
+++ b/records/12/parts_heldout.txt
@@ -0,0 +1,72 @@
+pages 6000
+claims_worded_by_people 3450
+relation_has_parts 3187
+person_wording_free_words 285
+person_wording_admitted 866
+person_wording_first 460
+unworded_claims_tried 3666
+unworded_claims_said 1200
+said_with_a_second_claim_owned 19
+mutant_written 56
+mutant_refused 56
+mutant_refused_as_its_own_claim 56
+ Navy is a type of military branch.
+ Benito Mussolini won Knight Grand Cross of the Military Order of Savoy.
+ Galileo Galilei worked as a mathematician.
+ Creativity should not be confused with creative labor.
+ Albert Einstein won honorary doctorate from Princeton University.
+ Kylie Minogue was the partner of Joshua Sasse.
+ Charles Dickens worked as a children's writer.
+ Viktor Yushchenko won Chatham House Prize.
+ Travel is a type of intentional human activity.
+ Vladimir Lenin was born in Ulyanovsk.
+ Socrates worked as an ethicist.
+ Robert II of France was married to Bertha of Burgundy.
+ Albert Einstein is the brother of Maja Einstein.
+ Sherlock Holmes is played by Matt Frewer.
+ Fruit is a type of plant-based food.
+ Sherlock Holmes first appeared in The Treasures of Agra.
+ Plato should not be confused with Pseudo-Plato.
+ Hilary Swank worked as a television actor.
+ Circle is a type of analytic manifold.
+ Natural resource is a type of environmental resource.
+ Bed is a type of reclining furniture.
+ Benito Mussolini was partners with Margherita Sarfatti.
+ Tutankhamun is the brother of Meritaten Tasherit.
+ Gwyneth Paltrow won Golden Globe Award for Best Actress in a Motion Picture – Musical or Comedy.
+ Vladimir Lenin speaks German.
+ Wigan Athletic F.C. competes in EFL League One.
+ Computer science is a type of formal science.
+ House is a type of shelter.
+ Quantity should not be confused with ordinal quantity.
+ Benito Mussolini won Knight grand cross of the order of the crown of Italy.
+ Town should not be confused with big city.
+ Suffix is the opposite of prefix.
+ Vietnam borders the People's Republic of China.
+ Abraham Lincoln was born at Sinking Spring Farm.
+ Socrates is the brother of Patrocles.
+ Plato wrote the book Rival Lovers.
+ Computer program should not be confused with process.
+ Vladimir Lenin speaks Russian.
+ West Ham United F.C. competes in EFL Championship.
+ Time limit should not be confused with Frist.
+ Kylie Minogue won Australian National Living Treasure.
+ Pencil was discovered by Nicolas-Jacques Conté.
+ Electron is the opposite of electron hole.
+ Vladimir Lenin worked in the field of politics.
+ Fawlty Towers originated in the United Kingdom.
+ Galileo Galilei worked at University of Padua.
+ Gwyneth Paltrow worked as a musician.
+ Sherlock Holmes is played by Peter Cushing.
+ Benito Mussolini was the father of Bruno Mussolini.
+ English should not be confused with Inglés.
+ Building should not be confused with built structure.
+ Apple Inc. is listed on Nasdaq.
+ Vladimir Lenin worked as a politician.
+ Table salt is a type of food ingredient.
+ America (disambiguation) should not be confused with America.
+ Anders Celsius worked as a chemist.
+ Animal is the type kingdom.
+ Sherlock Holmes first appeared in Arsène Lupin, Gentleman Burglar.
+ Viktor Yushchenko won St. George's Order of Victory.
+ Building is a type of built structure.
diff --git a/records/12/parts_paragraphs.txt b/records/12/parts_paragraphs.txt
new file mode 100644
index 0000000000000000000000000000000000000000..1ddaa6eb4e2ef034df97929fbb5fb3ea6c8c465b
--- /dev/null
+++ b/records/12/parts_paragraphs.txt
@@ -0,0 +1,12 @@
+Marie Curie -> Marie Curie was born in Warsaw. [wd:Q7186 P19] She studied at Flying University. [wd:Q7186 P69] She has been a professor. [wd:Q7186 P39] She won Nobel Prize in Physics. [wd:Q7186 P166] She was married to Pierre Curie. [wd:Q7186 P26] She worked as a physicist. [wd:Q7186 P106]
+Canberra -> Canberra is a city. [wd:Q3114 P31] It is a city in Australia. [wd:Q3114 P17] It is the capital of Australia. [wd:Q3114 P1376] It is a sister city of Beijing. [wd:Q3114 P190]
+Cello -> Cello is a type of necked box lute played with a bow. [wd:Q8371 P279]
+Portugal -> Portugal borders Spain. [wd:Q45 P47]
+The Godfather -> The Godfather starred Marlon Brando. [wd:Q47703 P161] It was directed by Francis Ford Coppola. [wd:Q47703 P57] It was distributed by Paramount Pictures. [wd:Q47703 P750] It is set in New York City. [wd:Q47703 P840] It was followed by The Godfather Part II. [wd:Q47703 P156] It was composed by Nino Rota. [wd:Q47703 P86]
+Photosynthesis -> Photosynthesis is a type of cell metabolism. [wd:Q11982 P279]
+Mount Everest -> Mount Everest is named after George Everest. [wd:Q513 P138] It should not be confused with Everest. [wd:Q513 P1889]
+Tokyo -> Tokyo is a metropolis. [wd:Q1490 P31] It is a city in Japan. [wd:Q1490 P17] It is the capital of Japan. [wd:Q1490 P1376] It is bordered by Chiba Prefecture. [wd:Q1490 P47] It should not be confused with Tokio. [wd:Q1490 P1889] It is a sister city of Rome. [wd:Q1490 P190]
+Abraham Lincoln -> Abraham Lincoln was born at Sinking Spring Farm. [wd:Q91 P19] He was a member of Republican Party. [wd:Q91 P102] He has been President-elect of the United States. [wd:Q91 P39] He was married to Mary Todd Lincoln. [wd:Q91 P26] He worked as a writer. [wd:Q91 P106] He was the son of Thomas Lincoln. [wd:Q91 P22]
+George Eliot -> George Eliot is from Nuneaton. [wd:Q131333 P19] She studied at Royal Holloway, University of London. [wd:Q131333 P69] She worked as a writer. [wd:Q131333 P106] She died in London. [wd:Q131333 P20] She died of kidney disease. [wd:Q131333 P509] She worked in the field of philosophy. [wd:Q131333 P101]
+Albert Einstein -> Albert Einstein was born in Ulm. [wd:Q937 P19] He was a member of German Democratic Party. [wd:Q937 P102] He went to ETH Zurich. [wd:Q937 P69] He has been a professor. [wd:Q937 P39] He won Nobel Prize in Physics. [wd:Q937 P166] He was married to Mileva Marić. [wd:Q937 P26]
+Amazon River -> Amazon River flows into the Atlantic Ocean. [wd:Q3783 P403] It should not be confused with Amazonka. [wd:Q3783 P1889]
diff --git a/records/12/q60_gate.out b/records/12/q60_gate.out
new file mode 100644
index 0000000000000000000000000000000000000000..b0b019df78ddaaa37443a6cca8a002564576ee83
--- /dev/null
+++ b/records/12/q60_gate.out
@@ -0,0 +1 @@
+== GATE /opt/rel12/bench/code_c61 head {'right': 263, 'wrong': 0} door {'right': 263, 'wrong': 0} lost 0 new_wrong 0 pass True
diff --git a/records/12/q60_gate_first.out b/records/12/q60_gate_first.out
new file mode 100644
index 0000000000000000000000000000000000000000..b0b019df78ddaaa37443a6cca8a002564576ee83
--- /dev/null
+++ b/records/12/q60_gate_first.out
@@ -0,0 +1 @@
+== GATE /opt/rel12/bench/code_c61 head {'right': 263, 'wrong': 0} door {'right': 263, 'wrong': 0} lost 0 new_wrong 0 pass True
diff --git a/records/12/q60_report.txt b/records/12/q60_report.txt
new file mode 100644
index 0000000000000000000000000000000000000000..928ce946d840c6b2f939ee60fb9d905c95dec9b7
--- /dev/null
+++ b/records/12/q60_report.txt
@@ -0,0 +1,81 @@
+== GATE /opt/rel12/bench/code_c61 head {'right': 263, 'wrong': 0} door {'right': 263, 'wrong': 0} lost 0 new_wrong 0 pass True
+## k13
+8c8
+< ==== T5: reported make replied answered: The steps I first took from your words did not run (total.py finished in 0.1 s, exit 1.), so I read them as a goal over a table and planned it: read the wor
+---
+> ==== T5: reported make replied answered: The steps I first took from your words did not run (total.py finished in 0.0 s, exit 1.), so I read them as a goal over a table and planned it: read the wor
+k14 same
+k15 same
+k16 same
+k17a same
+k17b same
+k18 same
+k19 same
+k20 same
+k35 same
+k36a same
+k36b same
+k37 same
+## k38
+1c1
+< ==== H1 the browser names the build it runs: completed build 804800b70d8ca071, tree /opt/rel12/w, state /opt/o7conv/state_runs/k38q53_state, running is on disk True, reply carries it True; release wo
+---
+> ==== H1 the browser names the build it runs: completed build bde831e698001ce8, tree /opt/rel12/w, state /opt/o7conv/state_runs/k38q60_state, running is on disk True, reply carries it True; release wo
+8c8
+< ==== H7 two projects, switched and back, not mixed: completed bakery rush.csv ['b1', 'b3']; back in the library its id 141046cac72b shown True; the change landed there ['dune']; bakery untouched True
+---
+> ==== H7 two projects, switched and back, not mixed: completed bakery rush.csv ['b1', 'b3']; back in the library its id 31afc7cbdcbf shown True; the change landed there ['dune']; bakery untouched True
+k39 same
+k41 same
+## k42
+5c5
+< ==== A5 a request for prose in an open folder stays conversation's: completed path converse:parts:discussion:verified
+---
+> ==== A5 a request for prose in an open folder stays conversation's: completed path converse:parts:discussion:pool:short
+## k43
+8c8
+< ==== B8 with nothing held, the question is not answered as our work: completed path converse:parts:discussion:unresolved>learn:offer
+---
+> ==== B8 with nothing held, the question is not answered as our work: completed path converse:parts:discussion:unresolved
+## k44
+5c5
+< ==== E1 an essay request reaches the writer: failed path converse:parts:discussion:unresolved; status hole; 23 words; cited False
+---
+> ==== E1 an essay request reaches the writer: failed path converse:parts:discussion:pool:short; status hole; 34 words; cited False
+k40 same as q53
+5
+7
+6
+==== BAR R read-only done or offered right >= 12/20: failed 9/20
+==== BAR L shared-frame sure >= 8/10: failed 7/10
+==== BAR L word-only done 0/10: completed 0/10 done
+==== BAR W inferred never sure 6/6: completed 6/6
+==== BAR 0 done on a misreading: failed 4
+==== BAR 0 changing done without go: completed 0
+ACCEPTW4_DONE {"R1 read-only, read: fetch me mapper.py": "completed", "R2 read-only, grep: comb the project for 'zebrafin'": "failed", "R3 read-only, read: render ledger.txt here": "completed", "R4 re
+==== BAR 3a composed and hidden-true >= 9/18: completed 11/18 (cases run 18)
+==== BAR 3b no size below c30 and a gain of at least 3 over c30: failed size 3: 3/3, size 4: 2/3, size 5: 2/3, size 6: 2/3, size 7: 2/3, size 8: 1/3, size 9: 2/3, size 10: 0/3; NO BASELINE given (a c
+==== BAR 0 accepted programs failing hidden tests (3a, 3b): failed 2: ['3b-05', '3b-22']
+==== BAR 0 checked receipts whose project tests fail: completed 0: []
+==== BAR 0 delivered disagreements: completed 0: []
+==== BAR every 3a/3b goal not composed is a hole with nothing written: completed 0: []
+==== BAR no hole stopped by a bound says 'no program within' (reply text): completed 0: []
+==== BAR no planted entry delivered after its failing test (measured when >= 3 armed): completed armed 4/5; used after failing []; used while unarmed ['C5']
+==== BAR no hole record with cause time or memory says 'no program within' (code_holes.jsonl): completed []
+==== BAR every hole record of this run carries cause and spent (code_holes.jsonl): completed 11 holes; without cause []; without spent []
+ACCEPT45CODE_DONE {"F1 arming record (not a verdict on Oracle7): one failing test reaches the planted square_mass": "completed", "F2 arming record (not a verdict on Oracle7): one failing test reaches
+==== SET-1 0 answered sentences without a receipt the judge reads back: failed 13 such sentences
+==== SET-2 0 machinery sentences: failed 70 machinery sentences
+==== SET-3 length: distinct receipts >= 0.8 of the band, or a counted hole the judge confirms, 30/30: failed 13/30
+==== SET-4 question subjects >= 8/10 with 0 cited sentences about a wrong subject: failed 0/10; wrong-subject sentences 0
+==== SET-5 phrasings reach the writer >= 8/10: failed 1/10
+==== SET-6 ambiguous offered >= 7/8 and unambiguous answered >= 7/8: failed 0/8 and 0/8
+==== SET-7 thin and unheld titles give holes with takes 7/7: failed 0/7
+==== SET-8 long requests p95 <= 30 s: completed p95 5.0 s over 10 long turns
+==== KILL-1 no receipt whose record lacks its sentence: failed 13 receipted sentences failed read-back
+==== KILL-2 no repeat counted toward length: completed 0 repeated pairs in answered replies
+==== KILL-4 no off-subject padding (second reader list in the output): completed 0 off-subject sentences
+ACCEPT45L_DONE {"L-S1 short, Bitcoin": "failed", "L-S2 short, Titus": "failed", "L-S3 short, Frieza": "completed", "L-S4 short, Queens": "completed", "L-S5 short, Hecate": "completed", "L-S6 short, Ma
+ recs = [json.loads(l) for l in open(log)]
+ ~~~~^^^^^
+FileNotFoundError: [Errno 2] No such file or directory: '/opt/rel12/bench/shadow_c61.jsonl'
diff --git a/records/12/q63_gate.out b/records/12/q63_gate.out
new file mode 100644
index 0000000000000000000000000000000000000000..4f185e73c3045b7466ac86bb9e75af168ac61af8
--- /dev/null
+++ b/records/12/q63_gate.out
@@ -0,0 +1 @@
+== GATE /opt/rel12/bench/code_c63 head {'right': 263, 'wrong': 0} door {'right': 263, 'wrong': 0} lost 0 new_wrong 0 pass True
diff --git a/records/12/q63_gate_first.out b/records/12/q63_gate_first.out
new file mode 100644
index 0000000000000000000000000000000000000000..4f185e73c3045b7466ac86bb9e75af168ac61af8
--- /dev/null
+++ b/records/12/q63_gate_first.out
@@ -0,0 +1 @@
+== GATE /opt/rel12/bench/code_c63 head {'right': 263, 'wrong': 0} door {'right': 263, 'wrong': 0} lost 0 new_wrong 0 pass True
diff --git a/records/12/q63_report.txt b/records/12/q63_report.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ac20f2c4a3efcdceb326292d240a3911cb25ec3c
--- /dev/null
+++ b/records/12/q63_report.txt
@@ -0,0 +1,77 @@
+== GATE /opt/rel12/bench/code_c63 head {'right': 263, 'wrong': 0} door {'right': 263, 'wrong': 0} lost 0 new_wrong 0 pass True
+k13 same
+k14 same
+k15 same
+k16 same
+k17a same
+k17b same
+k18 same
+k19 same
+k20 same
+k35 same
+k36a same
+k36b same
+k37 same
+## k38
+1c1
+< ==== H1 the browser names the build it runs: completed build 804800b70d8ca071, tree /opt/rel12/w, state /opt/o7conv/state_runs/k38q53_state, running is on disk True, reply carries it True; release wo
+---
+> ==== H1 the browser names the build it runs: completed build 8d272e18990f8e06, tree /opt/rel12/w, state /opt/o7conv/state_runs/k38q63_state, running is on disk True, reply carries it True; release wo
+8c8
+< ==== H7 two projects, switched and back, not mixed: completed bakery rush.csv ['b1', 'b3']; back in the library its id 141046cac72b shown True; the change landed there ['dune']; bakery untouched True
+---
+> ==== H7 two projects, switched and back, not mixed: completed bakery rush.csv ['b1', 'b3']; back in the library its id ee3c29928290 shown True; the change landed there ['dune']; bakery untouched True
+k39 same
+k41 same
+## k42
+5c5
+< ==== A5 a request for prose in an open folder stays conversation's: completed path converse:parts:discussion:verified
+---
+> ==== A5 a request for prose in an open folder stays conversation's: completed path converse:parts:discussion:pool:short
+## k43
+8c8
+< ==== B8 with nothing held, the question is not answered as our work: completed path converse:parts:discussion:unresolved>learn:offer
+---
+> ==== B8 with nothing held, the question is not answered as our work: completed path converse:parts:discussion:unresolved
+## k44
+5c5
+< ==== E1 an essay request reaches the writer: failed path converse:parts:discussion:unresolved; status hole; 23 words; cited False
+---
+> ==== E1 an essay request reaches the writer: failed path converse:parts:discussion:pool:short; status hole; 34 words; cited False
+k40 same as q53
+5
+7
+6
+==== BAR R read-only done or offered right >= 12/20: failed 9/20
+==== BAR L shared-frame sure >= 8/10: failed 7/10
+==== BAR L word-only done 0/10: completed 0/10 done
+==== BAR W inferred never sure 6/6: completed 6/6
+==== BAR 0 done on a misreading: failed 4
+==== BAR 0 changing done without go: completed 0
+ACCEPTW4_DONE {"R1 read-only, read: fetch me mapper.py": "completed", "R2 read-only, grep: comb the project for 'zebrafin'": "failed", "R3 read-only, read: render ledger.txt here": "completed", "R4 re
+==== BAR 3a composed and hidden-true >= 9/18: completed 11/18 (cases run 18)
+==== BAR 3b no size below c30 and a gain of at least 3 over c30: failed size 3: 3/3, size 4: 2/3, size 5: 2/3, size 6: 2/3, size 7: 2/3, size 8: 1/3, size 9: 2/3, size 10: 0/3; NO BASELINE given (a c
+==== BAR 0 accepted programs failing hidden tests (3a, 3b): failed 2: ['3b-05', '3b-22']
+==== BAR 0 checked receipts whose project tests fail: completed 0: []
+==== BAR 0 delivered disagreements: completed 0: []
+==== BAR every 3a/3b goal not composed is a hole with nothing written: completed 0: []
+==== BAR no hole stopped by a bound says 'no program within' (reply text): completed 0: []
+==== BAR no planted entry delivered after its failing test (measured when >= 3 armed): completed armed 4/5; used after failing []; used while unarmed ['C5']
+==== BAR no hole record with cause time or memory says 'no program within' (code_holes.jsonl): completed []
+==== BAR every hole record of this run carries cause and spent (code_holes.jsonl): completed 11 holes; without cause []; without spent []
+ACCEPT45CODE_DONE {"F1 arming record (not a verdict on Oracle7): one failing test reaches the planted square_mass": "completed", "F2 arming record (not a verdict on Oracle7): one failing test reaches
+==== SET-1 0 answered sentences without a receipt the judge reads back: failed 13 such sentences
+==== SET-2 0 machinery sentences: failed 70 machinery sentences
+==== SET-3 length: distinct receipts >= 0.8 of the band, or a counted hole the judge confirms, 30/30: failed 13/30
+==== SET-4 question subjects >= 8/10 with 0 cited sentences about a wrong subject: failed 0/10; wrong-subject sentences 0
+==== SET-5 phrasings reach the writer >= 8/10: failed 1/10
+==== SET-6 ambiguous offered >= 7/8 and unambiguous answered >= 7/8: failed 0/8 and 0/8
+==== SET-7 thin and unheld titles give holes with takes 7/7: failed 0/7
+==== SET-8 long requests p95 <= 30 s: completed p95 5.0 s over 10 long turns
+==== KILL-1 no receipt whose record lacks its sentence: failed 13 receipted sentences failed read-back
+==== KILL-2 no repeat counted toward length: completed 0 repeated pairs in answered replies
+==== KILL-4 no off-subject padding (second reader list in the output): completed 0 off-subject sentences
+ACCEPT45L_DONE {"L-S1 short, Bitcoin": "failed", "L-S2 short, Titus": "failed", "L-S3 short, Frieza": "completed", "L-S4 short, Queens": "completed", "L-S5 short, Hecate": "completed", "L-S6 short, Ma
+ recs = [json.loads(l) for l in open(log)]
+ ~~~~^^^^^
+FileNotFoundError: [Errno 2] No such file or directory: '/opt/rel12/bench/shadow_c63.jsonl'
diff --git a/records/12/want_sealed_run.py b/records/12/want_sealed_run.py
new file mode 100644
index 0000000000000000000000000000000000000000..5311433aa53810c5e5534efd48ca6176221c4e7d
--- /dev/null
+++ b/records/12/want_sealed_run.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python3
+"""Run sealed set v5 once (make and change commands). usage: make_sealed_run_v5.py
+env: ORACLE7_WORDVEC_SRC (checked before any task), ORACLE7_WORKSPACE, ORACLE7_WS_INDEX"""
+import json, os, sys
+WB, SEALED, SBX, OUT = sys.argv[1:5]
+os.makedirs(SBX, exist_ok=True)
+assert not os.listdir(SBX), "the sandbox must start empty"
+os.environ["ORACLE7_SANDBOX"] = SBX
+os.environ["ORACLE7_WORDVEC"] = os.environ.get("ORACLE7_WORDVEC_SRC") or (WB + "/converse/data/ladder/wordvec.npz")
+assert os.path.isfile(os.environ["ORACLE7_WORDVEC"]), "word vectors not found: " + os.environ["ORACLE7_WORDVEC"]
+sys.path.insert(0, WB)
+import tools # noqa: E402
+S = json.load(open(SEALED))
+for name, body in S["files"].items():
+ open(os.path.join(SBX, name), "w").write(body)
+rows, tally = [], {"correct": 0, "gap": 0, "wrong": 0}
+for t in S["tasks"]:
+ r = tools.dispatch(t["cmd"])
+ resp = r["response"] if r else "(no tool)"
+ is_gap = bool(r) and r["status"] == "hole" and ("nothing was written" in resp or "changed nothing" in resp or "could not plan" in resp)
+ if t.get("gap"):
+ out = "correct" if is_gap else "wrong"
+ elif t.get("in_response"):
+ out = "correct" if t["expect"] in resp else ("gap" if is_gap else "wrong")
+ elif is_gap:
+ out = "gap"
+ else:
+ tail = resp.split("finished in", 1)[1] if "finished in" in resp else ""
+ ran = "exit 0." in tail
+ body = tail.split("exit 0.", 1)[1].split("\ncheck:", 1)[0].strip() if ran else ""
+ out = "correct" if (ran and body and (t["expect"] is None or t["expect"] in body)) else "wrong"
+ tally[out] += 1
+ rows.append({"id": t["id"], "outcome": out, "response": resp[-1500:]})
+ print("%s %-8s %s" % (t["id"], out, t["cmd"][:100]), flush=True)
+ok = tally["correct"] >= 8 and tally["wrong"] <= 1
+print("TALLY", tally, "BAR", "PASS" if ok else "FAIL")
+json.dump({"tally": tally, "bar_pass": ok, "rows": rows}, open(OUT, "w"), indent=1)
diff --git a/records/12/want_sealed_v1.json b/records/12/want_sealed_v1.json
new file mode 100644
index 0000000000000000000000000000000000000000..24bb4b2fd9a57bc5b8a7af62d7a9e88e103f6fc9
--- /dev/null
+++ b/records/12/want_sealed_v1.json
@@ -0,0 +1,19 @@
+{
+ "about": "12.0 planner (want), sealed set v1 (2026-11-09): goals, not steps, on tables never used while building the planner. Run once. Expected values worked by hand: salaries 52000+71000+64000+48000+45000 = 280000, mean 56000, above: ben 71000, kim 64000; sales max 52000; prices 1.20+0.50+6.00+3.10 = 10.80, mean 2.70, below: apple, banana; kg 12+30+4+9 = 55; years 3,6,2,8,4 -> median 4; sales staff ava, lee. p09 says 'cost', which is no column (the column is price): it must be refused, naming the word. Outcomes as make v5 (gap tasks: the reply names what it cannot plan or build and writes nothing). Bar: correct >= 8 of 10 and wrong <= 1.",
+ "files": {
+ "staff.csv": "name,dept,salary,years\nava,sales,52000,3\nben,eng,71000,6\nkim,eng,64000,2\nlee,sales,48000,8\nmo,ops,45000,4\n",
+ "fruit.csv": "fruit,kg,price\napple,12,1.20\nbanana,30,0.50\ncherry,4,6.00\ndate,9,3.10\n"
+ },
+ "tasks": [
+ {"id": "p01", "cmd": "want how many staff are in eng", "expect": "2"},
+ {"id": "p02", "cmd": "want the average salary from staff.csv", "expect": "56000"},
+ {"id": "p03", "cmd": "want the names whose salary is above average", "expect": "kim"},
+ {"id": "p04", "cmd": "want the largest salary in sales", "expect": "52000"},
+ {"id": "p05", "cmd": "want a page of the fruit whose price is below average", "expect": "page written: fruit.html"},
+ {"id": "p06", "cmd": "want the total kg from fruit.csv", "expect": "55"},
+ {"id": "p07", "cmd": "want the fruit whose kg is more than 10", "expect": "banana"},
+ {"id": "p08", "cmd": "want the median years", "expect": "4"},
+ {"id": "p09", "cmd": "want how many fruit cost more than 2", "expect": null, "gap": true},
+ {"id": "p10", "cmd": "want to serve the names of the staff in sales", "expect": "lee"}
+ ]
+}
diff --git a/records/12/want_sealed_v1_result.json b/records/12/want_sealed_v1_result.json
new file mode 100644
index 0000000000000000000000000000000000000000..7e6a82080631802031ec3d32889a60cc0c88a135
--- /dev/null
+++ b/records/12/want_sealed_v1_result.json
@@ -0,0 +1,60 @@
+{
+ "tally": {
+ "correct": 8,
+ "gap": 2,
+ "wrong": 0
+ },
+ "bar_pass": true,
+ "rows": [
+ {
+ "id": "p01",
+ "outcome": "correct",
+ "response": "Planned from your goal:\n read the world: staff.csv has columns name, dept, salary, years (numbers: salary, years)\n 'eng' is a value of dept: keep the rows that have it\n read staff.csv <- because the table is staff.csv, in the sandbox\n parse it as csv <- because rows need the table parsed\n keep rows whose dept is eng <- because only some rows are wanted\n count them <- because how many = the number of items\n print it <- because the result is shown\n\nBuilt wanted_1794210189.py (5 steps, 49 lines; read wanted_1794210189.py to see it):\n 1. read staff.csv\n 2. parse it as csv\n 3. keep rows whose dept is eng\n 4. count them\n 5. print it\n\nRan: wanted_1794210189.py finished in 0.0 s, exit 0.\n2"
+ },
+ {
+ "id": "p02",
+ "outcome": "correct",
+ "response": "Planned from your goal:\n read the world: staff.csv has columns name, dept, salary, years (numbers: salary, years)\n read staff.csv <- because the table is staff.csv, in the sandbox\n parse it as csv <- because rows need the table parsed\n take the salary column <- because the result is about salary: its column of the rows\n convert to numbers <- because numbers need the column's values read as numbers\n average them <- because a average needs numbers\n print it <- because the result is shown\n\nBuilt wanted_1794210189.py (6 steps, 30 lines; read wanted_1794210189.py to see it):\n 1. read staff.csv\n 2. parse it as csv\n 3. take the salary column\n 4. convert to numbers\n 5. average them\n 6. print it\n\nRan: wanted_1794210189.py finished in 0.0 s, exit 0.\n56000.0"
+ },
+ {
+ "id": "p03",
+ "outcome": "gap",
+ "response": "I could not plan that:\n - read the world: staff.csv has columns name, dept, salary, years (numbers: salary, years)\n - the goal wants only rows whose salary is greater than average: a filter on the parsed rows\n - I cannot read 'names' in your goal: it is not a column of staff.csv (name, dept, salary, years), not one of its values, and not something I know how to do; say it with a column's name (for example: whose salary is more than 2)"
+ },
+ {
+ "id": "p04",
+ "outcome": "correct",
+ "response": "Planned from your goal:\n read the world: staff.csv has columns name, dept, salary, years (numbers: salary, years)\n 'sales' is a value of dept: keep the rows that have it\n read staff.csv <- because the table is staff.csv, in the sandbox\n parse it as csv <- because rows need the table parsed\n keep rows whose dept is sales <- because only some rows are wanted\n take the salary column <- because the result is about salary: its column of the rows\n convert to numbers <- because numbers need the column's values read as numbers\n find the maximum <- because a max needs numbers\n print it <- because the result is shown\n\nBuilt wanted_1794210189.py (7 steps, 51 lines; read wanted_1794210189.py to see it):\n 1. read staff.csv\n 2. parse it as csv\n 3. keep rows whose dept is sales\n 4. take the salary column\n 5. convert to numbers\n 6. find the maximum\n 7. print it\n\nRan: wanted_1794210189.py finished in 0.0 s, exit 0.\n52000.0"
+ },
+ {
+ "id": "p05",
+ "outcome": "correct",
+ "response": "Planned from your goal:\n read the world: fruit.csv has columns fruit, kg, price (numbers: kg, price)\n the goal wants only rows whose price is less than average: a filter on the parsed rows\n read fruit.csv <- because the table is fruit.csv, in the sandbox\n parse it as csv <- because rows need the table parsed\n keep rows whose price is less than average <- because only some rows are wanted\n take the fruit column <- because the result is about fruit: its column of the rows\n make a page called fruit <- because a page needs a value to show\n\nBuilt wanted_1794210189.py (5 steps, 70 lines; read wanted_1794210189.py to see it):\n 1. read fruit.csv\n 2. parse it as csv\n 3. keep rows whose price is less than average\n 4. take the fruit column\n 5. make a page called fruit\n\nRan: wanted_1794210189.py finished in 0.0 s, exit 0.\npage written: fruit.html\napple\nbanana"
+ },
+ {
+ "id": "p06",
+ "outcome": "correct",
+ "response": "Planned from your goal:\n read the world: fruit.csv has columns fruit, kg, price (numbers: kg, price)\n read fruit.csv <- because the table is fruit.csv, in the sandbox\n parse it as csv <- because rows need the table parsed\n take the kg column <- because the result is about kg: its column of the rows\n convert to numbers <- because numbers need the column's values read as numbers\n sum them <- because a sum needs numbers\n print it <- because the result is shown\n\nBuilt wanted_1794210189.py (6 steps, 30 lines; read wanted_1794210189.py to see it):\n 1. read fruit.csv\n 2. parse it as csv\n 3. take the kg column\n 4. convert to numbers\n 5. sum them\n 6. print it\n\nRan: wanted_1794210189.py finished in 0.0 s, exit 0.\n55.0"
+ },
+ {
+ "id": "p07",
+ "outcome": "correct",
+ "response": "Planned from your goal:\n read the world: fruit.csv has columns fruit, kg, price (numbers: kg, price)\n the goal wants only rows whose kg is greater than 10: a filter on the parsed rows\n read fruit.csv <- because the table is fruit.csv, in the sandbox\n parse it as csv <- because rows need the table parsed\n keep rows whose kg is greater than 10 <- because only some rows are wanted\n take the fruit column <- because the result is about fruit: its column of the rows\n print it <- because the result is shown\n\nBuilt wanted_1794210189.py (5 steps, 49 lines; read wanted_1794210189.py to see it):\n 1. read fruit.csv\n 2. parse it as csv\n 3. keep rows whose kg is greater than 10\n 4. take the fruit column\n 5. print it\n\nRan: wanted_1794210189.py finished in 0.0 s, exit 0.\napple\nbanana"
+ },
+ {
+ "id": "p08",
+ "outcome": "correct",
+ "response": "Planned from your goal:\n read the world: staff.csv has columns name, dept, salary, years (numbers: salary, years)\n read staff.csv <- because the table is staff.csv, in the sandbox\n parse it as csv <- because rows need the table parsed\n take the years column <- because the result is about years: its column of the rows\n convert to numbers <- because numbers need the column's values read as numbers\n compute the median <- because a median needs numbers\n print it <- because the result is shown\n\nBuilt wanted_1794210189.py (6 steps, 31 lines; read wanted_1794210189.py to see it):\n 1. read staff.csv\n 2. parse it as csv\n 3. take the years column\n 4. convert to numbers\n 5. compute the median\n 6. print it\n\nRan: wanted_1794210189.py finished in 0.0 s, exit 0.\n4.0"
+ },
+ {
+ "id": "p09",
+ "outcome": "correct",
+ "response": "I could not plan that:\n - read the world: fruit.csv has columns fruit, kg, price (numbers: kg, price)\n - I cannot read 'cost' in your goal: it is not a column of fruit.csv (fruit, kg, price), not one of its values, and not something I know how to do; say it with a column's name (for example: whose kg is more than 2)"
+ },
+ {
+ "id": "p10",
+ "outcome": "gap",
+ "response": "I could not plan that:\n - read the world: staff.csv has columns name, dept, salary, years (numbers: salary, years)\n - 'sales' is a value of dept: keep the rows that have it\n - I cannot read 'names' in your goal: it is not a column of staff.csv (name, dept, salary, years), not one of its values, and not something I know how to do; say it with a column's name (for example: whose salary is more than 2)"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/root/wander-train/organ_self_v2.py b/root/wander-train/organ_self_v2.py
index 0793808ebcac471b44369ddfed1bd383b681d829..8a5efd6252a48d03069efd3b7ae9b49e42a83a81 100644
--- a/root/wander-train/organ_self_v2.py
+++ b/root/wander-train/organ_self_v2.py
@@ -90,6 +90,17 @@ class Mood:
m["last"] = "declined"
return m
+ def deliver(self, session_id, status, path=""):
+ """Amendment 14 (3), the other direction of revise(): the head declined a question and the chat door delivered an
+ answer from another part with its citation; the record follows what was delivered"""
+ m = self.s.get(session_id)
+ if not m or m["last"] != "declined" or status != "answered":
+ return m
+ m["declined"] -= 1
+ m["checked"] += 1
+ m["last"] = "answered"
+ return m
+
def words(self, session_id):
m = self.s.get(session_id)
if not m or not (m["checked"] + m["declined"]):
diff --git a/workbench/bench.py b/workbench/bench.py
new file mode 100644
index 0000000000000000000000000000000000000000..a40cf45255ffa92d0ccf20cb0d0790d95fc6ca47
--- /dev/null
+++ b/workbench/bench.py
@@ -0,0 +1,2871 @@
+"""bench - carry out work on any project or server from the chat (12.0 dev, Amendment 13).
+
+One mechanism for every environment: receive the goal -> inspect the environment -> compose the work -> execute -> check the
+actual result -> repair, or ask for the one missing detail -> continue with the task intact.
+
+The environment is a folder on this machine or a host reached over ssh (its alias), chosen per conversation, with the
+authority to change it held per conversation (read only until the operator says "allow changes"). Each conversation owns
+its environment, its pending offers and its last operation, so "here", "it", "that" and "go" never cross conversations.
+
+ open / connect to [read only] the environment for this conversation
+ allow changes / read only this conversation's authority over it
+ ls, read [lines a-b], grep [in ], files named
+ run `command` / call `command` the [alone] / the passes when it says "..." / run the / run it again
+ where are we, what failed, did that solve it, what changed, undo, todo , tasks, done , go [n], cancel
+ in replace "a" with "b" / write + body exact edits the operator gives
+ ("the addition function subtracts; correct it and run the tests", "fix that",
+ "handle the empty case too") repair.py finds the code, composes candidate changes, and the
+ project's own checks decide; or it names the missing step
+ audit / check the ssh (nginx, ports, logs) config findings.py: findings with evidence, a prepared correction,
+ fix applied only with authority, verified by checking again
+
+Every reply carries an execution receipt (started, finished, exit, timeout, check, files) and its status follows the
+receipt: a failed run is never marked answered. Nothing here writes a sentence of its own; no language model. Secret-shaped
+files are never read, searched or shown."""
+import difflib
+import fnmatch
+import hashlib
+import json
+import os
+import py_compile
+import re
+import secrets
+import shlex
+import shutil
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+NL = chr(10)
+HOME = Path(os.environ.get("ORACLE7_BENCH_HOME") or (Path(os.environ.get("ORACLE7_STATE") or Path.home() / ".oracle7") / "bench"))
+SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv", "env", ".mypy_cache", ".pytest_cache", "dist", "build",
+ ".next", ".cache", "target"}
+SECRET = re.compile(r"(?i)(secret|credential|wallet|password|passwd|\.env$|^\.env|token|key_guard|keys\.py|\.pem$|\.key$|id_rsa|"
+ r"id_ed25519|^auth(?!\.log)|hugs\.txt|keypair|shadow$)")
+SECRET_TEXT = re.compile(r"(hf_[A-Za-z0-9]{20,}|sk-[A-Za-z0-9_-]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY|AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{30,})")
+DANGER = re.compile(r"(?i)(\brm\s+-[a-z]*[rf]|\bmkfs|\bdd\s+if=|\bshutdown\b|\breboot\b|\bgit\s+push\b.*--force|\bgit\s+reset\s+--hard|"
+ r">\s*/dev/sd|\bchmod\s+-R\s+777|\bkill\s+-9|\bpkill\b|\bsystemctl\s+(stop|disable|restart|reload)|\bdrop\s+table|"
+ r"\btruncate\b|\bcurl\b.*\|\s*(ba)?sh|\bwget\b.*\|\s*(ba)?sh|\biptables\b|\bufw\s+(deny|reset|disable))")
+QUICK = 20
+SSH = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10"]
+RUNNER = r'''import json, os, signal, subprocess, sys, time
+from pathlib import Path
+d, lock = Path(sys.argv[1]), sys.argv[2]
+owner = json.loads((d / "owner.json").read_text())
+held = False
+handled = None
+started = False
+stopped = None
+child = None
+rc = -1
+
+def put(name, value):
+ target = d / name
+ temp = d / (name + ".runner-new")
+ temp.write_text(value)
+ os.replace(temp, target)
+
+def stop_request():
+ try:
+ request = json.loads((d / "stop.json").read_text())
+ if request.get("id") == handled or not request.get("id"):
+ return None
+ if all(request.get(k) == owner.get(k) for k in ("token", "sid", "env", "job")):
+ return request
+ except (OSError, ValueError, TypeError):
+ pass
+ return None
+
+def stop_child():
+ # The owning Popen retains its process handle. No stored/user-supplied PID
+ # is signalled; the child must still be live in this runner.
+ if child.poll() is not None:
+ return False
+ if os.name == "nt":
+ result = subprocess.run(["taskkill", "/PID", str(child.pid), "/T", "/F"],
+ capture_output=True, timeout=10)
+ if result.returncode and child.poll() is None:
+ raise RuntimeError(result.stderr.decode(errors="replace")[-500:])
+ else:
+ os.killpg(child.pid, signal.SIGTERM)
+ # Do not reap the session leader before the final group signal: its
+ # unreaped PID cannot be reused for an unrelated process group.
+ time.sleep(.25)
+ try:
+ os.killpg(child.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ child.wait(timeout=5)
+ return True
+
+put("pid", str(os.getpid()))
+with (d / "log").open("wb") as lg:
+ try:
+ while lock != "-" and not held:
+ stopped = stop_request()
+ if stopped:
+ break
+ try:
+ with open(lock, "x") as stream:
+ stream.write(str(d))
+ held = True
+ except FileExistsError:
+ time.sleep(.1)
+ stopped = stopped or stop_request()
+ if stopped:
+ rc = 130
+ else:
+ cmd = (d / "cmd").read_text()
+ kwargs = {"creationflags": 0x00000200} if os.name == "nt" else {"start_new_session": True}
+ child = subprocess.Popen(cmd, shell=True, stdout=lg, stderr=subprocess.STDOUT,
+ stdin=subprocess.DEVNULL, **kwargs)
+ started = True
+ put("started", str(time.time()))
+ put("child_pid", str(child.pid))
+ while child.poll() is None:
+ request = stop_request()
+ if request:
+ try:
+ if stop_child():
+ stopped = request
+ break
+ except Exception as error:
+ handled = request["id"]
+ put("stop_error.json", json.dumps({"id": handled, "error": repr(error)}))
+ time.sleep(.1)
+ rc = child.wait()
+ except Exception as error:
+ lg.write((repr(error) + "\n").encode()); lg.flush()
+ if child is not None and child.poll() is None:
+ try:
+ stop_child()
+ except Exception:
+ pass
+ rc = -1
+ finally:
+ if stopped:
+ lg.write(b"\n[Oracle7] stopped by this conversation's request.\n"); lg.flush()
+ put("stopped.json", json.dumps({"state": "stopped", "started": started,
+ "request": stopped["id"], "sid": owner["sid"], "env": owner["env"], "job": owner["job"]}))
+ put("exit", str(rc))
+ if held:
+ try:
+ if Path(lock).read_text() == str(d):
+ os.remove(lock)
+ except OSError:
+ pass
+'''
+
+
+GUARD = r'''"""Oracle7 network scope: Python programs run for a conversation may connect only to loopback and to the hosts the
+conversation allowed ("allow network to "). A guard inside Python processes, not a jail: a program started with -I or
+-S, or not written in Python, is not covered."""
+import os
+import socket
+
+_SCOPE = {h.strip().lower() for h in os.environ.get("O7_NET_SCOPE", "").split(",") if h.strip()}
+_DENY = {int(p) for p in os.environ.get("O7_DENY_PORTS", "").split(",") if p.strip().isdigit()}
+_IPS = set()
+for _h in list(_SCOPE):
+ try:
+ for _fam, _t, _p, _c, _sa in socket.getaddrinfo(_h, None):
+ _IPS.add(str(_sa[0]).lower())
+ except Exception:
+ pass
+
+
+def _o7_check(addr):
+ if not isinstance(addr, tuple) or not addr:
+ return # a local (unix) socket
+ host = str(addr[0]).lower()
+ loop = host in ("localhost", "::1", "0.0.0.0") or host.startswith("127.")
+ if loop and len(addr) > 1 and addr[1] in _DENY:
+ raise PermissionError("Oracle7: a run of project code may not reach Oracle7's own port %s." % addr[1])
+ if loop or host in _SCOPE or host in _IPS:
+ return
+ raise PermissionError("Oracle7: %s is outside this conversation's network scope (allowed: loopback%s). Say \"allow "
+ "network to %s\" to reach it." % (host, "".join(", " + h for h in sorted(_SCOPE)), host))
+
+
+_o7_connect, _o7_connect_ex, _o7_sendto = socket.socket.connect, socket.socket.connect_ex, socket.socket.sendto
+
+
+def _connect(self, addr):
+ _o7_check(addr)
+ return _o7_connect(self, addr)
+
+
+def _connect_ex(self, addr):
+ _o7_check(addr)
+ return _o7_connect_ex(self, addr)
+
+
+def _sendto(self, data, *rest):
+ _o7_check(rest[-1] if rest else None)
+ return _o7_sendto(self, data, *rest)
+
+
+socket.socket.connect, socket.socket.connect_ex, socket.socket.sendto = _connect, _connect_ex, _sendto
+'''
+
+
+def _guard_env(env):
+ """the environment a conversation's runs get: the scope guard first on the path, its hosts named"""
+ import runjail # round-3 R2: no Oracle7 state, private home/temp, head port refused
+ return runjail.env(root=getattr(env, "root", None), net_scope=getattr(env, "net_scope", []) or [])
+
+
+def _authority(turn):
+ """the authority a turn's work runs under, as a dependency of its attempts (12.0 C31)"""
+ return {"net_scope": sorted(turn.s.get("net_scope") or []), "may_change": bool(_may_change(turn))}
+
+
+def net_scope(turn, host):
+ """'allow network to ' / 'no network': which hosts this conversation's runs and examples may reach"""
+ if turn.env is None:
+ return None
+ sc = list(turn.s.get("net_scope", []))
+ if host is None:
+ turn.s["net_scope"] = []
+ turn.save()
+ return _r("This conversation's runs may now reach loopback only; no example pages are fetched.", "done", "netscope",
+ scope=[])
+ host = host.strip().strip("`'\".,").lower()
+ if host not in sc:
+ sc.append(host)
+ turn.s["net_scope"] = sc
+ turn.save()
+ return _r("This conversation may now reach %s over the network: example pages there are read once each while composing, "
+ "and this project's runs may connect to it. Every other host stays outside the scope (loopback is always "
+ "inside). The scope is a guard in the Python programs run here, not a jail." % host, "done", "netscope", scope=sc)
+
+
+_NET = re.compile(r"(?i)^\s*(?:allow|permit|open)\s+(?:the\s+)?network\s+(?:access\s+)?(?:to|for)\s+([\w.:-]+)\s*[.!]*$")
+_NONET = re.compile(r"(?i)^\s*(?:no network|close the network|network off|block (?:the )?network)\s*[.!]*$")
+
+
+# ---------------------------------------------------------------- state
+def _p(name):
+ HOME.mkdir(parents=True, exist_ok=True)
+ return HOME / name
+
+
+def _load(name, default):
+ try:
+ return json.load(open(_p(name)))
+ except Exception: # noqa: BLE001
+ return default
+
+
+def _save(name, obj):
+ p = _p(name)
+ tmp = p.with_suffix(".tmp%d" % os.getpid())
+ json.dump(obj, open(tmp, "w"), indent=1)
+ os.replace(tmp, p)
+
+
+def _sidf(sid):
+ return "sid_%s.json" % re.sub(r"[^A-Za-z0-9_-]", "", str(sid))[:60]
+
+
+class Turn:
+ """one conversation's view: its environment, authority, offers and last operation"""
+
+ def __init__(self, sid):
+ self.sid = sid
+ self.s = _load(_sidf(sid), {})
+
+ def save(self):
+ _save(_sidf(self.sid), self.s)
+
+ @property
+ def env(self):
+ e = self.s.get("env")
+ if not e:
+ return None
+ env = Env(e)
+ env.net_scope = list(self.s.get("net_scope", []))
+ return env
+
+ def offer(self, o):
+ """12.5 step 8 (held register, design 1.3): one row set keyed by id. A new offer never drops an older one of the same
+ kind (a second `cmd` used to replace the first silently); only a row offering the very same thing is replaced by
+ the newer. Each row carries born, owner, env, the file's sha and the test verdict where they apply."""
+ offers = [x for x in self.s.get("offers", []) if _same_offer(x) != _same_offer(o)]
+ self.s["offer_seq"] = int(self.s.get("offer_seq") or 0) + 1
+ o["id"] = self.s["offer_seq"]
+ o.setdefault("owner", "bench")
+ o["t"] = time.time()
+ o["born"] = _delivered_seq(self.sid) # 12.5 step 7: the turn it was offered on (the one exit's own count)
+ if o.get("file") and self.env is not None: # 12.5 step 8: what the offer rests on, to be found unchanged at go
+ try:
+ o["file_sha"] = hashlib.sha256((self.env.read(o["file"]) or "").encode("utf-8", "replace")).hexdigest()
+ except Exception: # noqa: BLE001
+ o["file_sha"] = None
+ o["env"] = self.s.get("env")
+ offers.append(o)
+ self.s["offers"] = offers[-8:]
+ self.save()
+
+ def last(self, **kw):
+ if kw:
+ self.s["last"] = dict(kw, t=time.time(), env=self.s.get("env"))
+ self.save()
+ return self.s.get("last") or {}
+
+
+class Env:
+ """a folder here, or a host over ssh; root is where paths start"""
+
+ def __init__(self, d):
+ self.d = d
+ self.net_scope = []
+ self.kind, self.root, self.host = d["kind"], d["root"], d.get("host")
+ self.key = hashlib.sha256(json.dumps([self.kind, self.host, self.root]).encode()).hexdigest()[:12]
+
+ def label(self):
+ return ("host %s:%s" % (self.host, self.root)) if self.kind == "host" else self.root
+
+ def path(self, name):
+ name = name.strip().strip("`'\"")
+ if self.kind == "host":
+ return name if name.startswith("/") else (self.root.rstrip("/") + "/" + name)
+ p = Path(os.path.expanduser(name))
+ return str(p if p.is_absolute() else Path(self.root) / name)
+
+ def sh(self, cmd, timeout=60):
+ """(exit or None on timeout, output)"""
+ if self.kind == "host":
+ argv = SSH + [self.host, "cd %s && %s" % (shlex.quote(self.root), cmd)]
+ kw = {}
+ else:
+ argv, kw = cmd, {"shell": True, "cwd": self.root, "env": _guard_env(self)}
+ try:
+ r = subprocess.run(argv, capture_output=True, text=True, timeout=timeout, errors="replace", **kw)
+ return r.returncode, (r.stdout or "") + (r.stderr or "")
+ except subprocess.TimeoutExpired:
+ return None, "ran past %d s and was stopped" % timeout
+
+ def read(self, path, cap=2_000_000):
+ if SECRET.search(os.path.basename(path)):
+ return None
+ if self.kind == "host":
+ code, out = self.sh("test -f %s && head -c %d %s" % (shlex.quote(path), cap, shlex.quote(path)), 30)
+ s = out if code == 0 else None
+ else:
+ p = Path(path)
+ if not p.is_file() or p.stat().st_size > cap:
+ return None
+ b = p.read_bytes()
+ if b"\0" in b[:4096]:
+ return None
+ s = b.decode("utf-8", "replace")
+ return None if s is None or SECRET_TEXT.search(s) else s
+
+ def write(self, path, text):
+ if self.kind == "host":
+ q = shlex.quote(path)
+ r = subprocess.run(SSH + [self.host, "cat > %s.o7new && mv %s.o7new %s" % (q, q, q)], input=text, text=True,
+ capture_output=True, timeout=30)
+ if r.returncode != 0:
+ raise OSError(r.stderr.strip()[:200])
+ return
+ p = Path(path)
+ base = Path(self.root).resolve()
+ p = p.resolve()
+ if p != base and base not in p.parents:
+ raise ValueError("The write is outside the open folder. Open the intended project folder first.")
+ import work_tasks as _work
+ _work.guard_write(p)
+ before_bytes = p.read_bytes() if p.is_file() else None
+ if p.is_file():
+ os.unlink(p) # never through a hardlink into another tree
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(text, encoding="utf-8", newline="") # exactly the text given: read() keeps \r\n, so no translation
+ _work.note_write(p, before_bytes, p.read_bytes())
+ import repair as _rp
+ _rp.drop_bytecode(p) # no later run uses the old compiled code
+
+ def exists(self, path):
+ if self.kind == "host":
+ return self.sh("test -e %s" % shlex.quote(path), 20)[0] == 0
+ return os.path.exists(path)
+
+ def isdir(self, path):
+ if self.kind == "host":
+ return self.sh("test -d %s" % shlex.quote(path), 20)[0] == 0
+ return os.path.isdir(path)
+
+ def walk(self, sub="", limit=60000):
+ """file paths under the root (or sub), skipping build and vendor folders"""
+ base = self.path(sub) if sub else self.root
+ if self.kind == "host":
+ prune = " -o ".join("-name %s" % d for d in sorted(SKIP_DIRS))
+ code, out = self.sh("find %s \\( %s \\) -prune -o -type f -print 2>/dev/null | head -n %d" % (
+ shlex.quote(base), prune, limit), 60)
+ for ln in out.splitlines():
+ yield ln
+ return
+ if os.path.isfile(base):
+ yield base
+ return
+ n = 0
+ for dp, dns, fns in os.walk(base):
+ dns[:] = sorted(d for d in dns if d not in SKIP_DIRS and not d.startswith("."))
+ for f in sorted(fns):
+ n += 1
+ if n > limit:
+ return
+ yield os.path.join(dp, f)
+
+ def rel(self, path):
+ r = self.root.rstrip("/\\")
+ return path[len(r) + 1:].replace(os.sep, "/") if path.startswith(r + os.sep) or path.startswith(r + "/") else path
+
+ def resolve(self, name):
+ p = self.path(name)
+ if self.exists(p):
+ return [p]
+ name = name.strip().strip("`'\"").lstrip("./")
+ hits = []
+ for q in self.walk():
+ if os.path.basename(q) == name or q.replace(os.sep, "/").endswith("/" + name):
+ hits.append(q)
+ if len(hits) > 8:
+ break
+ return hits
+
+
+def _ago(t):
+ s = int(time.time() - t)
+ return "%ds" % s if s < 90 else "%dm" % (s // 60) if s < 5400 else "%.1fh" % (s / 3600)
+
+
+def _r(text, state, path, **rec):
+ """a reply and its receipt; the status follows the receipt"""
+ st = {"passed": "answered", "read": "answered", "changed-checked": "answered", "done": "answered",
+ "failed": "hole", "refused": "hole", "blocked": "hole", "missing": "hole",
+ "running": "offered", "queued": "offered", "changed-untested": "offered", "waiting": "offered",
+ "interrupted": "hole", "stopped": "answered"}[state]
+ rec["state"] = state
+ return {"status": st, "path": "bench:" + path, "response": text, "execution": rec}
+
+
+def _e(env, name):
+ return "%s.%s" % (env.key, name)
+
+
+# ---------------------------------------------------------------- environment
+def open_env(turn, arg, host=False, readonly=False):
+ arg = arg.strip().strip("`'\"")
+ windows_path = bool(re.match(r"^[A-Za-z]:[/\\]", arg))
+ if host or (not windows_path and re.match(r"^[\w.-]+:(/.*)?$", arg)):
+ h, _, root = arg.partition(":")
+ root = root or "/"
+ code, out = subprocess.run(SSH + [h, "test -d %s && hostname" % shlex.quote(root)], capture_output=True, text=True,
+ timeout=25).returncode, ""
+ if code != 0:
+ return _r("I could not reach %s over ssh (or %s is not a folder there). The host must be an ssh alias this "
+ "machine can log in to with a key." % (h, root), "blocked", "open:host", started=False)
+ d = {"kind": "host", "host": h, "root": root}
+ else:
+ p = Path(os.path.expanduser(arg)).resolve()
+ if not p.is_dir():
+ return None
+ d = {"kind": "folder", "root": str(p)}
+ try: # C11: the project goes with its environment, both ways
+ import continuation as CT
+ CT.switch(turn, d)
+ except Exception: # noqa: BLE001
+ turn.s["project"] = None
+ turn.s["env"] = d
+ turn.s["authority"] = "read" if (readonly or d["kind"] == "host") else "change"
+ turn.s["offers"] = []
+ turn.s["last"] = {}
+ turn.save()
+ env = Env(d)
+ kinds, n = {}, 0
+ for q in env.walk(limit=20000):
+ n += 1
+ s = os.path.splitext(q)[1] or os.path.basename(q)
+ kinds[s] = kinds.get(s, 0) + 1
+ top = sorted(kinds.items(), key=lambda kv: -kv[1])[:8]
+ out = ["Working in %s: %d files (%s)." % (env.label(), n, ", ".join("%s %d" % kv for kv in top))]
+ for f in ("README.md", "package.json", "pyproject.toml", "Makefile", "requirements.txt", "setup.py"):
+ if env.exists(env.path(f)):
+ out.append("Has " + f + ".")
+ names = _load(_e(env, "names.json"), {})
+ if names:
+ out.append("Named commands here: " + ", ".join(sorted(names)) + ".")
+ out.append("This conversation may %s." % ("read here, not change anything (say \"allow changes\")" if
+ turn.s["authority"] == "read" else "read and change files here"))
+ return _r(" ".join(out), "read", "open", env=env.label())
+
+
+def authority(turn, change):
+ if turn.env is None:
+ return None
+ turn.s["authority"] = "change" if change else "read"
+ turn.save()
+ return _r("This conversation may now %s %s." % ("read and change" if change else "only read", turn.env.label()), "done",
+ "authority", authority=turn.s["authority"])
+
+
+def _may_change(turn):
+ return turn.s.get("authority") == "change"
+
+
+# ---------------------------------------------------------------- reading
+def ls(turn, arg):
+ env = turn.env
+ d = env.path(arg) if arg.strip() else env.root
+ if not env.isdir(d):
+ return None
+ if env.kind == "host":
+ code, out = env.sh("ls -la %s" % shlex.quote(d), 20)
+ return _r(out.strip(), "read", "ls")
+ es = sorted(Path(d).iterdir(), key=lambda q: (not q.is_dir(), q.name.lower()))
+ out = [q.name + "/" if q.is_dir() else "%s (%d B)" % (q.name, q.stat().st_size) for q in es[:150] if q.name not in SKIP_DIRS]
+ return _r("%s:%s%s" % (env.rel(d) if d != env.root else env.root, NL, NL.join(out)), "read", "ls")
+
+
+def files_named(turn, pat):
+ pat = pat.strip().strip("`'\"")
+ if not any(c in pat for c in "*?["):
+ pat = "*" + pat + "*"
+ hits = [turn.env.rel(q) for q in turn.env.walk() if fnmatch.fnmatch(os.path.basename(q).lower(), pat.lower())][:60]
+ return _r(NL.join(hits) if hits else "No file named like %s here." % pat, "read", "files")
+
+
+def read(turn, arg):
+ env = turn.env
+ m = re.match(r"(?is)^(.+?)(?:\s+(?:lines?|from line)\s+(\d+)\s*(?:-|to|\.\.)?\s*(\d+)?)?\s*$", arg.strip())
+ name, a, b = m.group(1), m.group(2), m.group(3)
+ hits = env.resolve(name)
+ if not hits:
+ return None
+ if len(hits) > 1:
+ return _r("Several files are called that:" + NL + NL.join(env.rel(h) for h in hits[:8]), "read", "read:which")
+ p = hits[0]
+ if SECRET.search(os.path.basename(p)):
+ return _r("%s looks like it holds a secret, so I don't open it." % env.rel(p), "refused", "read:secret")
+ s = env.read(p)
+ if s is None:
+ return _r("%s is not text I can show (a folder, binary, too large, or it carries a secret)." % env.rel(p), "refused",
+ "read:binary")
+ lines = s.splitlines()
+ i = max(1, int(a)) if a else 1
+ j = int(b) if b else (i + 199 if a else 200)
+ body = NL.join("%5d %s" % (k, lines[k - 1]) for k in range(i, min(j, len(lines)) + 1))
+ more = "" if j >= len(lines) else NL + "... (%d lines in all; say \"read %s lines %d-%d\")" % (len(lines), env.rel(p), j + 1, j + 200)
+ turn.last(kind="read", file=p)
+ return _r("%s (%d lines)%s```%s%s%s```%s" % (env.rel(p), len(lines), NL, NL, body, NL, more), "read", "read", files=[env.rel(p)])
+
+
+def grep(turn, pat, where=None):
+ env = turn.env
+ pat = pat.strip().strip("`'\"")
+ if env.kind == "host":
+ tgt = env.path(where) if where else env.root
+ code, out = env.sh("grep -rIn --exclude-dir=.git -i -- %s %s 2>/dev/null | head -40" % (shlex.quote(pat), shlex.quote(tgt)), 60)
+ lines = [ln for ln in out.splitlines() if not SECRET.search(ln.split(":", 1)[0].rsplit("/", 1)[-1])]
+ return _r(NL.join(ln[:220] for ln in lines) if lines else "No line there has %s." % pat, "read", "grep")
+ files = []
+ if where:
+ for h in env.resolve(where):
+ files += list(env.walk(env.rel(h))) if os.path.isdir(h) else [h]
+ if not files:
+ return _r("There is no %s here." % where, "missing", "grep")
+ else:
+ files = env.walk()
+ out, low = [], pat.lower()
+ for p in files:
+ s = env.read(p, 1_000_000)
+ if s is None or low not in s.lower():
+ continue
+ for i, ln in enumerate(s.splitlines(), 1):
+ if low in ln.lower():
+ out.append("%s:%d %s" % (env.rel(p), i, ln.strip()[:170]))
+ if len(out) >= 40:
+ break
+ if len(out) >= 40:
+ break
+ return _r(NL.join(out) if out else "No line here has %s." % pat, "read", "grep")
+
+
+# ---------------------------------------------------------------- edits (hash-checked)
+def _sha(s):
+ return hashlib.sha256((s or "").encode("utf-8")).hexdigest()[:16]
+
+
+def _record_edit(turn, path, before, after, how):
+ env = turn.env
+ log = _load(_e(env, "edits.json"), [])
+ eid = 1 + len(log)
+ d = _p(_e(env, "edits"))
+ d.mkdir(exist_ok=True)
+ if before is not None:
+ (d / ("%d.before" % eid)).write_bytes(before.encode("utf-8")) # kept exactly, line endings included
+ log.append({"id": eid, "file": path, "t": time.time(), "existed": before is not None, "before": _sha(before),
+ "after": _sha(after), "how": how, "sid": turn.sid})
+ _save(_e(env, "edits.json"), log)
+ return eid
+
+
+def _compiles(path, new):
+ if not path.endswith(".py"):
+ return None
+ try:
+ compile(new, path, "exec")
+ return None
+ except SyntaxError as e:
+ return "%s (line %s)" % (e.msg, e.lineno)
+
+
+def _diff(env, path, a, b, tag=("before", "after")):
+ d = list(difflib.unified_diff((a or "").splitlines(), b.splitlines(), "%s/%s" % (tag[0], env.rel(path)),
+ "%s/%s" % (tag[1], env.rel(path)), n=2, lineterm=""))
+ return "```diff" + NL + NL.join(d[:80] + (["... (%d more lines)" % (len(d) - 80)] if len(d) > 80 else [])) + NL + "```"
+
+
+def _apply(turn, path, before, after, how):
+ """write a change the conversation has authority for; returns the edit id"""
+ turn.env.write(path, after)
+ return _record_edit(turn, path, before, after, how)
+
+
+def _check_name(env):
+ names = _load(_e(env, "names.json"), {})
+ return next((n for n in ("test", "tests", "check", "gate", "build") if n in names), None)
+
+
+_EDIT = (re.compile(r"(?is)^(?:please\s+)?in\s+(\S+?)\s*,?\s*(?:replace|change)\s+(```\w*\n?|`|\")(.+?)\2\s+(?:with|to|by|into)\s+(```\w*\n?|`|\")(.*?)\4\s*\.?$"),
+ re.compile(r"(?is)^(?:please\s+)?(?:replace|change)\s+(```\w*\n?|`|\")(.+?)\1\s+(?:with|to|by|into)\s+(```\w*\n?|`|\")(.*?)\3\s+in\s+(\S+?)\s*\.?$"))
+
+
+def edit(turn, text):
+ m = _EDIT[0].match(text.strip())
+ if m:
+ f, a, b = m.group(1), m.group(3), m.group(5)
+ else:
+ m = _EDIT[1].match(text.strip())
+ if not m:
+ return None
+ a, b, f = m.group(2), m.group(4), m.group(5)
+ env = turn.env
+ a, b = a.strip(NL), b.strip(NL)
+ hits = env.resolve(f)
+ if len(hits) != 1:
+ return _r("%s names %s here." % (f, "no file" if not hits else "%d files: %s" % (len(hits), ", ".join(env.rel(h) for h in hits[:5]))),
+ "missing", "edit:file", started=False)
+ p = hits[0]
+ if not _may_change(turn):
+ return _r("This conversation may only read %s. Say \"allow changes\" first." % env.label(), "refused", "edit:authority",
+ started=False)
+ s = env.read(p)
+ if s is None:
+ return _r("%s is not a text file I edit." % env.rel(p), "refused", "edit:file", started=False)
+ n = s.count(a)
+ if n != 1:
+ return _r("The text to replace occurs %d times in %s; it must occur exactly once." % (n, env.rel(p)), "missing",
+ "edit:match", started=False)
+ new = s.replace(a, b)
+ bad = _compiles(p, new)
+ if bad:
+ return _r("Not made: %s would not compile after it: %s" % (env.rel(p), bad), "failed", "edit:compile", started=False)
+ eid = _apply(turn, p, s, new, "exact")
+ return _after_change(turn, p, s, new, eid, "Edit %d made to %s as you gave it." % (eid, env.rel(p)))
+
+
+def write(turn, text):
+ m = re.match(r"(?is)^(?:please\s+)?(?:write|create|save)\s+(?:the\s+|a\s+)?(?:file\s+)?([\w./~-]+\.\w{1,8})\s*:?\s*\n(.*)$", text.strip())
+ if not m:
+ return None
+ env = turn.env
+ name, body = m.group(1), m.group(2)
+ f = re.match(r"(?s)^\s*```[\w+-]*\n(.*?)\n?```\s*$", body)
+ body = (f.group(1) if f else body.rstrip()) + NL
+ if not body.strip():
+ return None
+ p = env.path(name)
+ if SECRET.search(os.path.basename(p)):
+ return _r("%s is named like a secret file; I don't write those." % name, "refused", "write:secret", started=False)
+ if not _may_change(turn):
+ return _r("This conversation may only read %s. Say \"allow changes\" first." % env.label(), "refused", "write:authority",
+ started=False)
+ bad = _compiles(p, body)
+ if bad:
+ return _r("Not written: it would not compile: %s" % bad, "failed", "write:compile", started=False)
+ old = env.read(p) if env.exists(p) else None
+ eid = _apply(turn, p, old, body, "write")
+ return _after_change(turn, p, old or "", body, eid, "Edit %d wrote %s." % (eid, env.rel(p)))
+
+
+def _after_change(turn, p, s, new, eid, head):
+ env = turn.env
+ chk = _check_name(env)
+ tail = NL + head + " Backup kept; \"undo\" takes it back."
+ if chk:
+ turn.offer({"kind": "run", "name": chk, "why": "check edit %d" % eid})
+ tail += " Run the %s on it? Say go." % chk
+ turn.last(kind="edit", edit=eid, file=p)
+ return _r(_diff(env, p, s, new) + tail, "changed-untested", "edit", files=[env.rel(p)], edit=eid)
+
+
+def undo(turn):
+ env = turn.env
+ log = _load(_e(env, "edits.json"), [])
+ live = [e for e in log if not e.get("undone")]
+ if not live:
+ return _r("There is no edit to take back.", "done", "undo")
+ e = live[-1]
+ cur = env.read(e["file"]) if env.exists(e["file"]) else None
+ if _sha(cur) != e["after"]:
+ return _r("Edit %d to %s was not taken back: the file has changed since (its content is not what that edit left), so "
+ "undoing would lose the later work. \"what changed\" shows the difference." % (e["id"], env.rel(e["file"])),
+ "blocked", "undo:conflict", started=False)
+ if e.get("existed", True):
+ env.write(e["file"], (_p(_e(env, "edits")) / ("%d.before" % e["id"])).read_bytes().decode("utf-8"))
+ elif env.kind == "folder":
+ os.unlink(e["file"])
+ else:
+ env.sh("rm -f %s" % shlex.quote(e["file"]), 20)
+ e["undone"] = time.time()
+ _save(_e(env, "edits.json"), log)
+ return _r("Edit %d to %s taken back." % (e["id"], env.rel(e["file"])), "done", "undo", files=[env.rel(e["file"])])
+
+
+def changed(turn):
+ env = turn.env
+ log = [e for e in _load(_e(env, "edits.json"), []) if not e.get("undone")]
+ if not log:
+ return _r("No file has been changed here from the chat.", "read", "diff")
+ first = {}
+ for e in log:
+ first.setdefault(e["file"], e)
+ out = []
+ for f, e in first.items():
+ bp = _p(_e(env, "edits")) / ("%d.before" % e["id"])
+ a = bp.read_bytes().decode("utf-8") if e.get("existed", True) and bp.is_file() else ""
+ b = env.read(f) if env.exists(f) else ""
+ out.append(_diff(env, f, a, b or "", ("before", "now")))
+ return _r("%d file(s) changed here from the chat:%s%s" % (len(first), NL, NL.join(out)), "read", "diff",
+ files=[env.rel(f) for f in first])
+
+
+# ---------------------------------------------------------------- commands and jobs
+def _jobs(env):
+ jobs = _load(_e(env, "jobs.json"), [])
+ ch = False
+ for j in jobs:
+ if j["state"] in ("running", "queued"):
+ d = Path(j["dir"])
+ if (d / "started").is_file() and j["state"] == "queued":
+ j["state"], j["t"] = "running", os.path.getmtime(d / "started")
+ ch = True
+ if not (d / "exit").is_file() and (d / "pid").is_file() and not _alive((d / "pid").read_text().strip()):
+ time.sleep(0.3) # Amendment 15: the runner is gone and left no exit: the outcome is
+ if not (d / "exit").is_file(): # not known, and it is said so (never "running" for ever, never a guess)
+ j["state"], j["t_end"] = "interrupted", time.time()
+ j["result"] = "interrupted: the run stopped without an exit status; what it did is not known"
+ ch = True
+ continue
+ if (d / "exit").is_file():
+ if (d / "pid").is_file():
+ _reap((d / "pid").read_text().strip()) # the finished runner collected, so none are left behind
+ stopped = _load_stop_receipt(j, env)
+ j["state"] = "stopped" if stopped else "finished"
+ try:
+ j["exit"] = int((d / "exit").read_text().strip())
+ except ValueError:
+ j["exit"] = -1
+ j["t_end"] = os.path.getmtime(d / "exit")
+ log = (d / "log").read_text(errors="replace").splitlines() if (d / "log").is_file() else []
+ rule = j.get("passes")
+ hits = [ln for ln in log if rule and re.search(re.escape(rule), ln, re.I)]
+ j["passed"] = not stopped and j["exit"] == 0 and (bool(hits) if rule else True)
+ j["result"] = "stopped as requested; log preserved" if stopped else ((hits[-1] if hits else (log[-1] if log else "(no output)")))[:300]
+ if stopped:
+ j["stopped"], j["started"] = True, bool(stopped["started"])
+ ch = True
+ if ch:
+ _save(_e(env, "jobs.json"), jobs)
+ return jobs
+
+
+def _load_stop_receipt(job, env):
+ try:
+ receipt = json.loads((Path(job["dir"]) / "stopped.json").read_text())
+ if receipt.get("state") == "stopped" and all(receipt.get(k) == v for k, v in
+ (("job", job["id"]), ("sid", job.get("sid")), ("env", env.key))) and isinstance(receipt.get("started"), bool):
+ return receipt
+ except (OSError, ValueError, TypeError):
+ pass
+ return None
+
+
+def _alive(pid):
+ try:
+ pid = int(pid)
+ except ValueError:
+ return False
+ if os.name == "nt":
+ r = subprocess.run(["tasklist", "/FI", "PID eq %d" % pid], capture_output=True, text=True)
+ return str(pid) in r.stdout
+ _reap(pid) # a runner the server started and never collected is a zombie:
+ try: # os.kill(pid, 0) succeeds on it (acceptance I1, run 1)
+ with open("/proc/%d/stat" % pid) as fh:
+ if fh.read().rsplit(")", 1)[-1].split()[0] == "Z":
+ return False
+ except FileNotFoundError:
+ return False
+ except Exception: # noqa: BLE001
+ pass
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True
+ return True
+
+
+def _reap(pid):
+ """collect one of the bench's own runners if it has ended (only that pid: other children are their owners' to collect)"""
+ if os.name == "nt":
+ return
+ try:
+ os.waitpid(int(pid), os.WNOHANG)
+ except (ChildProcessError, OSError, ValueError):
+ pass
+
+
+def changed_since(env, t, limit=12):
+ """files of the environment changed after a moment: what an interrupted run may have done"""
+ out = []
+ if env.kind != "folder":
+ code, o = env.sh("find . -newermt @%d -type f 2>/dev/null | head -n %d" % (int(t), limit), 30)
+ return [x for x in o.splitlines() if x.strip()]
+ for p in env.walk(limit=20000):
+ try:
+ if os.path.getmtime(p) > t:
+ out.append(env.rel(p))
+ except OSError:
+ continue
+ if len(out) >= limit:
+ break
+ return out
+
+
+def interrupted_check(turn, j):
+ """before anything is run again after an interruption: what the environment shows now, and a go to repeat"""
+ env = turn.env
+ log = (Path(j["dir"]) / "log").read_text(errors="replace").splitlines() if (Path(j["dir"]) / "log").is_file() else []
+ ch = changed_since(env, j["t"])
+ turn.offer({"kind": "cmd", "cmd": j["cmd"], "name": j.get("name")})
+ return _r("Job %d (`%s`) was interrupted: it stopped without an exit status, so whether it finished its work is not known. "
+ "Before running it again, what the environment shows now:%s- files changed since it started: %s%s- the last lines it "
+ "wrote:%s%s%sIf it is safe to repeat, say go; otherwise tell me what to check first." % (
+ j["id"], j["cmd"][:100], NL, ", ".join(ch) if ch else "none", NL, NL,
+ NL.join(" " + ln[:200] for ln in log[-6:]) or " (nothing)", NL),
+ "waiting", "run:interrupted", job=j["id"], files=ch)
+
+
+def _receipt(j):
+ if j["state"] == "stopped":
+ return "stopped", {"job": j["id"], "started": j.get("started", True), "finished": True,
+ "exit": j.get("exit"), "stopped": True, "passed": False}
+ if j["state"] == "interrupted":
+ return "interrupted", {"job": j["id"], "started": True, "finished": False, "exit": None}
+ if j["state"] in ("running", "queued"):
+ return j["state"], {"job": j["id"], "started": j["state"] == "running", "finished": False}
+ return ("passed" if j.get("passed") else "failed"), {"job": j["id"], "started": True, "finished": True,
+ "exit": j.get("exit"), "check": j.get("passes"),
+ "timeout": False}
+
+
+def run_cmd(turn, cmd, name=None, confirmed=False):
+ env = turn.env
+ names = _load(_e(env, "names.json"), {})
+ alone = bool(name and names.get(name, {}).get("alone"))
+ if DANGER.search(cmd) and not confirmed:
+ turn.offer({"kind": "cmd", "cmd": cmd, "name": name})
+ return _r("That command can destroy, stop or restart things on %s:%s```%s%s%s```%sSay go to run it, or cancel." % (
+ env.label(), NL, NL, cmd, NL, NL), "waiting", "run:confirm", started=False)
+ if env.kind == "host" and not _may_change(turn) and not re.match(
+ r"^\s*(?:ls|cat|head|tail|grep|find|ps|ss|netstat|df|du|free|uptime|uname|whoami|id|systemctl\s+(?:status|is-active|"
+ r"list-units)|journalctl|stat|wc|sha256sum|nginx\s+-t|sshd\s+-t|git\s+(?:status|log|diff))\b", cmd):
+ return _r("This conversation may only read %s, and that command is not one I know to be read-only. Say \"allow "
+ "changes\" to run it." % env.label(), "refused", "run:authority", started=False)
+ if os.environ.get("ORACLE7_BENCH_DRY") == "1":
+ return _r("Would run on %s: %s (dry run)." % (env.label(), cmd), "waiting", "run", started=False)
+ jobs = _jobs(env)
+ if name:
+ live = [j for j in jobs if j.get("name") == name and j["state"] in ("running", "queued")]
+ if live:
+ return _r("The %s is already %s (job %d, %s)." % (name, live[0]["state"], live[0]["id"], _ago(live[0]["t"])),
+ live[0]["state"], "run:already", job=live[0]["id"])
+ jid = 1 + max([j["id"] for j in jobs] or [0])
+ d = _p(_e(env, "jobs")) / str(jid)
+ d.mkdir(parents=True, exist_ok=True)
+ full = cmd if env.kind == "folder" else " ".join(shlex.quote(x) for x in SSH + [env.host, "cd %s && %s" % (shlex.quote(env.root), cmd)])
+ (d / "cmd").write_text(full + NL)
+ (d / "owner.json").write_text(json.dumps({"token": secrets.token_urlsafe(32), "sid": turn.sid,
+ "env": env.key, "job": jid, "command_sha256": hashlib.sha256((full + NL).encode()).hexdigest()}))
+ rp = _p("runner.py")
+ if not rp.is_file() or rp.read_text() != RUNNER:
+ rp.write_text(RUNNER)
+ lock = _p("alone.lock")
+ busy = alone and lock.is_file()
+ kw = {"start_new_session": True} if os.name != "nt" else {"creationflags": 0x00000008 | 0x00000200}
+ own = Path(__file__).resolve().parent # Oracle7's own tools (its judges over its own candidates) run as
+ if env.kind == "folder" and not (name == "judge" and str(own / "judge") in cmd): # Oracle7; project code is jailed
+ kw["env"] = _guard_env(env) # the conversation's network scope holds in what it runs
+ subprocess.Popen([sys.executable, str(rp), str(d), str(lock) if alone else "-"], cwd=env.root if env.kind == "folder" else None,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL, **kw)
+ rule = names.get(name, {}).get("passes") if name else None
+ jobs.append({"id": jid, "name": name, "cmd": cmd, "dir": str(d), "t": time.time(), "sid": turn.sid,
+ "state": "queued" if busy else "running", "passes": rule, "control_version": 1})
+ _save(_e(env, "jobs.json"), jobs)
+ turn.last(kind="job", job=jid, cmd=cmd, name=name)
+ if not busy:
+ t0 = time.time()
+ while time.time() - t0 < QUICK and not (d / "exit").is_file():
+ time.sleep(0.3)
+ if (d / "exit").is_file():
+ time.sleep(0.05)
+ j = [x for x in _jobs(env) if x["id"] == jid][0]
+ log = (d / "log").read_text(errors="replace")
+ body = log[-6000:]
+ st, rec = _receipt(j)
+ verdict = "exit %d" % j["exit"] + ("" if not rule else (", passed" if j["passed"] else ", did not pass (looked for: %s)" % rule))
+ return _r("```%s$ %s%s%s%s```%s%s" % (NL, cmd, NL, body.rstrip(), NL, NL, verdict), st, "run", **rec)
+ label = ("the " + name) if name else "`%s`" % cmd[:80]
+ return _r("%s is %s as job %d. \"where are we\" or \"is it done\" shows how it stands; \"what failed\" reads its log." % (
+ label[:1].upper() + label[1:], "waiting its turn (one at a time)" if busy else "running (still going after %ds)" % QUICK, jid),
+ "queued" if busy else "running", "run:job", job=jid, started=not busy, finished=False)
+
+
+def stop_job(turn, number=None):
+ """Ask this local job's owning runner to stop; never signal a stored PID."""
+ env = turn.env
+ if env is None or env.kind != "folder":
+ return _r("Stopping an app needs its local project folder open in this conversation.", "missing", "stop", started=False)
+ if not _may_change(turn):
+ return _r("This conversation may only read this folder. Say \"allow changes\" before stopping its app.",
+ "refused", "stop:authority", started=False)
+ jobs = _jobs(env)
+ mine = [j for j in jobs if j.get("sid") == turn.sid]
+ if number is not None:
+ job = next((j for j in jobs if j["id"] == int(number)), None)
+ if job is None or job.get("sid") != turn.sid:
+ return _r("Job %s is not a job of this conversation in the currently open folder." % number,
+ "refused", "stop:ownership", started=False)
+ else:
+ live = [j for j in mine if j["state"] in ("running", "queued")]
+ if len(live) > 1:
+ return _r("Several jobs are running here. Say stop job %s to choose one." %
+ " or stop job ".join(str(j["id"]) for j in live), "missing", "stop:scope", started=False)
+ job = live[0] if live else mine[-1] if mine else None
+ if job is None:
+ return _r("This conversation has no app job in the currently open folder.", "missing", "stop", started=False)
+ if job["state"] == "stopped":
+ state, receipt = _receipt(job)
+ return _r("Job %d is already stopped. Its log is kept." % job["id"], state, "stop", **receipt)
+ if job["state"] not in ("running", "queued"):
+ return _r("Job %d is already %s; no process was stopped." % (job["id"], job["state"]),
+ "read", "stop", job=job["id"], job_state=job["state"], finished=True, stopped=False)
+ directory = Path(job["dir"]).resolve()
+ expected = (_p(_e(env, "jobs")) / str(job["id"])).resolve()
+ if directory != expected or job.get("control_version") != 1:
+ return _r("This older job has no owned stop control. Its process identity cannot safely be inferred; its log is kept.",
+ "missing", "stop:binding", job=job["id"], started=False)
+ try:
+ owner = json.loads((directory / "owner.json").read_text())
+ command = (directory / "cmd").read_text()
+ if not owner.get("token") or any(owner.get(k) != v for k, v in
+ (("sid", turn.sid), ("env", env.key), ("job", job["id"]))) or \
+ owner.get("command_sha256") != hashlib.sha256(command.encode()).hexdigest():
+ raise ValueError("the job's owner or command receipt changed")
+ except (OSError, ValueError, TypeError) as error:
+ return _r("This job's stop binding could not be checked: %s" % error,
+ "missing", "stop:binding", job=job["id"], started=False)
+ request = {k: owner[k] for k in ("token", "sid", "env", "job")}
+ request.update(id=secrets.token_urlsafe(20), requested=time.time())
+ temporary = directory / ("stop." + secrets.token_hex(6) + ".new")
+ try:
+ temporary.write_text(json.dumps(request)); os.replace(temporary, directory / "stop.json")
+ finally:
+ temporary.unlink(missing_ok=True)
+ deadline = time.monotonic() + 8
+ while time.monotonic() < deadline:
+ current = next(j for j in _jobs(env) if j["id"] == job["id"])
+ if current["state"] == "stopped":
+ state, receipt = _receipt(current)
+ return _r("Stopped job %d%s. Its log is kept; the run is marked stopped, not passed." %
+ (job["id"], " before it started" if not current.get("started") else ""), state, "stop", **receipt)
+ if current["state"] not in ("running", "queued"):
+ return _r("Job %d %s before the stop was acknowledged; its recorded result and log are kept." %
+ (job["id"], current["state"]), "read", "stop", job=job["id"],
+ job_state=current["state"], finished=True, stopped=False)
+ error_file = directory / "stop_error.json"
+ if error_file.is_file():
+ try:
+ error = json.loads(error_file.read_text())
+ if error.get("id") == request["id"]:
+ return _r("The owning runner could not finish stopping job %d: %s. The job remains observable; say stop job %d to retry." %
+ (job["id"], error.get("error"), job["id"]), "failed", "stop",
+ job=job["id"], finished=False, stopped=False)
+ except (OSError, ValueError):
+ pass
+ time.sleep(.1)
+ return _r("Job %d's owning runner received a stop request; it has not acknowledged stopping yet." % job["id"],
+ "running", "stop", job=job["id"], stop_requested=True, finished=False, stopped=False)
+
+
+def name_cmd(turn, cmd, name, alone):
+ env = turn.env
+ names = _load(_e(env, "names.json"), {})
+ old = names.get(name, {})
+ names[name] = {"cmd": cmd, "alone": alone or old.get("alone", False), "passes": old.get("passes")}
+ _save(_e(env, "names.json"), names)
+ return _r("\"run the %s\" now runs `%s` on %s%s." % (name, cmd, env.label(), ", one at a time" if names[name]["alone"] else ""),
+ "done", "name")
+
+
+def name_rule(turn, name, rule):
+ env = turn.env
+ names = _load(_e(env, "names.json"), {})
+ if name not in names:
+ return _r("There is no command called the %s here. Name one: call `command` the %s." % (name, name), "missing", "name")
+ names[name]["passes"] = rule
+ _save(_e(env, "names.json"), names)
+ return _r("The %s passes when its output says \"%s\" and it exits 0." % (name, rule), "done", "name")
+
+
+def status(turn):
+ env = turn.env
+ jobs = _jobs(env)
+ out = ["Environment: %s (this conversation may %s)" % (env.label(), "change it" if _may_change(turn) else "only read it")]
+ if turn.s.get("goal"):
+ out.append("Goal: " + turn.s["goal"])
+ pj = turn.s.get("project")
+ if pj and pj.get("env") in (None, env.key): # C11: the project of this environment, from its own record
+ att = pj.get("attempts") or []
+ try: # C31: the record is history; say when what it rested on has changed
+ import continuation as _ct
+ if att and env.kind == "folder" and att[-1].get("fp") and att[-1]["fp"] != _ct.fingerprint(pj, env.root, _authority(turn)):
+ out.append("Note: attempt %d's result rests on inputs or authority that have changed since (files, words or "
+ "permissions); it was true then and needs a fresh run to count now." % att[-1]["seq"])
+ except Exception: # noqa: BLE001
+ pass
+ out.append("Project %s (id %s): %s after attempt %d; your words kept: %d turn%s%s." % (
+ pj.get("module") or "(no module yet)", pj.get("pid", "?"), pj.get("status"), att[-1]["seq"] if att else 0,
+ len(pj.get("clauses") or []), "" if len(pj.get("clauses") or []) == 1 else "s",
+ ("; open holes: " + " | ".join(h.get("text", "")[:120] for h in pj.get("holes_kept") or [])) if pj.get("holes_kept") else ""))
+ others = [k for k in (turn.s.get("projects") or {}) if k != env.key and turn.s["projects"][k]]
+ if others:
+ out.append("Projects kept in other environments of this conversation: %s." % ", ".join(
+ "%s (%s)" % (turn.s["projects"][k].get("module") or "?", turn.s["projects"][k].get("env_root") or k) for k in others))
+ run = [j for j in jobs if j["state"] in ("running", "queued")]
+ fin = [j for j in jobs if j["state"] in ("finished", "interrupted", "stopped")][-6:]
+ if run or fin:
+ out += ["", "Jobs:"]
+ seen = turn.s.setdefault("log_seen", {})
+ for j in run: # C11: a job whose log grows is progressing; one whose log is still is not
+ lp = Path(j["dir"]) / "log"
+ size, mt = (lp.stat().st_size, lp.stat().st_mtime) if lp.is_file() else (0, j["t"])
+ before = seen.get(str(j["id"]))
+ how = ("progressing: %d bytes of output since you last asked" % (size - before) if before is not None and size > before
+ else "no new output since you last asked (last output %s ago)" % _ago(mt) if before is not None
+ else "%d bytes of output so far, the last %s ago" % (size, _ago(mt)))
+ seen[str(j["id"])] = size
+ out.append("- %d %s: %s, %s; %s" % (j["id"], j.get("name") or j["cmd"][:60], j["state"], _ago(j["t"]), how))
+ if run:
+ turn.save()
+ for j in reversed(fin):
+ mark = "STOPPED (as requested)" if j["state"] == "stopped" else "INTERRUPTED (outcome not known)" if j["state"] == "interrupted" else "passed" if j.get("passed") else \
+ "FAILED (exit %s)" % j.get("exit")
+ out.append("- %d %s: %s %s ago: %s" % (j["id"], j.get("name") or j["cmd"][:60], mark, _ago(j["t_end"]), j["result"]))
+ eds = [e for e in _load(_e(env, "edits.json"), []) if not e.get("undone")]
+ if eds:
+ out += ["", "Changed from the chat: " + ", ".join(sorted({env.rel(e["file"]) for e in eds})[:10])]
+ fs = turn.s.get("findings")
+ if fs:
+ out += ["", "Findings open: " + ", ".join("%d %s" % (i + 1, f["rule"]) for i, f in enumerate(fs) if not f.get("fixed"))]
+ offers = turn.s.get("offers", [])
+ if offers:
+ out += ["", "Waiting for your go:"] + ["- go %d: %s" % (i + 1, _offer_text(o)) for i, o in enumerate(offers)]
+ ts = [t for t in _load(_e(env, "tasks.json"), []) if not t.get("done")]
+ if ts:
+ out += ["", "Open tasks:"] + ["- %d. %s" % (t["id"], t["text"]) for t in ts[-8:]]
+ names = _load(_e(env, "names.json"), {})
+ if names:
+ out += ["", "Named commands: " + ", ".join(sorted(names))]
+ return _r(NL.join(out), "read", "status")
+
+
+def _offer_text(o):
+ k = o.get("kind")
+ if k == "run":
+ return "run the %s (%s)" % (o["name"], o.get("why", ""))
+ if k == "cmd":
+ return "run `%s`" % o["cmd"][:80]
+ if k == "repair_value":
+ return "finish the change to %s() once you say what it gives for an empty %s" % (o["function"], o["param"])
+ if k == "fix":
+ return "apply the correction for finding %d (%s)" % (o["n"], o["rule"])
+ if k == "resolved":
+ return "`%s` (how I read your words)" % o["sent"]
+ if k == "selfdev_build":
+ return "build the proposed change to myself (%s) as a candidate and judge it" % ", ".join("%s = %s" % kv for kv in sorted(o["new"].items()))
+ if k == "selfdev_adopt":
+ return "adopt the candidate the judge passed"
+ if k == "project_go":
+ return "go on with the project"
+ return k
+
+
+_FAILLINE = re.compile(r"(?i)(error|fail|traceback|exception|assert|fatal|denied|not found|no such)")
+
+
+def _job_for(turn, text):
+ env = turn.env
+ jobs = _jobs(env)
+ m = re.search(r"\bjob\s*(\d+)\b|\blog of (\d+)\b", text)
+ names = _load(_e(env, "names.json"), {})
+ nm = next((n for n in sorted(names, key=len, reverse=True) if re.search(r"\b" + re.escape(n) + r"\b", text.lower())), None)
+ if m:
+ return next((j for j in jobs if j["id"] == int(m.group(1) or m.group(2))), None)
+ if nm:
+ js = [j for j in jobs if j.get("name") == nm]
+ return js[-1] if js else None
+ last = turn.last()
+ if last.get("job"):
+ return next((j for j in jobs if j["id"] == last["job"]), None)
+ mine = [j for j in jobs if j.get("sid") == turn.sid]
+ return mine[-1] if mine else None
+
+
+def log_of(turn, text):
+ j = _job_for(turn, text)
+ if not j:
+ return _r("This conversation has not run anything here yet.", "missing", "log")
+ log = (Path(j["dir"]) / "log").read_text(errors="replace").splitlines() if (Path(j["dir"]) / "log").is_file() else []
+ st, rec = _receipt(j)
+ out = ["Job %d %s: %s%s" % (j["id"], j.get("name") or "", j["state"],
+ "" if j["state"] != "finished" else ", exit %s, %s" % (j["exit"], "passed" if j.get("passed") else "FAILED"))]
+ out.append("$ " + j["cmd"])
+ bad = [ln for ln in log if _FAILLINE.search(ln)]
+ if bad and not j.get("passed"):
+ out += ["", "Lines that report a failure (%d):" % len(bad)] + [" " + ln[:220] for ln in bad[-15:]]
+ out += ["", "Last lines of the log (%d in all):" % len(log)] + [" " + ln[:220] for ln in log[-25:]]
+ return _r(NL.join(out), "read", "log", job=j["id"], job_state=st)
+
+
+def solved(turn):
+ """did that solve it: the check run after the last change, or the offer to run it"""
+ env = turn.env
+ last = turn.last()
+ chk = _check_name(env)
+ eds = [e for e in _load(_e(env, "edits.json"), []) if not e.get("undone")]
+ after = max([e["t"] for e in eds] or [0])
+ js = [j for j in _jobs(env) if j["t"] >= after and (not chk or j.get("name") == chk)]
+ if js and js[-1]["state"] == "finished":
+ j = js[-1]
+ return _r("After the last change, %s %s: %s" % (j.get("name") or "`%s`" % j["cmd"], "passed" if j["passed"] else
+ "FAILED (exit %s)" % j["exit"], j["result"]), *_receipt(j)[:1], "solved",
+ **_receipt(j)[1])
+ if last.get("kind") == "repair" and last.get("checked"):
+ return _r("Yes: the change to %s() was kept because the check passed (%s)." % (last["function"], last.get("check")),
+ "passed", "solved")
+ if chk:
+ turn.offer({"kind": "run", "name": chk, "why": "see whether the last change solved it"})
+ return _r("Nothing has checked it since the last change. Run the %s? Say go." % chk, "waiting", "solved")
+ return _r("Nothing has checked it since the last change, and no check is named here (call `command` the test).",
+ "missing", "solved")
+
+
+# ---------------------------------------------------------------- described changes
+def repair_turn(turn, text, value=None):
+ import repair as R
+ env = turn.env
+ if env.kind != "folder":
+ return _r("Described code changes work on a folder; for %s, read the file and give the change, or audit it." % env.label(),
+ "missing", "repair", started=False)
+ if not _may_change(turn):
+ return _r("This conversation may only read %s. Say \"allow changes\" first." % env.label(), "refused", "repair:authority",
+ started=False)
+ req = R.read_request(text)
+ if value:
+ req["value"], req["empty"] = value, True
+ log_text = ""
+ j = _job_for(turn, "")
+ if j and j["state"] == "finished" and not j.get("passed"):
+ lp = Path(j["dir"]) / "log"
+ log_text = lp.read_text(errors="replace") if lp.is_file() else ""
+ prev = turn.s.get("repair_text")
+ if re.match(r"(?i)^\s*(?:ok(?:ay)?\s*,?\s*)?(?:fix|repair|correct)\s+(?:that|it|this)\b", text) and prev and not log_text:
+ req = R.read_request(prev)
+ names = _load(_e(env, "names.json"), {})
+ chk = _check_name(env)
+ cmd = names[chk]["cmd"] if chk else R.test_command(env.root)
+ last = turn.last()
+ prefer = (last["file"], last["function"]) if last.get("function") and last.get("file") else None
+ turn.s["goal"] = " ".join(text.split())[:200] if not re.match(r"(?i)^\s*(fix|repair|correct)\s+(that|it|this)\b", text) else turn.s.get("goal")
+ turn.s["repair_text"] = text
+ turn.save()
+ res = R.attempt(env.root, req, cmd, log_text, prefer=prefer)
+ if not res["done"] and res.get("missing") == "change" and cmd:
+ rc = recompose(turn, text, req, log_text, cmd, res) # CODE_SPEC C3: repair is composition aimed at the failing check
+ if rc:
+ return rc
+ if not res["done"]:
+ if res.get("missing") == "value":
+ turn.offer({"kind": "repair_value", "function": res["function"], "param": res["param"], "text": text})
+ why = ""
+ if res.get("considered"):
+ why = NL + "Looked at: " + "; ".join(res["considered"][:4])
+ if res.get("caps"): # the search reached its own limits: what reproduces this, for the judge
+ why += NL + "Ask \"propose an improvement to yourself\" to have that limit changed in a candidate and judged."
+ return _r(res["say"] + why, "waiting" if res.get("missing") == "value" else "missing", "repair:" + res["missing"],
+ started=bool(res.get("tried")), tried=res.get("tried", 0), caps=res.get("caps") or {},
+ request={"text": text, "root": env.root, "check": cmd, "log": log_text[-4000:] if log_text else ""})
+ p = str(res["file"])
+ eid = _record_edit(turn, p, res["before"], res["after"], "repair: " + res["what"])
+ turn.last(kind="repair", edit=eid, file=p, function=res["function"], checked=res["checked"], check=cmd)
+ head = "In %s(), %s, %s." % (res["function"], env.rel(p), res["what"])
+ if res["checked"]:
+ tail = "%s ran the check `%s` after it and it passed (%d candidate change%s tried). Edit %d; \"undo\" takes it back." % (
+ NL, cmd, res["tried"], "" if res["tried"] == 1 else "s", eid)
+ out = (res.get("check_out") or "").strip().splitlines()[-4:]
+ return _r(head + NL + _diff(env, p, res["before"], res["after"]) + tail + NL + "```" + NL + NL.join(out) + NL + "```",
+ "changed-checked", "repair", files=[env.rel(p)], edit=eid, check="passed", started=True, finished=True, exit=0,
+ function=res["function"], what=res["what"], tried=res["tried"])
+ env.write(p, res["after"])
+ if res.get("still_passes"):
+ note = ("Edit %d. The check `%s` passed before this change and still passes after it, so it does not test what you "
+ "asked: this is changed, and not yet checked for the new behaviour. Add a test for it, or try it with "
+ "run `command`." % (eid, cmd))
+ else:
+ note = "Edit %d. There is no check here to run, so this is changed but untested: name one with call `command` the test." % eid
+ return _r(head + NL + _diff(env, p, res["before"], res["after"]) + NL + note, "changed-untested", "repair",
+ files=[env.rel(p)], edit=eid, check="not testing this" if res.get("still_passes") else None,
+ function=res["function"], what=res["what"], tried=1)
+
+
+# ---------------------------------------------------------------- code written by composition (CODE_SPEC.md, C1-C3)
+def _module_of(env, p):
+ rel = os.path.relpath(p, env.root)
+ return ".".join(Path(rel).with_suffix("").parts)
+
+
+def _with_functions(old, sources, imports):
+ """the file with the composed functions appended and their imports added after the file's own"""
+ new = old or ""
+ have = set(re.findall(r"(?m)^(?:import|from) .+$", new))
+ add = ["import %s" % i for i in imports if "import %s" % i not in have]
+ if add:
+ lines = new.splitlines()
+ at = 0
+ for i, ln in enumerate(lines):
+ if re.match(r"^(?:import|from) ", ln):
+ at = i + 1
+ if at == 0 and lines and lines[0].startswith(('"""', "'''")): # after a module docstring
+ j = 0
+ q = lines[0][:3]
+ if not (lines[0].count(q) >= 2 and len(lines[0]) > 3):
+ j = next((k for k in range(1, len(lines)) if q in lines[k]), 0)
+ at = j + 1
+ lines[at:at] = add
+ new = NL.join(lines) + NL
+ out, have_defs = [], set(re.findall(r"(?m)^def (\w+)\(", new))
+ for s in sources: # a part already in the file (or already added) is not written twice
+ m = re.search(r"(?m)^def (\w+)\(", s)
+ if m and m.group(1) in have_defs:
+ continue
+ if m:
+ have_defs.add(m.group(1))
+ out.append(s)
+ if not out:
+ return new
+ return new.rstrip(NL) + (NL + NL + NL if new.strip() else "") + (NL + NL + NL).join(s.rstrip(NL) for s in out) + NL
+
+
+def _srcs(r):
+ """a composed function's source, with the parts from outside the project it calls written before it"""
+ return list(r.get("support") or []) + [r["source"]]
+
+
+def _how(r):
+ m = r.get("moves") or []
+ return "%s (%d move%s; %s; %d example%s, read back by a separate interpreter: %s)" % (
+ " -> ".join(m) if m else "composed", r.get("size") or len(m), "" if (r.get("size") or len(m)) == 1 else "s",
+ "branches" if r.get("branches") else "one expression", r["examples"], "" if r["examples"] == 1 else "s",
+ r["read_back"].replace("read back ", ""))
+
+
+def _check_cmd(env):
+ import repair as R
+ names = _load(_e(env, "names.json"), {})
+ chk = _check_name(env)
+ return names[chk]["cmd"] if chk else R.test_command(env.root)
+
+
+def _write_checked(turn, writes, how, head, ex_note=None):
+ """write the files, run the project's check; kept (and recorded as edits) only if the check passes after it, else put
+ back. writes: [(path, old or None, new)]"""
+ import repair as R
+ env = turn.env
+ cmd = _check_cmd(env)
+ for p, _old, new in writes:
+ bad = _compiles(p, new)
+ if bad:
+ return _r(head + NL + "Not written: the file would not compile: %s" % bad, "failed", "compose:compile", started=False)
+ before = R.run_check(cmd, env.root)[0] if cmd else None
+ for p, _old, new in writes:
+ env.write(p, new)
+ diff = NL.join(_diff(env, p, old or "", new) for p, old, new in writes)
+ if cmd:
+ ok, out, code = R.run_check(cmd, env.root)
+ if not ok:
+ for p, old, _new in writes:
+ if old is None:
+ os.remove(p)
+ else:
+ env.write(p, old)
+ return _r(head + NL + diff + NL + "The check `%s` FAILED after it, so it was put back:%s```%s%s%s```" % (
+ cmd, NL, NL, out[-1200:], NL), "failed", "compose:check", started=True, finished=True, exit=code,
+ files=[env.rel(p) for p, _o, _n in writes])
+ eids = [_record_edit(turn, p, old, new, how) for p, old, new in writes]
+ files = [env.rel(p) for p, _o, _n in writes]
+ ed = "Edit%s %s; \"undo\" takes %s back." % ("s" if len(eids) > 1 else "", ", ".join(map(str, eids)), "them" if len(eids) > 1 else "it")
+ if cmd:
+ tail = "The check `%s` %s and passes now. %s" % (cmd, "failed before" if not before else "passed before", ed)
+ if before and not ex_note:
+ # round-3 R3, the witness rule: composed content under a check that passed before as well is not told apart
+ return _r(head + NL + diff + NL + tail + " The check passed before this change as well, so it does not tell this "
+ "change apart: it is kept, not yet checked. Give an example or a test it must pass.", "changed-unwitnessed",
+ "compose", files=files, edit=eids[-1], check="passed before and after", started=True, finished=True, exit=0)
+ return _r(head + NL + diff + NL + tail, "changed-checked", "compose", files=files, edit=eids[-1],
+ check="passed" if not before else "your examples, and the check still passes", started=True, finished=True, exit=0)
+ if ex_note:
+ return _r(head + NL + diff + NL + "There are no tests here; %s. %s" % (ex_note, ed), "changed-checked", "compose",
+ files=files, edit=eids[-1], check="your examples", started=True, finished=True, exit=0)
+ return _r(head + NL + diff + NL + "There is no check here, so this is changed, not yet checked. " + ed, "changed-untested",
+ "compose", files=files, edit=eids[-1])
+
+
+def _gap_text(rs):
+ return NL.join(" - %s: %s" % (r["name"], r.get("gap") or r.get("status")) for r in rs)
+
+
+_TGOAL_VERB = re.compile(r"(?i)\b(?:make|get|write|create|implement|build|fill in|add)\b")
+_TGOAL_PASS = re.compile(r"(?i)\b(?:pass|passes|passing|green|needs?|expects?|calls?|wants?)\b")
+
+
+def project_turn(turn, text):
+ """a project described as a whole (project.py): read into a ledger of requirements, planned over shapes from its
+ outcomes back to its tables, written from parts, and judged requirement by requirement against what it does. A hole
+ (a word nobody owns, a table not there, a value no part makes) keeps the project as it is, in the conversation and in
+ the project's .oracle7 folder; the next turn's example, file, explanation or "drop" fills it and the build goes on,
+ after a restart too. A value made from a column comes from Oracle7's code store (by its sha) or is composed from
+ examples and kept once the project's judges pass with it."""
+ import project as PJ
+ import continuation as CT
+ env = turn.env
+ if env is None or env.kind != "folder":
+ return None
+ kept = CT.bind(turn, env) # C11: only the project of the environment that is open
+ if turn.s.get("focus") == "work" and not PJ.is_project(text, None):
+ return None # a follow-up belongs to the active work record
+ if kept is None and PJ.CONTINUE.match(text.strip()):
+ kept = PJ.load_project(env.root) # a project left unfinished, continued from its folder
+ import language_bridge as language
+ account = language.project_answer(text, kept)
+ if account:
+ return account
+ if language.asks_about(text):
+ return None # a question containing "now" is not a project revision
+ fresh = bool(kept and re.match(
+ r"(?i)^\s*(?:build|make|create|develop|start|set up)\s+(?:(?:a|an)\s+)?(?:new|separate)\s+"
+ r"(?:project|app|application|script|tool)\b", text))
+ if not PJ.is_project(text, None if fresh else kept):
+ return None
+ if not _may_change(turn):
+ return _r("This conversation may only read %s. Say \"allow changes\" first." % env.label(), "refused",
+ "project:authority", started=False)
+ if fresh:
+ # A separately requested project starts from its own clauses. The old
+ # project remains available in the conversation record.
+ turn.s.setdefault("project_history", []).append(kept)
+ kept = None
+ pre = []
+ auth = _authority(turn)
+ prev = CT.unchanged_retry(kept, env.root, text, auth) if kept else None
+ if prev: # going again on the same inputs would show the same: a different step
+ step = CT.choose(turn, kept, env.root, kept.get("last_reply") or {}, CT.used_for(kept, prev["sig"]), _guard_env(env))
+ if not step.get("rerun"):
+ same = {"response": "", "execution": dict((kept.get("last_reply") or {}).get("execution") or {})}
+ a = CT.record(kept, text, same, prev["fp"], cont=step["kind"])
+ a["sig"] = prev["sig"]
+ turn.s["project"] = kept
+ turn.save()
+ try:
+ PJ.save_project(env.root, kept)
+ except OSError:
+ pass
+ return _r("Nothing this project depends on has changed since attempt %d (the same words, meanings and examples, "
+ "the same files, the same store), so going again would show what it showed then. Instead: %s" % (
+ prev["seq"], step["text"]), prev.get("state") or "missing", "project:continue:" + step["kind"],
+ started=False, continuation={"attempt": a["seq"], "same_inputs_as": prev["seq"], "step": step["kind"],
+ "pid": kept.get("pid")})
+ pre.append(step["text"])
+ r = _project_core(turn, text, kept, env)
+ shape = turn.s.get("project")
+ st = (r.get("execution") or {}).get("state")
+ if shape is not None and st == "missing": # a missing table an adopted capability of mine makes: made, and on
+ step = None
+ for h in shape.get("holes_kept") or []:
+ got = CT._parts_for(h, shape) if h.get("kind") == "world" and h.get("file") else None
+ if got and got[0] == "capability":
+ step = CT.choose(turn, shape, env.root, r, (), _guard_env(env))
+ break
+ if step and step.get("rerun"):
+ pre.append(step["text"])
+ r = _project_core(turn, "continue", shape, env)
+ shape = turn.s.get("project")
+ if shape is None:
+ return r
+ a = CT.record(shape, text, r, CT.fingerprint(shape, env.root, _authority(turn)))
+ n_same = CT.same_outcome_run(shape)
+ if (r.get("execution") or {}).get("state") in CT.UNFINISHED and n_same >= 2:
+ step = CT.choose(turn, shape, env.root, r, CT.used_for(shape, a["sig"]), _guard_env(env))
+ a["cont"] = step["kind"]
+ r["response"] += NL + "This ended as attempt %d did (nothing new came of it), so this time, differently: %s" % (
+ shape["attempts"][-2]["seq"], step["text"])
+ if pre:
+ r["response"] = NL.join(pre) + NL + r["response"]
+ r.setdefault("execution", {})["continuation"] = {"attempt": a["seq"], "pid": shape.get("pid"), "env": env.key,
+ "same_outcome_as_before": n_same - 1, "step": a.get("cont")}
+ ex = r.get("execution") or {}
+ shape["last_reply"] = {"response": (r.get("response") or "")[-6000:],
+ "execution": {k: ex.get(k) for k in ("state", "requirements", "holes") if k in ex}}
+ turn.s["project"] = shape
+ turn.s["focus"] = "project"
+ turn.save()
+ try:
+ PJ.save_project(env.root, shape)
+ except OSError:
+ pass
+ return r
+
+
+def _project_core(turn, text, kept, env):
+ """one attempt of a project turn: received, planned, composed, written, judged (stages a turn job shows)"""
+ import project as PJ
+ import continuation as CT
+ CT.stage("receiving")
+ shape = CT.stamp(PJ.receive(text, env.root, kept), env)
+ pipes, holes, reqs, world = PJ.plan(shape, env.root)
+ CT.stage("composing")
+ composed = PJ.compose_holes(env.root, shape, holes, env.net_scope)
+ if composed:
+ pipes, holes, reqs, world = PJ.plan(shape, env.root)
+ CT.stage("planned")
+ # C15: a correction must change the project. One whose requirements come out exactly as before was not understood -
+ # it is a named hole, never a rebuild reported as done ("No, I meant above 200" read as nothing to change)
+ if kept and not holes and len(shape.get("clauses") or []) > len(kept.get("clauses") or []) and \
+ (PJ.REVISE.search(text) or re.match(r"(?i)^\s*(?:actually|no\b|wait|rather|sorry|i meant)", text)):
+ before = PJ.plan(json.loads(json.dumps(kept)), env.root)[2]
+
+ def _sig(rs):
+ return sorted((r["id"], r["kind"], r["status"], json.dumps(
+ {k: v for k, v in r.items() if k not in ("from", "clause", "evidence", "status", "superseded", "_carriers")},
+ sort_keys=True, default=str)) for r in rs)
+ if _sig(before) == _sig(reqs):
+ return _r("I read \"%s\" as a change to %s, but it changes none of its requirements, so nothing was rebuilt. "
+ "The requirements stay:%s%s%sSay what it changes with its column or value (for example \"%s\"), "
+ "or \"drop\" with a requirement's number." % (
+ text.strip()[:160], shape.get("module"), NL, NL.join(" " + x for x in PJ.ledger_lines(before)), NL,
+ next(("%s above 10 instead" % r["op"]["col"] for r in before if r["kind"] == "op" and
+ r["op"].get("op") == "filter"), "save to other.csv instead")),
+ "missing", "project:revision-unread", started=False,
+ holes=["the change \"%s\" names nothing to change" % text.strip()[:120]])
+ head = ("I changed the project %s (\"%s\")." % (shape["module"], text.strip()[:160]) if kept
+ else "I read the request as a project: %s." % shape["module"])
+ prop = [n for n, e in shape["entries"].items() if e.get("proposed")]
+ if prop:
+ head += " The request names no command%s for %s, so I propose %s." % (
+ "" if len(prop) == 1 else "s", "it" if not kept else "this", ", ".join(
+ "`python3 %s %s%s`" % (shape["module"], n, "".join(" " + a for a in shape["entries"][n]["args"])) for n in prop))
+ store_lines = [" %s made from %s: Oracle7's kept function %s (sha %s, kept from %s; its evidence replayed and holding)" % (
+ d["name"], d["col"], d["fn"], d["sha256"][:16], d.get("project") or "earlier work")
+ for d in (shape.get("derived") or {}).values() if d.get("from") == "store"]
+ probing = any(p["source"] == "probe" for p in pipes.values())
+ if world and probing and not holes:
+ scope = set(h.lower() for h in env.net_scope)
+ outside = [h for h in world.get("hosts", []) if not (h in ("localhost", "::1") or h.startswith("127.") or
+ h.lower() in scope)]
+ if outside:
+ holes.append({"kind": "netscope", "text": "the servers in %s include host%s outside this conversation's network "
+ "scope: %s. Say \"allow network to %s\" for each, then \"continue\"." % (
+ world["file"], "" if len(outside) == 1 else "s", ", ".join(outside),
+ outside[0])})
+ shape["status"] = "blocked"
+ shape["holes_kept"] = holes
+ turn.s["project"] = shape
+ turn.save()
+ try:
+ PJ.save_project(env.root, shape)
+ except OSError:
+ pass
+ ledger = PJ.ledger_lines(reqs)
+ if holes:
+ return _r(head + NL + "The requirements, as I read them:" + NL + NL.join(" " + x for x in ledger) +
+ ((NL + "Composed this turn:" + NL + NL.join(" " + c for c in composed)) if composed else "") + NL +
+ "Not all of it can be built yet, so nothing was written. What would fill each hole:" + NL +
+ NL.join(" - " + h["text"] for h in holes) + NL +
+ "The project is kept as it stands (here and in %s/.oracle7/project.json); the next turn goes on from it." % (
+ env.label()), "missing", "project:gap", started=False, holes=[h["text"] for h in holes],
+ requirements=[{"id": r["id"], "kind": r["kind"], "status": r["status"]} for r in reqs])
+ CT.stage("writing")
+ src = PJ.write(shape, pipes, reqs, world)
+ p = env.path(shape["module"])
+ old = env.read(p) if env.exists(p) else None
+ bad = _compiles(p, src)
+ if bad:
+ return _r("Not written: the project's code would not compile: %s" % bad, "failed", "project:compile", started=False)
+ eid = _apply(turn, p, old, src, "project")
+ CT.stage("judging")
+ ok, lines, jholes = PJ.judge(env.root, shape, pipes, reqs, world, _guard_env(env))
+ kept_now = PJ.keep_derived(env.root, shape) if ok else []
+ shape["status"] = "built" if ok else "failed"
+ turn.s["project"] = shape
+ turn.save()
+ try:
+ PJ.save_project(env.root, shape)
+ except OSError:
+ pass
+ turn.last(kind="edit", edit=eid, file=p)
+ pl = []
+ for name, pp in pipes.items():
+ e = shape["entries"][name]
+ pl.append(" `python3 %s %s%s`: %s" % (shape["module"], name, "".join(" " + a for a in e["args"]),
+ " -> ".join("%s (%s)" % (l["part"], l["why"]) for l in pp["links"])))
+ body = (head + NL + "The plan, from what each command must do back to its table:" + NL + NL.join(pl) + NL +
+ ((NL.join(store_lines) + NL) if store_lines else "") +
+ (("Composed this turn:" + NL + NL.join(" " + c for c in composed) + NL) if composed else "") +
+ _diff(env, p, old or "", src) + NL + "What happened when I ran it:" + NL + NL.join(" " + x for x in lines) + NL +
+ "Every requirement against it:" + NL + NL.join(" " + x for x in PJ.ledger_lines(reqs)))
+ rec = {"files": [env.rel(p)], "edit": eid, "requirements": [{"id": r["id"], "kind": r["kind"], "status": r["status"]}
+ for r in reqs],
+ "from_store": [{"name": d["fn"], "sha256": d["sha256"], "project": d.get("project")}
+ for d in (shape.get("derived") or {}).values() if d.get("from") == "store"]}
+ if not ok:
+ return _r(body + NL + "Not done - the requirements not met:" + NL + NL.join(" - " + h for h in jholes) + NL +
+ "Edit %d; \"undo\" takes it back." % eid, "failed", "project:judge", **rec)
+ if kept_now:
+ body += NL + "Kept in Oracle7's store for later work, with the examples they rest on: %s." % ", ".join(
+ "%s (sha %s)" % (e["name"], e["sha256"][:16]) for e in kept_now)
+ rec["kept"] = [e["id"] for e in kept_now]
+ first = next((n for n in pipes if "PORT" not in shape["entries"][n]["args"]), next(iter(pipes)))
+ return _r(body + NL + "Done: every requirement passed. Edit %d; \"undo\" takes it back. Run `python3 %s %s` again at "
+ "any time." % (eid, shape["module"], first), "changed-checked", "project", **rec)
+
+
+def _bound_record(goals, rs):
+ """for self-development: the goals the composer declined at its own time or memory bound, kept with the receipt"""
+ hit = [(g, r) for g, r in zip(goals, rs) if r["status"] != "composed" and
+ re.search(r"reached its (?:time limit|memory bound)", r.get("gap") or "")]
+ if not hit:
+ return {}
+ import compose_code as CC
+ keep = []
+ for g, _r_ in hit:
+ try:
+ json.dumps(g["examples"])
+ keep.append({"name": g["name"], "params": g["params"], "examples": g["examples"]})
+ except (TypeError, ValueError):
+ continue
+ if not keep:
+ return {}
+ return {"ccaps": {"GOAL_SECONDS": CC.GOAL_SECONDS, "CHAIN_SECONDS": CC.CHAIN_SECONDS}, "cgoals": keep}
+
+
+def tests_goal(turn, text):
+ """'make the tests in test_x.py pass', 'write x.py so that test_x.py passes': every function the tests call that the
+ project does not have is a goal; each is composed from the tests' examples, round by round (a function composed in this
+ turn is a part for the next), written, and the check decides"""
+ t = text.strip()
+ if not (_TGOAL_VERB.search(t) and _TGOAL_PASS.search(t)):
+ return None
+ import compose_code as CC
+ named = re.findall(r"[\w./-]+\.py\b", t)
+ tfiles = [x for x in named if CC.is_test_path(x)]
+ if not tfiles and not re.search(r"(?i)\b(?:the|its|my|all|these)\s+tests?\b", t):
+ return None
+ env = turn.env
+ if env.kind != "folder":
+ return None
+ if not _may_change(turn):
+ return _r("This conversation may only read %s. Say \"allow changes\" first." % env.label(), "refused", "compose:authority",
+ started=False)
+ tests = CC.read_tests(env.root, only=[os.path.basename(x) for x in tfiles] or None)
+ ctests = CC.read_class_tests(env.root, only=[os.path.basename(x) for x in tfiles] or None)
+ cmissing = {}
+ for cname, d in ctests.items():
+ mp = os.path.join(env.root, *d["module"].split(".")) + ".py"
+ txt = env.read(mp) if os.path.isfile(mp) else ""
+ if not re.search(r"(?m)^class %s\b" % re.escape(cname), txt or ""):
+ cmissing[cname] = d
+ tests = {n: d for n, d in tests.items() if n not in ctests}
+ if cmissing and not any(not re.search(r"(?m)^def %s\(" % re.escape(n), (env.read(os.path.join(env.root, *d["module"].split(".")) + ".py")
+ if os.path.isfile(os.path.join(env.root, *d["module"].split(".")) + ".py") else "") or "")
+ for n, d in tests.items()):
+ return classes_goal(turn, t, cmissing)
+ if not tests:
+ return _r("I found no assertion in %s that calls a function of this project with values I can read, so there is "
+ "nothing to compose from." % (", ".join(tfiles) or "the tests"), "missing", "compose:evidence", started=False)
+ missing, texts = [], {}
+ for name, d in tests.items():
+ mp = os.path.join(env.root, *d["module"].split(".")) + ".py"
+ txt = env.read(mp) if os.path.isfile(mp) else ""
+ texts[mp] = txt
+ if not re.search(r"(?m)^def %s\(" % re.escape(name), txt or ""):
+ missing.append((name, d, mp))
+ if not missing:
+ return repair_turn(turn, t) # everything the tests call exists: what fails is a change to make
+ goals = [{"name": n, "params": CC.param_names(d["examples"]), "module": d["module"], "examples": d["examples"],
+ "module_text": texts[mp]} for n, d, mp in missing]
+ res = CC.run_job(env.root, goals, words=t, net_scope=env.net_scope) if goals else {"results": []}
+ if "error" in res:
+ return _r("The composer did not finish: %s" % res["error"], "failed", "compose:run", started=True)
+ rs = res["results"]
+ bad = [r for r in rs if r["status"] != "composed"]
+ files = sorted({mp for _n, _d, mp in missing})
+ if bad:
+ done = [r for r in rs if r["status"] == "composed"]
+ return _r("The tests call %d function%s this project does not have. I composed %d of them, but not %s, so nothing was "
+ "written:%s%s%s" % (len(rs), "" if len(rs) == 1 else "s", len(done), ", ".join(r["name"] for r in bad), NL,
+ _gap_text(bad), (NL + "Composed: " + ", ".join(r["name"] for r in done)) if done else ""),
+ "missing", "compose:gap", started=False, gaps=[r.get("gap") for r in bad], **_bound_record(goals, rs))
+ writes, lines = [], []
+ for mp in files:
+ mine = [(g, r) for g, r in zip(goals, rs) if os.path.join(env.root, *g["module"].split(".")) + ".py" == mp]
+ imports = sorted({i for _g, r in mine for i in r["imports"] + r.get("support_imports", [])})
+ old = texts[mp] if os.path.isfile(mp) else None
+ writes.append((mp, old, _with_functions(old, [x for _g, r in mine for x in _srcs(r)], imports)))
+ for g, r in mine:
+ lines.append(" %s(%s): %s%s%s" % (g["name"], ", ".join(g["params"]), _how(r),
+ (" - uses " + ", ".join(r["uses"])) if r.get("uses") else "", _store_note(r)))
+ tf = sorted({f for _n, d, _mp in missing for f in d["files"]})
+ head = "The tests in %s call %d function%s the project does not have. I composed each from the tests' examples and " \
+ "wrote %s:%s%s" % (", ".join(tf), len(rs), "" if len(rs) == 1 else "s",
+ ", ".join("%s%s" % (env.rel(p), " (new file)" if o is None else "") for p, o, _n in writes),
+ NL, NL.join(lines))
+ turn.last(kind="newfn", file=files[-1], function=rs[-1]["name"])
+ reply = _write_checked(turn, writes, "composed from tests: " + ", ".join(r["name"] for r in rs), head)
+ return _keep_composed(env, list(zip(goals, rs)), tf, reply)
+
+
+def _keep_composed(env, pairs, files, reply):
+ """the functions just written are kept in Oracle7's store only when the project's check passed with them (the tests
+ decide); -> a line for the reply. When the project's check failed with a kept function inside what was written, that
+ failure is evidence against the kept function: it is retired with the receipt, so no later goal reuses it (12.5 C32)"""
+ if (reply.get("execution") or {}).get("state") != "changed-checked":
+ used = [f for _g, r in pairs for f in (r.get("from_store") or []) if f.get("id")]
+ if used and reply.get("path") == "bench:compose:check":
+ try:
+ import code_store as CS
+ gone = CS.retire([f["id"] for f in used], "the check of %s failed with it inside %s (%s)" % (
+ ", ".join(files) or "the project", ", ".join(r["name"] for _g, r in pairs), env.root))
+ except Exception: # noqa: BLE001
+ gone = []
+ if gone:
+ names = sorted({f["name"] for f in used if f["id"] in gone})
+ reply["response"] += NL + "The check failed with %s from Oracle7's store inside, so %s no longer reused: " \
+ "a failed check is evidence against a kept function." % (", ".join(names), "it is" if len(names) == 1 else "they are")
+ reply["execution"]["retired"] = gone
+ return reply
+ try:
+ import code_store as CS
+ added = CS.keep([CS.entry_for(r, g, env.root, files) for g, r in pairs])
+ except Exception as e: # noqa: BLE001
+ reply["response"] += NL + "(Not kept in the store: %s)" % str(e)[:120]
+ return reply
+ if added:
+ reply["response"] += NL + "Kept in Oracle7's store for later work, with the examples they rest on: %s." % (
+ ", ".join(e["name"] for e in added))
+ reply["execution"]["kept"] = [e["id"] for e in added]
+ return reply
+
+
+def _store_note(r):
+ fs = r.get("from_store") or []
+ return "".join(" - uses %s from Oracle7's store (kept from %s)" % (f["name"], f.get("project") or "earlier work") for f in fs)
+
+
+def classes_goal(turn, t, cmissing):
+ """classes the tests use: each query composed from what was done to the object and what it gave; written whole"""
+ import compose_code as CC
+ env = turn.env
+ res = CC.run_job(env.root, [], words=t, net_scope=env.net_scope, classes=cmissing)
+ if "error" in res:
+ return _r("The composer did not finish: %s" % res["error"], "failed", "compose:run", started=True)
+ rs = res["classes"]
+ bad = [r for r in rs if r["status"] != "composed"]
+ if bad:
+ return _r("The tests use %d class%s this project does not have. %s, so nothing was written:%s%s" % (
+ len(rs), "" if len(rs) == 1 else "es", "I composed %d of them, but not %s" % (len(rs) - len(bad), ", ".join(r["class"] for r in bad)),
+ NL, NL.join(" - %s: %s" % (r["class"], r.get("gap", "")) for r in bad)),
+ "missing", "compose:gap", started=False, gaps=[r.get("gap") for r in bad])
+ writes, lines, by = [], [], {}
+ for r in rs:
+ mp = os.path.join(env.root, *r["module"].split(".")) + ".py"
+ by.setdefault(mp, []).append(r)
+ for mp, group in by.items():
+ old = env.read(mp) if os.path.isfile(mp) else None
+ imports = sorted({i for r in group for i in r["imports"] + r.get("support_imports", [])})
+ writes.append((mp, old, _with_functions(old, [x for r in group for x in _srcs(r)], imports)))
+ for r in group:
+ lines.append(" class %s: what is done to it (%s) is kept as its history; %s" % (
+ r["class"], ", ".join(r["mutators"]) or "nothing", "; ".join(
+ "%s from %d examples (%s)" % (q["name"], q["examples"], " -> ".join(q["moves"] or [])) for q in r["queries"])))
+ head = "The tests use %d class%s the project does not have. I composed each query from what the tests did to the object " \
+ "and what it gave, and wrote %s:%s%s" % (len(rs), "" if len(rs) == 1 else "es",
+ ", ".join("%s%s" % (env.rel(p_), " (new file)" if o is None else "")
+ for p_, o, _n in writes), NL, NL.join(lines))
+ turn.last(kind="newfn", file=list(by)[-1], function=rs[-1]["class"])
+ return _write_checked(turn, writes, "composed classes: " + ", ".join(r["class"] for r in rs), head)
+
+
+def compose_function(turn, name, params, p, words):
+ """one named function, composed from the request's examples and the project's tests -> a reply, or (None, gap)"""
+ import compose_code as CC
+ env = turn.env
+ ex = CC.examples_in(words, name)
+ tests = CC.read_tests(env.root)
+ src_files = []
+ if name in tests:
+ have = {repr((a, o)) for a, o, _t in ex}
+ ex += [e for e in tests[name]["examples"] if repr((e[0], e[1])) not in have]
+ src_files = tests[name]["files"]
+ if params:
+ ex = [e for e in ex if len(e[0]) == len(params)]
+ if not ex:
+ return None, None
+ old = env.read(p) if env.exists(p) else None
+ goal = {"name": name, "params": params or CC.param_names(ex), "module": _module_of(env, p), "examples": ex,
+ "module_text": old or ""}
+ res = CC.run_job(env.root, [goal], words=words, net_scope=env.net_scope)
+ if "error" in res:
+ return None, res["error"]
+ r = res["results"][0]
+ if r["status"] != "composed" and r.get("network"): # outside the network scope: a hard stop, nothing else is tried
+ return _r("Nothing was fetched and nothing was written: %s" % r["gap"], "missing", "newfn:netscope", started=False), None
+ if r["status"] != "composed":
+ return None, r["gap"]
+ where = ("the tests in %s" % ", ".join(src_files)) if src_files else "your examples"
+ head = "Composed %s(%s) from %s: %s%s. Put it in %s:" % (name, ", ".join(goal["params"]), where, _how(r), _store_note(r),
+ env.rel(p))
+ turn.last(kind="newfn", file=p, function=name)
+ new = _with_functions(old, _srcs(r), r["imports"] + r.get("support_imports", []))
+ reply = _write_checked(turn, [(p, old, new)], "composed function " + name, head,
+ ex_note="your %d example%s were run on it by a separate interpreter and it gives each one (%s)" % (
+ r["examples"], "" if r["examples"] == 1 else "s", r["read_back"]))
+ return _keep_composed(env, [(goal, r)], src_files, reply), None
+
+
+def recompose(turn, text, req, log_text, cmd, res):
+ """repair as composition: the located function composed again from its tests, its body replaced, the check decides"""
+ import compose_code as CC
+ import repair as R
+ env = turn.env
+ tests = CC.read_tests(env.root)
+ for _score, p, fn, src in R.locate(env.root, req, log_text)[:3]:
+ d = tests.get(fn.name)
+ params = [a.arg for a in fn.args.args]
+ if not d or len(d["examples"]) < 2 or fn.col_offset != 0 or fn.args.vararg or fn.args.kwarg:
+ continue
+ ex = [e for e in d["examples"] if len(e[0]) == len(params)]
+ if len(ex) < 2:
+ continue
+ goal = {"name": fn.name, "params": params, "module": _module_of(env, str(p)), "examples": ex, "module_text": src}
+ out = CC.run_job(env.root, [goal], words=text, exclude=[fn.name], net_scope=env.net_scope)
+ if "error" in out or out["results"][0]["status"] != "composed":
+ continue
+ r = out["results"][0]
+ lines = src.splitlines()
+ b0 = fn.body[0]
+ A = ast_mod()
+ is_doc = isinstance(b0, A.Expr) and isinstance(getattr(b0, "value", None), A.Constant) and isinstance(b0.value.value, str)
+ start = b0.end_lineno if is_doc else b0.lineno - 1
+ body = r["source"].splitlines()[1:]
+ new = NL.join(lines[:start] + body + lines[fn.end_lineno:]) + NL
+ if r["imports"] or r.get("support"):
+ new = _with_functions(new, r.get("support", []), r["imports"] + r.get("support_imports", [])).rstrip(NL) + NL
+ head = ("%s; none made the check pass, so I composed %s() again from its %d tests in %s: %s." % (
+ res["say"].split(";")[0], fn.name, r["examples"], ", ".join(d["files"]), _how(r)))
+ rr = _write_checked(turn, [(str(p), src, new)], "repair by composition: " + fn.name, head)
+ if rr["execution"]["state"] == "changed-checked":
+ turn.last(kind="repair", edit=rr["execution"].get("edit"), file=str(p), function=fn.name, checked=True, check=cmd)
+ return rr
+ return None
+
+
+def ast_mod():
+ import ast as _a
+ return _a
+
+
+_FN = r"(\w+(?:\s*\([^)]*\))?)" # a name, and its inputs if the operator names them: big_total(xs, limit)
+_NEWFN = (re.compile(r"(?is)^(?:please\s+)?(?:add|write|create|make|build)\s+(?:a\s+)?(?:new\s+)?function\s+(?:called\s+|named\s+)?" + _FN +
+ r"\s+(?:to|in|into|inside)\s+([\w./~-]+\.py)\s*,?\s*(?:that|which|to|:|-)\s*(.+)$"),
+ re.compile(r"(?is)^(?:please\s+)?(?:in|to|into)\s+([\w./~-]+\.py)\s*,?\s*(?:add|write|create|make|build)\s+(?:a\s+)?(?:new\s+)?"
+ r"function\s+(?:called\s+|named\s+)?" + _FN + r"\s*(?:that|which|to|:|-)\s*(.+)$"),
+ re.compile(r"(?is)^(?:please\s+)?(?:create|make|write)\s+(?:a\s+)?(?:new\s+)?(?:file\s+)?([\w./~-]+\.py)\s+with\s+(?:a\s+)?"
+ r"function\s+(?:called\s+|named\s+)?" + _FN + r"\s*(?:that|which|to|:|-)\s*(.+)$"),
+ # 12.0 C28: a name written with its inputs right after the verb is a function by its own form ("add double(x)
+ # with these examples: ...", "write slug(title) to people.py: ..."); the file may be left to the project
+ re.compile(r"(?is)^(?:please\s+)?(?:add|write|create|make|build)\s+(\w+\s*\([^)]*\))\s*(?:(?:to|in|into|inside)\s+"
+ r"([\w./~-]+\.py)\s*)?,?\s*(?:with\s+(?:these\s+|the\s+following\s+|its\s+)?examples?\s*:?|that|which|:|-)\s*(.+)$"))
+
+
+def new_function(turn, text):
+ """a function composed from described steps by the program builder (make.py's moves), put into a project file, and the
+ project's checks run after it"""
+ t = text.strip()
+ m = _NEWFN[0].match(t)
+ if m:
+ name, f, steps = m.group(1), m.group(2), m.group(3)
+ else:
+ m = _NEWFN[1].match(t) or _NEWFN[2].match(t)
+ if m:
+ f, name, steps = m.group(1), m.group(2), m.group(3)
+ else:
+ m = _NEWFN[3].match(t)
+ if not m:
+ return None
+ name, f, steps = m.group(1), m.group(2), m.group(3)
+ if not f: # no file named: the project's one source file, or ask which
+ env0 = turn.env
+ if env0 is None or env0.kind != "folder":
+ return None
+ src = sorted(env0.rel(p) for p in env0.walk(limit=4000) if p.endswith(".py")
+ and not re.match(r"(?:test_|_)", os.path.basename(p)) and not os.path.basename(p).endswith("_test.py"))
+ if len(src) != 1:
+ return _r("Which file should %s go into? %s" % (re.match(r"\w+", name).group(0),
+ ("This folder has %s." % ", ".join(src[:8])) if src else "This folder has no Python file yet; "
+ "name one, for example `add %s to calc.py: ...`." % name.strip()), "missing", "newfn:file", started=False)
+ f = src[0]
+ fsig = re.sub(r"\s+", "", name) # "big_total(xs,limit)" goes to the builder; the bare name everywhere else
+ name = re.match(r"\w+", name).group(0)
+ env = turn.env
+ if env.kind != "folder":
+ return _r("Composing functions works on a folder; %s is a host." % env.label(), "missing", "newfn", started=False)
+ if not _may_change(turn):
+ return _r("This conversation may only read %s. Say \"allow changes\" first." % env.label(), "refused", "newfn:authority",
+ started=False)
+ hits0 = env.resolve(f)
+ p0 = hits0[0] if len(hits0) == 1 else env.path(f)
+ if env.exists(p0) and re.search(r"(?m)^def %s\(" % re.escape(name), env.read(p0) or ""):
+ return _r("%s already has a function called %s; say what to change in it instead." % (env.rel(p0), name), "missing",
+ "newfn:exists", started=False)
+ given = [x.strip() for x in fsig[len(name):].strip("()").split(",") if x.strip()] if "(" in fsig else None
+ rc, comp_gap = compose_function(turn, name, given, p0, t) # CODE_SPEC C1/C2: the composer, from examples and tests
+ if rc:
+ return rc
+ import ast as _ast
+ import make as _make
+ import tools as _tools
+ _make.KNOWN.clear()
+ src, P = _make.compose("function %s: %s" % (fsig, steps), _tools._find_recs, _tools._read_rec)
+ if P.gaps: # "that keeps ..., then sums them": the builder reads commands; the
+ def _imp(m): # description says what the function does - each clause's verb as a command
+ w = m.group(2)
+ v = w[:-3] + "y" if w.endswith("ies") else w[:-2] if re.search(r"(?:ch|sh|x|ss|z)es$", w) else w[:-1]
+ return m.group(1) + v
+ alt = re.sub(r"(?i)(^|,\s*(?:and\s+|then\s+)?|\bthen\s+|;\s*|\band\s+)([a-z]{3,}s)\b(?!\s*(?:of|is|are)\b)", _imp, steps.strip())
+ if alt != steps.strip():
+ src2, P2 = _make.compose("function %s: %s" % (fsig, alt), _tools._find_recs, _tools._read_rec)
+ if len(P2.gaps) < len(P.gaps):
+ src, P, steps = src2, P2, alt
+ if P.gaps:
+ return _r("I could not compose every step of %s, so nothing was written:%s%s%s" % (
+ name, NL, NL.join(" - " + g for g in P.gaps),
+ (NL + "From its examples and tests: " + comp_gap) if comp_gap else
+ (NL + "Give an example (%s(...) == ...) or a test, and it is composed from that." % name)),
+ "missing", "newfn:gap", started=False, gaps=P.gaps)
+ tree = _ast.parse(src)
+ keep, imports = [], []
+ for node in tree.body:
+ seg = _ast.get_source_segment(src, node) or ""
+ if isinstance(node, (_ast.Import, _ast.ImportFrom)):
+ imports.append(seg)
+ elif isinstance(node, _ast.FunctionDef) and node.name not in ("run", "main", "_show"):
+ keep.append(seg)
+ if not any(re.match(r"def %s\(" % re.escape(name), k) for k in keep):
+ return _r("The builder made no function called %s from those steps." % name, "missing", "newfn:gap", started=False)
+ keep = [NL.join(ln for ln in k.splitlines() if not re.match(r"^\s*_show\(", ln)) for k in keep]
+ hits = env.resolve(f)
+ p = hits[0] if len(hits) == 1 else env.path(f)
+ old = env.read(p) if env.exists(p) else ""
+ if old is None:
+ return _r("%s is not a text file I edit." % f, "refused", "newfn:file", started=False)
+ if re.search(r"(?m)^def %s\(" % re.escape(name), old or ""):
+ return _r("%s already has a function called %s; say what to change in it instead." % (env.rel(p), name), "missing",
+ "newfn:exists", started=False)
+ have = set(re.findall(r"(?m)^(?:import|from) .+$", old or ""))
+ add_imp = [i for i in imports if i not in have]
+ new = old or ""
+ if add_imp:
+ lines = new.splitlines()
+ at = 0
+ for i, ln in enumerate(lines):
+ if re.match(r"^(?:import|from) ", ln):
+ at = i + 1
+ lines[at:at] = add_imp
+ new = NL.join(lines) + (NL if lines else "")
+ new = new.rstrip(NL) + (NL + NL + NL if new.strip() else "") + (NL + NL + NL).join(keep) + NL
+ bad = _compiles(p, new)
+ if bad:
+ return _r("Not written: the composed function would not compile: %s" % bad, "failed", "newfn:compile", started=False)
+ import repair as R
+ names = _load(_e(env, "names.json"), {})
+ chk = _check_name(env)
+ cmd = names[chk]["cmd"] if chk else R.test_command(env.root)
+ before = R.run_check(cmd, env.root)[0] if cmd else None
+ eid = _apply(turn, p, old or None, new, "new function " + name)
+ steps_done = NL.join(" " + x for x in P.trace)
+ head = "Composed %s from your steps (%d move%s) and put it in %s:%s%s" % (name, len(P.trace), "" if len(P.trace) == 1 else "s",
+ env.rel(p), NL, steps_done)
+ sig = (" Its inputs: %s." % fsig[len(name):]) if "(" in fsig else " It takes one value and returns the result."
+ turn.last(kind="newfn", edit=eid, file=p, function=name)
+ if cmd:
+ ok, out, code = R.run_check(cmd, env.root)
+ if not ok:
+ return _r(head + NL + _diff(env, p, old or "", new) + NL + "The check `%s` FAILED after it (edit %d; \"undo\" takes it "
+ "back):%s```%s%s%s```" % (cmd, eid, NL, NL, out[-1200:], NL) + sig, "failed", "newfn", files=[env.rel(p)], edit=eid,
+ function=name, what="new function", exit=code)
+ if not before:
+ return _r(head + NL + _diff(env, p, old or "", new) + NL + "The check `%s` failed before and passes now. Edit %d." % (cmd, eid) + sig,
+ "changed-checked", "newfn", files=[env.rel(p)], edit=eid, function=name, what="new function", check="passed",
+ tried=1, exit=0)
+ return _r(head + NL + _diff(env, p, old or "", new) + NL + "Edit %d. %s, so this is changed, not yet checked for what it does." % (
+ eid, ("The check `%s` passed before and after it: it does not test %s" % (cmd, name)) if cmd else "There is no check here") + sig +
+ " Try it: run `python3 -c \"from %s import %s; print(%s(...))\"`" % (os.path.splitext(os.path.basename(p))[0], name, name),
+ "changed-untested", "newfn", files=[env.rel(p)], edit=eid, function=name, what="new function", tried=1)
+
+
+def value_reply(turn, text):
+ o = next((x for x in turn.s.get("offers", []) if x["kind"] == "repair_value"), None)
+ if not o:
+ return None
+ t = text.strip().rstrip(".")
+ m = re.match(r"(?i)^(?:it should\s+|make it\s+|just\s+)?(?:return|give)?\s*(none|0|0\.0|\[\]|''|\"\"|false|true|-?\d+(?:\.\d+)?)$", t) or \
+ re.match(r"(?i)^(?:return|give)\s+(none|0|0\.0|\[\]|''|\"\"|false|true|-?\d+(?:\.\d+)?)\b", t)
+ if m:
+ v = m.group(1)
+ v = {"none": "None", "false": "False", "true": "True"}.get(v.lower(), v)
+ else:
+ m = re.match(r"(?i)^(?:it should\s+)?raise\s+(?:an?\s+)?(\w*Error)\b", t)
+ if not m:
+ return None
+ v = "raise " + m.group(1)
+ turn.s["offers"] = [x for x in turn.s["offers"] if x["kind"] != "repair_value"]
+ turn.save()
+ return repair_turn(turn, o["text"], value=v)
+
+
+# ---------------------------------------------------------------- server findings
+def audit(turn, text):
+ import findings as F
+ env = turn.env
+ rules = F.rules_for(text)
+ found, looked, unread = [], [], []
+ eff, eff_rules = None, [r for r in rules if r.get("service") == "ssh" and "file" in r and r.get("fix")]
+ if eff_rules and env.kind == "folder" and os.path.isfile(env.path("etc/ssh/sshd_config")):
+ import effective as _eff # 12.5 12d(ii) (design 5.A): the service's own resolved reading
+ eff = _eff.sshd(env.root)
+ if eff.get("hole"):
+ unread.append("the service's own reading (sshd -T): " + eff["hole"])
+ eff = None
+ else:
+ looked += [env.rel(env.path("etc/ssh/sshd_config")),
+ "sshd -T (%s, sha %s)" % (eff["receipt"]["says"], eff["receipt"]["sha"][:12])]
+ ng, ng_rules = None, [r for r in rules if r.get("service") == "nginx" and "file" in r]
+ if ng_rules and env.kind == "folder" and os.path.isfile(env.path("etc/nginx/nginx.conf")):
+ import effective as _eff # 12.5 12d(iii): nginx's own reading (nginx -T), resolved by block
+ ng = _eff.nginx(env.root)
+ if ng.get("hole"):
+ unread.append("the service's own reading (nginx -T): " + ng["hole"])
+ ng = None
+ else:
+ looked += [env.rel(env.path(x.lstrip("/"))) for x in ng["receipt"]["files"]] + [
+ "nginx -T (%s, sha %s)" % (ng["receipt"]["says"], ng["receipt"]["sha"][:12])]
+ for r in rules:
+ if eff is not None and r in eff_rules: # judged on the value the service resolves, not on a file's text
+ found += _effective_finding(env, r, eff)
+ continue
+ if ng is not None and r in ng_rules:
+ found += _effective_nginx_finding(env, r, ng)
+ continue
+ if "file" in r:
+ pat = r["file"]
+ base = env.path(pat.lstrip("/")) if env.kind == "folder" else pat
+ paths = [base]
+ if any(c in pat for c in "*?"):
+ d = os.path.dirname(base)
+ if env.kind == "folder":
+ paths = [os.path.join(d, f) for f in sorted(os.listdir(d))] if os.path.isdir(d) else []
+ else:
+ paths = env.sh("ls -1d %s 2>/dev/null" % base, 20)[1].split()
+ for p in paths:
+ s = env.read(p)
+ if s is None:
+ continue
+ looked.append(env.rel(p))
+ for inc in _INCLUDE.findall(s): # 12.5 12d(i): what the service also loads, by its own directive
+ unread.append("%s (included by %s; the service reads it, this check did not)" % (inc.strip(), env.rel(p)))
+ for f in F.check_text(r, p, s):
+ found.append(dict(f, file=p, test=r.get("test"), reload=r.get("reload")))
+ elif "log" in r:
+ p = env.path(r["log"].lstrip("/")) if env.kind == "folder" else r["log"]
+ s = env.read(p, 50_000_000)
+ if s is not None:
+ looked.append(env.rel(p))
+ found += F.check_text(r, p, s)
+ d, b = os.path.split(p)
+ if env.kind == "folder" and os.path.isdir(d):
+ unread += ["%s (a rotated log)" % env.rel(os.path.join(d, x)) for x in sorted(os.listdir(d))
+ if x.startswith(b + ".")]
+ else:
+ unread.append("%s (not present here)" % r["log"])
+ elif "cmd" in r:
+ if env.kind == "host" or os.environ.get("ORACLE7_BENCH_LOCALCMD") == "1":
+ code, out = env.sh(r["cmd"], 30)
+ looked.append(r["cmd"])
+ found += F.check_cmd_output(r, out)
+ else:
+ unread.append("`%s` (a command check; not run on a folder)" % r["cmd"])
+ if ng is not None and any(f.get("effective_service") == "nginx" for f in found):
+ obs = _eff.observe_nginx(env.root, ng) # 12.5 12d(vii) (design 5.C): what the folder's own nginx serves
+ for f in found:
+ if f.get("effective_service") == "nginx":
+ f["observed"] = _observed_lines(f, obs)
+ looked = list(dict.fromkeys(looked))
+ unread = list(dict.fromkeys(unread))
+ found.sort(key=lambda f: f.get("low", False))
+ turn.s["findings"] = found
+ turn.s["goal"] = turn.s.get("goal") or " ".join(text.split())[:200]
+ turn.save()
+ turn.last(kind="audit", n=len(found))
+ if not looked:
+ return _r("I found none of the files these checks read on %s (looked for: %s)." % (env.label(), ", ".join(
+ sorted({r.get("file") or r.get("log") or r.get("cmd") for r in rules}))), "missing", "audit")
+ if not found:
+ # 12.5 12d(i) (round-2 design 5.D): an all-clear says what it read and what it did not; with anything unread it is
+ # not an all-clear for the service as it runs, and is offered, never answered
+ r = _r("Read %s on %s: no finding from the %d checks that apply, in what was read.%s" % (
+ ", ".join(looked), env.label(), len(rules),
+ (NL + "Not read, so this is not an all-clear for the service as it runs:" + NL + NL.join("- " + u for u in unread))
+ if unread else ""), "read", "audit", coverage={"read": looked, "not_read": unread})
+ if unread:
+ r["status"] = "offered"
+ return r
+ out = ["Read %s on %s. Findings:" % (", ".join(looked), env.label())]
+ for i, f in enumerate(found, 1):
+ out.append("")
+ out.append("%d. %s%s: %s" % (i, f["rule"], " (minor)" if f.get("low") else "", f["why"]))
+ if f.get("effective"):
+ ng_ = f.get("effective_service") == "nginx"
+ out.append(" the installed %s reports: %s (%s, sha %s)" % ("nginx" if ng_ else "sshd", f["effective"],
+ "nginx -T" if ng_ else "sshd -T", str(f.get("receipt"))[:12]))
+ for ln, txt in f["evidence"][:6]:
+ out.append(" %s:%s %s" % (env.rel(f["where"]), ln, str(txt).strip()[:180]))
+ for o_ in f.get("observed") or []:
+ out.append(" " + o_)
+ if f.get("manual"):
+ m_ = f["manual"]
+ out.append(" the installed manual, %s, says: %s [man:%s %s]" % (
+ m_["name"], " ".join(m_["said"])[:500], m_["name"], m_["sha"][:12]))
+ if f.get("fix") is None and m_.get("default") and m_["default"] not in " ".join(m_["said"]):
+ out.append(" and of the default: %s [man:%s %s]" % (m_["default"], m_["name"], m_["sha"][:12]))
+ elif f.get("manual_hole"):
+ out.append(" (no stated effect cited: %s)" % f["manual_hole"])
+ if f.get("fix"):
+ out.append(" correction prepared: \"%s\" -> \"%s\"; say fix %d" % (f["fix"][0], f["fix"][1], i))
+ if f.get("advice"):
+ out.append(" " + f["advice"])
+ if f.get("caution"):
+ out.append(" Caution: " + f["caution"])
+ if unread:
+ out += ["", "Not read (findings may also be there):"] + ["- " + u for u in unread]
+ return _r(NL.join(out), "read", "audit", findings=len(found), coverage={"read": looked, "not_read": unread})
+
+
+def _effective_finding(env, rule, eff):
+ """one ssh rule judged on the resolved value: the rule's own correction names the keyword and the value it corrects;
+ the origin pointer (the first line sshd obtained it from) is where the correction goes; an unset keyword's default is
+ a finding with no line to edit, said as such"""
+ key, bad = (x.lower() for x in rule["fix"][0].split(None, 1))
+ val = eff["values"].get(key)
+ if val is None or val.lower() != bad:
+ return []
+ base = {"rule": rule["id"], "why": rule["why"], "caution": rule.get("caution"), "low": rule.get("low", False),
+ "test": rule.get("test"), "reload": rule.get("reload"), "effective": "%s %s" % (key, val),
+ "effective_key": key, "effective_bad": bad, "receipt": eff["receipt"]["sha"]}
+ import effective as _eff # 12.5 12d(iv) (design 5.B): the consequence from the sealed manual
+ man = _eff.manual("ssh", key)
+ if isinstance(man, dict) and not man.get("hole"):
+ said = [man["paragraphs"][0]] if man["paragraphs"] else []
+ said += [x for x in man["paragraphs"][1:] if re.search(r"\bset to\s+%s\b" % re.escape(bad), x, re.I)][:1]
+ base["manual"] = {"name": man["name"], "said": said, "default": man["default"], "sha": man["sha"]}
+ else:
+ base["manual_hole"] = (man or {}).get("hole") or "the sealed manual holds no entry for %s" % key
+ o = eff["origin"].get(key)
+ if o:
+ p, ln, txt = o
+ return [dict(base, where=p, file=p, evidence=[(ln, txt)], fix=(txt.strip(), rule["fix"][1]))]
+ conf = env.path("etc/ssh/sshd_config")
+ return [dict(base, where=conf, file=conf, evidence=[], fix=None,
+ advice="No file read sets it, so sshd uses its default. To set it, add the line `%s` to %s." % (
+ rule["fix"][1], env.rel(conf)))]
+
+
+def _observed_effect(rule_id, obs):
+ """the served rows that show a rule's effect: a version in the Server header, or a listing"""
+ rows = obs.get("served") or []
+ if rule_id == "nginx-tokens":
+ return [r for r in rows if r.get("server") and "/" in r["server"]]
+ if rule_id == "nginx-autoindex":
+ return [r for r in rows if r.get("listed")]
+ return []
+
+
+def _observed_lines(f, obs):
+ if obs.get("hole"):
+ return ["(" + obs["hole"] + ")"]
+ seen = _observed_effect(f["rule"], obs)
+ out = ["observed in the folder's own nginx: %s answers `Server: %s`" % (r["url"], r["server"]) if f["rule"] == "nginx-tokens"
+ else "observed in the folder's own nginx: GET %s returns a listing" % r["url"] for r in seen[:4]]
+ if not seen:
+ out.append("(not observed: the folder's own nginx did not show it at the addresses read)")
+ return out + ["(%s)" % h for h in obs.get("holes") or []]
+
+
+def _effective_nginx_finding(env, rule, ng):
+ """one nginx rule judged where requests are served: the rule's own correction names the directive and the value it
+ corrects; one finding per file that sets it (the correction goes to that directive), or one for a default"""
+ bad_line, good_line = rule.get("fix") or rule["fix_by"][-1]
+ key, bad = bad_line.rstrip(";").split(None, 1)
+ hits = [o for o in ng["values"].get(key, []) if str(o["value"]).lower() == bad.lower()]
+ if not hits:
+ return []
+ base = {"rule": rule["id"], "why": rule["why"], "caution": rule.get("caution"), "low": rule.get("low", False),
+ "test": rule.get("test"), "reload": rule.get("reload"), "effective_service": "nginx", "effective_key": key,
+ "effective_bad": bad.lower(), "receipt": ng["receipt"]["sha"]}
+ out, by = [], {}
+ for o in hits:
+ by.setdefault(o["origin"]["file"] if o["origin"] else None, []).append(o)
+ for f, os_ in by.items():
+ where = ", ".join(sorted({o["scope"] for o in os_}))[:300]
+ if f is None:
+ conf = env.path("etc/nginx/nginx.conf")
+ out.append(dict(base, where=conf, file=conf, evidence=[], fix=None,
+ effective="%s %s (its default) at %s" % (key, bad, where),
+ advice="No file nginx loads sets it, so nginx uses its default. To set it, add `%s` to the http "
+ "block of %s." % (good_line, env.rel(conf))))
+ continue
+ ev = sorted({(o["origin"]["line"], o["origin"]["text"]) for o in os_})
+ src = next((o["origin"]["src"] for o in os_ if o["origin"].get("src")), None)
+ out.append(dict(base, where=f, file=f, evidence=ev, fix=(src, good_line) if src else None,
+ effective="%s %s at %s" % (key, bad, where)))
+ return out
+
+
+_INCLUDE = re.compile(r"(?im)^[ \t]*include[ \t]+([^;#\r\n]+?)[ \t]*;?[ \t]*\r?$") # sshd "Include x", nginx "include x;" (CRLF lines too)
+
+
+def fix_finding(turn, n):
+ import findings as F
+ env = turn.env
+ fs = turn.s.get("findings") or []
+ if not (1 <= n <= len(fs)):
+ return _r("There is no finding %d in this conversation; \"audit\" lists them." % n, "missing", "fix")
+ f = fs[n - 1]
+ if not f.get("fix"):
+ return _r("Finding %d (%s) has no line correction; %s" % (n, f["rule"], f.get("advice") or "it needs a decision."),
+ "missing", "fix")
+ p = f["file"]
+ s = env.read(p)
+ a, b = f["fix"]
+ lines = s.splitlines(keepends=True)
+ ev = {ln for ln, _ in f["evidence"]}
+ new = "".join((ln.replace(a, b, 1) if i in ev else ln) for i, ln in enumerate(lines, 1))
+ diff = _diff(env, p, s, new)
+ if not _may_change(turn):
+ turn.offer({"kind": "fix", "n": n, "rule": f["rule"], "file": p})
+ return _r(diff + NL + "Prepared, not applied: this conversation may only read %s. Say \"allow changes\", then go." % env.label(),
+ "waiting", "fix:authority", started=False)
+ eid = _apply(turn, p, s, new, "fix " + f["rule"])
+ rule = next(r for r in F.RULES if r["id"] == f["rule"])
+ out = [diff, "Edit %d applied to %s (backup kept; \"undo\" takes it back)." % (eid, env.rel(p))]
+ if f.get("effective_key") and f.get("effective_service") == "nginx":
+ import effective as _eff # 12.5 12d(iii): checked again by nginx's own reading
+ e2 = _eff.nginx(env.root) if env.kind == "folder" else {"hole": "not a folder"}
+ vals = (e2.get("values") or {}).get(f["effective_key"])
+ still = [o for o in (vals or []) if str(o["value"]).lower() == f["effective_bad"]]
+ ok = vals is not None and not still
+ out.append("Checked again by the service's own reading: %s." % (
+ "the installed nginx no longer serves %s %s anywhere" % (f["effective_key"], f["effective_bad"]) if ok else
+ "the installed nginx STILL serves %s %s at %s" % (f["effective_key"], f["effective_bad"],
+ ", ".join(o["scope"] for o in still)[:200]) if vals is not None
+ else "could not read it again (%s)" % e2.get("hole", "no value")))
+ elif f.get("effective_key"): # 12.5 12d(ii): checked again by the service's own reading
+ import effective as _eff
+ e2 = _eff.sshd(env.root) if env.kind == "folder" else {"hole": "not a folder"}
+ now = (e2.get("values") or {}).get(f["effective_key"])
+ ok = now is not None and now.lower() != f["effective_bad"]
+ out.append("Checked again by the service's own reading: %s." % (
+ "the installed sshd now reports %s %s" % (f["effective_key"], now) if ok else
+ "the installed sshd STILL reports %s %s" % (f["effective_key"], now) if now is not None else
+ "could not read it again (%s)" % e2.get("hole", "no value")))
+ else:
+ again = F.check_text(rule, p, env.read(p) or "")
+ ok = not again
+ out.append("Checked again: %s." % ("the finding is gone" if ok else "the finding is STILL there"))
+ test_state = None
+ if f.get("effective_key") and env.kind == "folder":
+ # 12.5 12d(ii)/(iii): in a folder the service's own config test is its own reading of the whole configuration in
+ # the folder (the rule's command would test a fragment, or this machine's own /etc); it loaded or it did not
+ test_state = "failed" if e2.get("hole") else "passed"
+ out.append("The service's own config test (%s of the whole configuration in this folder): %s" % (
+ "nginx -T" if f.get("effective_service") == "nginx" else "sshd -T",
+ "passed" if test_state == "passed" else "FAILED: " + e2["hole"][:300]))
+ ok = ok and test_state == "passed"
+ elif f.get("test"):
+ t = f["test"].format(file=p)
+ code, o = env.sh(t, 30)
+ test_state = "unrun" if (code is None or "not found" in o) else ("passed" if code == 0 else "failed")
+ if code is None or "not found" in o:
+ out.append("The service's own config test (%s) could not run here: %s" % (t, o.strip()[:160]))
+ else:
+ out.append("The service's own config test `%s`: %s%s" % (t, "passed" if code == 0 else "FAILED (exit %s)" % code,
+ ("" if code == 0 else NL + o.strip()[:400])))
+ ok = ok and code == 0
+ folder_nginx = f.get("effective_service") == "nginx" and env.kind == "folder"
+ if folder_nginx and ok: # 12.5 12d(vii) (design 5.C): done means the observed effect changed
+ obs2 = _eff.observe_nginx(env.root, e2)
+ if obs2.get("hole"):
+ out.append("Not observed after the change (%s)." % obs2["hole"])
+ else:
+ still_seen = _observed_effect(f["rule"], obs2)
+ ok = not still_seen
+ out.append("Observed in the folder's own nginx after the change: %s." % (
+ "the effect is gone at every address read" if ok else "STILL there at " + ", ".join(r["url"] for r in still_seen)))
+ out.append("This folder's nginx is not this machine's running service, so nothing here is reloaded.")
+ if f.get("reload") and ok and test_state in (None, "passed") and not folder_nginx: # 12.5 step 7: only after its test passed
+ turn.offer({"kind": "cmd", "cmd": f["reload"], "name": None, "file": p, "verdict": test_state or "passed"})
+ out.append("The running service reads it after a reload: `%s`. Say go to reload." % f["reload"])
+ elif f.get("reload") and not folder_nginx:
+ out.append("No reload is offered: %s." % ("the service's own config test did not pass" if test_state == "failed"
+ else "the service's own config test could not run here" if test_state == "unrun"
+ else "the finding is still there"))
+ f["fixed"] = ok
+ turn.save()
+ turn.last(kind="fix", edit=eid, file=p, rule=f["rule"])
+ return _r(NL.join(out), "changed-checked" if ok else "failed", "fix", files=[env.rel(p)], edit=eid, check="passed" if ok else "failed")
+
+
+# ---------------------------------------------------------------- tasks
+def task_add(turn, text):
+ env = turn.env
+ ts = _load(_e(env, "tasks.json"), [])
+ t = {"id": 1 + max([x["id"] for x in ts] or [0]), "text": " ".join(text.split())[:300], "t": time.time()}
+ ts.append(t)
+ _save(_e(env, "tasks.json"), ts)
+ return _r("Task %d: %s" % (t["id"], t["text"]), "done", "task")
+
+
+def tasks(turn, close=None):
+ env = turn.env
+ ts = _load(_e(env, "tasks.json"), [])
+ if close is not None:
+ for t in ts:
+ if t["id"] == close:
+ t["done"] = time.time()
+ _save(_e(env, "tasks.json"), ts)
+ return _r("Task %d closed: %s" % (close, t["text"]), "done", "task:done")
+ return _r("There is no task %d." % close, "missing", "task:done")
+ op = [t for t in ts if not t.get("done")]
+ return _r(NL.join("%d. %s (%s ago)" % (t["id"], t["text"], _ago(t["t"])) for t in op) if op else "No open tasks.", "read", "tasks")
+
+
+# ---------------------------------------------------------------- go
+def _delivered_seq(sid):
+ """how many turns of this conversation have left by the one exit (reflect's record); 0 where none is kept"""
+ try:
+ import reflect as _rf
+ return int(_rf.load(sid).get("seq") or 0)
+ except Exception: # noqa: BLE001
+ return 0
+
+
+def _same_offer(o):
+ """what a row offers, apart from when and to whom: two rows with the same key are one offer made again"""
+ return json.dumps([o.get(k) for k in ("kind", "cmd", "name", "n", "rule", "file", "function", "param", "sent", "dir")],
+ default=str)
+
+
+def _lapsed(o, offers):
+ """12.5 step 7, revised after q45 (held register, first row kind): an offer lapses once a later turn has offered
+ something else; reads, status and permission turns between the offer and the go leave it standing (frozen G4/T7/I2)"""
+ borns = [int(x["born"]) for x in offers if x.get("born") is not None]
+ return o.get("born") is not None and bool(borns) and int(o["born"]) < max(borns)
+
+
+def go(turn, which):
+ offers = [o for o in turn.s.get("offers", []) if o.get("env") == turn.s.get("env")]
+ if not offers:
+ return None
+ held = []
+ if which is None: # a bare go binds only what the latest offering turn offered
+ live = [o for o in offers if not _lapsed(o, offers)]
+ held = [o for o in offers if _lapsed(o, offers)]
+ offers = live or offers
+ if which is None and len(offers) > 1:
+ return _r("More than one thing is waiting:" + NL + NL.join("- go %d: %s" % (i + 1, _offer_text(o)) for i, o in enumerate(offers)),
+ "waiting", "go:which")
+ i = (which or 1) - 1
+ if not (0 <= i < len(offers)):
+ return _r("There is no go %d." % (i + 1), "missing", "go")
+ o = offers[i]
+ if o.get("file") and o.get("file_sha"): # 12.5 step 8 (held register): a go binds only what is as it was offered
+ try:
+ now_sha = hashlib.sha256((turn.env.read(o["file"]) or "").encode("utf-8", "replace")).hexdigest()
+ except Exception: # noqa: BLE001
+ now_sha = None
+ if now_sha != o["file_sha"]:
+ turn.s["offers"] = [x for x in turn.s["offers"] if x is not o and x != o]
+ turn.save()
+ return _r("Not done: %s changed after I offered this (%s), so what was offered no longer applies. Ask again and I "
+ "prepare it on the file as it is now." % (turn.env.rel(o["file"]), _offer_text(o)), "refused",
+ "go:stale", started=False)
+ if o.get("verdict") not in (None, "passed"): # 12.5 step 8: a change offer stands only on a passing test
+ turn.s["offers"] = [x for x in turn.s["offers"] if x is not o and x != o]
+ turn.save()
+ return _r("Not done: %s rests on a check that did not pass (%s)." % (_offer_text(o), o["verdict"]), "refused",
+ "go:verdict", started=False)
+ turn.s["offers"] = [x for x in turn.s["offers"] if x is not o and x != o]
+ turn.save()
+ r = _go_one(turn, o)
+ if held and isinstance(r, dict): # an older offer the bare go did not carry out is named, kept, not run
+ alln = [x for x in turn.s.get("offers", []) if x.get("env") == turn.s.get("env")]
+ r["response"] = str(r.get("response", "")) + NL + NL + "Not carried out (offered before your last offer, still waiting):" + NL + NL.join("- go %d: %s" % (alln.index(x) + 1, _offer_text(x)) for x in held if x in alln)
+ return r
+
+
+def _go_one(turn, o):
+ k = o["kind"]
+ if k == "run":
+ n = _load(_e(turn.env, "names.json"), {}).get(o["name"])
+ return run_cmd(turn, n["cmd"], o["name"]) if n else None
+ if k == "cmd":
+ return run_cmd(turn, o["cmd"], o.get("name"), confirmed=True)
+ if k == "fix":
+ return fix_finding(turn, o["n"])
+ if k == "repair_value":
+ turn.offer(o)
+ return _r("Say what %s() should give for an empty %s (for example: return 0, return None, raise ValueError)." % (
+ o["function"], o["param"]), "waiting", "go:value")
+ if k == "resolved": # the reading the operator accepted, carried out as its own sentence
+ r = handle(o["sent"], turn.sid)
+ if r:
+ r["path"] = str(r.get("path", "")) + ">resolved:" + o.get("op", "")
+ ex_ = r.get("execution") if isinstance(r.get("execution"), dict) else {}
+ carried = (r.get("status") not in ("hole", "declined", "error") and ex_.get("started", True) is not False
+ and ex_.get("state") not in ("failed", "refused", "blocked", "missing", "interrupted"))
+ if o.get("text") and carried: # C29 (receive): the confirmed wording is kept; next time it is sure
+ # 12.5 step 8: never from a go that was refused or not carried out
+ try:
+ import resolve as _rv
+ if _rv.learn(o["text"], o.get("op"), turn.env):
+ r["response"] = str(r.get("response", "")) + "%s(I keep that `%s` means %s; next time I do it at once%s.)" % (
+ NL + NL, o["text"][:80], o.get("op"), "" if o.get("op") in ("read", "ls", "grep", "diff", "log", "status", "tasks", "audit")
+ else ", after you say go")
+ except Exception: # noqa: BLE001
+ pass
+ return r
+ return _r("`%s` did not carry out here." % o["sent"], "missing", "resolved:go", started=False)
+ if k == "selfdev_build":
+ import selfdev
+ return selfdev.build(turn, o)
+ if k == "selfdev_adopt":
+ import selfdev
+ return selfdev.adopt(turn, o.get("dir"))
+ return None
+
+
+# ---------------------------------------------------------------- the door
+_POL = r"^\s*(?:ok(?:ay)?[\s,]*|now\s+|please\s+|can you\s+|could you\s+|lets\s+|let's\s+)*"
+_GO = re.compile(r"(?i)^\s*(?:ok(?:ay)?[\s,]*)?(?:yes|yep|yeah|go|go ahead|do it|run it|sure|proceed|lets do (?:it|that)|let's do (?:it|that))(?:\s+(\d))?\s*[.!]*\s*$")
+_CANCEL = re.compile(r"(?i)^\s*(?:cancel|no|don't|do not|never ?mind|stop that)\b[\s.!]*(?:that|it)?\s*[.!]*$")
+_OPEN = re.compile(r"(?i)" + _POL + r"(?:open|work (?:on|in)|switch to|cd|go to|project)\s+(?:the\s+)?(?:project\s+|folder\s+)?(\S.*?)(\s*,?\s*read[- ]only)?\s*$")
+_HOST = re.compile(r"(?i)" + _POL + r"(?:connect to|ssh (?:to|into)|log ?in to|work on (?:the )?host|open (?:the )?host)\s+([\w.-]+(?::/\S*)?)(\s*,?\s*read[- ]only)?\s*$")
+_ALLOW = re.compile(r"(?i)^\s*(?:(?:you may|you can|allow(?: you to)?)\s+(?:make )?changes?(?: here| on it| there)?|allow changes|"
+ r"you may change (?:it|this|files)|changes? (?:are )?allowed)\s*[.!]*$")
+_RO = re.compile(r"(?i)^\s*(?:read[- ]only|only read|no changes|don't change anything)\s*[.!]*$")
+_LS = re.compile(r"(?i)" + _POL + r"(?:ls|list(?: the)?(?: files)?(?: in)?|what(?:'s| is) in)\s*([\w./~-]*)\s*\??\s*$")
+_FILES = re.compile(r"(?i)" + _POL + r"(?:find )?files? (?:named|called|like)\s+(.+?)\s*\??$")
+_READ = re.compile(r"(?i)" + _POL + r"(?:read|show(?: me)?|open|cat|view|print)\s+(?:the\s+)?(?:file\s+)?([\w./~-]+\.\w{1,8}(?:\s+(?:lines?|from line)\s+\d+\s*(?:-|to|\.\.)?\s*\d*)?)\s*\??$")
+_GREP = re.compile(r"(?is)" + _POL + r"(?:grep|search(?: the (?:code|project))? for|where(?: in the (?:code|project))? (?:is|are|do we use))\s+(.+?)(?:\s+in\s+([\w./~-]+))?\s*\??$")
+_RUNQ = re.compile(r"(?is)" + _POL + r"(?:run|execute|start|launch)\s*:?\s*(?:```\w*\n(.+?)\n?```|`([^`]+)`)\s*\.?$")
+_STOPAPP = re.compile(r"(?i)" + _POL + r"(?:stop|cancel)\s+(?:(?:the\s+)?(?:app|application|program)(?:\s+here)?|job\s+(\d+))\s*[.!?]*$")
+_RUNN = re.compile(r"(?i)" + _POL + r"(?:run|rerun|start|launch|kick off|do)\s+(?:the\s+)?([\w -]{2,40}?)\s*(?:again|now)?\s*[.!]?$")
+_AGAIN = re.compile(r"(?i)" + _POL + r"(?:run (?:it|that) again|rerun(?: it| that)?|try (?:it|that) again|again)\s*[.!]?$")
+_CALL = re.compile(r"(?is)" + _POL + r"(?:call|name|save)\s+`([^`]+)`\s+(?:as\s+)?(?:the\s+)?([\w -]{2,30}?)(\s*,?\s*alone|\s*,?\s*one at a time)?\s*\.?$")
+_RULE = re.compile(r"(?i)^\s*(?:the\s+)?([\w -]{2,30}?)\s+passes\s+(?:when|if)\s+(?:it|the output)\s+says\s+[\"'`](.+?)[\"'`]\s*\.?$")
+_STATUS = re.compile(r"(?i)^\s*(?:ok(?:ay)?[\s,]*|so\s+)*(?:where are we(?: at| now)?|status|project|what(?:'s| is) running|"
+ r"is it (?:done|finished|ready)|did it (?:finish)|how(?:'s| is) (?:it|the \w+) going|"
+ r"is the \w+ (?:done|finished)|what(?:'s| is) the status)\s*[?.!]*\s*$")
+_SOLVED = re.compile(r"(?i)^\s*(?:did (?:that|it|this) (?:solve|fix|work)(?: it)?|did it pass|is it fixed|does it work now)\s*\??\s*$")
+_LOG = re.compile(r"(?i)\b(?:what failed|why did it fail|what went wrong|show (?:me )?the (?:log|output|failures?|results?)|"
+ r"log of|output of)\b")
+_DIFF = re.compile(r"(?i)^\s*(?:diff|show (?:me )?the diff|what did (?:we|you|i) change|what(?:'s| has| have we)? changed)\s*\??\s*$")
+_TASKS = re.compile(r"(?i)^\s*(?:tasks|todo|to do|task list|todo list|what(?:'s| is) left(?: to do)?|open tasks)\s*\??\s*$")
+_DONE = re.compile(r"(?i)^\s*(?:done|close task|finished task|task)\s+#?(\d+)(?:\s+(?:is\s+)?done)?\s*\.?$")
+_TODO = re.compile(r"(?i)^\s*(?:todo|to do|add a task|note a task)\s*:?\s+(\S.*)$")
+_AUDIT = re.compile(r"(?i)\b(?:audit|harden|security|secure|vulnerab\w*|check|inspect|investigate|look at|review)\b.*\b(?:ssh|sshd|nginx|"
+ r"ports?|logs?|server|host|config(?:uration)?|security|login)\b")
+_FIX = re.compile(r"(?i)^\s*(?:fix|apply|correct)\s+(?:finding\s+)?#?(\d+)\s*\.?$")
+_CHANGE = re.compile(r"(?i)\b(?:fix|correct|repair|should|instead|handle|wrong|broken|bug|doesn't|does not|isn't|is not|"
+ r"subtracts|adds|multiplies|divides|crash(?:es)?|fails?)\b")
+# a request to make or change something: never answered early as a reading of the folder
+_MAKING = re.compile(r"(?i)\b(?:write|make|add|build|create|implement|compose|generate|fix|repair|correct|change|replace|"
+ r"rename|remove|delete|so that|passes)\b")
+
+
+_OURS = re.compile(r"(?i)\b(?:we|us|our|ours)\b|\b(?:the|this|our)\s+(?:project|work|build|job|task)\b")
+_ASKS = re.compile(r"(?i)\?\s*$|^\s*(?:(?:so|and|ok(?:ay)?|hey|well)[\s,]+)*(?:how|where|what|are|is|have|has|did|do|when)\b")
+
+
+def ours_question(turn, t):
+ """12.0 C29 (Ben: hold the meanings of current projects): is this a question about the work this conversation holds
+ ("how far along are we?", "are we nearly there?", "how is our project coming along?")? Only a question that speaks of
+ the shared work, while a project, work or job is held here; never one that names a file or a function, asks to make
+ something, or has a sure reading of its own ("what files do we have?" stays ls)."""
+ env = turn.env
+ if env is None or not _ASKS.search(t) or not _OURS.search(t) or _MAKING.search(t):
+ return False
+ pj, wk = turn.s.get("project"), turn.s.get("work")
+ held = (pj and pj.get("env") in (None, env.key)) or (wk and wk.get("env") == env.key) or bool(_jobs(env))
+ if not held:
+ return False
+ try: # the project's own record answer keeps the questions it words
+ import language_bridge as _lb
+ if pj and pj.get("env") in (None, env.key) and _lb.project_answer(t, pj):
+ return False
+ except Exception: # noqa: BLE001
+ pass
+ try:
+ import resolve as _rv
+ b = _rv.bind(t, env)
+ if b.get("file") or b.get("function"):
+ return False
+ sent, _name, _changes, sure = _rv.resolve(t, env, near_ok=False)
+ if sent and sure:
+ return False # its own sure reading wins (ls, diff, tasks, ...)
+ except Exception: # noqa: BLE001
+ pass
+ return True
+
+
+def _about_our_work(turn, t):
+ """the question about our work, answered from that work's own record (the status of what is held here)"""
+ if not ours_question(turn, t):
+ return None
+ r = status(turn)
+ if r:
+ r["response"] = "(I read that as a question about the work we hold here; from its record:)%s%s" % (NL, r.get("response", ""))
+ r["path"] = str(r.get("path", "")) + ">ours"
+ return r
+
+
+def _resolved(turn, sid, t, sure_only, read_only=False):
+ try:
+ import resolve as _rv
+ if _rv.negated(t): # 12.5 C34: told not to; the operation it names is not done
+ pos = re.sub(r"(?i)\b(?:please\s+)?(?:do\s+not|don'?t|dont|never|not|no\s+need\s+to)\s+", "", t, count=1)
+ s0, n0, _c0, _s0 = _rv.resolve(pos, turn.env, near_ok=True) if pos != t else (None, None, None, None)
+ if s0:
+ return _r("Understood: I will not do that (`%s`). Nothing was run, read or changed." % s0, "done",
+ "resolved:declined:" + n0, started=False)
+ return None
+ sent, name, changes, sure = _rv.resolve(t, turn.env, near_ok=not sure_only)
+ except Exception: # noqa: BLE001
+ return None
+ if not sent or (sure_only and not sure) or sent.strip().lower() == t.strip().lower():
+ return None
+ if read_only and changes:
+ return None
+ if not changes and _MAKING.search(t): # 12.0 C28b: a request to make something is never read as a reading
+ return None
+ if sure and not changes:
+ r = handle(sent, sid)
+ if r:
+ r["response"] = "(I read that as: `%s`)%s%s" % (sent, NL, r.get("response", ""))
+ r["path"] = str(r.get("path", "")) + ">resolved:" + name
+ return r
+ return None
+ turn.offer({"kind": "resolved", "sent": sent, "op": name, "text": t})
+ return _r("I read that as `%s`%s. Say go, or say it another way." % (
+ sent, "" if sure else " (my nearest reading, not a sure one)"), "waiting", "resolved:offer:" + name, reading=sent)
+
+
+def work_turn(turn, text, reading=None):
+ """Compose general work in the same environment and authority as other bench parts."""
+ import work_tasks as work
+ import work_bindings as bindings
+ import interactive_program as programs
+ env = turn.env
+ if env is None or env.kind != "folder":
+ return None
+ if _READ.match(text) or _LS.match(text) or _FILES.match(text) or _GREP.match(text):
+ return None # the bench's own explicit command, whole: read, ls, files, grep
+ kept = turn.s.get("work")
+ if kept and kept.get("env") != env.key:
+ kept = None
+ explicit_work = bool(re.fullmatch(r"(?i)\s*(?:continue|resume)\s+(?:the\s+)?work[.!]?\s*", text))
+ if turn.s.get("focus") != "work" and not explicit_work:
+ # The mirror of project_turn's rule: while the folder's table project
+ # is the subject, its fills, additions, drops and revisions are its own
+ # ("also save each loan with its fee ... to fees.csv: 1 -> 3, ...").
+ import project as PJ
+ import language_bridge as _language
+ project = turn.s.get("project")
+ if project and project.get("env") in (None, env.key) and not _language.asks_about(text) and PJ.is_project(text, project):
+ return None
+ if turn.s.get("focus") not in (None, "work") and not explicit_work:
+ kept = None
+ if kept is None and (explicit_work or turn.s.get("focus") in (None, "work") and
+ re.fullmatch(r"(?i)\s*(?:continue|resume)[.!]?\s*", text)):
+ kept = work.load(env.root)
+ if kept is None and work.repair_owns(text, reading):
+ return None # a correction plus its check is repair's turn (repair runs the check)
+ if re.search(r"(?i)\b(?:in)?to\s+(?:yourself|oracle7)\b|^\s*(?:please\s+)?(?:build|add|make|give)\s+(?:yourself|oracle7)\s*[:,-]", text):
+ return None # a feature of Oracle7 itself: selfdev's project route (C10)
+ program, program_error = None, None
+ try:
+ program = programs.request_contract(text, env.root, reading=reading)
+ except programs.ProgramError as error:
+ program_error = str(error)
+ if not (program or program_error or work.accepts(text, env.root, kept=kept, reading=reading)
+ or bindings.accepts(text, env.root, reading=reading)):
+ return None
+ read_status = work.is_status(text)
+ if not _may_change(turn) and not read_status:
+ return _r("This conversation may only read %s. Say \"allow changes\" to carry out the requested work." % env.label(),
+ "refused", "work:authority", started=False)
+ received = text
+ if program:
+ received = json.dumps({"kind": "interactive_program", "args": program})
+ elif program_error:
+ received = json.dumps({"kind": "unbound", "args": {"error": program_error}})
+ shape = work.receive(received, env.root, kept=kept, reading=reading)
+ # one request, once its quoted examples are set aside: line breaks inside 'ab\ncd' join no clauses
+ unquoted = re.sub(r"'[^']*'|\"[^\"]*\"|`[^`]*`", "''", text, flags=re.S)
+ one_part = (len([s for s in shape.get("steps", []) if s.get("kind") != "check"]) == 1
+ or not re.search(r"(?i)[;\n]|\bthen\b|\band\s+(?:run|check|test|fix|add|write|make)\b", unquoted))
+ if (kept is None and not program and not program_error and not read_status and work._structured(text) is None
+ and one_part):
+ # One part's request (an edit, a file, a function from its examples or a
+ # module from its tests) is that part's: it is tried first as itself, and
+ # the work record takes over only when the part has nothing to give.
+ for part in (edit, write, new_function, tests_goal):
+ direct = part(turn, text)
+ if direct is not None:
+ return direct # done, or the part's own named hole with its reason
+ if received != text:
+ shape["turns"][-1]["text"] = text
+ constraints = shape.setdefault("constraints", [])
+ for constraint in (reading or {}).get("constraints", []):
+ if not any(c.get("id") == constraint.get("id") and c.get("text") == constraint.get("text") for c in constraints):
+ constraints.append(json.loads(json.dumps(constraint)))
+ if not kept:
+ shape["goal"] = text
+ old_ids = {step["id"] for step in (kept or {}).get("steps", [])}
+ for step in shape["steps"]:
+ if step["id"] not in old_ids:
+ step["request"] = text
+ for requirement in shape["requirements"]:
+ if requirement["id"] not in old_ids:
+ requirement["text"] = text
+ if not read_status:
+ shape = bindings.bind(shape, env.root, reading=reading)
+ shape["env"] = env.key
+ if not shape.get("check"):
+ shape["check"] = _check_cmd(env)
+
+ def dispatch(step, goal):
+ request = step.get("request") or step.get("text") or ""
+ kind = step.get("kind")
+ if step.get("binding_hole"):
+ return {"state": "missing", "response": step["binding_hole"],
+ "hole": {"kind": "binding", "text": step["binding_hole"]}}
+ if kind in bindings.REGISTRY:
+ result = bindings.execute(kind, step.get("args") or {}, env.root, runenv=_guard_env(env))
+ if result is not None:
+ return result
+ parts = {"edit": (edit,), "write": (write,), "compose": (new_function, tests_goal),
+ "repair": (repair_turn,), "project": (project_turn,), "interactive": (project_turn,),
+ "make": (new_function, tests_goal)}
+ for part in parts.get(kind, ()):
+ result = part(turn, request)
+ if result is not None:
+ return result
+ return {"state": "missing", "response": "The %s part needs a concrete request it can receive." % kind,
+ "hole": {"kind": "part", "text": "The %s part needs a concrete request it can receive." % kind},
+ "holes": [{"kind": "part", "step": step.get("id"), "text": request}]}
+
+ started_at = time.time()
+ result = work.advance(shape, env.root, dispatch=dispatch, runenv=_guard_env(env), allowed_hosts=env.net_scope)
+ # every change the work made goes into the conversation's one edit journal: "what changed" and "undo" see it
+ try:
+ for step in (result.get("shape") or {}).get("steps", []):
+ for attempt in step.get("attempts") or []:
+ if float(attempt.get("at") or 0) < started_at:
+ continue
+ for change in ((attempt.get("result") or {}).get("changes") or []):
+ path = Path(env.root) / change["file"]
+ before = change.get("before")
+ if isinstance(before, (bytes, bytearray)):
+ before = before.decode("utf-8", "replace")
+ now = env.read(str(path)) if path.is_file() else None # read as undo reads it (same line endings)
+ if before is not None and now is not None and "\r\n" in now and "\r\n" not in before:
+ before = before.replace("\n", "\r\n") # the work reads with \n; the file keeps \r\n
+ live = [e for e in _load(_e(env, "edits.json"), []) if e["file"] == str(path) and not e.get("undone")]
+ if now is not None and now != before and not (live and live[-1].get("after") == _sha(now)):
+ _record_edit(turn, str(path), before, now, "work %s" % step.get("id")) # once per resulting state
+ except Exception: # noqa: BLE001 - the journal never blocks the work's own record
+ pass
+ holes = result.get("holes") or []
+ if (kept is None and not program and not program_error and holes and not result.get("files")
+ and all(h.get("kind") == "part" for h in holes)):
+ return None # no part receives it: not work; nothing is kept, later receivers read it
+ shape = result.get("shape", shape)
+ shape["env"] = env.key
+ turn.s["work"] = shape
+ turn.s["focus"] = "work"
+ turn.save()
+ if not read_status:
+ work.save(env.root, shape)
+ response = result.get("response") or "The work record is updated."
+ if result.get("files"):
+ response += NL + "Files: " + ", ".join("`%s`" % name for name in result["files"]) + "."
+ for step in shape.get("steps", []):
+ if (step.get("kind") == "interactive_program" or step.get('kind') == 'described_program' and
+ shape.get('build_intent', {}).get('mode') == 'interactive') and step.get("state") == "done" and step.get("attempts"):
+ built = step["attempts"][-1]["result"].get("value") or {}
+ filename = built.get("file")
+ if filename and filename in result.get("files", []):
+ argument = ('"' + filename + '"') if os.name == "nt" else shlex.quote(filename)
+ response += NL + "To open this app, say: run `python %s 8000`. Then open http://127.0.0.1:8000/. Say stop app when finished." % argument
+ return _r(response, result.get("state", "missing"), "work",
+ files=result.get("files", []), checks=result.get("checks", []), holes=result.get("holes", []),
+ requirements=shape.get("requirements", []), work_id=shape.get("id"), steps=shape.get("steps", []))
+
+
+def handle(text, sid="default", reading=None):
+ t = (text or "").strip()
+ if not t:
+ return None
+ turn = Turn(sid)
+ turn.reading = reading
+ try:
+ try: # C11: a capability I built into myself and adopted, by its own words
+ import continuation as CT
+ rc = CT.capability_turn(t, sid)
+ if rc:
+ return rc
+ except Exception: # noqa: BLE001
+ pass
+ m = _HOST.match(t)
+ if m:
+ return open_env(turn, m.group(1), host=True, readonly=bool(m.group(2)))
+ m = _OPEN.match(t)
+ if m and os.path.isdir(os.path.expanduser(m.group(1).strip().strip("`'\""))):
+ return open_env(turn, m.group(1), readonly=bool(m.group(2)))
+ if turn.env is None:
+ return None # no environment open in this conversation: the chat is unchanged
+ try: # a question about its own work or the thread is reflection's
+ import reflect as _rf
+ if _rf.claims(t, sid):
+ return None
+ except Exception: # noqa: BLE001
+ pass
+ m = _GO.match(t)
+ if m:
+ return go(turn, int(m.group(1)) if m.group(1) else None)
+ if _CANCEL.match(t) and turn.s.get("offers"):
+ n = len(turn.s["offers"])
+ turn.s["offers"] = []
+ turn.save()
+ return _r("Cancelled %d waiting action%s." % (n, "" if n == 1 else "s"), "done", "cancel")
+ m = _NET.match(t)
+ if m:
+ return net_scope(turn, m.group(1))
+ if _NONET.match(t):
+ return net_scope(turn, None)
+ if _ALLOW.match(t):
+ return authority(turn, True)
+ if _RO.match(t):
+ return authority(turn, False)
+ r = value_reply(turn, t)
+ if r:
+ return r
+ m = re.match(r"(?i)^\s*(?:please\s+)?roll\s*back\s+(?:the\s+)?(?:capability\s+)?([\w-]+)\s*\.?$", t)
+ if m:
+ import selfdev
+ return selfdev.rollback(turn, m.group(1))
+ if turn.s.get("focus") == "self": # C11: a candidate of myself left with holes takes this turn's words
+ import selfdev
+ import project as PJ
+ cd = selfdev.open_candidate(turn)
+ if cd is not None and PJ.is_project(t, dict(PJ.load_project(cd) or {}, status="blocked")):
+ return selfdev.self_project(turn, t, cont=cd)
+ m = _RUNQ.match(t)
+ if m:
+ return run_cmd(turn, (m.group(1) or m.group(2)).strip())
+ m = _STOPAPP.match(t)
+ if m:
+ return stop_job(turn, int(m.group(1)) if m.group(1) else None)
+ kept_work = turn.s.get("work")
+ ours = _about_our_work(turn, t)
+ if ours:
+ return ours
+ if turn.s.get("focus") not in ("project", "self") and not _MAKING.search(t) and not (
+ kept_work and kept_work.get("env") == getattr(turn.env, "key", None)
+ and kept_work.get("state") not in ("done", "cancelled")):
+ # A sure, read-only reading of this environment ("let me look at calc.py",
+ # "what's in this folder") is that reading, done at once - not a work plan.
+ rs = _resolved(turn, sid, t, sure_only=True, read_only=True)
+ if rs:
+ return rs
+ try:
+ r = work_turn(turn, t, reading=reading)
+ except ImportError as e:
+ if e.name != "work_tasks":
+ raise
+ r = None
+ if r:
+ return r
+ for f in (project_turn, edit, write, new_function, tests_goal):
+ r = f(turn, t)
+ if r:
+ return r
+ if re.match(r"(?i)^\s*undo\b", t):
+ return undo(turn)
+ if _DIFF.match(t):
+ return changed(turn)
+ m = _DONE.match(t)
+ if m:
+ return tasks(turn, int(m.group(1)))
+ if _TASKS.match(t):
+ return tasks(turn)
+ m = _TODO.match(t)
+ if m:
+ return task_add(turn, m.group(1))
+ m = _CALL.match(t)
+ if m:
+ return name_cmd(turn, m.group(1).strip(), m.group(2).strip().lower(), bool(m.group(3)))
+ m = _RULE.match(t)
+ if m:
+ return name_rule(turn, m.group(1).strip().lower(), m.group(2))
+ m = _RUNQ.match(t)
+ if m:
+ return run_cmd(turn, (m.group(1) or m.group(2)).strip())
+ if _AGAIN.match(t):
+ last = turn.last()
+ lj = next((j for j in _jobs(turn.env) if j["id"] == last.get("job")), None) if last.get("job") else None
+ if lj and lj["state"] == "interrupted":
+ return interrupted_check(turn, lj)
+ if last.get("cmd"):
+ return run_cmd(turn, last["cmd"], last.get("name"))
+ chk = _check_name(turn.env)
+ if chk:
+ return run_cmd(turn, _load(_e(turn.env, "names.json"), {})[chk]["cmd"], chk)
+ m = _RUNN.match(t)
+ if m:
+ names = _load(_e(turn.env, "names.json"), {})
+ nm = m.group(1).strip().lower()
+ if nm in names:
+ return run_cmd(turn, names[nm]["cmd"], nm)
+ if nm in ("tests", "test", "the tests"):
+ import repair as R
+ cmd = R.test_command(turn.env.root) if turn.env.kind == "folder" else None
+ if cmd:
+ return run_cmd(turn, cmd, None)
+ if _SOLVED.match(t):
+ return solved(turn)
+ if _LOG.search(t):
+ return log_of(turn, t)
+ if _STATUS.match(t):
+ return status(turn)
+ m = re.match(r"(?i)^\s*(?:please\s+)?(?:build|add|make|give)\s+(?:in)?to\s+(?:yourself|oracle7)\s*[:,-]?\s*(.+)$|"
+ r"^\s*(?:please\s+)?(?:build|add|make|give)\s+(?:yourself|oracle7)\s*[:,-]\s*(.+)$", t)
+ if m: # a feature of Oracle7 itself, as a project over its own records (C10)
+ import selfdev
+ return selfdev.self_project(turn, (m.group(1) or m.group(2)).strip())
+ if re.match(r"(?i)^\s*(?:please\s+)?(?:propose|suggest|make)\s+(?:an?\s+)?(?:improvement|change|fix)\s+(?:to|for|of)\s+"
+ r"(?:yourself|your own code|you|oracle7)\b|^\s*(?:how could you|can you)\s+improve (?:yourself|your own code)\b|"
+ r"^\s*improve yourself\b", t):
+ import selfdev
+ import reflect as _rf2
+ return selfdev.propose(turn, _rf2.load(sid)["ledger"])
+ if re.match(r"(?i)^\s*(?:ok(?:ay)?[\s,]*)?adopt (?:it|the candidate|that|candidate)\b", t):
+ import selfdev
+ return selfdev.adopt(turn)
+ m = _FIX.match(t)
+ if m and turn.s.get("findings"):
+ return fix_finding(turn, int(m.group(1)))
+ m = _LS.match(t)
+ if m:
+ r = ls(turn, m.group(1))
+ if r:
+ return r
+ m = _FILES.match(t)
+ if m:
+ return files_named(turn, m.group(1))
+ m = _READ.match(t)
+ if m:
+ r = read(turn, m.group(1))
+ if r:
+ return r
+ m = _GREP.match(t)
+ if m:
+ return grep(turn, m.group(1), m.group(2))
+ if _AUDIT.search(t):
+ if turn.env.kind == "host" or re.search(r"(?i)\b(ssh|sshd|nginx|ports?|auth\.log|server|security|harden)\b", t):
+ return audit(turn, t)
+ # Amendment 16: a request in another wording, read by Oracle7's own word meanings (resolve.py). Sure and only reading:
+ # done, saying how it was read. Changing or running anything, or not sure: offered, done only on go.
+ rs = _resolved(turn, sid, t, sure_only=True)
+ if rs:
+ return rs
+ belief = False
+ if reading and reading.get("available") and reading.get("intent") not in ("request", "commitment"):
+ acting = any(c.get("kind") == "outcome" for c in reading.get("clauses", ()))
+ code_reference = any(item.get("kind") in ("code", "file") for item in reading.get("literals", ()))
+ code_reference = code_reference or bool(re.search(r"(?i)\b(?:function|method|module|codebase|repository|repo|traceback|exception|unit test)\b", t))
+ belief = not acting and not code_reference # a conversational belief is not a proposed repository repair
+ if not belief and _CHANGE.search(t) and turn.env.kind == "folder" and not t.rstrip().endswith("?"):
+ return repair_turn(turn, t)
+ rs = _resolved(turn, sid, t, sure_only=False)
+ if rs:
+ return rs
+ except Exception as e: # noqa: BLE001
+ return _r("That did not complete: %s" % repr(e)[:300], "failed", "error", started=False)
+ return None
diff --git a/workbench/body/ben_donors.py b/workbench/body/ben_donors.py
new file mode 100644
index 0000000000000000000000000000000000000000..f214cb3c4b3d842ca30a419b9ef832e772a04ead
--- /dev/null
+++ b/workbench/body/ben_donors.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python3
+"""12.0 step 4 (T3 route), first run: induction with Ben's own turns as donors, read rate on Ben's HELD-OUT turns.
+
+Ben's 746 turns (conv_set_v1.json, source ben_this_conversation) are shuffled once (seed 12) and split 60/40: donors (447) feed
+the autonomous induction (turn_kernel.induce, the M14 objective, unchanged; K8 reads first), held (299) are never seen by it.
+Read rate on the held turns, three readers: the dialogue rules shipped in 11.5, the rules induced from Ben's donors, and either.
+full = every clause of the turn read (K8 or a rule); part = at least one clause read.
+usage: ben_donors.py """
+import json
+import os
+import random
+import sys
+
+T, CS, OUT = sys.argv[1:4]
+sys.path[:0] = [T + "/workbench/converse", T + "/workbench/swarm", T + "/workbench"]
+import converse # noqa: E402,F401
+from turn_kernel import TurnKernel, induce, clauses, clean # noqa: E402
+from stage5m13e9_kernel_k8 import ConstructionKernelK8 # noqa: E402
+
+os.makedirs(OUT, exist_ok=True)
+items = json.load(open(CS))
+items = items if isinstance(items, list) else (items.get("items") or items.get("rows"))
+ben = [clean(it["turn"]) for it in items if it.get("source") == "ben_this_conversation" and it.get("turn", "").strip()]
+rng = random.Random(12)
+rng.shuffle(ben)
+cut = int(0.6 * len(ben))
+donors, held = ben[:cut], ben[cut:]
+print("Ben turns", len(ben), "donors", len(donors), "held", len(held), flush=True)
+dd_path = os.path.join(OUT, "ben_donors_dd.json")
+json.dump({"train": [{"utterances": [t], "acts": [0]} for t in donors], "validation": [], "test": []}, open(dd_path, "w"), ensure_ascii=False)
+json.dump({"donors": donors, "held": held}, open(os.path.join(OUT, "ben_split.json"), "w"), ensure_ascii=False)
+
+K8 = ConstructionKernelK8(compositional=True)
+try:
+ induce(dd_path, OUT, passes=3, k8=K8)
+except Exception as e: # noqa: BLE001
+ print("induce ended with", repr(e)[:160], "(conv_rules.json is kept if written)", flush=True)
+assert os.path.exists(os.path.join(OUT, "conv_rules.json")), "no rules written"
+ben_rules = json.load(open(os.path.join(OUT, "conv_rules.json")))["rules"]
+print("rules induced from Ben's donors:", len(ben_rules), flush=True)
+for r in ben_rules[:8]:
+ print(" ", r["skeleton"], "| donors", r["induct_donors"], "transfer", r["heldout_transfer"], "| e.g.", r["donor_examples"][0][:70])
+
+tk_dd = TurnKernel(K8, os.environ["ORACLE7_TK"])
+tk_ben = TurnKernel(K8, OUT)
+
+
+def rates(reader_fn, turns):
+ full = part = 0
+ for t in turns:
+ ps = reader_fn(t)
+ if ps and all(ps):
+ full += 1
+ if ps and any(ps):
+ part += 1
+ return full / len(turns), part / len(turns)
+
+
+def either(t):
+ a, b = tk_dd.compile(t), tk_ben.compile(t)
+ return [x or y for x, y in zip(a, b)] if a and b and len(a) == len(b) else (a or b)
+
+
+out = {}
+for name, fn in (("11.5 dialogue rules", tk_dd.compile), ("rules from Ben's donors", tk_ben.compile), ("either", either)):
+ f, p = rates(fn, held)
+ out[name] = {"full": f, "part": p}
+ print("%-26s held-out Ben turns: full %.1f%% part %.1f%%" % (name, 100 * f, 100 * p), flush=True)
+f, p = rates(tk_ben.compile, donors)
+print("%-26s DONOR turns (not held out): full %.1f%% part %.1f%%" % ("rules from Ben's donors", 100 * f, 100 * p))
+json.dump({"n_ben": len(ben), "donors": len(donors), "held": len(held), "ben_rules": len(ben_rules), "held_rates": out,
+ "donor_rates": {"full": f, "part": p}}, open(os.path.join(OUT, "ben_donors_result.json"), "w"), indent=1)
diff --git a/workbench/body/crossing_d.py b/workbench/body/crossing_d.py
new file mode 100644
index 0000000000000000000000000000000000000000..10ce9fc0f482ab22a9be2f856a8e00f78e484e3d
--- /dev/null
+++ b/workbench/body/crossing_d.py
@@ -0,0 +1,147 @@
+#!/usr/bin/env python3
+"""12.0 step 2, the D crossing measured on scene turns: what is asked (Chokmah) bound to the shape it takes (Binah), read out as a
+COMPOSED question, scored by the scene truth (conv_propagate.truth: no_question / wrong_class / wrong_slot / pass).
+
+The crossing, in this first form:
+ light the turn's context C(turn, prev, role_prev) lights the resonator's rows (the scene pairs: context -> next), one product;
+ class the obligation the turn opens is read as a bounded choice over the eleven question classes the lit rows' next moves
+ belong to (weighted by resonance) - never a choice among moves;
+ place the thing to ask for is read from the lit rows' next moves: the content words they ask for that the turn did not say,
+ pooled by resonance; the top word fills the place;
+ shape the reply's form is an induced form (conv_rules.json, autonomous induction) of that class with a place, the one with
+ the most donors; realized by skeleton refill. Nothing is copied from a scene; the words are the form's and the place's.
+usage: crossing_d.py [K=20] [out json]"""
+import json
+import os
+import re
+import sys
+
+T = sys.argv[1]
+SET = sys.argv[2]
+K = int(sys.argv[3]) if len(sys.argv) > 3 else 50
+OUT = sys.argv[4] if len(sys.argv) > 4 else None
+sys.path[:0] = [T + "/workbench/converse", T + "/workbench/swarm", T + "/workbench"]
+import converse # noqa: E402,F401 (data paths)
+import numpy as np # noqa: E402
+from resonance import Resonator, clean, words, DD # noqa: E402
+from scene_miner import nouns as _nouns # noqa: E402
+from turn_reader import Dict, open_dict # noqa: E402
+_DICT = Dict(open_dict())
+
+
+def asked_nouns(q, tw):
+ try:
+ ns = [n.lower() for n in _nouns(q, _DICT)]
+ except Exception: # noqa: BLE001
+ ns = []
+ return [n for n in ns if len(n) > 3 and n not in STOP and n not in tw]
+
+
+WORD = re.compile(r"[a-z][a-z'\-]+")
+YESNO_Q = re.compile(r"^\W*(do|does|did|is|are|was|were|can|could|would|will|shall|should|have|has|had|may|might)\b", re.I)
+WHS = ("how much", "how many", "how long", "how about", "what", "which", "who", "where", "when", "why", "how")
+STOP = set("the a an of to in on at for from by with and or is are was were be been it its this that these those there their then "
+ "you your yours i me my we our us they them he she his her him what which who where when why how about much many long "
+ "do does did can could would will shall should have has had may might not yes no sure please mean think know like want "
+ "really just also very thing things something anything some any".split())
+
+
+def classify(q):
+ """the question class of a move, read the way the scene truth reads it"""
+ low = q.lower().strip()
+ if YESNO_Q.match(q) and not re.search(r"\b(what|which|who|where|when|why|how)\b", low[:40]):
+ return "yes/no"
+ m = re.search(r"\b(how much|how many|how long|how about|what|which|who|where|when|why|how)\b", low)
+ return m.group(1) if m else None
+
+
+def asked_words(q, turn_words):
+ return [w for w in WORD.findall(q.lower()) if len(w) > 3 and w not in STOP and w not in turn_words]
+
+
+# ---- the forms of each class (induced; a place to fill)
+rules = json.load(open(os.path.join(T, "workbench/converse/data/tk/conv_rules.json")))["rules"]
+forms = {}
+for r in rules:
+ sk = r["skeleton"]
+ if "?" not in sk or not re.search(r"<(WORD|NAME|NUM)>", sk):
+ continue
+ c = classify(sk.replace("", "x").replace("", "X").replace("", "1"))
+ if c and (c not in forms or r["induct_donors"] > forms[c]["induct_donors"]):
+ forms[c] = r
+print("classes with an induced question form:", {c: forms[c]["skeleton"] for c in forms}, flush=True)
+
+
+def realize(c, fill):
+ r = forms.get(c)
+ if r is None:
+ return None
+ sk = r["skeleton"]
+ sk = re.sub(r"<(WORD|NAME|NUM)>", fill, sk, count=1)
+ sk = re.sub(r"<(WORD|NAME|NUM)>", "", sk)
+ return re.sub(r"\s+([?.,!])", r"\1", re.sub(r"\s+", " ", sk)).strip()
+
+
+# ---- the rows (the resonator, unchanged) and the next moves behind them
+R = Resonator(os.environ["ORACLE7_MOVES"])
+dd = json.load(open(DD))["train"]
+nexts = []
+for e in R.entries:
+ i, j = int(e["dlg"][1:]), int(e["id"].split("_")[1])
+ nexts.append(clean(dd[i]["utterances"][j + 1]))
+next_class = [classify(n) for n in nexts]
+
+items = json.load(open(SET))
+if isinstance(items, dict):
+ items = items.get("items") or items.get("rows")
+sys.path.insert(0, "/opt/o7conv")
+from conv_propagate import truth # noqa: E402
+
+counts = {"pass": 0, "wrong_class": 0, "wrong_slot": 0, "no_question": 0}
+class_right = 0
+rows = []
+for it in items:
+ hist = it.get("history")
+ if isinstance(hist, str):
+ try:
+ hist = json.loads(hist.replace("'", '"'))
+ except Exception: # noqa: BLE001
+ hist = []
+ prev = clean(hist[-2]) if len(hist) >= 2 else None
+ role_prev = clean(hist[-1]) if len(hist) >= 1 else None
+ c = R.med.C(clean(it["turn"]), prev, role_prev)
+ sc = np.real(R.M @ np.conj(c)) / R.M.shape[1]
+ top = np.argsort(-sc)[:K]
+ w = np.clip(sc[top], 0, None) ** 2
+ # class: a bounded choice over the eleven classes
+ vote = {}
+ for t_, wt in zip(top, w):
+ cl = next_class[t_]
+ if cl:
+ vote[cl] = vote.get(cl, 0.0) + float(wt)
+ cls = max(vote, key=vote.get) if vote else "what"
+ # place: what the lit rows go on to ask for, that the turn did not say
+ tw = set(WORD.findall(it["turn"].lower()))
+ pooln, poolw = {}, {}
+ for t_, wt in zip(top, w):
+ if next_class[t_] != cls:
+ continue
+ for a in asked_nouns(nexts[t_], tw):
+ pooln[a] = pooln.get(a, 0.0) + float(wt)
+ for a in asked_words(nexts[t_], tw):
+ poolw[a] = poolw.get(a, 0.0) + float(wt)
+ own = asked_nouns(it["turn"], set())
+ fill = max(pooln, key=pooln.get) if pooln else (max(poolw, key=poolw.get) if poolw else (own[-1] if own else "that"))
+ reply = realize(cls, fill) or ("%s %s?" % (cls, fill))
+ tr = truth(it, reply)
+ counts[tr] += 1
+ class_right += (cls == it.get("expected_wh"))
+ rows.append({"id": it["id"], "turn": it["turn"][:100], "expected_wh": it.get("expected_wh"), "expected_slot": it.get("expected_slot"),
+ "class": cls, "fill": fill, "reply": reply, "truth": tr})
+n = len(items)
+print("D crossing on %d scene turns, K=%d: PASS %d (%.1f%%) wrong_slot %d wrong_class %d no_question %d | class read right %.1f%%" % (
+ n, K, counts["pass"], 100.0 * counts["pass"] / n, counts["wrong_slot"], counts["wrong_class"], counts["no_question"], 100.0 * class_right / n), flush=True)
+for r in rows[:8]:
+ print(" ", r["truth"], "|", r["turn"][:60], "| want", r["expected_wh"], r["expected_slot"], "| got", r["class"], r["fill"], "|", r["reply"][:70])
+if OUT:
+ json.dump({"n": n, "K": K, "counts": counts, "class_right": class_right, "rows": rows}, open(OUT, "w"), indent=1)
diff --git a/workbench/body/crossing_d_reads.py b/workbench/body/crossing_d_reads.py
new file mode 100644
index 0000000000000000000000000000000000000000..c755eaefe416a74ebfe0d6be3bf496dc29c5123c
--- /dev/null
+++ b/workbench/body/crossing_d_reads.py
@@ -0,0 +1,143 @@
+#!/usr/bin/env python3
+"""12.0 step 2, the two reads of the D crossing measured apart on the development scenes, before any choice:
+ class read which of the eleven question classes the turn opens, by (a) resonance over the context (top K, weight res^p),
+ (b) the turn's FORM (its induced rules): rows whose turn has the same form vote, (c) both superposed;
+ place read the thing to ask for, by (a) pooled asked words, (b) pooled asked NOUNS (scene_miner.nouns), (c) the turn's own
+ nouns; scored by the truth's own slot test (expected_slot prefix, or a word the user's next turn goes on to say).
+Prints a table; the choice is made by the rule stated in PREREG_BODY_12 (the best class read, then the best place read, on dev).
+usage: crossing_d_reads.py """
+import json
+import os
+import re
+import sys
+
+T, SET = sys.argv[1], sys.argv[2]
+sys.path[:0] = [T + "/workbench/converse", T + "/workbench/swarm", T + "/workbench", "/opt/o7conv"]
+import converse # noqa: E402,F401
+import numpy as np # noqa: E402
+from resonance import Resonator, clean, words, clauses, DD # noqa: E402
+from scene_miner import nouns as _nouns # noqa: E402
+from turn_reader import Dict, open_dict # noqa: E402
+from conv_propagate import truth # noqa: E402
+
+_DICT = Dict(open_dict())
+
+
+def nouns(text):
+ return _nouns(text, _DICT)
+
+
+def form_of(text):
+ """the turn's form: the induced rule of each clause (the medium's own reader), as a key"""
+ out = []
+ for c in clauses(clean(text or "")):
+ r = R.med.ind.read(c)
+ if r and r.get("rule"):
+ out.append(r["rule"])
+ return tuple(out)
+
+WORD = re.compile(r"[a-z][a-z'\-]+")
+YESNO_Q = re.compile(r"^\W*(do|does|did|is|are|was|were|can|could|would|will|shall|should|have|has|had|may|might)\b", re.I)
+STOP = set("the a an of to in on at for from by with and or is are was were be been it its this that these those there their then "
+ "you your yours i me my we our us they them he she his her him what which who where when why how about much many long "
+ "do does did can could would will shall should have has had may might not yes no sure please mean think know like want "
+ "really just also very thing things something anything some any".split())
+
+
+def classify(q):
+ low = q.lower().strip()
+ if YESNO_Q.match(q) and not re.search(r"\b(what|which|who|where|when|why|how)\b", low[:40]):
+ return "yes/no"
+ m = re.search(r"\b(how much|how many|how long|how about|what|which|who|where|when|why|how)\b", low)
+ return m.group(1) if m else None
+
+
+def asked_words(q, tw):
+ return [w for w in WORD.findall(q.lower()) if len(w) > 3 and w not in STOP and w not in tw]
+
+
+def asked_nouns(q, tw):
+ try:
+ ns = [n.lower() for n in nouns(q)]
+ except Exception: # noqa: BLE001
+ ns = []
+ return [n for n in ns if len(n) > 3 and n not in STOP and n not in tw]
+
+
+R = Resonator(os.environ["ORACLE7_MOVES"])
+dd = json.load(open(DD))["train"]
+turns, nexts = [], []
+for e in R.entries:
+ i, j = int(e["dlg"][1:]), int(e["id"].split("_")[1])
+ turns.append(clean(dd[i]["utterances"][j]))
+ nexts.append(clean(dd[i]["utterances"][j + 1]))
+ncls = [classify(n) for n in nexts]
+# the rows' turn FORMS (rule ids), for the form-keyed vote
+rform = [form_of(t) for t in turns]
+by_form = {}
+for k, f in enumerate(rform):
+ if f:
+ by_form.setdefault(f, []).append(k)
+print("rows with a read form:", sum(1 for f in rform if f), "of", len(rform), "| distinct forms", len(by_form), flush=True)
+
+items = json.load(open(SET))
+items = items if isinstance(items, list) else (items.get("items") or items.get("rows"))
+res = {}
+for it in items:
+ hist = it.get("history")
+ if isinstance(hist, str):
+ try:
+ hist = json.loads(hist.replace("'", '"'))
+ except Exception: # noqa: BLE001
+ hist = []
+ prev = clean(hist[-2]) if len(hist) >= 2 else None
+ role_prev = clean(hist[-1]) if len(hist) >= 1 else None
+ turn = clean(it["turn"])
+ c = R.med.C(turn, prev, role_prev)
+ sc = np.real(R.M @ np.conj(c)) / R.M.shape[1]
+ order = np.argsort(-sc)
+ tw = set(WORD.findall(turn.lower()))
+ want = it.get("expected_wh")
+ # class reads
+ for K in (5, 10, 20, 50):
+ for p in (1, 2):
+ vote = {}
+ for t_ in order[:K]:
+ if ncls[t_]:
+ vote[ncls[t_]] = vote.get(ncls[t_], 0.0) + max(float(sc[t_]), 0.0) ** p
+ got = max(vote, key=vote.get) if vote else None
+ res.setdefault(("class", "res K=%d p=%d" % (K, p)), []).append(got == want)
+ f = form_of(turn)
+ vote = {}
+ for k in by_form.get(f, []):
+ if ncls[k]:
+ vote[ncls[k]] = vote.get(ncls[k], 0.0) + 1.0
+ res.setdefault(("class", "form-keyed (exact form)"), []).append((max(vote, key=vote.get) if vote else None) == want)
+ res.setdefault(("class", "form-keyed, else res K=20 p=2"), []).append(
+ ((max(vote, key=vote.get) if vote else None) or max({ncls[t_]: 0 for t_ in order[:20] if ncls[t_]}, key=lambda x: sum(max(float(sc[t_]), 0) ** 2 for t_ in order[:20] if ncls[t_] == x)) if any(ncls[t_] for t_ in order[:20]) else None) == want)
+ res.setdefault(("class", "always 'what'"), []).append("what" == want)
+ # place reads, scored with the truth's own slot test by composing " ?" with the TRUE class
+ def slot_ok(fill):
+ q = ("do you %s?" % fill) if want == "yes/no" else ("%s %s?" % (want, fill))
+ return truth(it, q) == "pass"
+ top = order[:20]
+ w = np.clip(sc[top], 0, None) ** 2
+ poolw, pooln = {}, {}
+ for t_, wt in zip(top, w):
+ if ncls[t_] != want:
+ continue
+ for a in asked_words(nexts[t_], tw):
+ poolw[a] = poolw.get(a, 0.0) + float(wt)
+ for a in asked_nouns(nexts[t_], tw):
+ pooln[a] = pooln.get(a, 0.0) + float(wt)
+ own = asked_nouns(turn, set())
+ res.setdefault(("place", "pooled asked words"), []).append(slot_ok(max(poolw, key=poolw.get)) if poolw else False)
+ res.setdefault(("place", "pooled asked nouns"), []).append(slot_ok(max(pooln, key=pooln.get)) if pooln else False)
+ res.setdefault(("place", "turn's own last noun"), []).append(slot_ok(own[-1]) if own else False)
+ res.setdefault(("place", "nouns, else words, else own"), []).append(
+ slot_ok(max(pooln, key=pooln.get)) if pooln else (slot_ok(max(poolw, key=poolw.get)) if poolw else (slot_ok(own[-1]) if own else False)))
+
+n = len(items)
+print("\n%-6s %-34s %s" % ("read", "method", "right on dev %d" % n))
+for (kind, name), v in res.items():
+ print("%-6s %-34s %5.1f%%" % (kind, name, 100.0 * sum(v) / n))
diff --git a/workbench/body/donor_curve.py b/workbench/body/donor_curve.py
new file mode 100644
index 0000000000000000000000000000000000000000..70c77bad15f214d40b04d09f4fa0b9f1a6ee285b
--- /dev/null
+++ b/workbench/body/donor_curve.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python3
+"""12.0 step 4 (T3 route): the reading curve against donor count. Donor sets, each inducted once with turn_kernel.induce
+(unchanged): B = Ben's 447 donor turns + the reference 600 questions; C = B + the 5,128 gate questions of 11.0.1 (the body's own
+traffic). Read rates on the 299 held-out Ben turns (never donors) and on the 68 general development turns, by the 11.5 dialogue
+rules, the curve rules, and either. usage: donor_curve.py """
+import json
+import os
+import sys
+
+T, CS, SPLIT, REF, GATE, OUT = sys.argv[1:7]
+sys.path[:0] = [T + "/workbench/converse", T + "/workbench/swarm", T + "/workbench"]
+import converse # noqa: E402,F401
+from turn_kernel import TurnKernel, induce, clean # noqa: E402
+from stage5m13e9_kernel_k8 import ConstructionKernelK8 # noqa: E402
+
+os.makedirs(OUT, exist_ok=True)
+split = json.load(open(SPLIT))
+donors_ben, held = split["donors"], split["held"]
+items = json.load(open(CS))
+items = items if isinstance(items, list) else (items.get("items") or items.get("rows"))
+general = [clean(it["turn"]) for it in items if it.get("source") == "general_dev" and it.get("turn", "").strip()]
+ref = [clean(r["q"]) for r in json.load(open(REF))["rows"] if r.get("q")]
+gate = []
+for line in open(GATE, encoding="utf-8"):
+ try:
+ q = json.loads(line).get("q")
+ if q:
+ gate.append(clean(q))
+ except Exception: # noqa: BLE001
+ pass
+sets = {"B: Ben 447 + ref 600": donors_ben + ref, "C: B + gate 5128": donors_ben + ref + gate}
+K8 = ConstructionKernelK8(compositional=True)
+tk_dd = TurnKernel(K8, os.environ["ORACLE7_TK"])
+
+
+def rates(fn, turns):
+ full = part = 0
+ for t in turns:
+ ps = fn(t)
+ full += bool(ps and all(ps))
+ part += bool(ps and any(ps))
+ return 100.0 * full / len(turns), 100.0 * part / len(turns)
+
+
+print("held Ben", len(held), "general dev", len(general), "| ref", len(ref), "gate", len(gate), flush=True)
+f, p = rates(tk_dd.compile, held)
+g, gp = rates(tk_dd.compile, general)
+print("%-28s rules %5d | held Ben full %5.1f%% part %5.1f%% | general full %5.1f%% part %5.1f%%" % ("11.5 dialogue rules", len(tk_dd.ind.rules) if hasattr(tk_dd.ind, "rules") else -1, f, p, g, gp), flush=True)
+results = {"11.5 dialogue rules": {"held": [f, p], "general": [g, gp]}}
+for name, donors in sets.items():
+ d = os.path.join(OUT, name.split(":")[0])
+ os.makedirs(d, exist_ok=True)
+ dd_path = os.path.join(d, "donors_dd.json")
+ json.dump({"train": [{"utterances": [t], "acts": [0]} for t in donors], "validation": [], "test": []}, open(dd_path, "w"), ensure_ascii=False)
+ try:
+ induce(dd_path, d, passes=3, k8=K8)
+ except Exception as e: # noqa: BLE001
+ print(name, "induce ended with", repr(e)[:120], flush=True)
+ if not os.path.exists(os.path.join(d, "conv_rules.json")):
+ print(name, "no rules written", flush=True)
+ continue
+ n_rules = len(json.load(open(os.path.join(d, "conv_rules.json")))["rules"])
+ tk = TurnKernel(K8, d)
+
+ def either(t, tk=tk):
+ a, b = tk_dd.compile(t), tk.compile(t)
+ return [x or y for x, y in zip(a, b)] if a and b and len(a) == len(b) else (a or b)
+ for label, fn in ((" curve rules", tk.compile), (" either", either)):
+ f, p = rates(fn, held)
+ g, gp = rates(fn, general)
+ print("%-28s rules %5d | held Ben full %5.1f%% part %5.1f%% | general full %5.1f%% part %5.1f%%" % (name + label, n_rules, f, p, g, gp), flush=True)
+ results[name + label] = {"rules": n_rules, "held": [f, p], "general": [g, gp]}
+json.dump(results, open(os.path.join(OUT, "donor_curve.json"), "w"), indent=1)
diff --git a/workbench/body/read_ben.py b/workbench/body/read_ben.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc086f71a04aaee1d89e481178da1e79f8a7d6f6
--- /dev/null
+++ b/workbench/body/read_ben.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python3
+"""T3 restated (PREREG_BODY_12, Amendment 2): the share of Ben's held-out turns where the body reads WHAT THE TURN ASKS:
+ op the frame's verb names a command of the launcher (build, compose, ask, chat, swarm, ...);
+ class the turn opens an obligation class: a question (mood question or a wh), or a request/directive with an object;
+ places the turn carries typed places the kernel reads (NAME / NUM) or named entities;
+ whole the whole-form read (every clause read by K8 or an induced rule), reported beside, as before.
+The reader is the pack's own (turn_reader.Reader, built as the converse session builds it). usage: read_ben.py """
+import json
+import os
+import re
+import sys
+
+T, SPLIT, CS = sys.argv[1:4]
+sys.path[:0] = [T + "/workbench/converse", T + "/workbench/swarm", T + "/workbench"]
+import converse # noqa: E402,F401
+from turn_reader import Dict, Speller, Reader, corpus_texts, open_dict # noqa: E402
+from turn_kernel import TurnKernel, clean, clauses # noqa: E402
+from stage5m13e9_kernel_k8 import ConstructionKernelK8 # noqa: E402
+import cli as _cli # noqa: E402
+
+COMMANDS = set(getattr(_cli, "COMMANDS", set())) | {"build", "compose", "ask", "chat", "swarm", "new", "example", "verify", "exam"}
+WH = re.compile(r"\b(what|which|who|where|when|why|how)\b", re.I)
+split = json.load(open(SPLIT))
+held = split["held"]
+items = json.load(open(CS))
+items = items if isinstance(items, list) else (items.get("items") or items.get("rows"))
+general = [clean(it["turn"]) for it in items if it.get("source") == "general_dev" and it.get("turn", "").strip()]
+
+dd = os.environ["ORACLE7_DAILYDIALOG"]
+db = open_dict()
+d = Dict(db)
+reader = Reader(d, Speller(d, corpus_texts(converse.TREE, dd, db)))
+K8 = ConstructionKernelK8(compositional=True)
+tk = TurnKernel(K8, os.environ["ORACLE7_TK"])
+
+
+def words_of(v):
+ return [str(x).lower() for x in (v if isinstance(v, (list, tuple)) else [v]) if x]
+
+
+def read(turn):
+ fr = reader.read(turn)
+ verb = " ".join(words_of(fr.get("verb")))
+ op = verb in COMMANDS or any(w in COMMANDS for w in verb.split())
+ mood = fr.get("mood")
+ cls = mood == "question" or bool(fr.get("wh")) or bool(WH.search(turn[:60])) or (mood in ("request", "directive") and bool(fr.get("object")))
+ ps = tk.compile(turn)
+ typed = any(p and p.get("kind") == "rule" and any(k in ("NAME", "NUM") for k in (p.get("slots") or {}).keys()) for p in (ps or []))
+ typed = typed or any(p and p.get("kind") == "k8" for p in (ps or [])) or bool(fr.get("keys")) or bool(fr.get("object"))
+ whole = bool(ps and all(ps))
+ return {"op": op, "class": cls, "places": typed, "asks": op or cls, "whole": whole, "verb": verb, "mood": mood}
+
+
+for name, turns in (("held-out Ben (299)", held), ("general dev (68)", general)):
+ agg = {"op": 0, "class": 0, "places": 0, "asks": 0, "whole": 0}
+ ex = []
+ for t in turns:
+ r = read(t)
+ for k in agg:
+ agg[k] += bool(r[k])
+ if len(ex) < 5 and r["asks"]:
+ ex.append((t[:70], r["verb"], r["mood"]))
+ n = len(turns)
+ print("%-20s op %.1f%% class %.1f%% places %.1f%% | asks (op or class) %.1f%% | whole-form %.1f%%" % (
+ name, 100 * agg["op"] / n, 100 * agg["class"] / n, 100 * agg["places"] / n, 100 * agg["asks"] / n, 100 * agg["whole"] / n), flush=True)
+ for e in ex:
+ print(" e.g.", e)
diff --git a/workbench/body/seats_plant.py b/workbench/body/seats_plant.py
new file mode 100644
index 0000000000000000000000000000000000000000..13f9e15db6a0b9005068cc18dc72078fe7826e0c
--- /dev/null
+++ b/workbench/body/seats_plant.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python3
+"""12.0 step 1, the seats as states: the fill curve of the spine's ten vectors (o7spine_v1, unchanged), read back by key.
+
+Plants N entries per vector (random 4-step walks from malkuth as routes, a status and a node field), then reads every one back
+by its exact key and scores: route right (recognised from the vector's own walk codebook, or decoded on the Tree with no
+codebook), fields right. PREREG_BODY_12 step 1 bar: 100% at 1,000 planted per vector for 4-step walks.
+usage: seats_plant.py [levels=100,300,1000,2000,4000]"""
+import random
+import sys
+import time
+
+T = sys.argv[1]
+sys.path.insert(0, T + "/workbench/swarm")
+import numpy as np # noqa: E402
+import o7spine_v1 as SP # noqa: E402
+
+LEVELS = [int(x) for x in (sys.argv[2] if len(sys.argv) > 2 else "100,300,1000,2000,4000").split(",")]
+random.seed(12)
+
+
+def random_walk(n=4, start="malkuth"):
+ cur, word = start, []
+ for _ in range(n):
+ e, nxt = random.choice(SP.ADJ[cur])
+ word.append(e)
+ cur = nxt
+ return word
+
+
+def plant(per_vector):
+ """one memory with about per_vector entries in each of the ten vectors (exact keys file by hash, so they fill evenly)"""
+ m = SP.SpineMemory("plant", max_entries=10 ** 7)
+ planted = []
+ counts = {s: 0 for s in SP.SEPH}
+ n = 0
+ while min(counts.values()) < per_vector:
+ key = "plant:%d" % n
+ word = random_walk(4)
+ m.write(key, word=word, fields={"status": "ok", "node": random.choice(SP.SEPH)}, weight=1.0)
+ counts[m.index[-1]["addr"]] += 1
+ planted.append((key, word, m.index[-1]["fields"]["node"]))
+ n += 1
+ m.counts = counts
+ return m, planted
+
+
+def score(m, planted, use_codebook, sample=1000):
+ rows = random.sample(planted, min(sample, len(planted)))
+ route = field = recognised = found = 0
+ t0 = time.time()
+ for key, word, node in rows:
+ r = m.recall(key, use_codebook=use_codebook, threshold=0.0)
+ if r is None:
+ continue
+ found += 1
+ route += (r["word"] == word)
+ field += (r["fields"].get("node") == node and r["fields"].get("status") == "ok")
+ recognised += (r["route"] == "recognised")
+ n = len(rows)
+ return {"n": n, "found": found, "route_right": route / n, "fields_right": field / n, "recognised": recognised / n,
+ "s_per_read": round((time.time() - t0) / n, 4)}
+
+
+print("D", SP.D, "paths", len(SP.EDGES), "seats", len(SP.SEPH), flush=True)
+for L in LEVELS:
+ t0 = time.time()
+ m, planted = plant(L)
+ per = m.counts
+ dw = {s: len(m.walks[s]) for s in SP.SEPH}
+ print("\n== %d per vector (%d entries, built in %.1f s; entries per vector min %d max %d; distinct walks per vector max %d)" % (
+ L, len(planted), time.time() - t0, min(per.values()), max(per.values()), max(dw.values())), flush=True)
+ for cb in (True, False):
+ r = score(m, planted, cb)
+ print(" codebook=%-5s route_right %.3f fields_right %.3f recognised %.3f (n %d, %.3f s/read)" % (cb, r["route_right"], r["fields_right"], r["recognised"], r["n"], r["s_per_read"]), flush=True)
diff --git a/workbench/body/seats_rows.py b/workbench/body/seats_rows.py
new file mode 100644
index 0000000000000000000000000000000000000000..b471c0527509d57ad82464282ee94ba54eeef1e4
--- /dev/null
+++ b/workbench/body/seats_rows.py
@@ -0,0 +1,158 @@
+#!/usr/bin/env python3
+"""12.0 step 1, Amendment 1: a seat as walk-addressed ROWS (the flash's form) and the single-vector working-set limit.
+
+(a) RowSeat: each entry's key spells a 4-step walk (flash_tol102.spell over base 22); the first PREFIX steps name the row; the
+ entry (key bound to its value: route walk + fields) is superposed into that row only. Read by key: the key's row is known
+ from the key, the value is unbound there. Capacity grows with the number of rows, never with the load of one vector.
+(b) The single-vector limit: entries per vector N = 2, 4, 8, 16, 32, 64; the largest N with 100% route recall is the working
+ set a crossing may hold.
+usage: seats_rows.py [levels=1000,4000,20000] [prefix=2]"""
+import random
+import sys
+import time
+
+T = sys.argv[1]
+sys.path.insert(0, T + "/workbench/swarm")
+import numpy as np # noqa: E402
+import o7spine_v1 as SP # noqa: E402
+
+LEVELS = [int(x) for x in (sys.argv[2] if len(sys.argv) > 2 else "1000,4000,20000").split(",")]
+PREFIX = int(sys.argv[3]) if len(sys.argv) > 3 else 2
+NE = len(SP.EDGES)
+random.seed(12)
+
+
+def random_walk(n=4, start="malkuth"):
+ cur, word = start, []
+ for _ in range(n):
+ e, nxt = random.choice(SP.ADJ[cur])
+ word.append(e)
+ cur = nxt
+ return word
+
+
+def spell(n, length=4):
+ """the flash's spelling: an index as a walk, base 22"""
+ out = []
+ for _ in range(length):
+ out.append(n % NE)
+ n //= NE
+ return out
+
+
+def key_walk(key):
+ import hashlib
+ return spell(int(hashlib.sha256(("o7addr:" + key).encode()).hexdigest(), 16) % (NE ** 4))
+
+
+class RowSeat:
+ """one seat: rows addressed by the first PREFIX steps of the key's walk; each row a SpineMemory-style vector"""
+
+ def __init__(self, name, prefix=PREFIX, dim=SP.D):
+ self.name, self.prefix, self.dim = name, prefix, dim
+ self.rows = {} # prefix tuple -> vector
+ self.walks = {} # prefix tuple -> {wkey: word} (the row's own route codebook)
+ self.vals = {} # prefix tuple -> field -> values
+ self.load = {}
+
+ def _row(self, key):
+ return tuple(key_walk(key)[: self.prefix])
+
+ def write(self, key, word, fields):
+ r = self._row(key)
+ f = {k: str(v) for k, v in fields.items()}
+ f["status"] = "%s|%d" % (f.get("status", ""), len(word))
+ v = SP.walk_vec(word, self.dim)
+ for fld, x in sorted(f.items()):
+ v = v + SP.bind(SP.osub_seed("o7role:" + fld, self.dim), SP.osub_seed("o7val:%s:%s" % (fld, x), self.dim))
+ self.rows[r] = self.rows.get(r, np.zeros(self.dim, np.complex64)) + SP.bind(SP.key_vec(key, self.dim), v)
+ self.walks.setdefault(r, {})[SP.wkey(word)] = list(word)
+ vals = self.vals.setdefault(r, {})
+ for k, x in f.items():
+ vals.setdefault(k, [])
+ if x not in vals[k]:
+ vals[k].append(x)
+ self.load[r] = self.load.get(r, 0) + 1
+
+ def recall(self, key, use_codebook=True):
+ r = self._row(key)
+ if r not in self.rows:
+ return None
+ v = SP.unbind(self.rows[r], SP.key_vec(key, self.dim))
+ got = {}
+ for fld, vals in self.vals[r].items():
+ est = SP.unbind(v, SP.osub_seed("o7role:" + fld, self.dim))
+ got[fld] = max(vals, key=lambda x: SP.sim(est, SP.osub_seed("o7val:%s:%s" % (fld, x), self.dim)))
+ status, n = got.get("status", "|0").rsplit("|", 1)
+ got["status"], n = status, int(n)
+ if use_codebook:
+ sc = sorted(((w, SP.sim(v, SP.walk_vec(w, self.dim))) for w in self.walks[r].values()), key=lambda t: -t[1])
+ if sc and len(sc[0][0]) == n:
+ return {"word": sc[0][0], "fields": got, "route": "recognised"}
+ word, _ = SP.decode_walk(v, n, dim=self.dim)
+ return {"word": word, "fields": got, "route": "decoded"}
+
+
+def run_rows(per_seat):
+ seats = {s: RowSeat(s) for s in SP.SEPH}
+ planted = []
+ counts = {s: 0 for s in SP.SEPH}
+ n = 0
+ t0 = time.time()
+ while min(counts.values()) < per_seat:
+ key = "plant:%d" % n
+ seat = SP.address(key)
+ word = random_walk(4)
+ node = random.choice(SP.SEPH)
+ seats[seat].write(key, word, {"status": "ok", "node": node})
+ counts[seat] += 1
+ planted.append((key, seat, word, node))
+ n += 1
+ built = time.time() - t0
+ loads = [l for s in seats.values() for l in s.load.values()]
+ rows = random.sample(planted, min(1000, len(planted)))
+ out = {}
+ for cb in (True, False):
+ route = field = 0
+ t1 = time.time()
+ for key, seat, word, node in rows:
+ r = seats[seat].recall(key, use_codebook=cb)
+ route += (r is not None and r["word"] == word)
+ field += (r is not None and r["fields"].get("node") == node and r["fields"].get("status") == "ok")
+ out[cb] = (route / len(rows), field / len(rows), (time.time() - t1) / len(rows))
+ print("== rows: %d per seat (%d entries, built %.1f s, rows per seat ~%d, row load max %d mean %.1f)" % (
+ per_seat, len(planted), built, len(loads) // 10, max(loads), sum(loads) / len(loads)), flush=True)
+ for cb in (True, False):
+ print(" codebook=%-5s route_right %.3f fields_right %.3f (%.4f s/read)" % (cb, *out[cb]), flush=True)
+
+
+def run_single_limit():
+ print("== single-vector limit (one vector, N entries, 4-step routes; 400 reads each)", flush=True)
+ for N in (2, 4, 8, 12, 16, 24, 32, 64):
+ route_cb = route_dec = 0
+ trials = 0
+ while trials < 400:
+ m = SP.SpineMemory("one", max_entries=10 ** 6)
+ m.vec = {s: np.zeros(SP.D, np.complex64) for s in SP.SEPH}
+ keys = []
+ for i in range(N):
+ key = "lim:%d:%d" % (trials, i)
+ keys.append((key, random_walk(4)))
+ # force all N into the same vector by filing them associatively under one node
+ for key, word in keys:
+ m.write({key: 1.0}, word=word, fields={"status": "ok"}, node="tiferet")
+ for key, word in keys[: min(N, 8)]:
+ r1 = m.recall({key: 1.0}, node="tiferet", threshold=0.0, use_codebook=True)
+ r2 = m.recall({key: 1.0}, node="tiferet", threshold=0.0, use_codebook=False)
+ route_cb += (r1 is not None and r1["word"] == word)
+ route_dec += (r2 is not None and r2["word"] == word)
+ trials += 1
+ if trials >= 400:
+ break
+ print(" N=%-3d route right: codebook %.3f decoded %.3f" % (N, route_cb / trials, route_dec / trials), flush=True)
+
+
+print("D", SP.D, "prefix", PREFIX, "rows possible per seat", NE ** PREFIX, flush=True)
+for L in LEVELS:
+ run_rows(L)
+run_single_limit()
diff --git a/workbench/cli.py b/workbench/cli.py
index ec8313d96a4bce9f142cad0db3fabdbf043efc16..504ce73d755748574fcd4cfce5d96dec1d343e58 100644
--- a/workbench/cli.py
+++ b/workbench/cli.py
@@ -20,7 +20,16 @@ so an answer here is the answer the page gives. `python oracle7.py help` lists t
operations [id] [--search W] [--kind K] [--cursor C] 10.2 what this install can do (oracle7-operation-v1)
invoke '' 10.2 call one operation directly: a formula part with typed arguments, or a command
ask "question" [--json] one question: the answer, its status and the path it took (your specialists included)
- chat a conversation (follow-ups work); /help, /path, /new, /quit inside
+ chat a conversation (follow-ups work); /help, /path, /why, /new, /quit inside
+ find 12.0 search your workspace's functions by meaning
+ read 12.0 show a sandbox or workspace file, or a function's source by name
+ write 12.0 write the code that follows to a file in the sandbox (end with a line ".")
+ run [args] 12.0 run a sandbox file, 60 s limit
+ fetch 12.0 a page from the verified sources, saved in the sandbox
+ make [name:] 12.0 build the described algorithm step by step, run and check it in the sandbox
+ index 12.0 index your own code for find, read and make (secret-shaped files left out)
+ change : 12.0 edit a copy of a script in the sandbox as described (replace, rename, delete, add)
+ want 12.0 what you want: planned backward from the goal over your tables, then built and checked
specialists [word] the 267 admitted specialists (and yours), with held-out scores
card one specialist's card
systems the five systems built the same way
@@ -73,7 +82,7 @@ HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
STAGE = {"L0": "Intake", "L1": "Parse", "L2": "Route", "L3": "Conversation", "L4": "Speak & verify", "L5": "Self-model",
"S": "Specialists", "E": "Engines", "V": "Knowledge vault"}
-COMMANDS = {"orbiters", "vision", "trafficcop", "deepspace", "chameleon", "artist", "part", "mcp", "operations", "invoke", "handoff", "check", "organs", "lesson", "compute", "grow", "packet", "place", "discover", "ledger", "air", "audit", "update", "swarm", "ask", "chat", "specialists", "card", "systems", "verify", "mine", "new", "example", "exam", "scan", "sensors",
+COMMANDS = {"kernel", "orbiters", "vision", "trafficcop", "deepspace", "chameleon", "artist", "part", "mcp", "operations", "invoke", "handoff", "check", "organs", "lesson", "compute", "grow", "packet", "place", "discover", "ledger", "air", "audit", "update", "swarm", "ask", "chat", "specialists", "card", "systems", "verify", "mine", "new", "example", "exam", "scan", "sensors",
"sensor-test", "history", "help", "registry", "registry-memo", "essay", "build", "compose", "memory", "sensor-ideal",
"sensor-pair", "sensor-history"}
@@ -120,6 +129,32 @@ def specialists_data():
return server.specialists_payload()
+
+SHOWN_TAGS = __import__("re").compile(r"\s*\[(?:(?:turn|form|scene|op|vessel|kernel|c8|m\d+)[:_][^\]]*|none)\]")
+
+
+def shown(r):
+ """what the screen shows of a reply: internal tags out (they stay in the record), sources in plain words, an offered
+ reply marked as not checked"""
+ import re as _re
+ t = SHOWN_TAGS.sub("", str(r.get("response", ""))).strip()
+ t = _re.sub(r"\[wd:(Q\d+)(?: (P\d+))?\]", lambda m: "[Wikidata %s%s]" % (m.group(1), " " + m.group(2) if m.group(2) else ""), t)
+ t = _re.sub(r"\[simplewiki_[0-9a-f]+\]", "[Simple Wikipedia]", t)
+ t = _re.sub(r"\[wiktionary:[^\]]*\]", "[Wiktionary]", t)
+ t = _re.sub(r"\(typed relations:[^)]*\)", "", t).strip()
+ if r.get("status") == "offered":
+ t += "\n(offered \u2014 not checked as an answer)"
+ return t or "(no answer)"
+
+
+def say(text):
+ lines = text.splitlines() or [""]
+ print("oracle7 \u203a " + lines[0])
+ for ln in lines[1:]:
+ print(" " + ln)
+ print()
+
+
def main(argv, engine_factory):
a = list(argv)
as_json = "--json" in a
@@ -128,6 +163,10 @@ def main(argv, engine_factory):
if cmd == "help":
print(__doc__.split("\n\n", 1)[1])
return 0
+ if cmd == "kernel": # 11.5: the kernel - every part composes through one law
+ sys.path.insert(0, str(Path(__file__).resolve().parent / "kernel"))
+ import kernel_cli
+ return kernel_cli.cli(rest)
if cmd == "orbiters": # 10.5: the six orbiters, as files in this pack
import orbiters
return orbiters.main(rest)
@@ -507,11 +546,37 @@ def main(argv, engine_factory):
return 0
if cmd == "chat":
sid = "cli%d" % int(time.time())
- print("Oracle7 (%s). Ask anything. /path shows the last path, /new starts over, /help lists Workbench features, /quit leaves." % eng.tip)
+ import threading as _th
+
+ class _Conversation:
+ """the screen carries the conversation; what organs print while they load in the background goes to stderr"""
+ def __init__(self, out):
+ self.out = out
+
+ def write(self, x):
+ return (self.out if _th.current_thread() is _th.main_thread() else sys.stderr).write(x)
+
+ def flush(self):
+ self.out.flush()
+ sys.stderr.flush()
+
+ def __getattr__(self, k):
+ return getattr(self.out, k)
+
+ sys.stdout = _Conversation(sys.stdout)
+ try: # the conversation door loads from now, in the background
+ sess.wb._converse()
+ except Exception: # noqa: BLE001
+ pass
+ print("Oracle7 12.0 \u00b7 %s \u00b7 no language model" % eng.tip.replace("oracle_release_runtime_", ""))
+ print("Talk or ask. Tools: index, find, read, write, run, fetch, make, change, want. /why /new /quit")
+ print("Work on a project: open , ls, read , grep , in replace \"a\" with \"b\", run `command`,")
+ print(" call `command` the , where are we, what failed, what changed, undo, todo , tasks, go.")
+ print()
last = None
while True:
try:
- q = input("> ").strip()
+ q = input("you \u203a ").strip()
except (EOFError, KeyboardInterrupt):
print()
return 0
@@ -526,9 +591,22 @@ def main(argv, engine_factory):
if q == "/path":
print(path_line(last["trace"]) if last else "(nothing asked yet)")
continue
+ if q == "/why":
+ print(last["why"] if last and last.get("why") else "(nothing to show)")
+ continue
+ if q.split(" ", 1)[0].lower() == "write" and chr(10) not in q:
+ body = []
+ while True:
+ try:
+ ln = input("")
+ except EOFError:
+ break
+ if ln.strip() == ".":
+ break
+ body.append(ln)
+ q = q + chr(10) + chr(10).join(body)
last = sess.ask(q, sid)
- print(last["response"].strip() or "(no answer)")
- if last["why"]:
- print(" why: %s" % last["why"])
+ print()
+ say(shown(last))
print("unknown command %s; try: help" % cmd)
return 2
diff --git a/workbench/code_discussion.py b/workbench/code_discussion.py
new file mode 100644
index 0000000000000000000000000000000000000000..a76094b25e3b5883745d861853f85e5473b89a7d
--- /dev/null
+++ b/workbench/code_discussion.py
@@ -0,0 +1,299 @@
+"""Receive questions about local code and answer from source and recorded runs.
+
+This is a read part of the same workbench, not a repair attempt. Python's syntax
+tree supplies definitions, control flow and calls; the existing runner supplies
+failure evidence. Neither an identifier nor a comment establishes what a program
+actually does at runtime. The original question and any missing evidence survive
+opening a folder and follow-up turns.
+"""
+import ast
+import hashlib
+import re
+from pathlib import Path
+
+
+EXTENSIONS = {'.py', '.js', '.ts', '.jsx', '.tsx', '.c', '.cpp', '.h', '.java',
+ '.rs', '.go', '.rb', '.php', '.cs', '.sh', '.ps1', '.html', '.css', '.sql'}
+DIAGNOSTIC = re.compile(r"\b(?:fail(?:s|ed|ing|ure)?|crash(?:es|ed|ing)?|error|exception|broken|wrong|bug)\b", re.I)
+REFERENCE = re.compile(r"\b(?:it|its|that|this|the code|the script|the function|the module)\b", re.I)
+
+
+def _sha(data):
+ return hashlib.sha256(data).hexdigest()
+
+
+def receive(text, native=None, previous=None):
+ """Identify an informational code question without accepting a work command."""
+ import language_bridge as language
+ from turn_meaning import literals, outside_literals
+ reading = language.request_reading(text)['reading'].strip()
+ instruction = outside_literals(reading)
+ if not language.asks_about(text):
+ return None
+ # A requested action following the explanation is still work. Do not answer
+ # one clause and silently consume the instruction to change/run something.
+ if re.search(r"(?:\b(?:and|then|also)\b|[;!?\n]|\.(?=\s|$))\s*"
+ r"(?:(?:and|then|also|please)\s+)*"
+ r"(?:(?:could|can|would|will)\s+you\s+(?:please\s+)?)?"
+ r"(?:fix|repair|change|build|create|write|run|execute|delete|send)\b", instruction, re.I):
+ return None
+ files = list(dict.fromkeys(item['text'].strip('`\"\'') for item in literals(text)
+ if item['kind'] == 'file' and
+ Path(item['text'].strip('`\"\'')).suffix.lower() in EXTENSIONS))
+ bound = False
+ # A demonstrative with its own named object is a new subject, not a bare
+ # reference to code ("this law" versus "this function").
+ foreign_subject = re.search(r'\b(?:this|that|the)\s+([A-Za-z]+)', instruction, re.I)
+ foreign_subject = bool(foreign_subject and foreign_subject[1].lower() not in
+ {'code', 'script', 'function', 'module', 'file', 'program', 'error', 'failure'})
+ if not files and previous and not foreign_subject and (REFERENCE.search(instruction) or
+ re.fullmatch(r"\s*(?:why|how|tell me more|explain further)[?.! ]*", reading, re.I)):
+ files = list(previous.get('files') or [])
+ bound = bool(files)
+ if not files:
+ return None
+ failure = bool(DIAGNOSTIC.search(instruction)) or bool(bound and previous.get('failure') and
+ re.fullmatch(r"\s*(?:why|how|tell me more|explain further)[?.! ]*", reading, re.I))
+ return {'question': text, 'files': files, 'failure': failure, 'bound_previous': bound,
+ 'basis': 'local source + existing run receipts',
+ 'request_graph': (native or {}).get('graph')}
+
+
+def _inside(root, path):
+ try:
+ Path(path).resolve().relative_to(Path(root).resolve())
+ return True
+ except ValueError:
+ return False
+
+
+def _expr(node):
+ return ast.unparse(node)
+
+
+def inspect_source(name, source):
+ """Facts mechanically recoverable from source, with line/column evidence."""
+ receipt = {'file': name, 'sha256': _sha(source.encode('utf-8')), 'facts': [], 'syntax': None}
+ if Path(name).suffix.lower() != '.py':
+ receipt['limit'] = 'A structural explanation part for this source language is not connected.'
+ return receipt
+ try:
+ tree = ast.parse(source, filename=name)
+ except SyntaxError as error:
+ receipt['syntax'] = {'message': error.msg, 'line': error.lineno, 'column': error.offset,
+ 'source': (error.text or '').strip()}
+ return receipt
+ receipt['doc'] = ast.get_docstring(tree) or '' # the module's own account of what it is for
+
+ def fact(node, kind, **content):
+ receipt['facts'].append(dict(kind=kind, line=node.lineno, end_line=node.end_lineno,
+ source=ast.get_source_segment(source, node), **content))
+
+ # Definition bodies have their own scope: a nested return is not a return
+ # from its enclosing function. All the source remains in the receipt.
+ def walk_scope(nodes, owner):
+ for node in nodes:
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ params = [a.arg for a in node.args.posonlyargs + node.args.args]
+ if node.args.vararg:
+ params.append('*' + node.args.vararg.arg)
+ params += [a.arg for a in node.args.kwonlyargs]
+ if node.args.kwarg:
+ params.append('**' + node.args.kwarg.arg)
+ path = owner + '.' + node.name if owner else node.name
+ fact(node, 'function', name=path, parameters=params,
+ asynchronous=isinstance(node, ast.AsyncFunctionDef),
+ docstring=ast.get_docstring(node))
+ walk_scope(node.body, path)
+ elif isinstance(node, ast.ClassDef):
+ path = owner + '.' + node.name if owner else node.name
+ fact(node, 'class', name=path, bases=[_expr(b) for b in node.bases])
+ walk_scope(node.body, path)
+ else:
+ if isinstance(node, ast.Return):
+ fact(node, 'return', owner=owner, value=_expr(node.value) if node.value else 'None')
+ elif isinstance(node, (ast.Import, ast.ImportFrom)):
+ fact(node, 'import', owner=owner, statement=_expr(node))
+ elif isinstance(node, ast.If):
+ fact(node, 'condition', owner=owner, condition=_expr(node.test), alternate=bool(node.orelse))
+ elif isinstance(node, (ast.For, ast.AsyncFor)):
+ fact(node, 'iteration', owner=owner, target=_expr(node.target), iterable=_expr(node.iter))
+ elif isinstance(node, ast.While):
+ fact(node, 'repetition', owner=owner, condition=_expr(node.test))
+ elif isinstance(node, ast.Raise):
+ fact(node, 'raise', owner=owner, value=_expr(node.exc) if node.exc else 'the active exception')
+ elif isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign)):
+ fact(node, 'assignment', owner=owner, statement=_expr(node))
+ elif isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):
+ fact(node, 'call', owner=owner, expression=_expr(node.value))
+ for field in ('body', 'orelse', 'finalbody'):
+ value = getattr(node, field, None)
+ if isinstance(value, list):
+ walk_scope(value, owner)
+ for handler in getattr(node, 'handlers', []):
+ walk_scope(handler.body, owner)
+ for case in getattr(node, 'cases', []):
+ walk_scope(case.body, owner)
+ walk_scope(tree.body, '')
+ return receipt
+
+
+def describe(receipt):
+ name = receipt['file']
+ if receipt.get('syntax'):
+ error = receipt['syntax']
+ return ['`%s` cannot be parsed as Python: %s at line %s, column %s.' %
+ (name, error['message'], error['line'], error['column']),
+ 'The source there is `%s`.' % error['source']]
+ if receipt.get('limit'):
+ return ['I can read `%s`, but %s' % (name, receipt['limit'][0].lower() + receipt['limit'][1:])]
+ facts = receipt['facts']
+ definitions = [f for f in facts if f['kind'] in ('function', 'class')]
+ sentences = ['`%s` parses as Python. This describes the source; it does not establish a successful run.' % name]
+ own = ' '.join(str(receipt.get('doc') or '').split())
+ if own: # what the file says it is for, in its own words, before its parts
+ sentences.insert(0, 'In its own words (its module docstring): ' + ' '.join(
+ __import__('re').split(r'(?<=[.!?])\s+', own)[:3]))
+ if not facts:
+ sentences.append('The structural reader found no definitions, assignments, calls, imports, or control-flow statements to explain.')
+ for item in definitions:
+ if item['kind'] == 'class':
+ sentences.append('Line %d defines the class `%s`%s.' % (item['line'], item['name'],
+ ' with bases ' + ', '.join('`' + b + '`' for b in item['bases']) if item['bases'] else ''))
+ continue
+ sentence = 'Line %d defines `%s(%s)`' % (item['line'], item['name'], ', '.join(item['parameters']))
+ returns = [f for f in facts if f['kind'] == 'return' and f['owner'] == item['name']]
+ sentence += ('. Its return expressions are ' + '; '.join('`%s` (line %d)' % (f['value'], f['line']) for f in returns)
+ if returns else '. There is no explicit return in that function body')
+ sentences.append(sentence + '.')
+ wording = {
+ 'import': lambda f: '`%s`' % f['statement'],
+ 'condition': lambda f: 'tests `%s`%s' % (f['condition'], ' and has an alternative branch' if f['alternate'] else ''),
+ 'iteration': lambda f: 'iterates `%s` over `%s`' % (f['target'], f['iterable']),
+ 'repetition': lambda f: 'repeats while `%s`' % f['condition'],
+ 'raise': lambda f: 'raises `%s`' % f['value'],
+ 'assignment': lambda f: 'assigns `%s`' % f['statement'],
+ 'call': lambda f: 'calls `%s`' % f['expression'],
+ }
+ for item in facts:
+ if item['kind'] in wording:
+ sentences.append('At line %d, %s %s.' % (item['line'],
+ '`%s`' % item['owner'] if item['owner'] else 'the module', wording[item['kind']](item)))
+ return sentences
+
+
+def failure_evidence(turn, sources, text):
+ """Read a current conversation's existing failed run; never execute one."""
+ import bench
+ import repair
+ if turn is None or turn.env is None:
+ return None
+ job = bench._job_for(turn, text)
+ if not job or job.get('sid') != turn.sid or job.get('state') != 'finished' or job.get('passed'):
+ return None
+ path = Path(job['dir']) / 'log'
+ if not path.is_file() or path.stat().st_size > 2_000_000:
+ return None
+ raw = path.read_bytes()
+ log = raw.decode('utf-8', 'replace')
+ if bench.SECRET_TEXT.search(log):
+ return None
+ errors = re.findall(r'^([\w.]+(?:Error|Exception)(?::[^\n]*)?|AssertionError(?::[^\n]*)?)$', log, re.M)
+ frames = []
+ for source, line in repair.frames_of(log, turn.env.root):
+ record = sources.get(str(source))
+ if record:
+ lines = record['source'].splitlines()
+ current = lines[line - 1].strip() if 0 < line <= len(lines) else None
+ frames.append({'file': record['name'], 'line': line, 'current_source': current})
+ if not frames:
+ return None
+ return {'job': job['id'], 'command': job.get('cmd'), 'exit': job.get('exit'),
+ 'log_sha256': _sha(raw), 'errors': errors, 'frames': frames,
+ 'freshness': 'historical run; current source inspected separately'}
+
+
+def handle(text, native, env, turn=None):
+ previous = None
+ if turn is not None:
+ kept = turn.s.get('code_discussion')
+ if kept and kept.get('env') in (None, env.key if env else None):
+ import reflect
+ ledger = reflect.load(turn.sid).get('ledger') or []
+ if not ledger or str(ledger[-1].get('path', '')).startswith('bench:code:'):
+ previous = kept
+ received = receive(text, native, previous)
+ if received is None:
+ return None
+ received['env'] = env.key if env else None
+ if turn is not None:
+ turn.s['code_discussion'] = received
+ if env is None:
+ turn.s['pending_context_focus'] = 'code'
+ turn.save()
+ names = ', '.join('`' + file + '`' for file in received['files'])
+ missing, records, sources = [], [], {}
+ if env is None:
+ missing.append({'kind': 'code_explanation', 'question': text, 'files': received['files'],
+ 'environment': None, 'needed': 'project folder'})
+ response = 'Which project folder contains %s? Open it with `open ` so I can inspect the local code.' % names
+ elif env.kind != 'folder':
+ missing.append({'kind': 'code_explanation', 'question': text, 'files': received['files'],
+ 'environment': env.key, 'needed': 'local source inspection'})
+ response = 'This code explanation part needs a local project folder. The question about %s is kept.' % names
+ else:
+ lines = []
+ for name in received['files']:
+ candidates = [p for p in env.resolve(name) if _inside(env.root, p)]
+ if len(candidates) != 1:
+ missing.append({'kind': 'code_explanation', 'question': text, 'files': [name],
+ 'environment': env.key, 'needed': 'one readable source file',
+ 'candidates': [env.rel(p) for p in candidates]})
+ lines.append('I have not established an explanation for `%s`: %s.' %
+ (name, 'several matching files need a specific path' if candidates else 'that file is not available in this folder'))
+ continue
+ path = candidates[0]
+ source = env.read(path)
+ if source is None:
+ missing.append({'kind': 'source', 'file': name, 'needed': 'readable source'})
+ lines.append('`%s` is not available as readable source.' % name)
+ continue
+ record = inspect_source(env.rel(path), source)
+ records.append(record)
+ sources[str(Path(path).resolve())] = {'source': source, 'name': env.rel(path)}
+ lines.extend(describe(record))
+ if record.get('limit'):
+ missing.append({'kind': 'source_language', 'file': name, 'needed': record['limit']})
+ evidence = failure_evidence(turn, sources, text) if received['failure'] else None
+ if evidence:
+ lines.append('The recorded run of `%s` (job %s) exited with %s%s.' %
+ (evidence['command'], evidence['job'], evidence['exit'],
+ ' and reported ' + '; '.join('`' + e + '`' for e in evidence['errors']) if evidence['errors'] else ''))
+ frame = evidence['frames'][-1]
+ lines.append('Its traceback reaches `%s`, line %s. The current source there is `%s`.' %
+ (frame['file'], frame['line'], frame['current_source']))
+ lines.append('That log describes the earlier run; I have not rerun the current files or established their runtime values.')
+ elif received['failure'] and not any(r.get('syntax') for r in records):
+ missing.append({'kind': 'failure_evidence', 'question': text, 'files': received['files'],
+ 'environment': env.key, 'needed': 'a failing run or traceback tied to these files'})
+ lines.append('I do not yet have a failing run tied to these files. Run the failing command here, or provide its traceback and inputs, so I can distinguish a source observation from the cause of a failure.')
+ response = '\n\n'.join(lines)
+ received['source_receipts'] = records
+ received['failure_evidence'] = evidence
+ if turn is not None:
+ turn.s['code_discussion'] = received
+ turn.save()
+ return {'status': 'hole' if missing else 'answered',
+ 'path': 'bench:code:context' if not records else 'bench:code:explain',
+ 'response': response, 'code_reading': received, 'missing_evidence': missing,
+ 'execution': {'state': 'missing' if missing else 'read', 'started': False, 'changed': False,
+ 'files_read': [r['file'] for r in records], 'source_receipts': records}}
+
+
+def resume_after_open(sid):
+ import bench
+ turn = bench.Turn(sid)
+ kept = turn.s.get('code_discussion')
+ if not kept or kept.get('env') is not None or turn.env is None or turn.s.get('pending_context_focus') not in (None, 'code'):
+ return None
+ return handle(kept['question'], None, turn.env, turn)
diff --git a/workbench/code_store.py b/workbench/code_store.py
new file mode 100644
index 0000000000000000000000000000000000000000..1af4e1f3d80d1c2b56d9452335df441433cf4fcc
--- /dev/null
+++ b/workbench/code_store.py
@@ -0,0 +1,377 @@
+"""code_store - Oracle7's store of the functions it has composed, on the Tree of Life spine (12.0, CODE_SPEC C7).
+
+KEPT a function composed for a project is kept only after the project's own check passed with it (the law decides, not
+ the composer). Kept with its evidence: the examples it was made from, its read-back, the project and test files,
+ the shapes it takes and gives, the words of its name and of the request, the moves it is built from, sha256.
+ Pure functions only (no file, process or network call): what is kept is what any later goal may call.
+ON THE SPINE every kept function is an item spelled as a walk over the 22 paths (o7spine_v1's codebook and walks, as
+ flash_tol102 spells its store). Its facts are bound to it: bind(walk(key), walk(value)) for each shape it takes
+ (by place and in any place), the shape it gives, its arity, each word, each move. One matrix, one row per
+ function.
+LIT a goal's own facts (the shapes of its examples, the shape of its answers, its arity, the words of its name and of
+ the request) are the cue: one matrix product over the whole store gives every function's resonance, adding where
+ facts meet. Only the lit functions become moves in that goal's search, so the search is one size however large
+ the store grows; cleanup is the 22-way choice per position, never against the store's size.
+THE LAW lit is a proposal. A lit function is used only where its shapes fit, its source passes the check below, and the
+ composed program reads back and passes the project's check.
+CHECK a kept source is called only if it is one function, with no import, no dunder attribute, and names drawn only
+ from its parameters, its own comprehension names, the composer's modules and builtins, and other kept functions.
+No language model; numpy and the standard library."""
+from __future__ import annotations
+
+import ast
+import builtins
+import hashlib
+import json
+import os
+import re
+import sys
+import time
+from pathlib import Path
+
+WB = Path(__file__).resolve().parent
+for _d in (WB / "swarm",):
+ if str(_d) not in sys.path:
+ sys.path.insert(0, str(_d))
+
+MODULES = {"math", "statistics", "collections", "functools", "itertools", "re", "hashlib", "base64", "hmac", "json"}
+IMPURE = {"open", "print", "input", "exec", "eval", "compile", "__import__", "exit", "quit", "breakpoint", "setattr",
+ "delattr", "globals", "locals", "vars", "getattr"}
+TOP = 24
+
+
+def store_path():
+ if os.environ.get("ORACLE7_CODE_STORE"):
+ return Path(os.environ["ORACLE7_CODE_STORE"])
+ if os.environ.get("ORACLE7_STATE"):
+ return Path(os.environ["ORACLE7_STATE"]) / "code_parts.jsonl"
+ return WB / "local" / "code_parts.jsonl"
+
+
+def _beside(name):
+ """a file kept beside the store: its retirements, its holes, its dreams"""
+ return store_path().with_name(name)
+
+
+def retired_ids():
+ p = _beside("code_retired.jsonl")
+ out = set()
+ if p.is_file():
+ for ln in p.read_text(encoding="utf-8").splitlines():
+ try:
+ out.add(json.loads(ln)["id"])
+ except Exception: # noqa: BLE001
+ continue
+ return out
+
+
+def load(with_retired=False):
+ p = store_path()
+ out, seen = [], set() if with_retired else retired_ids() # a retired function stays in the file (replay reaches it)
+ if p.is_file():
+ for ln in p.read_text(encoding="utf-8").splitlines():
+ try:
+ e = json.loads(ln)
+ except Exception: # noqa: BLE001
+ continue
+ if e.get("id") and e["id"] not in seen:
+ seen.add(e["id"])
+ out.append(e)
+ return out
+
+
+def checked_source(src, name, known):
+ """None when the source is one function built only from the composer's names; else the reason it is not called"""
+ try:
+ tree = ast.parse(src)
+ except SyntaxError as e:
+ return "does not parse: %s" % e
+ fns = [n for n in tree.body if isinstance(n, ast.FunctionDef)]
+ if len(tree.body) != 1 or len(fns) != 1 or fns[0].name != name:
+ return "is not one function called %s" % name
+ fn = fns[0]
+ allowed = set(MODULES) | set(dir(builtins)) | set(known) | {a.arg for a in fn.args.args}
+ for n in ast.walk(fn):
+ if isinstance(n, (ast.Import, ast.ImportFrom, ast.Global, ast.Nonlocal, ast.While, ast.Try)) and \
+ not isinstance(n, (ast.While, ast.Try)):
+ return "imports or reaches outside itself"
+ if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store):
+ allowed.add(n.id)
+ if isinstance(n, ast.arg):
+ allowed.add(n.arg)
+ for n in ast.walk(fn):
+ if isinstance(n, ast.Attribute) and n.attr.startswith("__"):
+ return "reaches a dunder attribute"
+ if isinstance(n, ast.Name) and n.id not in allowed:
+ return "names %s, which is not one of the composer's" % n.id
+ if isinstance(n, ast.Name) and n.id in IMPURE:
+ return "calls %s" % n.id
+ return None
+
+
+def entry_for(r, g, project, test_files):
+ """the record kept for a composed function, or None when it is not kept (impure, or not confirmed)"""
+ src = r.get("source") or ""
+ if not src or not r.get("confirmed"):
+ return None
+ if checked_source(src, g["name"], set(r.get("uses") or [])) is not None:
+ return None
+ deps = dict(r.get("deps") or {})
+ if any(u not in deps for u in (r.get("uses") or [])):
+ return None # it calls something whose exact source is not kept with it
+ sha = hashlib.sha256((g["name"] + "\n" + src).encode()).hexdigest()
+ return {"id": sha[:16], "sha256": sha, "name": g["name"], "source": src, "params": list(g["params"]), "deps": deps,
+ "imports": list(r.get("imports") or []), "uses": list(r.get("uses") or []),
+ "in_shapes": r.get("in_shapes") or [], "out_shape": r.get("out_shape"), "words": r.get("words") or [],
+ "moves": [str(m) for m in (r.get("moves") or [])][:40], "examples": r.get("evidence") or [],
+ "read_back": r.get("read_back"), "project": project, "test_files": list(test_files or []), "t": time.time()}
+
+
+def keep(entries, deps_from=()):
+ """append the confirmed functions not already kept; -> the ones added. A function composed in the same job and called by
+ another is kept too (its record carries its own evidence), so every dependency is in the store by its sha"""
+ have = {e["id"] for e in load()}
+ add = [e for e in entries if e and e["id"] not in have]
+ if add:
+ p = store_path()
+ p.parent.mkdir(parents=True, exist_ok=True)
+ with open(p, "a", encoding="utf-8") as f:
+ for e in add:
+ f.write(json.dumps(e) + "\n")
+ return add
+
+
+def retire(ids, why):
+ """kept functions taken out of reuse, each with the receipt why (12.5 C32): a kept function is trusted on the evidence it
+ was kept with, and a later check that failed with it inside is evidence too. It stays in the file (replay reaches it);
+ -> the ids newly retired"""
+ have = retired_ids()
+ new = [i for i in dict.fromkeys(ids) if i and i not in have]
+ if new:
+ p = _beside("code_retired.jsonl")
+ p.parent.mkdir(parents=True, exist_ok=True)
+ with open(p, "a", encoding="utf-8") as f:
+ for i in new:
+ f.write(json.dumps({"id": i, "receipt": str(why)[:400], "t": time.time()}) + "\n")
+ return new
+
+
+# ---------------------------------------------------------------- holes and the night
+def note_hole(goal, gap, project=None, cause=None, spent=None, work=None):
+ """a code goal the composer declined, kept as a hole for the night: its name, its examples, why, what stopped it
+ (cause: time, memory, stopped, searched = every program within the bound tried, evidence = the examples do not
+ decide) and the seconds it was given (12.5 C33)"""
+ ev = []
+ for a, o, _t in goal.get("examples") or []:
+ try:
+ json.dumps([list(a), o])
+ ev.append([list(a), o])
+ except Exception: # noqa: BLE001
+ pass
+ if not ev:
+ return
+ p = _beside("code_holes.jsonl")
+ p.parent.mkdir(parents=True, exist_ok=True)
+ key = hashlib.sha256(json.dumps([goal["name"], ev], sort_keys=True).encode()).hexdigest()[:16]
+ try: # 12.5 step 5: the code hole is one kind of the one hole record too
+ import holes as _holes
+ _holes.record("code", "composing %s: %s" % (goal["name"], str(gap)[:300]), cause=cause or "evidence",
+ takes=["one more example of %s, or a narrower description" % goal["name"]], spent=spent,
+ route="compose", extra={"name": goal["name"], "code_hole": key, "work": work})
+ except Exception: # noqa: BLE001
+ pass
+ with open(p, "a", encoding="utf-8") as f:
+ f.write(json.dumps({"id": key, "name": goal["name"], "params": list(goal.get("params") or []), "examples": ev,
+ "gap": str(gap)[:400], "project": project, "cause": cause or "evidence", "spent": spent, "work": work,
+ "t": time.time()}) + "\n")
+
+
+def _holes():
+ p = _beside("code_holes.jsonl")
+ out = {}
+ if p.is_file():
+ for ln in p.read_text(encoding="utf-8").splitlines():
+ try:
+ h = json.loads(ln)
+ out[h["id"]] = h
+ except Exception: # noqa: BLE001
+ continue
+ return list(out.values())
+
+
+REPLAY = """
+import json, sys
+job = json.load(open(sys.argv[1]))
+ns = {}
+for m in job["imports"]:
+ ns[m.split(".")[0]] = __import__(m)
+for src in job["deps"] + [job["source"]]:
+ exec(compile(src, "kept", "exec"), ns)
+fn = ns[job["name"]]
+out = []
+for args, want in job["examples"]:
+ try:
+ got = fn(*args)
+ out.append(json.dumps(got, sort_keys=True) == json.dumps(want, sort_keys=True) or
+ (isinstance(got, float) and isinstance(want, (int, float)) and abs(got - want) < 1e-9))
+ except Exception:
+ out.append(False)
+print(json.dumps(out))
+"""
+
+
+def replay(e, by_sha):
+ """a kept function re-run on its own evidence in a separate interpreter (with exactly the dependencies it was kept
+ with): -> None when every example still holds, else the receipt why not"""
+ import subprocess
+ import tempfile
+ deps, seen = [], set()
+
+ def add(x):
+ for _n, sha in (x.get("deps") or {}).items():
+ d = by_sha.get(sha)
+ if d is None:
+ raise KeyError(_n)
+ if sha not in seen:
+ seen.add(sha)
+ add(d)
+ deps.append(d["source"])
+ try:
+ add(e)
+ except KeyError as k:
+ return "a function it calls (%s) is no longer kept by the source it was checked with" % k
+ if checked_source(e["source"], e["name"], set(e.get("uses") or [])) is not None:
+ return "its source no longer passes the store's check"
+ if not e.get("examples"):
+ return None
+ with tempfile.TemporaryDirectory(prefix="o7night_") as d:
+ jp = os.path.join(d, "job.json")
+ json.dump({"name": e["name"], "source": e["source"], "deps": deps, "imports": e.get("imports") or [],
+ "examples": e["examples"]}, open(jp, "w"))
+ sp = os.path.join(d, "replay.py")
+ open(sp, "w").write(REPLAY)
+ try:
+ r = subprocess.run([sys.executable, "-I", sp, jp], capture_output=True, text=True, timeout=60, cwd=d,
+ env=__import__("runjail").env(root=d)) # round-3 R2
+ got = json.loads(r.stdout.strip().splitlines()[-1])
+ except Exception as x: # noqa: BLE001
+ return "its replay did not finish (%s)" % type(x).__name__
+ bad = [i for i, g in enumerate(got) if not g]
+ if bad:
+ return "%d of its %d examples no longer hold (the first: %r)" % (len(bad), len(got), e["examples"][bad[0]])
+ return None
+
+
+def nightly(night=None, dream=True, dream_seconds=120):
+ """the code store's night (sleep's steps 4 and 3 for kept code): every kept function replayed on its evidence and
+ retired with a receipt when it no longer holds; then each day's code hole tried again with the store as it now is. A
+ dream that composes is recorded, never kept: it is kept only after a project's check passes with it (the law)."""
+ t0 = time.time()
+ entries = load()
+ by_sha = {e["sha256"]: e for e in load(with_retired=True)}
+ rep = {"night": night, "kept": len(entries), "replayed": 0, "retired": [], "holes": 0, "dreamt": []}
+ for e in entries:
+ why = replay(e, by_sha)
+ rep["replayed"] += 1
+ if why:
+ rep["retired"].append({"id": e["id"], "name": e["name"], "receipt": why})
+ if rep["retired"]:
+ with open(_beside("code_retired.jsonl"), "a", encoding="utf-8") as f:
+ for r in rep["retired"]:
+ f.write(json.dumps(dict(r, night=night, t=time.time())) + "\n")
+ if dream:
+ import tempfile
+ import compose_code as CC
+ dreams_p = _beside("code_dreams.jsonl")
+ done = set()
+ if dreams_p.is_file():
+ for ln in dreams_p.read_text(encoding="utf-8").splitlines():
+ try:
+ done.add(json.loads(ln)["hole"])
+ except Exception: # noqa: BLE001
+ continue
+ holes = [h for h in _holes() if h["id"] not in done]
+ rep["holes"] = len(holes)
+ for h in holes:
+ ex = [(tuple(a), o, None) for a, o in h["examples"]]
+ goal = {"name": h["name"], "params": h["params"] or CC.param_names(ex), "module": "dream", "examples": ex,
+ "module_text": ""}
+ with tempfile.TemporaryDirectory(prefix="o7dream_") as d:
+ res = CC.run_job(d, [goal], timeout=dream_seconds)
+ r = (res.get("results") or [{}])[0] if "error" not in res else {}
+ if r.get("status") == "composed":
+ rec = {"hole": h["id"], "name": h["name"], "source": r["source"], "read_back": r.get("read_back"),
+ "night": night, "t": time.time()}
+ rep["dreamt"].append({"name": h["name"], "source": r["source"]})
+ with open(dreams_p, "a", encoding="utf-8") as f:
+ f.write(json.dumps(rec) + "\n")
+ rep["seconds"] = round(time.time() - t0, 1)
+ return rep
+
+
+# ---------------------------------------------------------------- the spine
+class CodeFlash:
+ """the kept functions as one matrix of walks; a goal's facts light them in one product"""
+
+ def __init__(self, entries):
+ import numpy as np
+ import o7spine_v1 as SP
+ self.np, self.SP = np, SP
+ self.D = SP.D
+ self.NE = len(SP.EDGES)
+ self.entries = entries
+ self._lab = {}
+ M = np.zeros((max(1, len(entries)), self.D), np.complex64)
+ for n, e in enumerate(entries):
+ for k, v in self.facts_of_entry(e):
+ M[n] += self.lab("K:" + k) * self.val(v)
+ norms = np.sqrt(np.sum(np.abs(M) ** 2, axis=1, keepdims=True))
+ self.M = (M / np.maximum(norms, 1e-6)).astype(np.complex64)
+
+ def _walk(self, n, length):
+ out = []
+ for _ in range(length):
+ out.append(n % self.NE)
+ n //= self.NE
+ return self.SP.walk_vec(out)
+
+ def lab(self, key):
+ if key not in self._lab:
+ h = int(hashlib.sha256(("o7code:" + key).encode()).hexdigest(), 16)
+ self._lab[key] = self._walk(h % (self.NE ** 3), 3)
+ return self._lab[key]
+
+ def val(self, v):
+ h = int(hashlib.sha256(("o7codeval:" + str(v)).encode()).hexdigest(), 16)
+ return self._walk(h % (self.NE ** 4), 4)
+
+ @staticmethod
+ def facts_of_entry(e):
+ out = [("arity", len(e.get("params") or []))]
+ for i, s in enumerate(e.get("in_shapes") or []):
+ out += [("in", s), ("in%d" % i, s)]
+ if e.get("out_shape"):
+ out.append(("out", e["out_shape"]))
+ out += [("word", w) for w in (e.get("words") or [])]
+ return out
+
+ def light(self, in_shapes, out_shape, words, top=TOP):
+ """-> [(resonance, entry)], the kept functions the goal's facts light, strongest first"""
+ if not self.entries:
+ return []
+ np = self.np
+ cue = np.zeros(self.D, np.complex64)
+ for i, s in enumerate(in_shapes):
+ cue += self.lab("K:in") * self.val(s)
+ if out_shape:
+ cue += self.lab("K:out") * self.val(out_shape)
+ for w in words:
+ cue += 2.0 * self.lab("K:word") * self.val(w)
+ res = np.real(self.M @ np.conj(cue)) / self.D
+ order = np.argsort(-res)[:top]
+ return [(float(res[i]), self.entries[i]) for i in order if res[i] > 0.02]
+
+
+if __name__ == "__main__": # the night, by a timer or by hand: python3 code_store.py nightly
+ if sys.argv[1:2] == ["nightly"]:
+ print(json.dumps(nightly(night=time.strftime("%Y-%m-%d")), indent=1))
diff --git a/workbench/compose_code.py b/workbench/compose_code.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac5d473f6d4ed8a5380522e162349b072363ab26
--- /dev/null
+++ b/workbench/compose_code.py
@@ -0,0 +1,4172 @@
+"""compose_code - the code composer over the shapes of Python values, with the project's own functions as moves (12.0,
+CODE_SPEC.md; Ben 2026-11-11: "Code is rules and composition. It can do novel code. It can do larger code.").
+
+This is composer_v3 (swarm/composer_v3.py: typed moves, type-directed bottom-up search, observational equivalence, shortest
+first, emitted code read back by a separate interpreter, admitted programs becoming moves) with its types widened from the
+dimensions of numbers to the shapes of values: number, text, truth, list of T, mapping, nothing. The rules are what Python
+does to each shape:
+ MOVES arithmetic, comparison and logic; text (lower, upper, strip, split, join, replace, slices, starts/ends, count);
+ lists (len, sum, max, min, mean, median, sorted, reversed, unique, counts, index, slices, membership);
+ mappings (lookup, keys, values, items); and the bodies of comprehensions - map, filter, sort/max/min by a key,
+ a mapping built from a list, any/all - each body composed in its own search over the elements
+ PARTS the project's own functions (read from its files: name, inputs, the values the tests show them taking), called
+ where their inputs fit; pure ones only (no file, process, network or printing calls)
+ LIBRARY every function composed and read back in this job is a part for the next (a module is composed round by
+ round: a function that needs another is reached once that one exists)
+ EVIDENCE the project's tests (assert f(...) == v, assertEqual, approx, abs(... - v) < eps) and the examples written
+ in the request (f(...) == v / -> v / returns v)
+ WORDS the request's words for the moves (sum, sort, keep, lower, ...) lower a move's cost: among programs that give
+ the examples, the one the request describes wins
+ BRANCHES when no single expression gives every example, a decision list (if c: return a ... return b) in which each
+ branch rests on at least two examples, or on one when its condition is an emptiness test (the guard)
+ READ-BACK the function is written out and run by a separate interpreter on every example; it must give each one
+It declines, and names the gap and the nearest program it reached, when nothing within its bounds gives every example.
+All-number goals the shape search does not reach go to composer_v3 itself (units, cited constants, meet-in-the-middle);
+its fitted-constant programs are refused here (code is not curve-fitting). No language model.
+
+usage (child process, run by run_job): compose_code.py """
+import ast
+import builtins
+import hashlib
+import itertools
+import json
+import math
+import os
+import re
+import subprocess
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+WB = Path(__file__).resolve().parent
+MAX_SIZE = 7 # nodes in an outer program
+INNER_MAX = 4 # nodes in a comprehension's body
+L_MAX = 5 # nodes in the list a comprehension runs over
+L_COUNT = 70 # lists per size a comprehension is tried over (the cheapest)
+IDEMPOTENT = {"sorted", "sorted_desc", "unique", "dedupe", "lower", "upper", "strip", "title", "capitalize", "abs", "round",
+ "int", "float", "str"}
+INVOLUTION = {"reversed", "neg", "not"}
+BANK_CAP = 150000 # programs kept per bank
+MEM_MB = int(os.environ.get("O7_COMPOSE_MEM_MB", "2600")) # the search's memory bound (banks inside banks share it)
+_MEM = {"t": 0.0, "over": False, "hit": False}
+# 12.5 step 6 (round-2 design 3.A): one work counter per goal, charged where a program is evaluated, by stage (bank: every
+# program the banks see; probe: every evaluation in the disagreement pass). It is recorded with the result and the hole; it
+# changes no decision (allowances by stage come later, set from this count measured on c31).
+_WORK = {"bank": 0, "probe": 0, "last": None}
+
+
+def mem_over():
+ """the composer's memory past its bound (read at most four times a second): every bank stops growing, as at its time"""
+ now = time.time()
+ if now - _MEM["t"] > 0.25:
+ _MEM["t"] = now
+ try:
+ with open("/proc/self/statm") as f:
+ rss = int(f.read().split()[1]) * os.sysconf("SC_PAGE_SIZE") >> 20
+ except (OSError, ValueError, AttributeError):
+ rss = 0
+ _MEM["over"] = rss > MEM_MB
+ _MEM["hit"] = _MEM["hit"] or _MEM["over"]
+ return _MEM["over"]
+INNER_CAP = 6000
+GOAL_SECONDS = 50 # search time per goal
+CHAIN_SECONDS = 70 # past the bound: chains (a body as its own goal, two programs joined)
+PASS_SECONDS = 220 # one goal's whole pass (search, chains, the child's start and read-back), as run_job counts it
+CHAIN_SECONDS_SUB = 12 # the same inside a body's own goal
+MAX_DEPTH = 3 # goals inside goals: a list of pieces, then each piece
+CHAIN_BESIDE_SECONDS = 20 # chains weighed beside a first fit that does not say its whole name
+WORD_BONUS = 0.35 # a move the request names costs this much less
+NAME_BONUS = 1.5 # each word of the function's name that a move of the program names: the name is a description
+LOSSY = {"round", "rounded", "floor", "ceil", "int", "floordiv", "mod"} # moves that throw information away
+BITWISE = {"band", "bor", "bxor", "shl", "shr", "hmac"} # numbers read as bits: weak evidence unless the words say bits
+SPECIAL = {"entropy", "log2", "hexof", "binof", "sha256", "sha1", "md5", "b64enc", "b64dec", "hexenc", "hexdec", "int16",
+ "int2", "ord", "chr"} # special-purpose moves: a fit through one is weak evidence unless the words name it
+ARBITRARY = re.compile(r"at1$|take\d|drop\d") # a fixed position other than first or last: a choice two examples cannot make
+AMBIG = 1.0 # rival programs this close in cost that answer differently elsewhere: ask, do not guess
+LOSSY_PEN = 3.0 # their cost when the request does not name them: a fit through rounding is weak evidence
+LAMBDA_BONUS = 0.2
+ERR = ""
+SECRET = re.compile(r"(?i)(secret|credential|wallet|password|passwd|token|key_guard|keys\.py|keypair|\.env)")
+IMPURE_CALLS = {"open", "print", "input", "exec", "eval", "compile", "__import__", "exit", "quit", "breakpoint", "setattr",
+ "delattr", "globals", "locals"}
+IMPURE_MODS = {"os", "sys", "subprocess", "shutil", "socket", "requests", "urllib", "pathlib", "http", "random", "time",
+ "datetime", "threading", "multiprocessing", "signal", "sqlite3", "logging", "tempfile", "glob", "io"}
+
+
+# ================================================================ shapes (types read from values)
+def tyof(v):
+ if v is None:
+ return "none"
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float" if math.isfinite(v) else "?"
+ if isinstance(v, str):
+ return "str"
+ if isinstance(v, (list, tuple)):
+ t = None
+ for x in v:
+ t = join(t, tyof(x))
+ if t == "?":
+ return "?"
+ return ("list" if isinstance(v, list) else "tuple", t)
+ if isinstance(v, dict):
+ kt = vt = None
+ mixed = False
+ for k, x in v.items():
+ kt = join(kt, tyof(k))
+ if not mixed:
+ vt = join(vt, tyof(x))
+ if vt == "?": # a record: fields of different shapes, each read on its own
+ mixed, vt = True, None
+ if kt == "?":
+ return "?"
+ return ("dict", kt, vt)
+ return "?"
+
+
+def join(a, b):
+ if a is None:
+ return b
+ if b is None:
+ return a
+ if a == b:
+ return a
+ if {a, b} == {"int", "float"}:
+ return "float"
+ if isinstance(a, tuple) and isinstance(b, tuple) and a[0] == b[0] and len(a) == len(b):
+ parts = [join(x, y) for x, y in zip(a[1:], b[1:])]
+ return "?" if "?" in parts else (a[0],) + tuple(parts)
+ return "?"
+
+
+def ty_of_vals(vals):
+ t = None
+ for v in vals:
+ if v is ERR:
+ continue
+ t = join(t, tyof(v))
+ if t == "?":
+ return "?"
+ return t
+
+
+def is_num(t):
+ return t in ("int", "float")
+
+
+def is_seq(t):
+ return isinstance(t, tuple) and t[0] in ("list", "tuple")
+
+
+def is_lnum(t):
+ return is_seq(t) and t[1] in (None, "int", "float")
+
+
+def is_lstr(t):
+ return is_seq(t) and t[1] in (None, "str")
+
+
+def is_lbool(t):
+ return is_seq(t) and t[1] in (None, "bool")
+
+
+def is_hashable_seq(t):
+ return is_seq(t) and t[1] in (None, "int", "float", "str", "bool")
+
+
+def is_iter(t):
+ return is_seq(t) or t == "str"
+
+
+def is_dict(t):
+ return isinstance(t, tuple) and t[0] == "dict"
+
+
+def is_sortable(t):
+ return (is_seq(t) and t[1] in (None, "int", "float", "str")) or t == "str"
+
+
+def elem(t):
+ return "str" if t == "str" else (t[1] if is_seq(t) else None)
+
+
+def same(a, b, tol=None):
+ """the equality a test asks for: numbers within the test's tolerance (or exactly), truth values strictly"""
+ if a is ERR:
+ return False
+ if isinstance(a, bool) or isinstance(b, bool):
+ return isinstance(a, bool) and isinstance(b, bool) and a == b
+ if isinstance(a, (int, float)) and isinstance(b, (int, float)):
+ if isinstance(b, float) and not isinstance(a, float) and tol is None:
+ return False # an example written as 5.0 says the value is a decimal number
+ if tol is not None:
+ return abs(a - b) <= tol
+ return abs(a - b) <= 1e-9 * max(1.0, abs(b))
+ if isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)):
+ return type(a) is type(b) and len(a) == len(b) and all(same(x, y) for x, y in zip(a, b))
+ if isinstance(a, dict) and isinstance(b, dict):
+ return a.keys() == b.keys() and all(same(a[k], b[k]) for k in a)
+ if isinstance(a, str) and isinstance(b, str):
+ return str(a) == str(b) # a constant read from a name or a field is text like any other
+ return type(a) is type(b) and a == b
+
+
+def norm(v):
+ if v is ERR:
+ return ("E",)
+ if isinstance(v, float):
+ return ("f", round(v, 9))
+ if isinstance(v, list):
+ return ("L",) + tuple(norm(x) for x in v)
+ if isinstance(v, tuple):
+ return ("T",) + tuple(norm(x) for x in v)
+ if isinstance(v, dict):
+ return ("D",) + tuple(sorted(((norm(k), norm(x)) for k, x in v.items()), key=repr))
+ if isinstance(v, bool):
+ return ("b", v)
+ return v
+
+
+# ================================================================ moves: what Python does to each shape
+def _nonempty(f):
+ def g(a):
+ if not a:
+ raise ValueError("empty")
+ return f(a)
+ return g
+
+
+def _smallint(f):
+ def g(a, b):
+ if not isinstance(b, int) or isinstance(b, bool) or abs(b) > 8:
+ raise ValueError("exponent")
+ return f(a, b)
+ return g
+
+
+def _mean(a):
+ import statistics
+ return statistics.fmean(a) # an average is a decimal number
+
+
+def _median(a):
+ import statistics
+ return statistics.median(a)
+
+
+def _ap_prod(a):
+ v = math.prod(a)
+ if abs(v) > 10 ** 15:
+ raise OverflowError("product")
+ return v
+
+
+def _horner(base):
+ def f(a):
+ acc = 0
+ for d in a:
+ if isinstance(d, bool) or not isinstance(d, int):
+ raise TypeError("digits")
+ acc = acc * base + d
+ if abs(acc) > 10 ** 15:
+ raise OverflowError("fold")
+ return acc
+ return f
+
+
+def _hexdigest(name):
+ def f(t):
+ import hashlib
+ return hashlib.new(name, t.encode()).hexdigest()
+ return f
+
+
+def _b64enc(t):
+ import base64
+ return base64.b64encode(t.encode()).decode()
+
+
+def _b64dec(t):
+ import base64
+ return base64.b64decode(t, validate=True).decode()
+
+
+def _entropy(a):
+ import collections
+ if not a:
+ raise ValueError("empty")
+ n = len(a)
+ return -sum(c / n * math.log2(c / n) for c in collections.Counter(a).values()) + 0.0
+
+
+def _hmac(k, m):
+ import hashlib
+ import hmac
+ return hmac.new(k.encode(), m.encode(), hashlib.sha256).hexdigest()
+
+
+def _is_int(t):
+ return t == "int"
+
+
+def _shift(f):
+ def g(a, b):
+ if not 0 <= b <= 64:
+ raise ValueError("shift")
+ return f(a, b)
+ return g
+
+
+PATTERNS = { # named shapes of text, found with re.findall; the request's or the name's words choose them
+ "ipv4s": (r"\b(?:\d{1,3}\.){3}\d{1,3}\b", "ip ips address addresses ipv4"),
+ "emails": (r"[\w.+-]+@[\w-]+\.[\w.-]+", "email emails mail address addresses"),
+ "urls": (r"https?://[^\s\"'<>]+", "url urls link links address"),
+ "hexes": (r"\b[0-9a-fA-F]{8,}\b", "hex hash hashes digest token"),
+ "numbers": (r"-?\d+", "number numbers digits integers"),
+}
+
+
+def _tlit(v):
+ """a value written into a move's code template: its braces are the value's, not the template's"""
+ return repr(v).replace("{", "{{").replace("}", "}}")
+
+
+def _findall(pat):
+ def f(t):
+ return re.findall(pat, t)
+ return f
+
+
+def _counter(a):
+ import collections
+ return dict(collections.Counter(a))
+
+
+# name, applies to (type), the operation, its code, the words for it, imports
+UNARY = [
+ ("neg", is_num, lambda a: -a, "(-{0})", "negative negate minus opposite", ()),
+ ("abs", is_num, abs, "abs({0})", "absolute magnitude distance", ()),
+ ("round", lambda t: t == "float", round, "round({0})", "round rounded nearest whole", ()),
+ ("int", lambda t: t in ("float", "str"), int, "int({0})", "integer whole convert number", ()),
+ ("float", lambda t: t == "str", float, "float({0})", "decimal convert number", ()),
+ ("str", is_num, str, "str({0})", "text string convert digits digit", ()),
+ ("not", lambda t: t == "bool", lambda a: not a, "(not {0})", "not opposite", ()),
+ ("sqrt", is_num, math.sqrt, "math.sqrt({0})", "square root", ("math",)),
+ ("floor", lambda t: t == "float", math.floor, "math.floor({0})", "floor down", ("math",)),
+ ("ceil", lambda t: t == "float", math.ceil, "math.ceil({0})", "ceiling up", ("math",)),
+ ("len", lambda t: is_iter(t) or is_dict(t), len, "len({0})", "count number length how many size", ()),
+ ("empty", lambda t: is_iter(t) or is_dict(t), lambda a: not a, "(not {0})", "empty nothing none no", ()),
+ ("sum", is_lnum, sum, "sum({0})", "sum total add together", ()),
+ ("prod", is_lnum, lambda a: _ap_prod(a), "math.prod({0})", "product multiply multiplied all together", ("math",)),
+ ("max", is_sortable, _nonempty(max), "max({0})", "max maximum largest biggest highest most greatest expensive dearest", ()),
+ ("min", is_sortable, _nonempty(min), "min({0})", "min minimum smallest lowest least fewest cheap cheapest", ()),
+ ("mean", is_lnum, _nonempty(_mean), "statistics.fmean({0})", "average mean", ("statistics",)),
+ ("median", is_lnum, _nonempty(_median), "statistics.median({0})", "median middle", ("statistics",)),
+ ("sorted", is_sortable, sorted, "sorted({0})", "sort sorted order ascending alphabetical", ()),
+ ("sorted_desc", is_sortable, lambda a: sorted(a, reverse=True), "sorted({0}, reverse=True)",
+ "sort sorted descending reverse largest first", ()),
+ ("reversed", lambda t: is_seq(t) or t == "str", lambda a: a[::-1], "{0}[::-1]", "reverse reversed backwards", ()),
+ ("unique", is_hashable_seq, lambda a: sorted(set(a)), "sorted(set({0}))", "unique distinct deduplicate different", ()),
+ ("dedupe", is_hashable_seq, lambda a: list(dict.fromkeys(a)), "list(dict.fromkeys({0}))",
+ "unique distinct dedupe duplicates repeats order", ()),
+ ("nunique", is_hashable_seq, lambda a: len(set(a)), "len(set({0}))", "distinct unique different count", ()),
+ ("counts", is_hashable_seq, _counter, "dict(collections.Counter({0}))", "count counts frequency occurrences each tally",
+ ("collections",)),
+ ("any", is_lbool, any, "any({0})", "any some at least one", ()),
+ ("all", is_lbool, all, "all({0})", "all every each", ()),
+ ("chars", lambda t: t == "str", list, "list({0})", "characters letters chars", ()),
+ ("sha256", lambda t: t == "str", _hexdigest("sha256"), "hashlib.sha256({0}.encode()).hexdigest()",
+ "sha256 sha hash digest checksum hex", ("hashlib",)),
+ ("sha1", lambda t: t == "str", _hexdigest("sha1"), "hashlib.sha1({0}.encode()).hexdigest()", "sha1 sha hash digest checksum",
+ ("hashlib",)),
+ ("md5", lambda t: t == "str", _hexdigest("md5"), "hashlib.md5({0}.encode()).hexdigest()", "md5 hash digest checksum hex",
+ ("hashlib",)),
+ ("b64enc", lambda t: t == "str", _b64enc, "base64.b64encode({0}.encode()).decode()", "base64 b64 encode encoded", ("base64",)),
+ ("b64dec", lambda t: t == "str", _b64dec, "base64.b64decode({0}).decode()", "base64 b64 decode decoded from", ("base64",)),
+ ("hexenc", lambda t: t == "str", lambda a: a.encode().hex(), "{0}.encode().hex()", "hex hexadecimal encode to", ()),
+ ("hexdec", lambda t: t == "str", lambda a: bytes.fromhex(a).decode(), "bytes.fromhex({0}).decode()",
+ "hex hexadecimal decode from", ()),
+ ("int16", lambda t: t == "str", lambda a: int(a, 16), "int({0}, 16)", "hex hexadecimal parse number from", ()),
+ ("int2", lambda t: t == "str", lambda a: int(a, 2), "int({0}, 2)", "binary bits parse number from", ()),
+ ("hexof", _is_int, lambda a: format(a, "x"), "format({0}, 'x')", "hex hexadecimal to", ()),
+ ("binof", _is_int, lambda a: format(a, "b"), "format({0}, 'b')", "binary bits to", ()),
+ ("ord", lambda t: t == "str", lambda a: ord(a) if len(a) == 1 else 1 / 0, "ord({0})", "code ord ascii codepoint", ()),
+ ("chr", _is_int, lambda a: chr(a) if 0 <= a < 0x110000 else 1 / 0, "chr({0})", "character chr letter ascii", ()),
+ ("bool", is_num, bool, "bool({0})", "set nonzero true flag is", ()),
+ ("log2", is_num, math.log2, "math.log2({0})", "log logarithm bits", ("math",)),
+ ("entropy", lambda t: t == "str" or is_hashable_seq(t), _entropy,
+ "(-sum(c / len({0}) * math.log2(c / len({0})) for c in collections.Counter({0}).values()) + 0.0)",
+ "entropy shannon randomness information", ("math", "collections")),
+ ("lower", lambda t: t == "str", str.lower, "{0}.lower()", "lower lowercase case small ignoring", ()),
+ ("upper", lambda t: t == "str", str.upper, "{0}.upper()", "upper uppercase capitals capital shout loud", ()),
+ ("strip", lambda t: t == "str", str.strip, "{0}.strip()", "strip trim whitespace spaces ends", ()),
+ ("title", lambda t: t == "str", str.title, "{0}.title()", "title capitalize capitalise capitals", ()),
+ ("capitalize", lambda t: t == "str", str.capitalize, "{0}.capitalize()", "capitalize capitalise first capital", ()),
+ ("words", lambda t: t == "str", str.split, "{0}.split()", "split words spaces whitespace collapse", ()),
+ ("lines", lambda t: t == "str", str.splitlines, "{0}.splitlines()", "lines line", ()),
+ ("isdigit", lambda t: t == "str", str.isdigit, "{0}.isdigit()", "digit digits number numeric", ()),
+ ("isalpha", lambda t: t == "str", str.isalpha, "{0}.isalpha()", "letter letters alphabetic", ()),
+ ("isupper", lambda t: t == "str", str.isupper, "{0}.isupper()", "upper uppercase capital", ()),
+ ("keys", is_dict, lambda a: sorted(a), "sorted({0})", "keys", ()),
+ ("values", is_dict, lambda a: list(a.values()), "list({0}.values())", "values", ()),
+ ("items", is_dict, lambda a: sorted(a.items()), "sorted({0}.items())", "items pairs entries", ()),
+]
+
+CMP_WORDS = ("greater more over above larger exceeds bigger positive less under below smaller fewer negative most within least "
+ "at alphabetical alphabetically before after") # one comparison read from either side (x > 0 is 0 < x): the same words
+BINARY = [ # name, applies to (ta, tb), operation, code, words, commutative
+ ("add", lambda a, b: is_num(a) and is_num(b), lambda a, b: a + b, "({0} + {1})", "add plus sum total more", True),
+ ("sub", lambda a, b: is_num(a) and is_num(b), lambda a, b: a - b, "({0} - {1})", "subtract minus difference less", False),
+ ("mul", lambda a, b: is_num(a) and is_num(b), lambda a, b: a * b, "({0} * {1})", "multiply times product double", True),
+ ("div", lambda a, b: is_num(a) and is_num(b), lambda a, b: a / b, "({0} / {1})", "divide divided ratio per half share", False),
+ ("floordiv", lambda a, b: a == "int" and b == "int", lambda a, b: a // b, "({0} // {1})",
+ "divide whole digit digits half halve halving halvings", False),
+ ("mod", lambda a, b: a == "int" and b == "int", lambda a, b: a % b, "({0} % {1})",
+ "remainder modulo even odd divisible multiple digit digits", False),
+ ("pow", lambda a, b: is_num(a) and b == "int", _smallint(lambda a, b: a ** b), "({0} ** {1})", "power squared cubed", False),
+ ("max2", lambda a, b: is_num(a) and is_num(b), max, "max({0}, {1})", "max at least floor clamp between larger", True),
+ ("min2", lambda a, b: is_num(a) and is_num(b), min, "min({0}, {1})", "min at most cap limit clamp between smaller", True),
+ ("concat", lambda a, b: a == "str" and b == "str", lambda a, b: a + b, "({0} + {1})",
+ "append add concatenate join suffix prefix end", False),
+ ("repeat", lambda a, b: a == "str" and b == "int", lambda a, b: a * b if 0 <= b <= 64 else 1 / 0, "({0} * {1})",
+ "repeat times", False),
+ ("lconcat", lambda a, b: is_seq(a) and is_seq(b) and a[0] == b[0] and join(a, b) != "?", lambda a, b: a + b,
+ "({0} + {1})", "append add combine join extend", False),
+ ("eq", lambda a, b: a == b and a in ("int", "str", "bool") or (is_num(a) and is_num(b)), lambda a, b: a == b,
+ "({0} == {1})", "equal equals same is", True),
+ ("ne", lambda a, b: a == b and a in ("int", "str") or (is_num(a) and is_num(b)), lambda a, b: a != b, "({0} != {1})",
+ "not different other", True),
+ ("lt", lambda a, b: (is_num(a) and is_num(b)) or a == b == "str", lambda a, b: a < b, "({0} < {1})",
+ CMP_WORDS, False),
+ ("le", lambda a, b: (is_num(a) and is_num(b)), lambda a, b: a <= b, "({0} <= {1})", CMP_WORDS, False),
+ ("gt", lambda a, b: (is_num(a) and is_num(b)) or a == b == "str", lambda a, b: a > b, "({0} > {1})",
+ CMP_WORDS, False),
+ ("ge", lambda a, b: (is_num(a) and is_num(b)), lambda a, b: a >= b, "({0} >= {1})", CMP_WORDS, False),
+ ("and", lambda a, b: a == b == "bool", lambda a, b: a and b, "({0} and {1})", "and both", True),
+ ("or", lambda a, b: a == b == "bool", lambda a, b: a or b, "({0} or {1})", "or either", True),
+ ("in", lambda a, b: (b == "str" and a == "str") or (is_seq(b) and b[1] in (None, a)) or (is_dict(b) and b[1] in (None, a)),
+ lambda a, b: a in b, "({0} in {1})", "in contains includes has member among", False),
+ ("count", lambda a, b: (a == "str" and b == "str") or (is_seq(a) and a[1] in (None, b)), lambda a, b: a.count(b),
+ "{0}.count({1})", "count occurrences times how many", False),
+ ("at", lambda a, b: is_iter(a) and b == "int", lambda a, b: a[b], "{0}[{1}]", "at index position element item", False),
+ ("get", lambda a, b: is_dict(a) and a[1] in (None, b), lambda a, b: a[b], "{0}[{1}]", "lookup value of for", False),
+ ("startswith", lambda a, b: a == b == "str", lambda a, b: a.startswith(b), "{0}.startswith({1})", "starts begins prefix", False),
+ ("band", lambda a, b: a == b == "int", lambda a, b: a & b, "({0} & {1})", "and mask masked byte low bits bitwise nibble byte bit bits", True),
+ ("bor", lambda a, b: a == b == "int", lambda a, b: a | b, "({0} | {1})", "or set combine flag flags bitwise nibble byte bit bits", True),
+ ("bxor", lambda a, b: a == b == "int", lambda a, b: a ^ b, "({0} ^ {1})", "xor exclusive flip toggle bitwise nibble byte bit bits", True),
+ ("shl", lambda a, b: a == b == "int", _shift(lambda a, b: a << b), "({0} << {1})", "shift left bit bits nibble byte bit bits", False),
+ ("shr", lambda a, b: a == b == "int", _shift(lambda a, b: a >> b), "({0} >> {1})", "shift right bit bits nibble byte bit bits", False),
+ ("hmac", lambda a, b: a == b == "str", _hmac, "hmac.new({0}.encode(), {1}.encode(), hashlib.sha256).hexdigest()",
+ "hmac mac signature sign signed keyed", False),
+ ("endswith", lambda a, b: a == b == "str", lambda a, b: a.endswith(b), "{0}.endswith({1})", "ends suffix", False),
+ ("rounded", lambda a, b: a == "float" and b == "int", lambda a, b: round(a, b) if 0 <= b <= 6 else 1 / 0,
+ "round({0}, {1})", "round decimals places", False),
+]
+
+# three-place moves: Python's chained comparison (a <= x <= b is one move, as the language writes it)
+TERNARY = [
+ ("between", lambda a, b, c: is_num(a) and is_num(b) and is_num(c), lambda a, b, c: a <= b <= c, "{0} <= {1} <= {2}",
+ CMP_WORDS + " between inclusive range from to", ()),
+ ("between_open", lambda a, b, c: is_num(a) and is_num(b) and is_num(c), lambda a, b, c: a < b < c, "{0} < {1} < {2}",
+ CMP_WORDS + " between strictly exclusive range", ()),
+ ("between_text", lambda a, b, c: a == b == c == "str", lambda a, b, c: a.split(b, 1)[1].split(c, 1)[0] if b and c else 1 / 0,
+ "{0}.split({1}, 1)[1].split({2}, 1)[0]", "between inside tag text within enclosed", ()),
+]
+
+# two programs joined side by side, found from the answer: given one side's values, the other side's values are known
+JOINS = ["add", "sub", "mul", "div", "concat", "lconcat"]
+
+LAMBDAS = { # the comprehension forms: code with {v} (the element), {L} (the list), {b} (the body); words
+ "map": ("[{b} for {v} in {L}]", "each every all of"),
+ "filter": ("[{v} for {v} in {L} if {b}]", "keep keeps only where filter select which that whose remove drop"),
+ "sortkey": ("sorted({L}, key=lambda {v}: {b})", "sort sorted order by"),
+ "maxkey": ("max({L}, key=lambda {v}: {b})", "longest largest biggest most max highest expensive dearest priciest"),
+ "minkey": ("min({L}, key=lambda {v}: {b})", "shortest smallest least min lowest cheap cheapest"),
+ "dictof": ("{{{v}: {b} for {v} in {L}}}", "mapping dictionary each count per"),
+ "anyof": ("any({b} for {v} in {L})", "any some contains"),
+ "allof": ("all({b} for {v} in {L})", "all every each"),
+}
+
+
+def stem(w):
+ w = w.lower()
+ if len(w) > 6 and w.endswith("iest"):
+ return w[:-4] # a superlative is its base: priciest -> pric, busiest -> bus
+ if len(w) > 6 and w.endswith("est") and not w.endswith(("ffest", "quest", "interest", "contest", "protest")):
+ return w[:-3] # cheapest -> cheap, longest -> long
+ for suf in ("ing", "es", "ed"):
+ if len(w) > 4 and w.endswith(suf):
+ return w[: -len(suf)]
+ if len(w) > 3 and w.endswith("s") and not w.endswith(("ss", "us", "is")):
+ return w[:-1] # a short plural too: odds, keys, bits
+ return w
+
+
+# ================================================================ expressions
+class X:
+ __slots__ = ("op", "args", "val", "t", "size", "cost", "inp", "dead", "rmask", "imports", "pen", "uses", "nmask", "live",
+ "lossy", "waived")
+
+ def __init__(self, op, args, val, size, inp, named=(0, 0), imports=(), uses=0):
+ self.uses = uses
+ for a in args:
+ if isinstance(a, X):
+ self.uses |= a.uses
+ self.op, self.args, self.val = op, tuple(args), val
+ self.t = ty_of_vals(val)
+ self.size, self.inp, self.dead = size, inp, False
+ # a move on constants alone is a constant: it describes nothing (no word of the request or the name is covered by it)
+ self.live = op[0] in ("in", "var", "body") or (op[0] == "outer" and op[1].live) or any(a.live for a in args if isinstance(a, X))
+ rm, nm = named if isinstance(named, tuple) else (0, 0)
+ body = op[1] if op[0] in ("body", "scan", "zip") else None # a step composed as its own goal: it carries its words
+ # the request's words / the name's words this names (a text constant names the words it spells)
+ self.rmask, self.nmask = (rm, nm) if (self.live or (op[0] == "const" and isinstance(op[1], str))) else (0, 0)
+ pasted = op[0] == "b" and op[1] in ("concat", "lconcat")
+ for a in args:
+ if isinstance(a, X):
+ if pasted and _unouter(a).op[0] == "const" and isinstance(_unouter(a).op[1], str):
+ continue # a text pasted onto the data is not looked for: it says nothing (C8h)
+ self.rmask |= a.rmask
+ self.nmask |= a.nmask
+ weak = weak_move(op, args)
+ own = LOSSY_PEN if (weak and not (rm or nm)) else 0.0
+ # a weak move a word excused: it may be chosen, but it never makes a program say more of the name than another
+ self.waived = bool(weak and (rm or nm)) or any(a.waived for a in args if isinstance(a, X)) or (body is not None and body.waived)
+ if body is not None:
+ self.rmask, self.nmask, own = body.rmask, body.nmask, body.pen
+ self.lossy = own > 0 or any(a.lossy for a in args if isinstance(a, X)) or (body is not None and body.lossy)
+ if op[0] == "lam":
+ own -= LAMBDA_BONUS # at equal size, the program that works element by element
+ self.pen = own + sum(a.pen for a in args if isinstance(a, X))
+ # each word counts once, however many moves name it (a move added only to name a word again gains nothing)
+ self.cost = size - WORD_BONUS * bin(self.rmask).count("1") - NAME_BONUS * bin(self.nmask).count("1") + self.pen
+ self.imports = set(imports) | (body.imports if body is not None else set())
+ for a in args:
+ if isinstance(a, X):
+ self.imports |= a.imports
+
+
+WEAK = { # a fit through one of these moves is weak evidence unless the request or the name says it; declared once, why
+ **{m: "throws information away" for m in LOSSY},
+ **{m: "reads numbers as bits" for m in BITWISE},
+ **{m: "special-purpose" for m in SPECIAL},
+}
+
+
+_COMMUTES = (ast.Add, ast.Mult, ast.BitAnd, ast.BitOr, ast.BitXor)
+
+
+def _canon(n):
+ """a program's shape with the two sides of a commuting move in one order (state + value is value + state)"""
+ if isinstance(n, ast.BinOp) and isinstance(n.op, _COMMUTES):
+ a, b = sorted([_canon(n.left), _canon(n.right)])
+ return "BinOp(%s,%s,%s)" % (type(n.op).__name__, a, b)
+ if isinstance(n, ast.Compare) and len(n.ops) == 1 and isinstance(n.ops[0], (ast.Eq, ast.NotEq)):
+ a, b = sorted([_canon(n.left), _canon(n.comparators[0])])
+ return "Compare(%s,%s,%s)" % (type(n.ops[0]).__name__, a, b)
+ if isinstance(n, ast.AST):
+ return "%s(%s)" % (type(n).__name__, ",".join(_canon(v) for _f, v in ast.iter_fields(n)))
+ if isinstance(n, list):
+ return "[%s]" % ",".join(_canon(v) for v in n)
+ return repr(n)
+
+
+def _unwrapped_dumps(t):
+ """the program with each one-argument call around a part of it taken away, one at a time"""
+ out = []
+ def inner(ch):
+ if isinstance(ch, ast.Call) and len(ch.args) == 1 and not ch.keywords:
+ return ch.args[0]
+ return None # a sign is never a wrapper: -x and x differ wherever x is not 0
+ i0 = inner(t.body)
+ if i0 is not None:
+ out.append(_canon(i0))
+ for node in ast.walk(t):
+ for field, val in ast.iter_fields(node):
+ items = val if isinstance(val, list) else [val]
+ for i, ch in enumerate(items):
+ if not isinstance(ch, ast.AST):
+ continue
+ inn = inner(ch)
+ if inn is None:
+ continue
+ if isinstance(val, list):
+ val[i] = inn
+ else:
+ setattr(node, field, inn)
+ out.append(_canon(t.body))
+ if isinstance(val, list):
+ val[i] = ch
+ else:
+ setattr(node, field, ch)
+ return out
+
+
+def wraps(a_src, b_src):
+ """one program is the other with a wrapper around some part of it (abs(state) for state): the same program, never
+ a rival - the plainer is kept"""
+ a_src, b_src = a_src.strip(), b_src.strip()
+ try:
+ at, bt = ast.parse(a_src, mode="eval"), ast.parse(b_src, mode="eval")
+ except SyntaxError: # a program over lines: read as text
+ return a_src in b_src or b_src in a_src
+ da, db = _canon(at.body), _canon(bt.body)
+ return da == db or da in _unwrapped_dumps(bt) or db in _unwrapped_dumps(at)
+
+
+def weak_name(name):
+ """a move weak by its kind alone, whatever it is given"""
+ return name in WEAK or name in PATTERNS or name.startswith("fold") or bool(ARBITRARY.match(name))
+
+
+def _unouter(x):
+ """a value carried into a comprehension's body from outside it, as it is outside"""
+ while isinstance(x, X) and x.op[0] == "outer" and isinstance(x.op[1], X):
+ x = x.op[1]
+ return x
+
+
+def weak_move(op, args):
+ """why a move is weak evidence here, or None"""
+ if op[0] not in ("u", "b"):
+ return None
+ name = op[1]
+ args = [_unouter(a) for a in args]
+ a0 = args[0] if args and isinstance(args[0], X) else None
+ if name == "int" and a0 is not None and a0.t == "str":
+ return None # parsing text keeps all it says
+ if name == "repeat":
+ return "a text repeated"
+ if name == "pow" and len(args) == 2 and isinstance(args[1], X) and args[1].live:
+ return "a power read from the data"
+ if name == "mod" and len(args) == 2 and isinstance(args[1], X) and args[1].live:
+ return "a remainder by a value read from the data"
+ if name in ("dedupe", "unique") and a0 is not None and a0.op[0] == "u" and a0.op[1] in ("readlines", "readtext", "lines"):
+ return "repeated lines of the input dropped" # what is unique is what the answer names, not the raw input
+ if name == "mod" and len(args) == 2 and isinstance(args[1], X) and args[1].op[0] == "const" and args[1].op[1] == 2:
+ return None # odd or even: an ordinary property of a whole number
+ if name in WEAK:
+ return WEAK[name]
+ if name in PATTERNS or name.startswith("fold"):
+ return "special-purpose"
+ if ARBITRARY.match(name):
+ return "a fixed position"
+ if name == "at" and len(args) == 2 and isinstance(args[1], X) and not args[1].live and \
+ any(v not in (0, -1) for v in args[1].val if v is not ERR):
+ return "a fixed position"
+ if name == "str" and a0 is not None and is_num(a0.t):
+ return "a number's digits read as text"
+ if (name in ("lt", "le", "gt", "ge", "max", "min", "sorted", "sorted_desc", "unique")) and a0 is not None and a0.t == "str":
+ return "letters' alphabetical order"
+ if name in ("eq", "ne") and any(isinstance(a, X) and a.op[0] == "const" and isinstance(a.op[1], Boundary) for a in args):
+ return "one value taken from the examples"
+ return None
+
+
+def _ap(f, *xs):
+ if any(x is ERR for x in xs):
+ return ERR
+ try:
+ v = f(*xs)
+ except Exception: # noqa: BLE001
+ return ERR
+ if isinstance(v, float) and not math.isfinite(v):
+ return ERR
+ if isinstance(v, (int,)) and not isinstance(v, bool) and abs(v) > 10 ** 15:
+ return ERR
+ if isinstance(v, (str, list, tuple, dict)) and len(v) > 2000:
+ return ERR
+ return v
+
+
+class Bank:
+ """one search: leaves, then every move whose types fit, level by level; two programs that give the same values on every
+ row are one (the cheaper kept)"""
+
+ def __init__(self, n, deadline, cap, words, consts, parts, outer=None, namewords=()):
+ self.namewords = list(namewords)
+ self.n, self.deadline, self.cap, self.words = n, deadline, cap, words
+ self.seen, self.lv, self.consts, self.parts, self.outer = {}, {}, consts, parts, outer
+ self.ex = None # the examples (outer search only): which inputs matter
+ self.alts = {} # programs that gave the examples but lost on cost, by key
+ self.subalts = {} # parts that gave the same values as a kept part, by key
+ self.inner_cache = {}
+ self.unary = list(UNARY)
+ strs = [c for c in consts if isinstance(c, str) and not isinstance(c, Field)]
+ for sep in strs: # moves with a constant folded in: join with ", ", split on "-"
+ self.unary.append(("join%r" % sep, is_lstr, (lambda s: lambda a: s.join(a))(sep), "%s.join({0})" % _tlit(sep),
+ "join joined combine together glue with", ()))
+ if sep:
+ self.unary.append(("split%r" % sep, lambda t: t == "str", (lambda s: lambda a: a.split(s))(sep),
+ "{0}.split(%s)" % _tlit(sep), "split separate", ()))
+ for a_, b_ in itertools.permutations(strs, 2):
+ if a_:
+ self.unary.append(("replace%r%r" % (a_, b_), lambda t: t == "str",
+ (lambda x, y: lambda s: s.replace(x, y))(a_, b_), "{0}.replace(%s, %s)" % (_tlit(a_), _tlit(b_)),
+ "replace swap substitute remove", ()))
+ for base in sorted({c for c in consts if isinstance(c, int) and not isinstance(c, bool) and 2 <= c <= 16} | {2, 10}):
+ # a loop that carries a state: each element folded into the total so far, by position (digits, bits)
+ self.unary.append(("fold%d" % base, lambda t: is_seq(t) and t[1] in (None, "int"), _horner(base),
+ "functools.reduce(lambda acc, d: acc * %d + d, {0}, 0)" % base,
+ "digits digit number base binary bits positional combine fold %s" % (
+ "decimal" if base == 10 else "binary" if base == 2 else ""), ("functools",)))
+ for k, w in ((0, "first head initial"), (-1, "last final end"), (1, "second")):
+ self.unary.append(("at%d" % k, is_iter, (lambda i: lambda a: a[i])(k), "{0}[%d]" % k, w + " letter element item", ()))
+ for k in sorted({c for c in consts if isinstance(c, int) and not isinstance(c, bool) and 1 <= c <= 10} | {1, 2}):
+ self.unary.append(("take%d" % k, lambda t: is_seq(t) or t == "str", (lambda i: lambda a: a[:i])(k), "{0}[:%d]" % k,
+ "first top take head", ()))
+ self.unary.append(("drop%d" % k, lambda t: is_seq(t) or t == "str", (lambda i: lambda a: a[i:])(k), "{0}[%d:]" % k,
+ "rest drop skip tail without leading remove", ()))
+ for pn, (pat, pw) in PATTERNS.items():
+ self.unary.append((pn, lambda t: t == "str", _findall(pat), "re.findall(%s, {0})" % _tlit(pat), pw, ("re",)))
+ self.unary = [(n, ok, f, code, self.nw(w), imp) for n, ok, f, code, w, imp in self.unary]
+ self.binary = [(n, ok, f, code, self.nw(w), c) for n, ok, f, code, w, c in BINARY]
+ # a remainder says 'even' or 'odd' only when it is by 2 (C8h): by anything else it is a remainder
+ self._mod_other_nw = self.nw("remainder modulo divisible multiple digit digits")
+ self.ternary =[(n, ok, f, code, self.nw(w), imp) for n, ok, f, code, w, imp in TERNARY]
+
+ def nw(self, words):
+ """(the request's words this move names, the name's words it names), as bit masks"""
+ ws = {stem(w) for w in words.split()}
+ if not hasattr(self, "reqwords"):
+ self.reqwords = sorted(self.words)[:60]
+ rm = sum(1 << i for i, w in enumerate(self.reqwords) if w in ws)
+ nm = sum(1 << i for i, w in enumerate(self.namewords) if any(wmatch(w, u) for u in ws))
+ return (rm, nm)
+
+ def key(self, x):
+ """programs that read different inputs, or name different words of the name, are never merged"""
+ return (repr(x.t), x.uses, x.nmask if self.outer is None else 0, tuple(norm(v) for v in x.val))
+
+ def rank(self, x):
+ """what decides between two programs that give the same values: in a comprehension's body, size (and lossy moves)
+ only, since the words a program names count for the whole program, not a part of it"""
+ if self.outer is not None:
+ return (0, x.size + x.pen)
+ return (0, x.cost)
+
+ def choice(self, x):
+ """the final choice among programs that give every example: the one naming more of the name's words, then cost"""
+ return (len(self.namewords) - bin(x.nmask).count("1"), x.cost, x.size)
+
+ def time_up(self):
+ return time.time() > self.deadline or len(self.seen) >= self.cap or mem_over()
+
+ def add(self, x):
+ _WORK["bank"] += 1
+ _WORK["last"] = "bank"
+ if x.t in (None, "?") or all(v is ERR for v in x.val):
+ return None
+ k = self.key(x) # programs reading different inputs are not merged
+ o = self.seen.get(k)
+ if o is not None:
+ if self.ex is not None and as_described(x, o) and len(self.subalts.setdefault(k, [])) < 2:
+ self.subalts[k].append(x) # a part as plain and as described as the kept one: a rival inside
+ if self.ex is not None and fits_all(x, self.ex):
+ al = self.alts.setdefault(k, []) # rivals that also give the examples: kept to compare
+ for y in (o, x):
+ if len(al) < 10 and all(y is not z for z in al):
+ al.append(y)
+ rx, ro = self.rank(x), self.rank(o)
+ if rx[0] < ro[0] or (rx[0] == ro[0] and rx[1] < ro[1] - 1e-9):
+ o.dead = True
+ self.seen[k] = x
+ self.lv.setdefault(x.size, []).append(x)
+ return x
+ if self.ex is not None and bin(x.uses).count("1") > 1 and \
+ not matters(lambda inp: evalx(o, inp), self.ex, o.uses) and matters(lambda inp: evalx(x, inp), self.ex, x.uses):
+ o.dead = True # the kept one only seemed to read an input: the one that does replaces it
+ self.seen[k] = x
+ self.lv.setdefault(x.size, []).append(x)
+ return x
+ return None
+ self.seen[k] = x
+ self.lv.setdefault(x.size, []).append(x)
+ return x
+
+ def alive(self, size):
+ return [x for x in self.lv.get(size, []) if not x.dead]
+
+ def by_type(self, size):
+ g = {}
+ for x in self.alive(size):
+ g.setdefault(repr(x.t), []).append(x)
+ return g
+
+ def grow(self, size, lambdas=False):
+ """every program of this many nodes: the moves that are strong evidence first, the weak ones (special-purpose,
+ lossy, bits) after, unless asked for - when the bound cuts a size short, what it cuts is the weak evidence"""
+ if size == 1:
+ return
+ def named(m):
+ return bool(m[4][0] or m[4][1])
+ weak_u = [u for u in self.unary if not named(u) and weak_name(u[0])]
+ weak_b = [b for b in self.binary if not named(b) and weak_name(b[0])]
+ strong_u = sorted((u for u in self.unary if u not in weak_u), key=lambda m: not named(m)) # named first
+ strong_b = sorted((b for b in self.binary if b not in weak_b), key=lambda m: not named(m))
+ self._grow(size, strong_u, strong_b, True, lambdas)
+ if not self.time_up():
+ self._grow(size, weak_u, weak_b, False, False)
+
+ def _grow(self, size, unary, binary, rest, lambdas):
+ for name, ok, f, code, nw, imp in unary:
+ for x in self.alive(size - 1):
+ if ok(x.t) and (x.inp or self.outer is not None) and canonical(name, x):
+ vals = tuple(_ap(f, v) for v in x.val)
+ if not nw[0] and (_same_vals(vals, x.val) or (x.op[0] == "u" and _same_vals(vals, x.args[0].val))):
+ continue # it changes nothing the examples show (int(str(n))), unless asked
+ self.add(X(("u", name, code, f), [x], vals, size, x.inp, nw, imp))
+ if self.time_up():
+ return
+ for a in range(1, size - 1):
+ b = size - 1 - a
+ ga, gb = self.by_type(a), self.by_type(b)
+ for name, ok, f, code, nw, comm in binary:
+ if comm and a > b:
+ continue
+ for ta, xs in ga.items():
+ for tb, ys in gb.items():
+ if not ok(xs[0].t, ys[0].t):
+ continue
+ for x in xs:
+ for y in ys:
+ if comm and a == b and id(x) > id(y):
+ continue
+ if not (x.inp or y.inp):
+ continue
+ vals = tuple(_ap(f, p, q) for p, q in zip(x.val, y.val))
+ if not nw[0] and (_same_vals(vals, x.val) or _same_vals(vals, y.val)):
+ continue # x | 0, x + 0, x | x: it changes nothing the examples show
+ self.add(X(("b", name, code, f), [x, y], vals, size, True,
+ self._mod_other_nw if name == "mod" and not (_unouter(y).op[0] == "const" and
+ _unouter(y).op[1] == 2)
+ else nw))
+ if self.time_up():
+ return
+ if not rest:
+ return
+ for combo in _splits(size - 1, 3): # chained comparisons: lo <= x <= hi (three single values)
+ if max(combo[1:]) > 1 or combo[0] > 2:
+ continue
+ # a read of the world (a file's text, a fetched page) is a leaf too: the input as it is read
+ pools = [[x for x in self.alive(s) if (is_num(x.t) or x.t == "str") and (s == 1 or x.op[1] in EDGE_READS)]
+ for s in combo]
+ for args in itertools.product(*pools):
+ if not any(x.inp for x in args) or not args[1].live:
+ continue
+ for name, ok, f, code, nw, imp in self.ternary:
+ if ok(*[x.t for x in args]):
+ self.add(X(("b", name, code, f), list(args),
+ tuple(_ap(f, *vs) for vs in zip(*[x.val for x in args])), size, True, nw, imp))
+ if self.time_up():
+ return
+ for part in self.parts: # the project's functions and the composed ones, where inputs fit
+ k = part["arity"]
+ if not part.get("types") and size > 3:
+ continue # a part the tests show no inputs for: tried on small values only
+ if k == 1:
+ for x in self.alive(size - 1):
+ if part_fits(part, [x.t]):
+ self.add(X(("p", part["name"], part["code"], part["fn"]), [x], tuple(_ap(part["fn"], v) for v in x.val), size,
+ x.inp, self.nw(part["words"]), part["imports"]))
+ elif k in (2, 3):
+ for combo in _splits(size - 1, k):
+ if 0 in combo or max(combo) > 2:
+ continue
+ pools = [self.alive(s) for s in combo]
+ for args in itertools.product(*pools):
+ if not any(x.inp for x in args) or not part_fits(part, [x.t for x in args]):
+ continue
+ self.add(X(("p", part["name"], part["code"], part["fn"]), list(args),
+ tuple(_ap(part["fn"], *vs) for vs in zip(*[x.val for x in args])), size, True,
+ self.nw(part["words"]), part["imports"]))
+ if self.time_up():
+ return
+ if lambdas:
+ self.grow_lambdas(size)
+
+ def grow_lambdas(self, size):
+ for a in range(1, min(L_MAX, size - 3) + 1):
+ b = size - 1 - a
+ if b < 2:
+ continue
+ for L in sorted((L for L in self.alive(a) if is_iter(L.t) and L.inp), key=lambda x: x.cost)[:L_COUNT]:
+ inner = self.inner(L, INNER_SEQ if L.size == 1 else INNER_MAX) # an input list: tests of 5
+ if inner is None:
+ continue
+ bank, rows = inner
+ for body in bank.alive(b):
+ if not body.inp: # a body that never reads the element is not a comprehension
+ continue
+ self.lambda_moves(L, body, rows, size)
+ if self.time_up():
+ return
+
+ def inner(self, L, depth=INNER_MAX):
+ key = (id(L), depth)
+ if key in self.inner_cache:
+ return self.inner_cache[key]
+ rows = [(i, e) for i, lst in enumerate(L.val) if lst is not ERR for e in lst]
+ if not rows or len(rows) > 400:
+ self.inner_cache[key] = None
+ return None
+ bank = Bank(len(rows), min(self.deadline, time.time() + (4 if depth <= INNER_MAX else 8)),
+ INNER_CAP if depth <= INNER_MAX else 4 * INNER_CAP, self.words, self.consts, namewords=self.namewords, parts=
+ [p for p in self.parts if p["arity"] == 1], outer=self)
+ bank.add(X(("var",), [], tuple(e for _i, e in rows), 1, True))
+ for x in self.alive(1): # the function's inputs, the constants, the list itself
+ if x.op[0] in ("in", "const"):
+ bank.add(X(("outer", x), [], tuple(x.val[i] for i, _e in rows), 1, False, uses=x.uses))
+ if L.size > 1:
+ bank.add(X(("outer", L), [], tuple(L.val[i] for i, _e in rows), 1, False, uses=L.uses))
+ for s in range(2, depth + 1):
+ bank.grow(s)
+ self.inner_cache[key] = (bank, rows)
+ return self.inner_cache[key]
+
+ def lambda_moves(self, L, body, rows, size):
+ per = [[] for _ in range(self.n)]
+ for (i, e), bv in zip(rows, body.val):
+ per[i].append((e, bv))
+ bad = {i for i, lst in enumerate(L.val) if lst is ERR}
+ for k, b in enumerate(L.val):
+ if b is not ERR and any(bv is ERR for _e, bv in per[k]):
+ bad.add(k)
+
+ def mk(kind, f):
+ vals = tuple(ERR if k in bad else _ap(f, per[k]) for k in range(self.n))
+ nw = self.nw(LAMBDAS[kind][1])
+ self.add(X(("lam", kind), [L, body], vals, size, True, nw))
+
+ mk("map", LAM_F["map"])
+ bt = body.t
+ if bt == "bool":
+ for kind in ("filter", "anyof", "allof"):
+ mk(kind, LAM_F[kind])
+ if bt in ("int", "float", "str"):
+ for kind in ("sortkey", "maxkey", "minkey"):
+ mk(kind, LAM_F[kind])
+ if elem(L.t) in ("int", "str", None) and bt not in ("?", None):
+ mk("dictof", LAM_F["dictof"])
+
+
+LAM_F = { # what each comprehension gives from its (element, body value) pairs
+ "map": lambda ps: [bv for _e, bv in ps],
+ "filter": lambda ps: [e for e, bv in ps if bv],
+ "anyof": lambda ps: any(bv for _e, bv in ps),
+ "allof": lambda ps: all(bv for _e, bv in ps),
+ "sortkey": lambda ps: [e for e, _bv in sorted(ps, key=lambda p: p[1])],
+ "maxkey": lambda ps: max(ps, key=lambda p: p[1])[0] if ps else 1 / 0,
+ "minkey": lambda ps: min(ps, key=lambda p: p[1])[0] if ps else 1 / 0,
+ "dictof": lambda ps: {e: bv for e, bv in ps},
+}
+
+
+def evalx(x, inp, v=None, sub=None):
+ """a composed expression's value on other inputs (the program run in-process, every move as in the search); sub: a
+ part of it replaced by a rival that gave the same values on the examples"""
+ if sub and id(x) in sub:
+ return evalx(sub[id(x)], inp, v) # the rival as itself (it may contain the part it replaces)
+ k = x.op[0]
+ if k == "in":
+ return inp[x.op[1]]
+ if k == "const":
+ return x.op[1]
+ if k == "var":
+ return v
+ if k == "outer":
+ return evalx(x.op[1], inp, None, sub)
+ if k == "body": # its own goal: the element first, then the function's inputs
+ return evalx(x.op[1], [v] + list(inp))
+ if k == "loop":
+ return _run_loop(x, inp)
+ if k == "guard":
+ return _run_guard(x, inp)
+ if k == "zip":
+ la, lb = evalx(x.args[0], inp, None, sub), evalx(x.args[1], inp, None, sub)
+ if la is ERR or lb is ERR or not isinstance(la, list) or not isinstance(lb, list) or len(la) != len(lb):
+ return ERR
+ out = [evalx(x.op[1], [a, b] + list(inp)) for a, b in zip(la, lb)]
+ return ERR if any(v is ERR for v in out) else out
+ if k == "scan": # the state so far and the next element give the next state
+ lst = evalx(x.args[0], inp, None, sub)
+ if lst is ERR or not isinstance(lst, (list, tuple, str)):
+ return ERR
+ out, acc = [], None
+ for i, e in enumerate(lst):
+ acc = e if i == 0 else evalx(x.op[1], [acc, e] + list(inp))
+ if acc is ERR:
+ return ERR
+ out.append(acc)
+ return out
+ if k in ("u", "b", "p"):
+ return _ap(x.op[3], *[evalx(a, inp, v, sub) for a in x.args])
+ if k == "lam":
+ L, body = x.args
+ lst = evalx(L, inp, None, sub)
+ if lst is ERR:
+ return ERR
+ try:
+ ps = [(e, evalx(body, inp, e, sub)) for e in lst]
+ except TypeError:
+ return ERR
+ if any(bv is ERR for _e, bv in ps):
+ return ERR
+ return _ap(LAM_F[x.op[1]], ps)
+ return ERR
+
+
+def eval_steps(steps, inp):
+ for c, e in steps:
+ if c is None or evalx(c, inp) is True:
+ return evalx(e, inp)
+ return ERR
+
+
+def matters(run, ex, which=None):
+ """every input matters: given another example's value for that input, the program's answer changes for some example.
+ An input the examples never vary is not judged (they cannot show it)."""
+ base = [run(list(a)) for a, _o, _t in ex]
+ for i in range(len(ex[0][0])):
+ if which is not None and not (which >> i) & 1:
+ continue
+ others = {repr(a[i]): a[i] for a, _o, _t in ex}
+ if len(others) < 2:
+ continue
+ moved = False
+ for j, (a, _o, _t) in enumerate(ex):
+ for key, val in others.items():
+ if key == repr(a[i]):
+ continue
+ b = list(a)
+ b[i] = val
+ got = run(b)
+ if (got is ERR) != (base[j] is ERR) or (got is not ERR and not same(got, base[j]) and not same(base[j], got)):
+ moved = True
+ break
+ if moved:
+ break
+ if not moved:
+ return False
+ return True
+
+
+def _same_vals(a, b):
+ """the same values on every example (a number cast to another number type with the same value counts as the same)"""
+ def eq(p, q):
+ if isinstance(p, (int, float)) and isinstance(q, (int, float)) and not isinstance(p, bool) and not isinstance(q, bool):
+ return p == q
+ return norm(p) == norm(q) and type(p) is type(q)
+ return len(a) == len(b) and all(eq(p, q) for p, q in zip(a, b))
+
+
+def canonical(name, x):
+ """one way to write each thing: no move on its own result where that adds nothing (sorted(sorted(x)), x[::-1][::-1]),
+ no slice of a slice (one slice says it)"""
+ inner = x.op[1] if x.op[0] == "u" else None
+ if inner is None:
+ return True
+ if name == inner and (name in IDEMPOTENT or name in INVOLUTION):
+ return False
+ if re.match(r"(take|drop)\d", name) and re.match(r"(take|drop)\d", inner):
+ return False
+ if inner in REORDER and name in ORDER_FREE: # sum(sorted(x)) is sum(x): the order was never used
+ return False
+ if inner in ("sorted", "sorted_desc") and name in ("at0", "at-1"):
+ return False # sorted(x)[0] is min(x)
+ if inner == "take1" and name in ("sum", "max", "min", "mean", "median"):
+ return False # a summary of a one-element slice is that element
+ return True
+
+
+REORDER = {"sorted", "sorted_desc", "reversed", "unique"}
+ORDER_FREE = {"sum", "len", "max", "min", "mean", "median", "nunique", "counts", "any", "all", "empty", "sorted", "sorted_desc",
+ "unique"}
+
+
+def _splits(total, k):
+ if k == 1:
+ yield (total,)
+ return
+ for i in range(1, total):
+ for rest in _splits(total - i, k - 1):
+ yield (i,) + rest
+
+
+def part_fits(part, tys):
+ want = part.get("types")
+ return bool(want) and all(compat(w, t) for w, t in zip(want, tys))
+
+
+def compat(w, t):
+ """a value of shape t may be given where the part was seen taking shape w (None in w: any)"""
+ if w is None:
+ return True
+ if t is None:
+ return False
+ if w == t or (is_num(w) and is_num(t)):
+ return True
+ if isinstance(w, tuple) and isinstance(t, tuple) and w[0] == t[0] and len(w) == len(t):
+ return all(compat(a, b) or b is None for a, b in zip(w[1:], t[1:]))
+ return False
+
+
+# ================================================================ writing the program out
+def var_name(L, params):
+ e = elem(L.t)
+ v = "ch" if L.t == "str" else "word" if e == "str" else "x" if e in ("int", "float") else "item"
+ while v in params:
+ v += "_"
+ return v
+
+
+HOIST = {} # while a chain is written out: the steps already named on their own lines
+STEP_NAMES = {"max": "largest", "min": "smallest", "sum": "total", "len": "count", "mean": "average", "median": "middle",
+ "sub": "difference", "add": "total", "mul": "product", "div": "ratio", "words": "words", "lower": "lowered",
+ "counts": "counts", "sorted": "ordered", "map": "values", "filter": "kept", "concat": "text", "lconcat": "items"}
+
+
+def step_name(x, taken):
+ k = x.op[1] if x.op[0] in ("u", "b", "p", "lam") else ""
+ base = (k if x.op[0] == "p" else STEP_NAMES.get(k, "part")).lower()
+ nm, i = base, 2
+ while nm in taken:
+ nm, i = "%s%d" % (base, i), i + 1
+ return nm
+
+
+def code(x, names, v=None):
+ if id(x) in HOIST:
+ return HOIST[id(x)]
+ k = x.op[0]
+ if k == "in":
+ return names[x.op[1]]
+ if k == "const":
+ c = x.op[1]
+ if isinstance(c, float) and c == math.pi:
+ return "math.pi"
+ if isinstance(c, (int, float)) and not isinstance(c, bool) and c < 0:
+ return "(%r)" % c # -1 ** x is -(1 ** x): a negative constant is written in parentheses
+ return repr(c)
+ if k == "var":
+ return v
+ if k == "outer":
+ return code(x.op[1], names)
+ if k == "body":
+ return code(x.op[1], [v] + list(names))
+ if k == "zip":
+ a, b = ("x", "y") if not {"x", "y"} & set(names) else ("x_", "y_")
+ return "[%s for %s, %s in zip(%s, %s)]" % (bare(code(x.op[1], [a, b] + list(names))), a, b, code(x.args[0], names),
+ code(x.args[1], names))
+ if k == "loop":
+ st = code(x.args[0], names)
+ return "" % (bare(code(x.op[2], [st])), st, bare(code(x.op[3], [st])))
+ if k == "guard":
+ return "<%s, or None where it fails%s>" % (bare(code(x.op[1], names)),
+ "" if x.op[2] is None else " or not " + bare(code(x.op[2], ["value"])))
+ if k == "scan":
+ L = x.args[0]
+ vn = var_name(L, names)
+ acc = "acc" if "acc" not in names else "so_far"
+ return "list(itertools.accumulate(%s, lambda %s, %s: %s))" % (code(L, names), acc, vn,
+ bare(code(x.op[1], [acc, vn] + list(names))))
+ if k in ("u", "b"):
+ return x.op[2].format(*[code(a, names, v) for a in x.args])
+ if k == "p":
+ return "%s(%s)" % (x.op[2], ", ".join(code(a, names, v) for a in x.args))
+ if k == "lam":
+ L, body = x.args
+ vn = var_name(L, names)
+ return LAMBDAS[x.op[1]][0].format(v=vn, L=code(L, names), b=code(body, names, vn))
+ raise ValueError(k)
+
+
+def bare(s):
+ """drop one pair of parentheses around a whole expression"""
+ if s.startswith("(") and s.endswith(")"):
+ depth = 0
+ for i, ch in enumerate(s):
+ depth += ch == "("
+ depth -= ch == ")"
+ if depth == 0 and i < len(s) - 1:
+ return s
+ return s[1:-1]
+ return s
+
+
+def moves_of(x, out=None):
+ out = [] if out is None else out
+ for a in x.args:
+ if isinstance(a, X):
+ moves_of(a, out)
+ if x.op[0] in ("u", "b", "p"):
+ out.append(x.op[1])
+ elif x.op[0] == "lam":
+ out.append(x.op[1])
+ elif x.op[0] == "body":
+ moves_of(x.op[1], out)
+ elif x.op[0] == "scan":
+ out.append("scan")
+ moves_of(x.op[1], out)
+ elif x.op[0] == "zip":
+ out.append("zip")
+ moves_of(x.op[1], out)
+ elif x.op[0] == "loop":
+ out.append("while")
+ for z in x.op[2:5]:
+ if z is not None:
+ moves_of(z, out)
+ elif x.op[0] == "guard":
+ out.append("try")
+ for z in x.op[1:3]:
+ if z is not None:
+ moves_of(z, out)
+ return out
+
+
+# ================================================================ composing one goal
+def leaves_for(goal, bank, consts):
+ ex = goal["examples"]
+ n = len(ex)
+ k = len(ex[0][0])
+ for i in range(k):
+ bank.add(X(("in", i), [], tuple(e[0][i] for e in ex), 1, True, uses=1 << i))
+ texts = []
+ for e in ex:
+ _texts(list(e[0]), texts, 20000)
+ texty = bool(texts) # a spelled word can only point at text the inputs hold (or name)
+ for c in consts: # a text the function looks for says the words it spells
+ named = bank.nw(" ".join(re.findall(r"[a-z]+", c.lower()))) if texty and isinstance(c, str) and c.strip() \
+ else (0, 0)
+ bank.add(X(("const", c), [], tuple(c for _ in range(n)), 1, False, named))
+
+
+def const_pool(goal, words_text):
+ ex = goal["examples"]
+ pool = [0, 1, 2, -1, "", " ", None, True, False, []]
+ name_parts = [w for w in re.sub(r"([a-z])([A-Z])", r"\1 \2", goal["name"]).replace("_", " ").lower().split()]
+ for w in re.findall(r"[a-z]+", _strip_examples(words_text, goal["name"]).lower()) + name_parts:
+ v = NUMBER_WORDS.get(w)
+ if v is not None and v not in pool:
+ pool.append(v)
+ if 0 <= v <= 9 and Field(str(v)) not in pool:
+ pool.append(Field(str(v))) # "zeros": the digit as text too
+ for w in name_parts: # the name's words are texts the function may look for
+ if len(w) > 1 and w not in NAME_STOP and not NUMBER_WORDS.get(w):
+ for form in (w, w.capitalize()):
+ if form not in pool:
+ pool.append(Field(form))
+ for tag in re.findall(r"\b([a-z]+) tags?\b", (words_text or "").lower()):
+ for form in ("<%s>" % tag, "%s>" % tag): # "the title tag": its opening and closing marks
+ if form not in pool:
+ pool.append(Field(form))
+ if all(isinstance(o, bool) for _a, o, _t in ex): # a yes/no answer: the values the data shows are candidate boundaries
+ seen_n = []
+
+ def nums(v):
+ if isinstance(v, bool):
+ return
+ if isinstance(v, (int, float)):
+ yield v
+ elif isinstance(v, (list, tuple)):
+ for y in v:
+ yield from nums(y)
+ elif isinstance(v, dict):
+ for y in v.values():
+ yield from nums(y)
+ for args, _o, _t in ex:
+ for v in itertools.chain(*[nums(a) for a in args]):
+ if v not in seen_n and v not in pool:
+ seen_n.append(v)
+ pool += [Boundary(v) if isinstance(v, int) else v for v in seen_n[:8]]
+ for m in re.findall(r"(?|=>|returns?|gives?)\s*\S+" % re.escape(name), " ", text or "")
+
+
+def fits_all(x, ex):
+ return all(same(v, out, tol) for v, (_a, out, tol) in zip(x.val, ex))
+
+
+def mask_of(x, ex):
+ m = 0
+ for i, (v, (_a, out, tol)) in enumerate(zip(x.val, ex)):
+ if same(v, out, tol):
+ m |= 1 << i
+ return m
+
+
+def decision_list(bank, ex, every=0):
+ """if c1: return e1 / if c2: return e2 / return e3 - each branch resting on two examples, or one under an emptiness test"""
+ n = len(ex)
+ full = (1 << n) - 1
+ best_by_mask = {}
+ for x in bank.seen.values():
+ if x.dead or not x.inp and x.op[0] != "const":
+ continue
+ m = mask_of(x, ex)
+ if m and (m not in best_by_mask or x.cost < best_by_mask[m].cost):
+ best_by_mask[m] = x
+ conds = [x for x in bank.seen.values() if not x.dead and x.t == "bool" and x.inp and x.size <= 5
+ and all(v is not ERR for v in x.val)]
+ conds.sort(key=lambda x: x.cost)
+ conds = [(c, sum(1 << i for i, v in enumerate(c.val) if v), c.op[0] == "u" and c.op[1] == "empty") for c in conds[:900]]
+ masks = sorted(best_by_mask.items(), key=lambda kv: kv[1].cost)
+ covers = {}
+
+ def cover(rest):
+ if rest not in covers:
+ covers[rest] = next((e for m, e in masks if m & rest == rest), None)
+ return covers[rest]
+
+ opts_cache = {}
+
+ def options(rest):
+ if rest in opts_cache:
+ return opts_cache[rest]
+ out = []
+ for c, cm, guard in conds:
+ tm = cm & rest
+ if not tm or tm == rest or bin(tm).count("1") < (1 if guard else 2):
+ continue
+ e = cover(tm)
+ if e is not None:
+ out.append((c.cost + e.cost, c, e, tm))
+ out.sort(key=lambda o: o[0])
+ opts_cache[rest] = out[:12]
+ return opts_cache[rest]
+
+ best = [None]
+
+ def dfs(rest, steps, cost, depth): # the cheapest decision list, searched (not greedy)
+ if bin(rest).count("1") >= 2:
+ e = cover(rest)
+ used = e.uses if e is not None else 0
+ for c_, e_ in steps:
+ used |= c_.uses | e_.uses
+ if e is not None and used & every == every and (best[0] is None or cost + e.cost < best[0][0]):
+ best[0] = (cost + e.cost, steps + [(None, e)])
+ if depth == 3:
+ return
+ for oc, c, e, tm in options(rest):
+ if best[0] is not None and cost + oc >= best[0][0]:
+ break
+ dfs(rest & ~tm, steps + [(c, e)], cost + oc, depth + 1)
+
+ dfs(full, [], 0.0, 0)
+ return best[0][1] if best[0] else None
+
+
+def _mirror(v):
+ if isinstance(v, str):
+ return "".join(chr(ord("a") + ord("z") - ord(c)) if "a" <= c <= "z" else
+ chr(ord("A") + ord("Z") - ord(c)) if "A" <= c <= "Z" else c for c in v)
+ if isinstance(v, list):
+ return [_mirror(y) for y in v]
+ return v
+
+
+def probes(ex):
+ """other inputs made from the examples' own: lists reversed or joined, words in another order, texts joined"""
+ ins = [list(a) for a, _o, _t in ex]
+ out = []
+ for a in ins:
+ for i, v in enumerate(a):
+ b = list(a)
+ if isinstance(v, list) and len(v) > 1:
+ b[i] = v[::-1]
+ elif isinstance(v, str) and len(v.split()) > 1:
+ b[i] = " ".join(v.split()[::-1])
+ elif isinstance(v, str) and len(v) > 1:
+ b[i] = v[::-1]
+ else:
+ continue
+ out.append(b)
+ for a in ins:
+ for c in ins:
+ if a is c:
+ continue
+ b, moved = list(a), False
+ for i, (v, w) in enumerate(zip(a, c)):
+ if isinstance(v, list) and isinstance(w, list):
+ b[i], moved = v + w, True
+ elif isinstance(v, str) and isinstance(w, str) and v and w:
+ b[i], moved = (v + " " + w) if (" " in v or " " in w) else v + w, True
+ if moved:
+ out.append(b)
+ if len(ins[0]) > 1: # inputs crossed between examples (a from one, b from another)
+ for combo in itertools.product(*[sorted({repr(a[i]): a[i] for a in ins}.values(), key=repr) for i in range(len(ins[0]))]):
+ if list(combo) not in ins:
+ out.append(list(combo))
+ for i in range(len(ins[0])): # lists made from pairs of elements of different examples, both orders
+ lists = [a[i] for a in ins if isinstance(a[i], list)]
+ if len(lists) < 2:
+ continue
+ pool = [e for lst in lists for e in lst]
+ pairs = 0
+ for p_, q_ in itertools.permutations(range(len(pool)), 2):
+ if pairs >= 16:
+ break
+ if repr(pool[p_]) == repr(pool[q_]):
+ continue
+ b = list(ins[0])
+ b[i] = [pool[p_], pool[q_]]
+ if b not in ins and b not in out:
+ out.append(b)
+ pairs += 1
+ for a in ins: # letters mirrored: alphabetical order reversed, structure kept
+ b = [_mirror(v) for v in a]
+ if b != a and b not in out:
+ out.insert(0, b)
+ for a in ins: # numbers next to the examples' own
+ for i, v in enumerate(a):
+ if isinstance(v, int) and not isinstance(v, bool):
+ for w in (v + 1, v + 2, 2 * v + 1):
+ b = list(a)
+ b[i] = w
+ out.append(b)
+ return out[:80]
+
+
+def disagreement(best, rivals, ex):
+ """the first rival that answers differently from the chosen program on an input made from the examples"""
+ if not rivals:
+ return None
+ for p in probes(ex):
+ bv = evalx(best, p)
+ _WORK["probe"] += 1
+ _WORK["last"] = "probe"
+ if bv is ERR:
+ continue
+ for y in rivals:
+ yv = evalx(y, p)
+ _WORK["probe"] += 1
+ if yv is not ERR and not same(yv, bv) and not same(bv, yv):
+ return y, p, bv, yv
+ return None
+
+
+def as_described(x, o):
+ """x gave the same values as the kept o, and is as plain (one node more at most, no extra lossy move) and names at least
+ the words o names: a real rival, not noise"""
+ return (x is not o and x.size <= o.size + 1 and x.pen <= o.pen + 1e-9 and x.cost < o.cost + 1.0 and (x.nmask & o.nmask) == o.nmask
+ and (x.rmask & o.rmask) == o.rmask)
+
+
+def inner_disagreement(best, bank, ex):
+ """a part of the chosen program replaced by its rival (same values on the examples): does the whole program answer
+ differently on an input made from the examples? Observational equivalence keeps one of the two; this looks again."""
+ nodes, stack = [], [best]
+ while stack:
+ x = stack.pop()
+ if x.op[0] in ("u", "b", "p", "lam"):
+ nodes.append(x)
+ if x.op[0] == "lam":
+ stack.append(x.args[0]) # the body belongs to its own search
+ else:
+ stack.extend(a for a in x.args if isinstance(a, X))
+ pn = ["_in%d" % i for i in range(len(ex[0][0]))]
+ ps = probes(ex)
+ for node in nodes:
+ for alt in bank.subalts.get(bank.key(node), []):
+ if alt is node or not as_described(alt, node):
+ continue # judged against the part kept now
+ nc, ac = code(node, pn), code(alt, pn)
+ if wraps(nc, ac):
+ continue # the same part with a wrapper added is not a rival
+ for p in ps:
+ bv = evalx(best, p)
+ if bv is ERR:
+ continue
+ yv = evalx(best, p, sub={id(node): alt})
+ if yv is not ERR and not same(yv, bv) and not same(bv, yv):
+ return ("sub", node, alt), p, bv, yv
+ return None
+
+
+NAME_STOP = {"get", "make", "calc", "calculate", "compute", "do", "to", "of", "the", "a", "an", "and", "in", "on", "for", "by",
+ "from", "with", "my", "fn", "func", "function", "helper", "value", "result"}
+
+
+def wmatch(w, u):
+ """a word of the name and a word of a move or a field: the same stem, or one begins the other (pric / price)"""
+ return w == u or (len(w) >= 4 and len(u) >= 4 and (u.startswith(w) or w.startswith(u)))
+
+
+def name_words(name):
+ """the words of a function's name (snake_case or camelCase), as stems, without the words every name has"""
+ parts = re.sub(r"([a-z])([A-Z])", r"\1 \2", name).replace("_", " ").lower().split()
+ out = []
+ for w in parts:
+ s = stem(w)
+ if w not in NAME_STOP and len(w) > 1 and s not in out:
+ out.append(s)
+ return out[:6]
+
+
+def pick(hits, bank):
+ """among the programs that give every example and cost at most one more than the cheapest, the one naming the most
+ words of the function's name (then cost): the name decides close calls, never against a much plainer program. A program
+ that is weak evidence (a lossy move no word excused) is chosen only when no program that is not fits: a weak fit is not
+ a fit beside a strong one (C10f: skew_ratio's (max - mean) / (max - min) lost to a cheaper entropy that fit by chance)"""
+ strong = [x for x in hits if not x.lossy]
+ hits = strong or hits
+ low = min(x.cost for x in hits)
+ return min((x for x in hits if x.cost <= low + 1.0), key=bank.choice)
+
+
+def decide(hits, bank, ex, names, ok):
+ """the choice among programs that give every example, and the ask when rivals as plain answer differently elsewhere"""
+ best = pick(hits, bank)
+ bc = code(best, names)
+ namewords = bank.namewords
+
+ def rival(y): # a program described as well as the chosen one, as plain
+ says_more = (y.nmask & best.nmask) == best.nmask and y.nmask != best.nmask and (best.waived or not y.waived) # more of the name said, and not only by an excused weak move
+ if y is best or y.pen > best.pen + 1e-9 or (y.waived and not best.waived):
+ return False
+ if not says_more and (y.cost > best.cost + AMBIG or y.size > best.size + 1):
+ return False
+ if says_more and y.cost > best.cost + 2 * AMBIG + 1.0:
+ return False # a plainer program over one that says more of the name: asked
+ if (y.nmask & best.nmask) != best.nmask or (y.rmask & best.rmask) != best.rmask:
+ return False
+ yc = code(y, names)
+ return not wraps(bc, yc) and ok(y) # not the same program with a wrapper added
+ seen_r, rivals = set(), []
+ for y in hits + [z for al in bank.alts.values() for z in al]:
+ if id(y) not in seen_r and rival(y):
+ seen_r.add(id(y))
+ rivals.append(y)
+ amb = disagreement(best, rivals, ex) or inner_disagreement(best, bank, ex)
+ if amb:
+ return {"kind": "ambiguous", "x": best, "rival": amb[0], "probe": amb[1], "va": amb[2], "vb": amb[3], "bank": bank}
+ w = unsaid_in_data(best, bank) if getattr(bank, "depth", 0) == 0 else None
+ if w:
+ return {"kind": "unsaid", "x": best, "word": w, "bank": bank}
+ return {"kind": "expr", "x": best, "steps": None, "bank": bank, "covered": bin(best.nmask).count("1") == len(namewords)}
+
+
+def _walk_x(x, seen=None):
+ seen = set() if seen is None else seen
+ if id(x) in seen:
+ return
+ seen.add(id(x))
+ yield x
+ for a in list(x.args) + [o for o in x.op if isinstance(o, X)]:
+ if isinstance(a, X):
+ yield from _walk_x(a, seen)
+
+
+def _texts(v, out, cap=300000):
+ if sum(len(t) for t in out) > cap:
+ return
+ if isinstance(v, str):
+ out.append(v)
+ elif isinstance(v, dict):
+ for k, u in v.items():
+ _texts(k, out, cap)
+ _texts(u, out, cap)
+ elif isinstance(v, (list, tuple)):
+ for u in v[:2000]:
+ _texts(u, out, cap)
+
+
+def unsaid_in_data(best, bank):
+ """a word of the function's name that the inputs (or the files and pages they name) contain, and that the chosen
+ program neither names by a move nor looks for as a text: the name points at something there, and the fit ignores it"""
+ nws = bank.namewords
+ said = {w for i, w in enumerate(nws) if best.nmask >> i & 1}
+ for z in _walk_x(best):
+ if z.op[0] == "const" and isinstance(z.op[1], str):
+ said |= {stem(t) for t in re.findall(r"[a-z]+", z.op[1].lower())}
+ unsaid = [w for w in nws if w not in said]
+ if not unsaid:
+ return None
+ texts = []
+ for x in list(bank.alive(1)) + list(bank.alive(2)):
+ if x.op[0] == "in" or (x.op[0] == "u" and x.op[1] in ("readtext", "readlines", "readjson", "fetch")):
+ _texts(list(x.val), texts)
+ data = {stem(t) for txt in texts for t in re.findall(r"[a-z]+", txt.lower())}
+ return next((w for w in unsaid if any(wmatch(w, u) for u in data)), None)
+
+
+def _vkey(vals):
+ """values as a key: numbers by value (5 and 5.0 alike), the rest as they are"""
+ out = []
+ for v in vals:
+ if v is ERR:
+ return None
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
+ out.append(("n", round(float(v), 7)))
+ else:
+ out.append(norm(v))
+ return tuple(out)
+
+
+def _needs(name, outs, pv):
+ """given one side's values, the other side's values that make the join give the answer: (values, this side first)"""
+ num = all(isinstance(o, (int, float)) and not isinstance(o, bool) for o in outs) and \
+ all(isinstance(p, (int, float)) and not isinstance(p, bool) for p in pv)
+ if name in ("add", "sub", "mul", "div") and not num:
+ return
+ try:
+ if name == "add":
+ yield [o - p for o, p in zip(outs, pv)], True
+ elif name == "sub":
+ yield [p - o for o, p in zip(outs, pv)], True # a - b = o
+ yield [o + p for o, p in zip(outs, pv)], False # b - a = o
+ elif name == "mul":
+ if all(p != 0 for p in pv):
+ yield [o / p for o, p in zip(outs, pv)], True
+ elif name == "div":
+ if all(o != 0 for o in outs):
+ yield [p / o for o, p in zip(outs, pv)], True # a / b = o
+ if all(p != 0 for p in pv):
+ yield [o * p for o, p in zip(outs, pv)], False # b / a = o
+ elif name in ("concat", "lconcat"):
+ kind = str if name == "concat" else list
+ if all(isinstance(o, kind) and isinstance(p, kind) for o, p in zip(outs, pv)):
+ if all(o[:len(p)] == p for o, p in zip(outs, pv)):
+ yield [o[len(p):] for o, p in zip(outs, pv)], True
+ if all(len(p) <= len(o) and o[len(o) - len(p):] == p for o, p in zip(outs, pv)):
+ yield [o[:len(o) - len(p)] for o, p in zip(outs, pv)], False
+ except (ZeroDivisionError, OverflowError, TypeError):
+ return
+
+
+def join_top(bank, ex, ok, deadline, cap=60):
+ """larger code side by side: two programs of the search joined by one move. The answer and one side give the other
+ side's values, which are looked up among every program kept (meet in the middle), so each side may be as large as the
+ search reaches. Evidence bound: a joined program has at most two nodes per example, plus one."""
+ outs = [o for _a, o, _t in ex]
+ pool = sorted((x for x in bank.seen.values() if not x.dead and (x.live or x.op[0] == "const")
+ and all(v is not ERR for v in x.val)), key=lambda x: x.cost)
+ idx = {}
+ for x in pool:
+ k = _vkey(x.val)
+ if k is not None:
+ lst = idx.setdefault(k, [])
+ if len(lst) < 3:
+ lst.append(x)
+ binops = {b[0]: b for b in bank.binary}
+ limit = 2 * len(ex) + 1
+ hits, seen = [], set()
+ for a in pool:
+ if not a.inp or not a.live or a.size >= limit - 1:
+ continue
+ if time.time() > deadline or len(hits) >= cap:
+ break
+ for name in JOINS:
+ _n, okf, f, cd, nw, _comm = binops[name]
+ for need, a_first in _needs(name, outs, a.val):
+ k = _vkey(need)
+ for b in idx.get(k, []) if k is not None else []:
+ if b is a or a.size + b.size + 1 > limit:
+ continue
+ args = [a, b] if a_first else [b, a]
+ if not okf(args[0].t, args[1].t):
+ continue
+ sig = (name, id(args[0]), id(args[1]))
+ if sig in seen:
+ continue
+ seen.add(sig)
+ vals = tuple(_ap(f, p, q) for p, q in zip(args[0].val, args[1].val))
+ x = X(("b", name, cd, f), args, vals, a.size + b.size + 1, True, nw)
+ if ok(x):
+ hits.append(x)
+ return hits
+
+
+def _subseq(lv, o):
+ """which elements of lv the answer o keeps, in order (None when o is not lv with some left out)"""
+ flags, j = [], 0
+ for e in lv:
+ if j < len(o) and same(e, o[j]):
+ flags.append(True)
+ j += 1
+ else:
+ flags.append(False)
+ return flags if j == len(o) else None
+
+
+def deduce_select(goal, bank, parts, words_text, deadline, ok, L):
+ """[g(x) for x in L if p(x)]: a small step g on each element whose values, with some left out, are the answer; the
+ flags (kept or not) are then known, so the test p is a goal of its own"""
+ ex = goal["examples"]
+ outs = [o for _a, o, _t in ex]
+ inner = bank.inner(L)
+ if inner is None:
+ return None
+ ib, rows = inner
+ gs = sorted((b for sz in (2, 3) for b in ib.alive(sz) if b.inp and all(v is not ERR for v in b.val)),
+ key=lambda b: b.cost)[:60]
+ found = []
+ for g in gs:
+ per = [[] for _ in ex]
+ for (i, e), gv in zip(rows, g.val):
+ per[i].append((e, gv))
+ flags = [_subseq([gv for _e, gv in ps], o) for ps, o in zip(per, outs)]
+ flat = [t for fl in flags if fl is not None for t in fl]
+ if any(fl is None for fl in flags) or all(flat) or not any(flat):
+ continue
+ prow, keyed, clash = [], {}, False
+ for (args, _o, _t), ps, fl in zip(ex, per, flags):
+ for (e, _gv), t in zip(ps, fl):
+ kk = repr((e,) + tuple(args))
+ if kk in keyed:
+ clash = clash or keyed[kk] != t
+ continue
+ keyed[kk] = t
+ prow.append(((e,) + tuple(args), t, None))
+ if clash or len(prow) < 2:
+ continue
+ vname = var_name(L, goal["params"])
+ sub = {"name": goal["name"], "params": [vname] + list(goal["params"]), "examples": prow, "need": 1}
+ res = compose_goal(sub, parts, words_text, depth=goal.get("_depth", 0) + 1, seconds=max(5.0, min(20.0, deadline - time.time() - 2)))
+ if res["kind"] != "expr" or not (res["x"].uses & 1):
+ continue
+ bx = res["x"]
+ w = X(("body", bx), [], bx.val, bx.size, True, uses=bx.uses >> 1)
+ fvals = []
+ for (args, _o, _t), lv in zip(ex, L.val):
+ ps = [(e, evalx(w, list(args), e)) for e in lv]
+ fvals.append(ERR if any(bv is ERR for _e, bv in ps) else _ap(LAM_F["filter"], ps))
+ kept = X(("lam", "filter"), [L, w], tuple(fvals), 1 + L.size + w.size, True, bank.nw(LAMBDAS["filter"][1]))
+ mvals = []
+ for (args, _o, _t), fv in zip(ex, kept.val):
+ ps = [] if fv is ERR else [(e, evalx(g, list(args), e)) for e in fv]
+ mvals.append(ERR if fv is ERR or any(bv is ERR for _e, bv in ps) else _ap(LAM_F["map"], ps))
+ x = X(("lam", "map"), [kept, g], tuple(mvals), 1 + kept.size + g.size, True, bank.nw(LAMBDAS["map"][1]))
+ if ok(x):
+ found.append(x)
+ if len(found) >= 4 or time.time() > deadline - 3:
+ break
+ return {"kind": "cands", "xs": found} if found else None
+
+
+def deduce(goal, bank, parts, words_text, deadline, ok):
+ """larger code in sequence: when the answer is a list made from a list (the same length: each element turned into
+ something; or some left out: a test on each), the body's values are known from the answer, so the body is a goal of its
+ own, composed by the same search (and may itself be large or joined)"""
+ ex = goal["examples"]
+ outs = [o for _a, o, _t in ex]
+ if not all(isinstance(o, list) for o in outs):
+ return None
+ Ls = sorted((x for x in bank.seen.values() if not x.dead and x.inp and x.live and is_seq(x.t) and x.size <= 3
+ and all(isinstance(v, list) for v in x.val) and any(x.val)), key=lambda x: (x.size, x.cost))
+ tried, asked = 0, None
+ for L in Ls:
+ if time.time() > deadline - 2 or tried >= 4:
+ break
+ if all(len(lv) == len(o) for lv, o in zip(L.val, outs)):
+ if all(same(lv, o) for lv, o in zip(L.val, outs)):
+ continue
+ kind, targets = "map", outs
+ else:
+ targets = [_subseq(lv, o) for lv, o in zip(L.val, outs)]
+ flat = [t for tg in targets if tg is not None for t in tg]
+ if any(tg is None for tg in targets) or all(flat) or not any(flat):
+ if time.time() < deadline - 4:
+ r = deduce_select(goal, bank, parts, words_text, deadline, ok, L)
+ if r is not None:
+ return r # {"kind": "cands"}: weighed with every other chain
+ continue
+ kind = "filter"
+ rows, keyed, clash = [], {}, False
+ for (args, _o, tol), lv, tg in zip(ex, L.val, targets):
+ for e, t in zip(lv, tg):
+ k = repr((e,) + tuple(args))
+ if k in keyed:
+ clash = clash or not same(keyed[k], t)
+ continue
+ keyed[k] = t
+ rows.append(((e,) + tuple(args), t, tol if kind == "map" else None))
+ if clash or len(rows) < 2:
+ continue
+ tried += 1
+ vname = var_name(L, goal["params"])
+ sub = {"name": goal["name"], "params": [vname] + list(goal["params"]), "examples": rows, "need": 1}
+ res = compose_goal(sub, parts, words_text, depth=goal.get("_depth", 0) + 1, seconds=max(5.0, min(22.0, deadline - time.time() - 2)))
+ if res["kind"] == "ambiguous" and asked is None:
+ asked = (L, kind, vname, sub, res)
+ continue
+ if res["kind"] != "expr" or not (res["x"].uses & 1):
+ continue
+ bx = res["x"]
+ w = X(("body", bx), [], bx.val, bx.size, True, uses=bx.uses >> 1)
+ vals = []
+ for (args, _o, _t), lv in zip(ex, L.val):
+ ps = [(e, evalx(w, list(args), e)) for e in lv]
+ vals.append(ERR if any(bv is ERR for _e, bv in ps) else _ap(LAM_F[kind], ps))
+ lam = X(("lam", kind), [L, w], tuple(vals), 1 + L.size + w.size, True, bank.nw(LAMBDAS[kind][1]))
+ if ok(lam):
+ return {"kind": "expr", "x": lam, "steps": None, "bank": bank,
+ "covered": bin(lam.nmask).count("1") == len(bank.namewords)}
+ if asked is not None:
+ L, kind, vname, sub, res = asked
+ return {"kind": "ambiguous_body", "L": L, "lam": kind, "sub": sub, "res": res}
+ return None
+
+
+SEQ_REDUCERS = {"sum", "prod", "len", "max", "min", "mean", "median", "nunique", "any", "all", "sorted", "sorted_desc", "unique",
+ "dedupe"}
+SEQ_L_COUNT = 120 # lists the chain stage continues from (the cheapest)
+INNER_SEQ = 5 # a step over each element of a short list (an input, its words, its letters) may be this large
+
+
+def evidenced(x, n):
+ """a program past the bound rests on its examples: at most two nodes per example plus one, and two more for each word of
+ the request or the name it says (a described move is not a free choice)"""
+ if x.size <= MAX_SIZE:
+ return True
+ named = bin(x.rmask).count("1") + bin(x.nmask).count("1")
+ return x.size <= 2 * n + 1 + 2 * named
+
+
+def seq_stage(bank, ex, ok, deadline, cap=40):
+ """larger code in sequence: any list the search made (a filtered list, words, letters) is carried one step further: a
+ step on each element (map) or a test on each (filter), then a summary of the result (sum, count, largest, average,
+ joined into text, ...). Each step is small; the chain is as long as they are together."""
+ outs = [o for _a, o, _t in ex]
+ out_list = all(isinstance(o, list) for o in outs)
+ reducers = [u for u in bank.unary if u[0] in SEQ_REDUCERS or u[0].startswith("join") or u[0].startswith("fold")]
+ Ls = sorted((x for x in bank.seen.values() if not x.dead and x.inp and x.live and is_seq(x.t)
+ and all(isinstance(v, (list, tuple)) for v in x.val) and any(x.val)), key=lambda x: x.cost)[:SEQ_L_COUNT]
+ target = _vkey(outs)
+ hits = []
+ for L in Ls:
+ if time.time() > deadline or len(hits) >= cap:
+ break
+ inner = bank.inner(L, INNER_SEQ if L.size <= 2 else INNER_MAX)
+ if inner is None:
+ continue
+ ib, rows = inner
+ depth = INNER_SEQ if L.size <= 2 else INNER_MAX
+ for body in [b for sz in range(1, depth + 1) for b in ib.alive(sz)]:
+ if not body.inp or time.time() > deadline:
+ continue
+ per = [[] for _ in range(len(ex))]
+ for (i, e), bv in zip(rows, body.val):
+ per[i].append((e, bv))
+ if any(bv is ERR for lst in per for _e, bv in lst):
+ continue
+ kinds = ["map"] + (["filter"] if body.t == "bool" else [])
+ for kind in kinds:
+ vals = tuple(_ap(LAM_F[kind], ps) for ps in per)
+ if any(v is ERR for v in vals):
+ continue
+ lam = None
+ if out_list:
+ if L.size + body.size + 1 > MAX_SIZE and all(same(v, o, t) for v, (_a, o, t) in zip(vals, ex)):
+ lam = X(("lam", kind), [L, body], vals, 1 + L.size + body.size, True, bank.nw(LAMBDAS[kind][1]))
+ if ok(lam):
+ hits.append(lam)
+ continue
+ vt = ty_of_vals(vals)
+ for name, okr, f, cd, nw, imp in reducers:
+ if not okr(vt):
+ continue
+ rv = tuple(_ap(f, v) for v in vals)
+ k = _vkey(rv)
+ if k is None or k != target and not all(same(v, o, t) for v, (_a, o, t) in zip(rv, ex)):
+ continue
+ if 1 + L.size + body.size + 1 <= MAX_SIZE:
+ continue # within the bound: the search itself had it
+ if lam is None:
+ lam = X(("lam", kind), [L, body], vals, 1 + L.size + body.size, True, bank.nw(LAMBDAS[kind][1]))
+ x = X(("u", name, cd, f), [lam], rv, lam.size + 1, True, nw, imp)
+ if ok(x):
+ hits.append(x)
+ return hits
+
+
+def deduce_scan(goal, bank, parts, words_text, deadline, ok):
+ """a loop that carries a state: when the answer is a list as long as a list the search made, starting from its first
+ element, each answer is made from the previous answer and the next element: those pairs are known, so the step is a
+ goal of its own (its inputs: the state so far, the element, the function's inputs)"""
+ ex = goal["examples"]
+ outs = [o for _a, o, _t in ex]
+ if not all(isinstance(o, list) for o in outs):
+ return None
+ Ls = sorted((x for x in bank.seen.values() if not x.dead and x.inp and x.live and is_seq(x.t) and x.size <= 3
+ and all(isinstance(v, list) for v in x.val) and any(len(v) >= 2 for v in x.val)), key=lambda x: (x.size, x.cost))
+ tried = 0
+ for L in Ls:
+ if time.time() > deadline - 2 or tried >= 3:
+ break
+ if not all(len(lv) == len(o) and (not lv or same(o[0], lv[0])) for lv, o in zip(L.val, outs)):
+ continue
+ if all(same(lv, o) for lv, o in zip(L.val, outs)):
+ continue
+ rows, keyed, clash = [], {}, False
+ for (args, o, tol), lv in zip(ex, L.val):
+ for k in range(1, len(lv)):
+ kk = repr((o[k - 1], lv[k]) + tuple(args))
+ if kk in keyed:
+ clash = clash or not same(keyed[kk], o[k])
+ continue
+ keyed[kk] = o[k]
+ rows.append(((o[k - 1], lv[k]) + tuple(args), o[k], tol))
+ if clash or len(rows) < 3:
+ continue
+ tried += 1
+ vname = var_name(L, goal["params"])
+ sub = {"name": goal["name"], "params": ["acc", vname] + list(goal["params"]), "examples": rows, "need": 3}
+ res = compose_goal(sub, parts, words_text, depth=goal.get("_depth", 0) + 1, seconds=max(5.0, min(20.0, deadline - time.time() - 2)))
+ if res["kind"] != "expr" or (res["x"].uses & 3) != 3:
+ continue
+ bx = res["x"]
+ x = X(("scan", bx), [L], tuple(outs), 1 + L.size + bx.size, True, imports=("itertools",), uses=bx.uses >> 2)
+ x.val = tuple(evalx(x, list(a)) for a, _o, _t in ex)
+ if ok(x):
+ return {"kind": "expr", "x": x, "steps": None, "bank": bank,
+ "covered": bin(x.nmask).count("1") == len(bank.namewords)}
+ return None
+
+
+def _fn(x, nvars=1):
+ """a composed program as a Python function of its inputs (fast to run many times; same moves as the search)"""
+ return lambda *vs: evalx(x, list(vs))
+
+
+def deduce_zip(goal, bank, parts, words_text, deadline, ok):
+ """two lists in step: when the answer is as long as two input lists, each answer is made from the pair at its place, so
+ the step is a goal of its own (its inputs: the two elements, then the function's inputs)"""
+ ex = goal["examples"]
+ outs = [o for _a, o, _t in ex]
+ if not all(isinstance(o, list) for o in outs) or not any(outs):
+ return None
+ k = len(ex[0][0])
+ leaves = {x.op[1]: x for x in bank.alive(1) if x.op[0] == "in"}
+ for i in range(k):
+ for j in range(i + 1, k):
+ A, B = leaves.get(i), leaves.get(j)
+ if A is None or B is None or not (is_seq(A.t) and is_seq(B.t)):
+ continue
+ if not all(isinstance(a[i], list) and isinstance(a[j], list) and len(a[i]) == len(a[j]) == len(o)
+ for a, o, _t in ex):
+ continue
+ rows, keyed, clash = [], {}, False
+ for args, o, tol in ex:
+ for p, q, t in zip(args[i], args[j], o):
+ kk = repr((p, q) + tuple(args))
+ if kk in keyed:
+ clash = clash or not same(keyed[kk], t)
+ continue
+ keyed[kk] = t
+ rows.append(((p, q) + tuple(args), t, tol))
+ if clash or len(rows) < 3:
+ continue
+ sub = {"name": goal["name"], "params": ["x", "y"] + list(goal["params"]), "examples": rows, "need": 3}
+ res = compose_goal(sub, parts, words_text, depth=goal.get("_depth", 0) + 1, seconds=max(5.0, min(20.0, deadline - time.time() - 2)))
+ if res["kind"] != "expr" or (res["x"].uses & 3) != 3:
+ continue
+ bx = res["x"]
+ x = X(("zip", bx), [A, B], tuple(outs), 1 + A.size + B.size + bx.size, True, uses=bx.uses >> 2)
+ x.val = tuple(evalx(x, list(a)) for a, _o, _t in ex)
+ if ok(x):
+ return {"kind": "expr", "x": x, "steps": None, "bank": bank,
+ "covered": bin(x.nmask).count("1") == len(bank.namewords)}
+ return None
+
+
+LOOP_WORDS = "while loop until repeat repeatedly each step steps times count how many keep"
+LOOP_CAP = 1000 # iterations a candidate loop may take on one example
+
+
+def _samples(vals):
+ """states a loop may pass through, made from the examples' own: numbers below them, texts shortened"""
+ out = []
+ for v in vals:
+ if isinstance(v, bool):
+ continue
+ if isinstance(v, int):
+ for w in (v, v - 1, v // 2, v // 10, v * 3 + 1, -v):
+ if w not in out:
+ out.append(w)
+ elif isinstance(v, str):
+ for w in (v, v[1:], v[:-1], v[2:], v.strip(), ""):
+ if w not in out:
+ out.append(w)
+ for w in (0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 16, 25) if all(isinstance(v, int) for v in vals) else ("0", "a", " a", "00"):
+ if w not in out:
+ out.append(w)
+ return out[:60]
+
+
+def loop_candidates(goal, bank, ok, deadline):
+ """a while loop over the function's one input: a test, a step, and what it gives (how many steps, the total of a value
+ taken at each step, or the state it ends in). The test and the step are found by the same search, over states made from
+ the examples; each loop is run on the real examples with a cap on its steps."""
+ ex = goal["examples"]
+ if len(ex[0][0]) != 1:
+ return []
+ vals = [a[0] for a, _o, _t in ex]
+ if not all(isinstance(v, int) and not isinstance(v, bool) for v in vals) and not all(isinstance(v, str) for v in vals):
+ return []
+ outs = [o for _a, o, _t in ex]
+ st = tyof(vals[0])
+ samples = _samples(vals)
+ sb = Bank(len(samples), min(deadline, time.time() + 10), 30000, bank.words, bank.consts, [], namewords=bank.namewords)
+ sb.add(X(("in", 0), [], tuple(samples), 1, True, uses=1))
+ for c in bank.consts:
+ sb.add(X(("const", c), [], tuple(c for _ in samples), 1, False))
+ for size in range(2, 5):
+ sb.grow(size)
+ live = [x for x in sb.seen.values() if not x.dead and x.inp]
+ steps = sorted((x for x in live if x.t == st and x.size >= 2), key=lambda x: x.cost)[:70]
+ conds = sorted((x for x in live if x.t == "bool" and x.size >= 2 and any(v is True for v in x.val)
+ and any(v is False for v in x.val)), key=lambda x: x.cost)[:40]
+ band = [b for b in sb.binary if b[0] == "and"][0]
+ for c1, c2 in itertools.combinations(conds[:12], 2): # two tests together: len(s) > 1 and s[0] == '0'
+ conds.append(X(("b", "and", band[3], band[2]), [c1, c2], tuple(_ap(band[2], p, q) for p, q in zip(c1.val, c2.val)),
+ c1.size + c2.size + 1, True, band[4]))
+ gs = sorted((x for x in live if is_num(x.t) and x.size <= 3), key=lambda x: x.cost)[:30] \
+ if all(isinstance(o, (int, float)) and not isinstance(o, bool) for o in outs) else []
+ cf = [(c, _fn(c)) for c in conds]
+ sf = [(s_, _fn(s_)) for s_ in steps]
+ gf = [(g, _fn(g)) for g in gs]
+ leaf = [x for x in bank.alive(1) if x.op[0] == "in" and x.op[1] == 0][0]
+ nw = bank.nw(LOOP_WORDS)
+ hits = []
+ for c, cfn in cf:
+ if time.time() > deadline or len(hits) >= 30:
+ break
+ for s_, sfn in sf:
+ runs = []
+ for v in vals:
+ state, n, trail = v, 0, [v]
+ ok_run = True
+ while True:
+ t = cfn(state)
+ if t is ERR or not isinstance(t, bool):
+ ok_run = False
+ break
+ if not t:
+ break
+ state = sfn(state)
+ n += 1
+ if state is ERR or n > LOOP_CAP:
+ ok_run = False
+ break
+ trail.append(state)
+ if not ok_run:
+ break
+ runs.append((state, n, trail))
+ if len(runs) != len(vals) or not any(n for _s, n, _t in runs):
+ continue
+ kinds = [("count", None, tuple(n for _s, n, _t in runs)), ("final", None, tuple(s2 for s2, _n, _t in runs))]
+ for g, gfn in gf:
+ tot = []
+ for _s, _n, trail in runs:
+ vs_ = [gfn(z) for z in trail[:-1]]
+ tot.append(ERR if any(v_ is ERR for v_ in vs_) else sum(vs_))
+ kinds.append(("total", g, tuple(tot)))
+ for kind, g, got in kinds:
+ if all(v_ is not ERR and same(v_, o, t) for v_, (_a, o, t) in zip(got, ex)):
+ parts_ = [c, s_] + ([g] if g is not None else [])
+ rm = nm = 0
+ pen = 0.0
+ for z in parts_:
+ rm |= z.rmask
+ nm |= z.nmask
+ pen += z.pen
+ x = X(("loop", kind, c, s_, g), [leaf], got, 2 + sum(z.size for z in parts_), True,
+ (nw[0] | rm, nw[1] | nm))
+ x.pen += pen
+ x.cost += pen
+ x.lossy = x.lossy or any(z.lossy for z in parts_)
+ x.waived = x.waived or any(z.waived for z in parts_)
+ for z in parts_:
+ x.imports |= z.imports
+ if ok(x):
+ hits.append(x)
+ if not hits and time.time() < deadline - 2 and all(isinstance(o, int) and not isinstance(o, bool) for o in outs):
+ hits = _branch_loops(ex, vals, samples, sb, st, conds, leaf, nw, ok, deadline)
+ return hits
+
+
+BRANCH_CONDS, BRANCH_A, BRANCH_B = 8, 20, 400 # tests, first sides, second sides tried for a step with a branch
+
+
+def _side_loses(side, states):
+ """a weak side of a branch is weak only if it throws something away on the states the test sends it: n // 2 on even n"""
+ if not side.lossy:
+ return False
+ if side.op[0] == "b" and side.op[1] == "floordiv" and isinstance(side.args[1], X) and side.args[1].op[0] == "const" and not side.args[0].lossy and side.args[1].op[1]:
+ k = side.args[1].op[1]
+ got = [evalx(side.args[0], [z]) for z in states]
+ return not all(isinstance(g, int) and g % k == 0 for g in got)
+ return True
+
+
+def _branch_loops(ex, vals, samples, sb, st, conds, leaf, nw, ok, deadline):
+ """while test: state = (a if c else b); count the steps. The sides and tests come from the same pool as plain steps
+ (one size larger); each trial runs on the values the pool already has on the sample states, and stops once its count
+ passes the largest count asked for."""
+ sb.deadline = min(deadline - 1, time.time() + 8)
+ sb.grow(5)
+ live = [x for x in sb.seen.values() if not x.dead and x.inp]
+ steps = sorted((x for x in live if x.t == st and x.size >= 2), key=lambda x: x.cost)
+ tests = sorted((x for x in live if x.t == "bool" and x.size >= 2 and any(v is True for v in x.val)
+ and any(v is False for v in x.val)), key=lambda x: x.cost)[:BRANCH_CONDS]
+ idx = {}
+ for i, v in enumerate(samples):
+ idx.setdefault(v, i)
+ want = [o for _a, o, _t in ex]
+ top = max(want)
+ order = sorted(range(len(vals)), key=lambda i: want[i])
+
+ def runs_to(lc, nxt, v, target):
+ n, state, trail = 0, v, [v]
+ while True:
+ i = idx.get(state)
+ t = lc.val[i] if i is not None else evalx(lc, [state]) # off the samples: the program itself
+ if t is ERR or not isinstance(t, bool):
+ return None
+ if not t:
+ return trail if n == target else None
+ n += 1
+ if n > target:
+ return None
+ state = nxt(state, i)
+ if state is ERR:
+ return None
+ trail.append(state)
+
+ seen_b, hits = set(), []
+ for c in tests:
+ for a in steps[:BRANCH_A]:
+ for b in steps[:BRANCH_B]:
+ if a is b or time.time() > deadline:
+ return hits
+ bv = tuple(av if cv is True else bv_ if cv is False else ERR for cv, av, bv_ in zip(c.val, a.val, b.val))
+ if bv in seen_b:
+ continue
+ seen_b.add(bv)
+
+ def nxt(state, i, bv=bv, c=c, a=a, b=b):
+ if i is not None:
+ return bv[i]
+ t = evalx(c, [state])
+ return evalx(a, [state]) if t is True else evalx(b, [state]) if t is False else ERR
+ for lc in conds[:6]:
+ trails = []
+ for i in order:
+ tr = runs_to(lc, nxt, vals[i], want[i])
+ if tr is None:
+ break
+ trails.append(tr)
+ if len(trails) != len(vals):
+ continue
+ states = [z for tr in trails for z in tr[:-1]]
+ ta = [z for z in states if evalx(c, [z]) is True]
+ tb = [z for z in states if evalx(c, [z]) is False]
+ lossy = c.lossy or lc.lossy or _side_loses(a, ta) or _side_loses(b, tb)
+ br = X(("b", "branch", "({1} if {0} else {2})", lambda cv, av, bv_: av if cv else bv_), [c, a, b], bv,
+ c.size + a.size + b.size + 1, True)
+ br.lossy, br.waived = lossy, c.waived or a.waived or b.waived
+ br.pen = LOSSY_PEN if lossy else 0.0
+ br.cost = br.size - WORD_BONUS * bin(br.rmask).count("1") - NAME_BONUS * bin(br.nmask).count("1") + br.pen
+ x = X(("loop", "count", lc, br, None), [leaf], tuple(want), 2 + lc.size + br.size, True,
+ (nw[0] | lc.rmask | br.rmask, nw[1] | lc.nmask | br.nmask))
+ x.pen, x.lossy, x.waived = br.pen + lc.pen, lossy, br.waived or lc.waived
+ x.cost = x.size - WORD_BONUS * bin(x.rmask).count("1") - NAME_BONUS * bin(x.nmask).count("1") + x.pen
+ x.imports |= lc.imports | c.imports | a.imports | b.imports
+ x.val = tuple(_run_loop(x, [v]) for v in vals)
+ if ok(x):
+ hits.append(x)
+ if len(hits) >= 4:
+ return hits
+ return hits
+
+
+def _run_loop(x, inp):
+ kind, c, s_, g = x.op[1], x.op[2], x.op[3], x.op[4]
+ state = evalx(x.args[0], inp)
+ if state is ERR:
+ return ERR
+ n, tot = 0, 0
+ while True:
+ t = evalx(c, [state])
+ if t is ERR or not isinstance(t, bool):
+ return ERR
+ if not t:
+ break
+ if g is not None:
+ gv = evalx(g, [state])
+ if gv is ERR:
+ return ERR
+ tot += gv
+ state = evalx(s_, [state])
+ n += 1
+ if state is ERR or n > LOOP_CAP:
+ return ERR
+ return n if kind == "count" else tot if kind == "total" else state
+
+
+def _run_guard(x, inp):
+ p, c = x.op[1], x.op[2]
+ v = evalx(p, inp)
+ if v is ERR:
+ return None
+ if c is not None and evalx(c, [v]) is not True:
+ return None
+ return v
+
+
+# ================================================================ THE ONE LOOP (C8)
+# Every goal: forward search within the bound; then each move's declared INVERSE (how a wanted result constrains the
+# move's inputs) yields smaller goals, solved by this same loop; forward continuations carry any list made to a summary,
+# or a state through a loop. Everything that gives the examples is a candidate, weighed together; the law judges.
+def subgoal_same_inputs(goal, wanted, keep=None):
+ """a goal over the same inputs with other wanted values: what an inverse asks of one side"""
+ ex = goal["examples"]
+ idx = range(len(ex)) if keep is None else keep
+ rows = [(ex[i][0], wanted[i], ex[i][2]) for i in idx]
+ sub = {"name": goal["name"], "params": list(goal["params"]), "examples": rows, "need": 0, "module": goal.get("module"),
+ "module_text": ""}
+ for k in ("root", "fetched", "net_scope", "no_namewords"):
+ if k in goal:
+ sub[k] = goal[k]
+ return sub
+
+
+ASKS = [] # questions met inside inverses during one goal (an ambiguous step is asked about, never dropped)
+
+
+def _ask_text(sub, res):
+ call = "%s" % ", ".join("%s=%r" % (n, v) for n, v in zip(sub["params"], res["probe"]))
+ rv = res["rival"][2] if isinstance(res["rival"], tuple) else res["rival"]
+ return ("a step inside it fits more than one program, and they answer differently elsewhere: `%s` gives %r and `%s` gives "
+ "%r for %s. Which is right? Add an example or a test that decides it." % (
+ bare(code(res["x"], sub["params"])), res["va"], bare(code(rv, sub["params"])), res["vb"], call))
+
+
+def _solve(sub, parts, words_text, goal, deadline, share=1.0):
+ secs = max(4.0, min(30.0, (deadline - time.time()) * share))
+ if deadline - time.time() < 3:
+ return None
+ res = compose_goal(sub, parts, words_text, depth=goal.get("_depth", 0) + 1, seconds=secs)
+ if res["kind"] == "ambiguous":
+ ASKS.append(_ask_text(sub, res))
+ return res["x"] if res["kind"] == "expr" else None
+
+
+def inv_text(goal, bank, parts, words_text, deadline, ok):
+ """joining text, backwards: the answer split by the separator (or into equal pieces, one per element of a list the
+ search made) is the list that was joined - a list goal, free to be a map, a filter, a running state..."""
+ ex = goal["examples"]
+ outs = [o for _a, o, _t in ex]
+ if not all(isinstance(o, str) for o in outs):
+ return []
+ found = []
+ joins = [u for u in bank.unary if u[0].startswith("join")]
+ lists = sorted((x for x in bank.seen.values() if not x.dead and x.inp and x.live and is_seq(x.t) and x.size <= 3
+ and all(isinstance(v, list) for v in x.val) and any(x.val)), key=lambda x: (x.size, x.cost))[:4]
+ for name, okj, f, cd, nw, imp in joins:
+ if time.time() > deadline - 3 or len(found) >= 3:
+ break
+ sep = ast.literal_eval(name[4:])
+ wanted_sets = []
+ if sep:
+ pcs = [o.split(sep) if o else [] for o in outs]
+ if not all(len(p) <= 1 for p in pcs):
+ wanted_sets.append(pcs)
+ else:
+ for L in lists: # one piece per element: equal lengths
+ if not all(lv and len(o) % len(lv) == 0 or (not lv and o == "") for lv, o in zip(L.val, outs)):
+ continue
+ pcs = [[o[i * (len(o) // len(lv)):(i + 1) * (len(o) // len(lv))] for i in range(len(lv))] if lv else []
+ for lv, o in zip(L.val, outs)]
+ if not all(len(p) <= 1 for p in pcs) and pcs not in wanted_sets:
+ wanted_sets.append(pcs)
+ for pcs in wanted_sets[:2]:
+ lx = _solve(subgoal_same_inputs(goal, pcs), parts, words_text, goal, deadline, 0.5)
+ if lx is None:
+ continue
+ x = X(("u", name, cd, f), [lx], tuple(_ap(f, v) for v in lx.val), lx.size + 1, True, nw, imp)
+ if ok(x):
+ found.append(x)
+ return found
+
+
+def inv_guard(goal, bank, parts, words_text, deadline, ok):
+ """try/except, backwards: where the answer is a value, a program that gives it (a goal over those rows); where it is
+ None, that program must fail, or a test on its value must turn it away (a yes/no goal over the values)"""
+ ex = goal["examples"]
+ outs = [o for _a, o, _t in ex]
+ if not any(o is None for o in outs) or all(o is None for o in outs):
+ return []
+ keep = [i for i, o in enumerate(outs) if o is not None]
+ if len(keep) < 2:
+ return []
+ px = _solve(subgoal_same_inputs(goal, outs, keep), parts, words_text, goal, deadline, 0.5)
+ if px is None:
+ return []
+ vals = [evalx(px, list(a)) for a, _o, _t in ex]
+ refused = [i for i, (v, o) in enumerate(zip(vals, outs)) if o is None and v is not ERR]
+ found = []
+ if not refused:
+ x = X(("guard", px, None), [], tuple(outs), px.size + 2, True, uses=px.uses)
+ else:
+ rows = [((v,), o is not None, None) for v, o in zip(vals, outs) if v is not ERR]
+ tsub = {"name": goal["name"], "params": ["value"], "examples": rows, "need": 1, "module": goal.get("module"),
+ "module_text": "", "no_namewords": True}
+ res = compose_goal(tsub, parts, words_text, depth=goal.get("_depth", 0) + 1,
+ seconds=max(4.0, min(20.0, deadline - time.time())))
+ if res["kind"] == "ambiguous":
+ ASKS.append(_ask_text(tsub, res))
+ if res["kind"] != "expr":
+ return []
+ c = res["x"]
+ x = X(("guard", px, c), [], tuple(outs), px.size + c.size + 3, True, uses=px.uses)
+ c = x.op[2]
+ x.rmask = px.rmask | (c.rmask if c is not None else 0)
+ x.nmask = px.nmask | (c.nmask if c is not None else 0)
+ x.pen = px.pen + (c.pen if c is not None else 0)
+ x.lossy = px.lossy or (c is not None and c.lossy)
+ x.waived = px.waived or (c is not None and c.waived)
+ x.imports = set(px.imports) | (set(c.imports) if c is not None else set())
+ x.cost = x.size - WORD_BONUS * bin(x.rmask).count("1") - NAME_BONUS * bin(x.nmask).count("1") + x.pen
+ if ok(x):
+ found.append(x)
+ return found
+
+
+def inv_arith(goal, bank, parts, words_text, deadline, ok):
+ """a + b, a - b, a * b, a / b, text or list joined, backwards: with one side among the programs kept, the other side's
+ values are known - looked up among every program kept (meet in the middle), and, failing that, a goal of its own for
+ the two plainest first sides"""
+ found = join_top(bank, goal["examples"], ok, deadline)
+ if found or time.time() > deadline - 5 or goal.get("_depth", 0) > 0:
+ return found
+ ex = goal["examples"]
+ outs = [o for _a, o, _t in ex]
+ binops = {b[0]: b for b in bank.binary}
+ firsts = sorted((x for x in bank.seen.values() if not x.dead and x.inp and x.live and x.size >= 2
+ and all(v is not ERR for v in x.val)), key=lambda x: x.cost)
+ tried = 0
+ for a in firsts:
+ if tried >= 4 or time.time() > deadline - 4:
+ break
+ for name in JOINS:
+ _n, okf, f, cd, nw, _c = binops[name]
+ for need, a_first in _needs(name, outs, a.val):
+ if tried >= 4:
+ break
+ tried += 1
+ bx = _solve(subgoal_same_inputs(goal, need), parts, words_text, goal, deadline, 0.3)
+ if bx is None:
+ continue
+ args = [a, bx] if a_first else [bx, a]
+ if not okf(args[0].t, args[1].t):
+ continue
+ x = X(("b", name, cd, f), args, tuple(_ap(f, p, q) for p, q in zip(args[0].val, args[1].val)),
+ a.size + bx.size + 1, True, nw)
+ if ok(x):
+ found.append(x)
+ return found
+
+
+def _as_list(r):
+ if r is None:
+ return [], None
+ if isinstance(r, list):
+ return r, None
+ if r["kind"] == "expr":
+ return [r["x"]], None
+ if r["kind"] == "cands":
+ return list(r["xs"]), None
+ if r["kind"] == "ambiguous_body":
+ return [], r
+ return [], None
+
+
+INVERSES = ( # (inverse, its share of the time): each turns the wanted answer into smaller goals for the same loop
+ (deduce_scan, 0.10), # running state: (state, element) -> next state
+ (deduce_zip, 0.15), # two lists in step: (a, b) -> each answer
+ (inv_text, 0.30), # joined text: the pieces, a list goal
+ (deduce, 0.50), # a list from a list: each element's value, or kept-or-not, or a step's values some left out
+ (inv_guard, 0.65), # try/except: the value where there is one, a test where there is none
+)
+
+
+def decompose(goal, bank, parts, words_text, ok, seconds=None):
+ """the one loop past the forward search: every declared inverse, then the forward continuations (a summary of any list
+ made, a while loop over the input, two sides joined); all candidates returned to be weighed together"""
+ ex = goal["examples"]
+ t0 = time.time()
+ end = t0 + (seconds or CHAIN_SECONDS)
+ bank.deadline = end
+ hits, asked = [], None
+ n_asks = len(ASKS)
+ for inv, share in INVERSES:
+ xs, a = _as_list(inv(goal, bank, parts, words_text, min(end, t0 + share * (end - t0) + 2), ok))
+ hits += xs
+ asked = asked or a
+ if any(evidenced(x, len(ex)) and not x.lossy for x in hits): # a strong fit in hand: the rest weighed beside it
+ end = min(end, time.time() + CHAIN_BESIDE_SECONDS)
+ bank.deadline = end
+ looped = any(bank.nw(LOOP_WORDS)) # the request or the name says a loop: the loop is given most of the time
+ more = loop_candidates(goal, bank, ok, min(end, time.time() + (0.7 if looped else 0.35) * max(0.0, end - time.time())))
+ more += seq_stage(bank, ex, ok, min(end, time.time() + 0.5 * max(0.0, end - time.time())))
+ more += inv_arith(goal, bank, parts, words_text, max(end, time.time() + 3), ok)
+ if asked is None and len(ASKS) > n_asks and goal.get("_depth", 0) == 0:
+ asked = {"kind": "ask", "gap": ASKS[n_asks]}
+ return hits + [x for x in more if evidenced(x, len(ex))], asked
+
+
+def compose_goal(goal, parts, words_text, depth=0, seconds=None):
+ goal["_depth"] = depth
+ ex = goal["examples"]
+ names = goal["params"]
+ words = {stem(w) for w in re.findall(r"[a-z]+", (words_text or "").lower())}
+ namewords = [] if goal.get("no_namewords") else name_words(goal["name"]) # the name describes it too
+ deadline = time.time() + (seconds or GOAL_SECONDS)
+ consts = const_pool(goal, words_text)
+ bank = Bank(len(ex), deadline, BANK_CAP, words, consts, parts, namewords=namewords)
+ bank.ex = ex
+ bank.depth = depth
+ leaves_for(goal, bank, consts)
+ if goal.get("root"):
+ edge_leaves(goal, bank)
+ nearest = None
+ every = goal.get("need", (1 << len(ex[0][0])) - 1) # every input the function takes is read (a body: its element)
+
+ def ok(x):
+ return (x.uses & every) == every and (depth > 0 or "need" in goal or x.uses == every) and \
+ (x.uses != 0 or goal.get("allow_const")) and \
+ fits_all(x, ex) and matters(lambda inp: evalx(x, inp), ex, x.uses)
+ for size in range(1, MAX_SIZE + 1):
+ bank.grow(size, lambdas=True)
+ hits = [x for s in range(1, size + 1) for x in bank.alive(s) if ok(x)]
+ if hits:
+ best = pick(hits, bank)
+ nxt = size + 1 # a larger program may still cost less (named moves, no lossy ones)
+ while nxt <= MAX_SIZE and (nxt - (1.0 + NAME_BONUS * len(namewords)) < best.cost or
+ bin(best.nmask).count("1") < len(namewords)) and not bank.time_up():
+ # the choice puts the name's words first: while a word of the name is unsaid, larger programs are grown
+ bank.grow(nxt, lambdas=True)
+ more = [x for x in bank.alive(nxt) if ok(x)]
+ hits += more
+ if more:
+ best = pick(hits, bank)
+ nxt += 1
+ if nxt == size + 1 and nxt <= MAX_SIZE and not bank.time_up(): # rivals one node larger must exist to compare
+ bank.grow(nxt, lambdas=True)
+ hits += [x for x in bank.alive(nxt) if ok(x)]
+ if depth == 0: # the inverses are weighed beside the first fit (a short pass)
+ # the fit found first does not say all its name: programs made by chains are weighed beside it. A first
+ # fit that is only weak evidence is not a fit: the inverses then get their whole time
+ strong = any(not x.lossy for x in hits)
+ more, _asked = decompose(goal, bank, parts, words_text, ok, CHAIN_BESIDE_SECONDS if strong else None)
+ hits += more
+ return decide(hits, bank, ex, names, ok)
+ if bank.time_up():
+ break
+ # past the bound: larger code as chains of the programs found (in sequence: a body as its own goal; side by side: a join)
+ chain_deadline = time.time() + (CHAIN_SECONDS if depth == 0 else CHAIN_SECONDS_SUB)
+ if depth < MAX_DEPTH:
+ hits, asked = decompose(goal, bank, parts, words_text, ok, None if depth == 0 else CHAIN_SECONDS_SUB * (MAX_DEPTH - depth))
+ else:
+ bank.deadline = chain_deadline
+ hits, asked = [x for x in join_top(bank, ex, ok, chain_deadline) if evidenced(x, len(ex))], None
+ if hits:
+ return decide(hits, bank, ex, names, ok)
+ if asked is not None:
+ return asked
+ steps = decision_list(bank, ex, every)
+ if steps and matters(lambda inp: eval_steps(steps, inp), ex):
+ m = 0
+ for c, e in steps:
+ m |= e.nmask | (c.nmask if c is not None else 0)
+ return {"kind": "branches", "steps": steps, "bank": bank, "covered": bin(m).count("1") == len(namewords)}
+ for x in bank.seen.values():
+ if not x.dead and x.inp:
+ c = bin(mask_of(x, ex)).count("1")
+ if nearest is None or (c, -x.cost) > (nearest[0], -nearest[1].cost):
+ nearest = (c, x)
+ return {"kind": "none", "nearest": nearest, "bank": bank,
+ "searched": len(bank.seen), "time_up": time.time() > deadline, "capped": len(bank.seen) >= bank.cap}
+
+
+def function_source(goal, res):
+ names = goal["params"]
+ imports = set()
+ if res["kind"] == "expr":
+ x = res["x"]
+ imports |= x.imports
+ body = []
+ HOIST.clear()
+ if x.op[0] == "loop":
+ st = code(x.args[0], names)
+ kind, c, s_, g = x.op[1], x.op[2], x.op[3], x.op[4]
+ if kind == "count":
+ body += [" count = 0", " while %s:" % bare(code(c, [st])), " %s = %s" % (st, bare(code(s_, [st]))),
+ " count += 1", " return count"]
+ elif kind == "total":
+ body += [" total = 0", " while %s:" % bare(code(c, [st])), " total += %s" % bare(code(g, [st])),
+ " %s = %s" % (st, bare(code(s_, [st]))), " return total"]
+ else:
+ body += [" while %s:" % bare(code(c, [st])), " %s = %s" % (st, bare(code(s_, [st]))),
+ " return %s" % st]
+ x = None
+ elif x.op[0] == "guard":
+ p_, c = x.op[1], x.op[2]
+ body += [" try:", " value = %s" % bare(code(p_, names)),
+ " except (ValueError, TypeError, KeyError, IndexError, ZeroDivisionError, AttributeError):",
+ " return None"]
+ if c is not None:
+ body += [" if not (%s):" % bare(code(c, ["value"])), " return None"]
+ body += [" return value"]
+ x = None
+ if x is not None and x.op[0] == "b" and x.size > MAX_SIZE: # larger code as the chain it is: each side a named step
+ taken = set(names)
+ for a in x.args:
+ if isinstance(a, X) and a.size >= 2 and a.live:
+ nm = step_name(a, taken)
+ taken.add(nm)
+ body.append(" %s = %s" % (nm, bare(code(a, names))))
+ HOIST[id(a)] = nm
+ if x is not None:
+ body.append(" return %s" % bare(code(x, names)))
+ HOIST.clear()
+ x = res["x"]
+ moves = moves_of(x)
+ size = x.size
+ else:
+ body, moves, size = [], [], 0
+ for c, e in res["steps"]:
+ imports |= e.imports | (c.imports if c else set())
+ moves += moves_of(e) + (moves_of(c) if c else [])
+ size += e.size + (c.size if c else 0)
+ if c is None:
+ body.append(" return %s" % bare(code(e, names)))
+ else:
+ body += [" if %s:" % bare(code(c, names)), " return %s" % bare(code(e, names))]
+ for x in _all_nodes(res):
+ if x.op[0] == "const" and isinstance(x.op[1], float) and x.op[1] == math.pi:
+ imports.add("math")
+ text_all = "\n".join(body)
+ for mod in ("hashlib", "hmac", "base64", "re", "math", "collections", "functools", "itertools", "json", "statistics",
+ "urllib.request"):
+ if re.search(r"\b%s\." % re.escape(mod), text_all):
+ imports.add(mod)
+ src = "def %s(%s):\n%s\n" % (goal["name"], ", ".join(names), "\n".join(body))
+ return src, sorted(imports), moves, size
+
+
+def _all_nodes(res):
+ roots = [res["x"]] if res["kind"] == "expr" else [z for st in res["steps"] for z in st if z is not None]
+ stack = list(roots)
+ while stack:
+ x = stack.pop()
+ yield x
+ stack.extend(a for a in x.args if isinstance(a, X))
+ if x.op[0] in ("outer", "body", "scan", "zip"):
+ stack.append(x.op[1])
+ if x.op[0] == "loop":
+ stack.extend(z for z in x.op[2:5] if z is not None)
+ if x.op[0] == "guard":
+ stack.extend(z for z in x.op[1:3] if z is not None)
+
+
+def via_composer_v3(goal):
+ """all-number goals the shape search did not reach: composer_v3 itself (its fitted constants are refused)"""
+ ex = goal["examples"]
+ if not all(isinstance(a, (int, float)) and not isinstance(a, bool) for args, _o, _t in ex for a in args):
+ return None
+ if not all(isinstance(o, (int, float)) and not isinstance(o, bool) for _a, o, _t in ex):
+ return None
+ for d in (WB / "swarm", WB.parents[1] / "specbuild"):
+ if (d / "composer_v3.py").is_file():
+ sys.path.insert(0, str(d))
+ break
+ try:
+ import composer_v3 as C3
+ except Exception: # noqa: BLE001
+ return None
+ r = C3.compose({"id": goal["name"], "title": goal["name"], "dev": [{"in": list(a), "out": o} for a, o, _t in ex]})
+ if r.get("status") != "composed" or r.get("kind") != "expr" or r.get("fitted"):
+ return None
+ if not all(re.search(r"\bx%d\b" % (i + 1), r["expr_py"]) for i in range(len(goal["params"]))):
+ return None # every input is read
+ expr = re.sub(r"\bx(\d+)\b", lambda m: goal["params"][int(m.group(1)) - 1], r["expr_py"])
+ return {"source": "def %s(%s):\n return %s\n" % (goal["name"], ", ".join(goal["params"]), bare(expr)),
+ "imports": ["math"] if "math." in expr else [], "moves": ["composer_v3: " + r["derivation"]], "size": r.get("size")}
+
+
+# ================================================================ parts: the project's functions
+try:
+ import signal as _signal
+ _CAN_BOUND = hasattr(_signal, "setitimer")
+except Exception: # noqa: BLE001
+ _CAN_BOUND = False
+
+
+def is_pure(fn_node):
+ for n in ast.walk(fn_node):
+ if isinstance(n, (ast.Global, ast.Nonlocal, ast.Yield, ast.YieldFrom)):
+ return False
+ if isinstance(n, ast.While) and not _CAN_BOUND:
+ return False # nothing would stop a loop that does not end
+ if isinstance(n, ast.Call):
+ f = n.func
+ if isinstance(f, ast.Name) and f.id in IMPURE_CALLS:
+ return False
+ if isinstance(f, ast.Attribute):
+ root = f
+ while isinstance(root, ast.Attribute):
+ root = root.value
+ if isinstance(root, ast.Name) and root.id in IMPURE_MODS:
+ return False
+ return True
+
+
+def read_parts(root, target_module, exclude, seen_types):
+ """the project's pure functions: name, module, inputs, and the shapes of the values it is seen to take (the tests, the
+ project's own calls with literal values, or its annotations)"""
+ out = []
+ root = Path(root)
+ n = 0
+ calls_seen = {}
+ for p in sorted(root.rglob("*.py"))[:200]:
+ try:
+ for c in ast.walk(ast.parse(p.read_text(encoding="utf-8"))):
+ if isinstance(c, ast.Call) and isinstance(c.func, (ast.Name, ast.Attribute)) and c.args and not c.keywords:
+ fname = c.func.id if isinstance(c.func, ast.Name) else c.func.attr
+ try:
+ calls_seen.setdefault(fname, [tyof(ast.literal_eval(x)) for x in c.args])
+ except Exception: # noqa: BLE001
+ pass
+ except Exception: # noqa: BLE001
+ continue
+ for p in sorted(root.rglob("*.py")):
+ rel = p.relative_to(root)
+ if any(part.startswith(".") or part in ("node_modules", "__pycache__", "venv", ".venv", "build", "dist")
+ for part in rel.parts) or is_test_path(rel) or SECRET.search(p.name) or p.name.startswith("_hidden"):
+ continue
+ n += 1
+ if n > 80:
+ break
+ try:
+ tree = ast.parse(p.read_text(encoding="utf-8"))
+ except Exception: # noqa: BLE001
+ continue
+ mod = ".".join(rel.with_suffix("").parts)
+ for node in tree.body:
+ if not isinstance(node, ast.FunctionDef) or node.name in exclude or node.name.startswith("test"):
+ continue
+ a = node.args
+ if a.vararg or a.posonlyargs or any(d is None for d in a.kw_defaults):
+ continue # optional keywords (with defaults, or **kw) are left as they are
+ k = len(a.args) - len(a.defaults)
+ if not 1 <= k <= 3 or not is_pure(node):
+ continue
+ types = seen_types.get(node.name) or calls_seen.get(node.name) or annotated(node)
+ if not types or len(types) != k:
+ continue # a part is used only where its inputs' shapes are known
+ out.append({"name": node.name, "module": mod, "arity": k, "types": types,
+ "code": node.name if mod == target_module else "%s.%s" % (mod, node.name),
+ "imports": () if mod == target_module else (mod,),
+ "words": " ".join(re.findall(r"[a-z]+", node.name.lower() + " " + (ast.get_docstring(node) or "").lower()))})
+ return out
+
+
+ANN = {"int": "int", "float": "float", "str": "str", "bool": "bool", "list": ("list", None), "dict": ("dict", None, None),
+ "tuple": ("tuple", None)}
+
+
+def annotated(fn):
+ out = []
+ for a in fn.args.args[:len(fn.args.args) - len(fn.args.defaults)]:
+ h = a.annotation
+ if isinstance(h, ast.Name) and h.id in ANN:
+ out.append(ANN[h.id])
+ elif isinstance(h, ast.Subscript) and isinstance(h.value, ast.Name) and h.value.id in ("list", "List") and \
+ isinstance(h.slice, ast.Name) and h.slice.id in ANN:
+ out.append(("list", ANN[h.slice.id]))
+ else:
+ return None
+ return out
+
+
+def is_test_path(rel):
+ rel = Path(rel)
+ return rel.name.startswith("test_") or rel.name.endswith("_test.py") or "tests" in rel.parts or rel.name == "conftest.py"
+
+
+def load_part_fns(root, parts):
+ import contextlib
+ import importlib
+ import io
+ sys.path.insert(0, str(root))
+ ok = []
+ for p in parts:
+ try:
+ with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
+ m = importlib.import_module(p["module"])
+ p["fn"] = _guarded(getattr(m, p["name"]))
+ ok.append(p)
+ except Exception: # noqa: BLE001
+ continue
+ return ok
+
+
+def _guarded(f):
+ """a project function called by the search: time-limited, its output silenced"""
+ import contextlib
+ import io
+
+ def g(*a):
+ import signal
+ if hasattr(signal, "setitimer"):
+ signal.signal(signal.SIGALRM, _alarm)
+ signal.setitimer(signal.ITIMER_REAL, 0.25)
+ try:
+ with contextlib.redirect_stdout(io.StringIO()):
+ return f(*a)
+ finally:
+ if hasattr(signal, "setitimer"):
+ signal.setitimer(signal.ITIMER_REAL, 0)
+ return g
+
+
+def _alarm(*_a):
+ raise TimeoutError("part ran too long")
+
+
+# ================================================================ read-back: a separate interpreter
+def read_back(root, module_text, name, ex):
+ with tempfile.TemporaryDirectory(prefix="o7code_") as d:
+ open(os.path.join(d, "o7prog.py"), "w", encoding="utf-8").write(module_text)
+ runner = ("import sys, json\nsys.path[:0] = [%r, %r]\nimport o7prog\nrows = eval(sys.stdin.read())\nout = []\n"
+ "for r in rows:\n try:\n out.append(repr(o7prog.%s(*r)))\n except Exception as e:\n"
+ " out.append('' %% type(e).__name__)\nprint(json.dumps(out))\n" % (d, str(root), name))
+ try:
+ r = subprocess.run([sys.executable, "-I", "-c", runner], input=repr([list(a) for a, _o, _t in ex]),
+ capture_output=True, text=True, timeout=30, cwd=str(root) if os.path.isdir(str(root)) else d)
+ got = json.loads(r.stdout)
+ except Exception as e: # noqa: BLE001
+ return False, "the written function did not run: %s" % str(e)[:120]
+ ok = 0
+ for g, (_a, out, tol) in zip(got, ex):
+ try:
+ v = ast.literal_eval(g)
+ except Exception: # noqa: BLE001
+ v = ERR
+ ok += same(v, out, tol)
+ return ok == len(ex), "read back %d/%d" % (ok, len(ex))
+
+
+# ================================================================ a job: goals composed round by round
+def _in_child(work, name):
+ """one goal composed in a forked child: its search's memory is given back when it ends, so the next goal starts from
+ the job's own size (Python keeps what it has used). Where there is no fork, in this process."""
+ def oom():
+ return {"name": name, "status": "declined", "seconds": 0.0,
+ "gap": "composing %s ran out of memory (the bound is %d MB); nothing was written for it" % (name, MEM_MB),
+ "cause": "memory"}
+ if not hasattr(os, "fork"):
+ try:
+ return work()
+ except MemoryError:
+ return oom()
+ rfd, wfd = os.pipe()
+ pid = os.fork()
+ if pid == 0: # the child: compose, send the result, leave at once
+ os.close(rfd)
+ code_ = 0
+ try:
+ _MEM["over"], _MEM["hit"], _MEM["t"] = False, False, 0.0
+ try:
+ out = work()
+ except MemoryError:
+ out = oom()
+ data = json.dumps(out, default=lambda o: sorted(o, key=str) if isinstance(o, (set, frozenset)) else str(o)).encode()
+ except BaseException as e: # noqa: BLE001
+ data = json.dumps({"name": name, "status": "declined", "gap": "the composer stopped on %s: %s" % (
+ name, repr(e)[:300]), "cause": "stopped"}).encode()
+ code_ = 1
+ with os.fdopen(wfd, "wb") as f:
+ f.write(data)
+ os._exit(code_)
+ os.close(wfd)
+ with os.fdopen(rfd, "rb") as f:
+ data = f.read()
+ _p, status = os.waitpid(pid, 0)
+ try:
+ return json.loads(data.decode())
+ except ValueError:
+ sig = os.WTERMSIG(status) if os.WIFSIGNALED(status) else 0
+ return {"name": name, "status": "declined", "seconds": 0.0,
+ "gap": "composing %s stopped%s; nothing was written for it" % (
+ name, " by signal %d (the system's memory stop)" % sig if sig == 9 else
+ (" by signal %d" % sig if sig else "")), "cause": "memory" if sig == 9 else "stopped"}
+
+
+def run_goals(job):
+ root = job["root"]
+ goals = job["goals"]
+ exclude = set(job.get("exclude", ()))
+ tests = read_tests(root)
+ seen_types = {n: [tyof(a) for a in d["examples"][0][0]] for n, d in tests.items() if d["examples"]}
+ target_mods = {g["module"] for g in goals}
+ parts_all = read_parts(root, next(iter(target_mods)) if len(target_mods) == 1 else None,
+ exclude | {g["name"] for g in goals}, seen_types)
+ parts_all = load_part_fns(root, parts_all)
+ results, library, pending = {}, [], list(goals)
+ flash, stored = store_flash()
+ project_names = {p["name"] for p in parts_all}
+ rnd = 0
+ while pending:
+ rnd += 1
+ progress = False
+ for g in list(pending):
+ g.setdefault("root", root)
+ g.setdefault("net_scope", job.get("net_scope", []))
+ g["project_names"] = project_names
+ kept = store_parts(flash, stored, g, exclude | {x["name"] for x in goals})
+ faces = kernel_faces(g, job.get("words", "")) # the kernel's formula parts the goal's words light
+ # Two passes, each with its own budget: the project's parts first, then (only if that does not compose) the
+ # kept functions the goal lights as well. A kept part adds reach; it never displaces what the base finds,
+ # and it never takes the base search's time (the banks are bounded by deadline, size and memory).
+ r, spent = None, 0.0
+ for lit in ([faces, faces + kept] if kept else [faces]):
+ if r is not None and time.time() + PASS_SECONDS * len(pending) > job.get("ends_at", float("inf")):
+ break # no room for it and the rest's first passes: the base answer stands
+ parts = [p for p in parts_all] + [lib for lib in library] + lit
+ _MEM["hit"] = False
+ t_goal = time.time()
+ r2 = _in_child(lambda: compose_one(root, g, parts, job.get("words", ""), library + lit), g["name"])
+ spent += time.time() - t_goal # wall time of every pass, measured outside the child
+ if r is None or r2["status"] == "composed":
+ r = r2
+ if r["status"] == "composed":
+ break
+ r["round"] = rnd
+ r["spent"] = round(spent, 3)
+ results[g["name"]] = r
+ if r["status"] == "composed":
+ pending.remove(g)
+ progress = True
+ if not r.get("confirmed") or g.get("class"):
+ continue # a part for the next only once confirmed (three examples, or its name)
+ ns = {}
+ try:
+ exec(compile("\n".join("import %s" % i for i in r["imports"]) + "\n" +
+ "\n".join(lib["source"] for lib in library) + "\n" + r["source"], g["name"], "exec"), ns)
+ library.append({"name": g["name"], "module": g["module"], "arity": len(g["params"]),
+ "types": [tyof(a) for a in g["examples"][0][0]], "code": g["name"], "imports": (),
+ "words": " ".join(re.findall(r"[a-z]+", g["name"].lower())),
+ "fn": _guarded(ns[g["name"]]), "source": r["source"], "lib_imports": r["imports"]})
+ except Exception: # noqa: BLE001
+ pass
+ if not progress:
+ break
+ try: # a declined goal is a hole for the night (code_store.nightly)
+ import code_store as CS
+ for g in goals:
+ rg = results[g["name"]]
+ if rg["status"] != "composed" and not rg.get("ambiguous"):
+ CS.note_hole(g, rg.get("gap"), root, cause=rg.get("cause") or "evidence", spent=rg.get("spent"),
+ work=rg.get("work"))
+ except Exception: # noqa: BLE001
+ pass
+ return {"results": [results[g["name"]] for g in goals]}
+
+
+_FACES = {}
+SI_UNITS = {"m", "kg", "s", "m^2", "m^3", "m/s", "m/s^2", "N", "Pa", "J", "W", "K", "A", "V", "Hz", "kg/m^3", "N*m", "1"}
+
+
+def _organ():
+ wb = Path(__file__).resolve().parent
+ for d in (os.environ.get("ORACLE7_FORMULA_ORGAN"), wb.parent / "root" / "organs10" / "physics"):
+ if d and (Path(d) / "swarm" / "parts.json").is_file():
+ return Path(d)
+ return None
+
+
+def kernel_faces(g, words_text):
+ """the kernel's admitted formula parts (Wikidata systems, solved and checked by substitution) a numeric goal's words
+ light: the part's output is a word of the name or request, its system (a shape, a law) is one too, and it takes as
+ many values as the goal. Each comes as a part with its own program, renamed, and its title kept in its docstring."""
+ ex = g.get("examples") or []
+ if not ex or not all(is_num(tyof(a)) for a in ex[0][0]) or not all(isinstance(o, (int, float)) and not isinstance(o, bool)
+ for _a, o, _t in ex):
+ return []
+ org = _organ()
+ if org is None:
+ return []
+ if "all" not in _FACES:
+ faces = []
+ try:
+ pj = json.loads((org / "swarm" / "parts.json").read_text(encoding="utf-8"))
+ for pid, pt in pj.items():
+ if pt.get("kind") != "formula" or not pt.get("output"):
+ continue
+ d = org / "specialists" / pid
+ try:
+ title = json.loads((d / "spec.json").read_text(encoding="utf-8")).get("title", "")
+ prog = (d / "program.py").read_text(encoding="utf-8")
+ except OSError:
+ continue
+ units = [re.search(r"\(([^)]*)\)", x) for x in pt["inputs"] + [pt["output"]]]
+ if any(u is None or u.group(1).strip() not in SI_UNITS for u in units):
+ continue # the plain SI faces only: no hidden unit scaling in a written function
+ m = re.search(r"\(([^)]+)\)\s*$", title)
+ sysw = {stem(w) for w in re.findall(r"[a-z]+", (m.group(1) if m else "").lower())}
+ out_n = {stem(w) for w in re.findall(r"[a-z]+", pt["output"].split("(")[0].lower())}
+ faces.append({"id": pid, "title": title, "prog": prog, "k": len(pt["inputs"]), "out": out_n, "sys": sysw,
+ "ins": [x.split("(")[0].strip() for x in pt["inputs"]]})
+ except (OSError, ValueError):
+ faces = []
+ _FACES["all"] = faces
+ ws = set(name_words(g["name"])) | {stem(w) for w in re.findall(r"[a-z]+", (words_text or "").lower())}
+ k = len(ex[0][0])
+ out = []
+ for f in _FACES["all"]:
+ if f["k"] != k or not (f["out"] & ws) or not (f["sys"] & ws):
+ continue
+ fname = "face_" + re.sub(r"\W+", "_", f["id"]).strip("_").lower()
+ src = re.sub(r"(?m)^def compute\(", "def %s(" % fname, f["prog"])
+ imports = re.findall(r"(?m)^import (\w+)\s*$", src)
+ src = re.sub(r"(?m)^import \w+\s*\n", "", src).strip()
+ src = re.sub(r'^"""', '"""Oracle7 kernel part %s: ' % f["id"], src, count=1) if src.startswith('"""') else src
+ ns = {}
+ try:
+ for i in imports:
+ ns[i] = __import__(i)
+ exec(compile(src, "face:" + f["id"], "exec"), ns)
+ except Exception: # noqa: BLE001
+ continue
+ out.append({"name": fname, "module": None, "arity": k, "types": [tyof(a) for a in ex[0][0]], "code": fname,
+ "imports": (), "words": " ".join(sorted(f["out"] | f["sys"])), "fn": _guarded(ns[fname]),
+ "source": src, "lib_imports": imports, "face": {"id": f["id"], "title": f["title"]}})
+ if len(out) >= 6:
+ break
+ return out
+
+
+def store_flash():
+ """Oracle7's kept functions on the spine (code_store), or (None, []) when there are none"""
+ try:
+ import code_store as CS
+ except Exception: # noqa: BLE001
+ return None, []
+ entries = CS.load()
+ if not entries:
+ return None, []
+ try:
+ return CS.CodeFlash(entries), entries
+ except Exception: # noqa: BLE001
+ return None, []
+
+
+def store_parts(flash, stored, g, exclude):
+ """the kept functions a goal's facts light, as parts: shapes fit, source checked, the kept functions they call loaded
+ first; each carries its record so the reply can say where it came from"""
+ if flash is None or not g.get("examples") or g.get("class"):
+ return [] # a class's methods stay within the class
+ import code_store as CS
+ ex = g["examples"]
+ in_shapes = [repr(tyof(a)) for a in ex[0][0]]
+ out_shape = repr(ty_of_vals([o for _a, o, _t in ex]))
+ lit = flash.light(in_shapes, out_shape, name_words(g["name"]))
+ by_sha = {e["sha256"]: e for e in stored}
+ known = {e["name"] for e in stored}
+ taken = set(g.get("project_names") or []) # the project's own functions keep their names
+ out, loaded, ids = [], {}, {}
+
+ def load(e, depth=0):
+ if e["name"] in loaded: # one name, one implementation: a different record is not used
+ return loaded[e["name"]] if ids.get(e["name"]) == e["sha256"] else None
+ if depth > 6 or e["name"] in taken:
+ return None
+ for dn, dsha in (e.get("deps") or {}).items(): # what it calls, by the exact source it was checked with
+ dep = by_sha.get(dsha)
+ if dep is None or load(dep, depth + 1) is None:
+ return None
+ if CS.checked_source(e["source"], e["name"], known) is not None:
+ return None
+ ns = {}
+ try:
+ import importlib
+ for m in e.get("imports") or []:
+ ns[m.split(".")[0]] = importlib.import_module(m)
+ for dn, dp in loaded.items():
+ if dp is not None:
+ ns[dn] = dp["fn"]
+ exec(compile(e["source"], "store:" + e["name"], "exec"), ns)
+ except Exception: # noqa: BLE001
+ return None
+ part = {"name": e["name"], "module": None, "arity": len(e["params"]), "code": e["name"], "imports": (),
+ "types": [ast.literal_eval(t) if t.startswith(("(", "'")) else t for t in e.get("in_shapes") or []] or None,
+ "words": " ".join(re.findall(r"[a-z]+", e["name"].lower())), "fn": _guarded(ns[e["name"]]),
+ "source": e["source"], "lib_imports": list(e.get("imports") or []), "store": {"project": e.get("project"),
+ "id": e["id"]}}
+ loaded[e["name"]] = part
+ ids[e["name"]] = e["sha256"]
+ return part
+ for _res, e in lit:
+ if e["name"] in exclude or e["name"] == g["name"]:
+ continue
+ if len(e.get("params") or []) > 3:
+ continue
+ pt = load(e)
+ if pt is not None and pt not in out:
+ out.append(pt)
+ for dn, dp in loaded.items(): # what a lit function calls comes with it
+ if dp is not None and dp not in out:
+ out.append(dp)
+ return out
+
+
+def compose_one(root, g, parts, words_text, library):
+ """one goal composed; its result carries the work it was given (12.5 step 6)"""
+ _WORK.update(bank=0, probe=0, last=None)
+ r = _compose_one(root, g, parts, words_text, library)
+ if isinstance(r, dict):
+ r = dict(r, work={"bank": _WORK["bank"], "probe": _WORK["probe"], "stage": _WORK["last"]})
+ return r
+
+
+def _compose_one(root, g, parts, words_text, library):
+ ex = g["examples"]
+ if not ex:
+ return {"name": g["name"], "status": "declined", "gap": "no examples or tests say what %s gives" % g["name"]}
+ keyed = {}
+ for a, o, _t in ex:
+ k = repr(a)
+ if k in keyed and not same(keyed[k], o):
+ return {"name": g["name"], "status": "declined", "gap": "the examples disagree: %s gives two answers for %s" % (g["name"], k)}
+ keyed[k] = o
+ if len({len(a) for a, _o, _t in ex}) != 1:
+ return {"name": g["name"], "status": "declined", "gap": "%s is called with different numbers of inputs" % g["name"]}
+ t0 = time.time()
+ pages, gap = fetch_examples(g)
+ if gap:
+ return {"name": g["name"], "status": "declined", "gap": gap, "network": True}
+ g["fetched"] = pages
+ res = compose_goal(g, parts, words_text)
+ if res["kind"] == "ask": # a step inside it, read two ways
+ return {"name": g["name"], "status": "declined", "seconds": round(time.time() - t0, 1), "ambiguous": True,
+ "gap": "the %d examples of %s are within reach, but %s" % (len(ex), g["name"], res["gap"])}
+ if res["kind"] == "ambiguous_body": # the body of a comprehension, composed as its own goal, read two ways
+ sub, br = res["sub"], res["res"]
+ el = repr(br["probe"][0])
+ others = ", ".join("%s=%r" % (n, v) for n, v in zip(g["params"], br["probe"][1:]))
+ if isinstance(br["rival"], tuple):
+ _s, node, alt = br["rival"]
+ HOIST.clear()
+ HOIST[id(node)] = bare(code(alt, sub["params"]))
+ rcode = bare(code(br["x"], sub["params"]))
+ HOIST.clear()
+ else:
+ rcode = bare(code(br["rival"], sub["params"]))
+ return {"name": g["name"], "status": "declined", "seconds": round(time.time() - t0, 1), "ambiguous": True,
+ "gap": "the %d examples make %s a list built from `%s`, %s, but the step for each element fits more than "
+ "one program, and they answer differently elsewhere: for the element %s (with %s), `%s` gives %r and "
+ "`%s` gives %r. Which is right? Add an example (or a test) that has such an element." % (
+ len(ex), g["name"], bare(code(res["L"], g["params"])),
+ "one value per element" if res["lam"] == "map" else "keeping some elements", el, others,
+ bare(code(br["x"], sub["params"])), br["va"], rcode, br["vb"])}
+ if res["kind"] == "ambiguous":
+ call = "%s(%s)" % (g["name"], ", ".join(repr(v) for v in res["probe"]))
+ if isinstance(res["rival"], tuple): # a part of it read another way
+ _s, node, alt = res["rival"]
+ return {"name": g["name"], "status": "declined", "seconds": round(time.time() - t0, 1), "ambiguous": True,
+ "gap": "the %d examples fit more than one program, and they answer differently elsewhere: `%s` gives %r "
+ "for %s, but with `%s` read as `%s` it gives %r. Which is right? Say it as an example (%s == ...) "
+ "or add it to the tests." % (len(ex), bare(code(res["x"], g["params"])), res["va"], call,
+ bare(code(node, g["params"])), bare(code(alt, g["params"])), res["vb"], call)}
+ return {"name": g["name"], "status": "declined", "seconds": round(time.time() - t0, 1), "ambiguous": True,
+ "gap": "the %d examples fit more than one program, and they answer differently elsewhere: `%s` gives %r "
+ "for %s, `%s` gives %r. Which is right? Say it as an example (%s == ...) or add it to the tests." % (
+ len(ex), bare(code(res["x"], g["params"])), res["va"], call,
+ bare(code(res["rival"], g["params"])), res["vb"], call)}
+ if res["kind"] == "unsaid":
+ return {"name": g["name"], "status": "declined", "seconds": round(time.time() - t0, 1),
+ "gap": "the name says '%s' and the data has it, but the program found for the %d examples does not use it: "
+ "`%s`. That fits by coincidence as likely as not, so it was not written; add an example where it "
+ "matters, or say how '%s' is meant." % (res["word"], len(ex), bare(code(res["x"], g["params"])),
+ res["word"])}
+ lossy = res["kind"] in ("expr", "branches") and any(x.lossy for x in _all_nodes(res))
+ v3 = via_composer_v3(g) if lossy else None # a fit through an unnamed lossy move: composer_v3 has none of those
+ if v3 is not None:
+ src, imports, moves, size = v3["source"], v3["imports"], v3["moves"], v3["size"]
+ elif lossy: # weak evidence: say what it would be, write nothing
+ prog = bare(code(res["x"], g["params"])) if res["kind"] == "expr" else "a branch list"
+ return {"name": g["name"], "status": "declined", "seconds": round(time.time() - t0, 1),
+ "gap": "the only programs within reach that give the %d examples of %s throw information away (rounding, "
+ "//, %%, a fixed position, or a number's digits read as text): `%s`. That is weak evidence, so it "
+ "was not written; if that reading is meant, say so in the request (e.g. 'by its digits'), or add "
+ "examples." % (len(ex), g["name"], prog)}
+ elif res["kind"] in ("expr", "branches"):
+ try: # 12.5 12c(i): the sufficiency judge in shadow (changes no answer)
+ import shadow as _shadow
+ _shadow.record(res, ex, g["name"], sys.modules[__name__])
+ except Exception: # noqa: BLE001
+ pass
+ src, imports, moves, size = function_source(g, res)
+ else:
+ v3 = via_composer_v3(g)
+ if v3 is None:
+ near = res.get("nearest")
+ near_txt = ""
+ if near and near[0]:
+ near_txt = " The nearest program gives %d of the %d: %s" % (near[0], len(ex), bare(code(near[1], g["params"])))
+ bound = "memory" if _MEM["hit"] else "time" if res.get("time_up") else "cap" if res.get("capped") else None
+ if bound: # 12.5 C33: a stopped search did not cover the space; it says so
+ gap = ("the search for %s stopped at its %s after %d distinct programs, none giving all %d examples; the "
+ "programs within %d moves were not all tried, so one may still exist.%s" % (
+ g["name"], "memory bound (%d MB)" % MEM_MB if bound == "memory" else
+ "bound of %d kept programs" % BANK_CAP if bound == "cap" else "time limit",
+ res.get("searched", 0), len(ex), MAX_SIZE, near_txt))
+ else:
+ gap = ("no program within %d moves over these shapes (nor a branch list whose branches each rest on two "
+ "examples) gives all %d examples of %s; %d distinct programs were tried.%s" % (
+ MAX_SIZE, len(ex), g["name"], res.get("searched", 0), near_txt))
+ return {"name": g["name"], "status": "declined", "seconds": round(time.time() - t0, 1), "gap": gap,
+ "cause": bound or "searched"}
+ src, imports, moves, size = v3["source"], v3["imports"], v3["moves"], v3["size"]
+ used_lib = [lib for lib in library if re.search(r"\b%s\(" % re.escape(lib["name"]), src)]
+ grew = True
+ while grew:
+ grew = False
+ for lib in library:
+ if lib not in used_lib and any(re.search(r"\b%s\(" % re.escape(lib["name"]), u.get("source") or "") for u in used_lib):
+ used_lib.insert(0, lib)
+ grew = True
+ lib_imports = sorted({i for lib in used_lib for i in lib.get("lib_imports", [])})
+ base = g.get("module_text", "")
+ base = _drop_function(base, g["name"])
+ mod_imports = sorted(set(imports) | set(lib_imports))
+ text = "\n".join("import %s" % i for i in mod_imports) + "\n" + base + "\n\n" + \
+ "\n\n".join(lib["source"] for lib in used_lib) + "\n\n" + src
+ ok, note = read_back(root, text, g["name"], ex)
+ if not ok:
+ return {"name": g["name"], "status": "declined", "gap": "the written %s disagreed with its examples (%s)" % (g["name"], note)}
+ confirmed = len(ex) >= 3 or bool(res.get("covered") and v3 is None)
+ evidence = []
+ for a, o, _t in ex:
+ try:
+ json.dumps([list(a), o])
+ evidence.append([list(a), o])
+ except Exception: # noqa: BLE001
+ pass
+ from_store = [{"name": lib["name"], "project": lib["store"].get("project"), "id": lib["store"].get("id")}
+ for lib in used_lib if lib.get("store")]
+ deps = {lib["name"]: hashlib.sha256((lib["name"] + "\n" + lib["source"]).encode()).hexdigest()
+ for lib in used_lib if lib.get("source")}
+ return {"name": g["name"], "status": "composed", "source": src, "imports": imports, "moves": moves, "size": size,
+ "confirmed": confirmed, "evidence": evidence[:40], "in_shapes": [repr(tyof(a)) for a in ex[0][0]],
+ "out_shape": repr(ty_of_vals([o for _a, o, _t in ex])), "words": name_words(g["name"]),
+ "from_store": from_store, "deps": deps,
+ "examples": len(ex), "read_back": note, "seconds": round(time.time() - t0, 1),
+ "uses": [lib["name"] for lib in used_lib], "branches": res["kind"] == "branches",
+ # the parts from outside the project (kept functions, the kernel's formula faces) travel with it: what is
+ # written must run where it is written (12.0 C8h)
+ "support": [lib["source"] for lib in used_lib if (lib.get("store") or lib.get("face")) and lib.get("source")],
+ "support_imports": sorted({i for lib in used_lib if lib.get("store") or lib.get("face")
+ for i in lib.get("lib_imports", [])})}
+
+
+def _drop_function(text, name):
+ try:
+ tree = ast.parse(text)
+ except Exception: # noqa: BLE001
+ return text
+ lines = text.splitlines()
+ for node in tree.body:
+ if isinstance(node, ast.FunctionDef) and node.name == name:
+ start = node.lineno - 1 - len(node.decorator_list)
+ return "\n".join(lines[:start] + lines[node.end_lineno:])
+ return text
+
+
+# ================================================================ evidence (read in the bench's own process: parsing only)
+def _lit(n, env):
+ if isinstance(n, ast.Name) and n.id in env:
+ return env[n.id]
+ return ast.literal_eval(n)
+
+
+def read_tests(root, only=None):
+ """{name: {"module": m, "examples": [(args, out, tol)], "files": [...]}} from the project's test files"""
+ root = Path(root)
+ found = {}
+ for p in sorted(root.rglob("*.py")):
+ rel = p.relative_to(root)
+ if any(part.startswith(".") or part in ("node_modules", "__pycache__", "venv", ".venv") for part in rel.parts):
+ continue
+ if not is_test_path(rel) or p.name.startswith("_hidden"):
+ continue
+ if only and p.name not in only and str(rel).replace(os.sep, "/") not in only:
+ continue
+ try:
+ tree = ast.parse(p.read_text(encoding="utf-8"))
+ except Exception: # noqa: BLE001
+ continue
+ env, names, mods = {}, {}, {}
+ for node in tree.body:
+ if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
+ try:
+ env[node.targets[0].id] = ast.literal_eval(node.value)
+ except Exception: # noqa: BLE001
+ pass
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ImportFrom) and node.level == 0 and node.module and \
+ node.module.split(".")[0] not in sys.stdlib_module_names and node.module not in ("pytest", "unittest"):
+ for a in node.names:
+ if a.name != "*":
+ names[a.asname or a.name] = (node.module, a.name)
+ else:
+ names.setdefault("*", []).append(node.module)
+ elif isinstance(node, ast.Import):
+ for a in node.names:
+ if a.name.split(".")[0] not in sys.stdlib_module_names and a.name not in ("pytest", "unittest"):
+ mods[a.asname or a.name] = a.name
+
+ def target(call):
+ if not isinstance(call, ast.Call) or call.keywords:
+ return None
+ f = call.func
+ if isinstance(f, ast.Name) and f.id in names and f.id != "*":
+ return names[f.id]
+ if isinstance(f, ast.Attribute) and isinstance(f.value, ast.Name) and f.value.id in mods:
+ return (mods[f.value.id], f.attr)
+ if isinstance(f, ast.Name) and "*" in names and not f.id[0].isupper() and f.id not in dir(builtins):
+ return (names["*"][0], f.id)
+ return None
+
+ def record(call, out, tol=None):
+ t = target(call)
+ if t is None:
+ return
+ try:
+ args = tuple(_lit(a, env) for a in call.args)
+ except Exception: # noqa: BLE001
+ return
+ d = found.setdefault(t[1], {"module": t[0], "examples": [], "files": []})
+ if repr((args, out)) not in {repr((a, o)) for a, o, _t in d["examples"]}:
+ d["examples"].append((args, out, tol))
+ if str(rel) not in d["files"]:
+ d["files"].append(str(rel).replace(os.sep, "/"))
+
+ def value(n):
+ if isinstance(n, ast.Call) and isinstance(n.func, (ast.Attribute, ast.Name)) and \
+ (getattr(n.func, "attr", None) == "approx" or getattr(n.func, "id", None) == "approx") and n.args:
+ return _lit(n.args[0], env), 1e-6 * max(1.0, abs(_lit(n.args[0], env)))
+ return _lit(n, env), None
+
+ for node in ast.walk(tree):
+ try:
+ if isinstance(node, ast.Assert):
+ tst = node.test
+ if isinstance(tst, ast.Compare) and len(tst.ops) == 1:
+ op, left, right = tst.ops[0], tst.left, tst.comparators[0]
+ if isinstance(op, ast.Eq):
+ if target(left):
+ v, tol = value(right)
+ record(left, v, tol)
+ elif target(right):
+ v, tol = value(left)
+ record(right, v, tol)
+ elif isinstance(op, ast.Is) and isinstance(right, ast.Constant) and target(left):
+ record(left, right.value)
+ elif isinstance(op, (ast.Lt, ast.LtE)) and isinstance(left, ast.Call) and \
+ getattr(left.func, "id", None) == "abs" and len(left.args) == 1 and \
+ isinstance(left.args[0], ast.BinOp) and isinstance(left.args[0].op, ast.Sub):
+ a, b = left.args[0].left, left.args[0].right
+ eps = _lit(right, env)
+ if target(a):
+ record(a, _lit(b, env), eps)
+ elif target(b):
+ record(b, _lit(a, env), eps)
+ elif target(tst):
+ record(tst, True)
+ elif isinstance(tst, ast.UnaryOp) and isinstance(tst.op, ast.Not) and target(tst.operand):
+ record(tst.operand, False)
+ elif isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.args:
+ m = node.func.attr
+ a0 = node.args[0]
+ if m in ("assertEqual", "assertEquals") and len(node.args) >= 2:
+ if target(a0):
+ record(a0, _lit(node.args[1], env))
+ elif target(node.args[1]):
+ record(node.args[1], _lit(a0, env))
+ elif m == "assertAlmostEqual" and len(node.args) >= 2 and target(a0):
+ places = _lit(node.args[2], env) if len(node.args) > 2 else 7
+ record(a0, _lit(node.args[1], env), 0.5 * 10 ** (-places))
+ elif m == "assertTrue" and target(a0):
+ record(a0, True)
+ elif m == "assertFalse" and target(a0):
+ record(a0, False)
+ elif m == "assertIsNone" and target(a0):
+ record(a0, None)
+ except Exception: # noqa: BLE001
+ continue
+ return found
+
+
+def _scan_value(s):
+ """the literal at the start of s: the shortest prefix, cut at a comma, semicolon or 'and' outside brackets and quotes"""
+ depth, q, cuts = 0, None, []
+ i = 0
+ while i < len(s):
+ ch = s[i]
+ if q:
+ if ch == "\\":
+ i += 2
+ continue
+ if ch == q:
+ q = None
+ elif ch in "'\"":
+ q = ch
+ elif ch in "([{":
+ depth += 1
+ elif ch in ")]}":
+ depth -= 1
+ if depth < 0:
+ cuts.append(i)
+ break
+ elif depth == 0 and (ch in ",;" or s[i:i + 5] == " and " or (ch == "." and (i + 1 == len(s) or s[i + 1] == " "))):
+ cuts.append(i)
+ i += 1
+ cuts.append(len(s))
+ for c in cuts:
+ try:
+ return ast.literal_eval(s[:c].strip()), True
+ except Exception: # noqa: BLE001
+ continue
+ return None, False
+
+
+def _quoted_breaks(s):
+ """a line break inside a quoted text is written as \\n, so the literal reads (a Python literal cannot hold a bare one)"""
+ out, q = [], None
+ for ch in s:
+ if q:
+ if ch == q:
+ q = None
+ elif ch == "\n":
+ ch = "\\n"
+ elif ch in "'\"":
+ q = ch
+ out.append(ch)
+ return "".join(out)
+
+
+def examples_in(text, name):
+ """examples written in the request: name(args) == v / -> v / returns v / gives v / is v / should be v"""
+ out = []
+ for m in re.finditer(r"\b%s\s*\(" % re.escape(name), text or ""):
+ i, depth, q = m.end() - 1, 0, None
+ j = i
+ while j < len(text):
+ ch = text[j]
+ if q:
+ if ch == "\\":
+ j += 2
+ continue
+ if ch == q:
+ q = None
+ elif ch in "'\"":
+ q = ch
+ elif ch in "([{":
+ depth += 1
+ elif ch in ")]}":
+ depth -= 1
+ if depth == 0:
+ break
+ j += 1
+ inner = _quoted_breaks(text[i + 1:j]) # a line break typed inside a quoted example is \n
+ rest = text[j + 1:]
+ mm = re.match(r"\s*(?:==|->|=>|\u2192|returns?|gives?|should (?:be|give|return)|is)\s*", rest)
+ if not mm:
+ continue
+ try:
+ args = ast.literal_eval("(%s,)" % inner) if inner.strip() else ()
+ except Exception: # noqa: BLE001
+ continue
+ v, ok = _scan_value(_quoted_breaks(rest[mm.end():]))
+ if ok:
+ out.append((tuple(args), v, None))
+ return out
+
+
+def param_names(ex, given=None):
+ if given:
+ return list(given)
+ out = []
+ for a in ex[0][0]:
+ t = tyof(a)
+ base = "xs" if is_seq(t) and t[1] in ("int", "float", None) else "items" if is_seq(t) else "text" if t == "str" else \
+ "mapping" if is_dict(t) else "flag" if t == "bool" else "n" if t == "int" else "x"
+ name, k = base, 2
+ while name in out:
+ name, k = "%s%d" % (base, k), k + 1
+ out.append(name)
+ if out == ["x", "x2"]:
+ out = ["a", "b"]
+ if out == ["n", "n2"]:
+ out = ["a", "b"]
+ return out
+
+
+# ================================================================ classes: an object's state is what was done to it
+# ================================================================ objects as a state carried through ordered actions
+def read_object_runs(root, only=None):
+ """{Class: {"module", "files", "ctor", "mutators", "runs": [{"ctor": args, "events": [(m, args)], "obs": [(k, q, qargs,
+ out)]}]}} - every object the tests make, the actions done to it IN ORDER, and what each query gave after the first k of
+ them. Order between different actions is kept (the class-history representation lost it: set;reset == reset;set)."""
+ root = Path(root)
+ found = {}
+ for p in sorted(root.rglob("*.py")):
+ rel = p.relative_to(root)
+ if any(part.startswith(".") or part in ("node_modules", "__pycache__", "venv", ".venv") for part in rel.parts):
+ continue
+ if not is_test_path(rel) or p.name.startswith("_hidden"):
+ continue
+ if only and p.name not in only and str(rel).replace(os.sep, "/") not in only:
+ continue
+ try:
+ tree = ast.parse(p.read_text(encoding="utf-8"))
+ except Exception: # noqa: BLE001
+ continue
+ classes = {}
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ImportFrom) and node.level == 0 and node.module and \
+ node.module.split(".")[0] not in sys.stdlib_module_names:
+ for a in node.names:
+ if a.name[:1].isupper():
+ classes[a.asname or a.name] = (node.module, a.name)
+ if not classes:
+ continue
+ bodies = [tree.body] + [n.body for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)]
+ for body in bodies:
+ objs, env = {}, {}
+ for st in body:
+ try:
+ if isinstance(st, ast.Assign) and len(st.targets) == 1 and isinstance(st.targets[0], ast.Name):
+ v = st.value
+ if isinstance(v, ast.Call) and isinstance(v.func, ast.Name) and v.func.id in classes and not v.keywords:
+ mod, real = classes[v.func.id]
+ d = found.setdefault(real, {"module": mod, "files": [], "ctor": len(v.args), "mutators": [], "runs": []})
+ run = {"ctor": tuple(_lit(a, env) for a in v.args), "events": [], "obs": []}
+ d["runs"].append(run)
+ objs[st.targets[0].id] = (real, run)
+ if str(rel) not in d["files"]:
+ d["files"].append(str(rel).replace(os.sep, "/"))
+ else:
+ try:
+ env[st.targets[0].id] = ast.literal_eval(v)
+ except Exception: # noqa: BLE001
+ pass
+ elif isinstance(st, ast.Expr) and isinstance(st.value, ast.Call) and \
+ isinstance(st.value.func, ast.Attribute) and isinstance(st.value.func.value, ast.Name) and \
+ st.value.func.value.id in objs:
+ real, run = objs[st.value.func.value.id]
+ m = st.value.func.attr
+ run["events"].append((m, tuple(_lit(a, env) for a in st.value.args)))
+ if m not in found[real]["mutators"]:
+ found[real]["mutators"].append(m)
+ elif isinstance(st, ast.Assert) and isinstance(st.test, ast.Compare) and len(st.test.ops) == 1 and \
+ isinstance(st.test.ops[0], (ast.Eq, ast.Is)):
+ left, right = st.test.left, st.test.comparators[0]
+ if not (isinstance(left, ast.Call) and isinstance(left.func, ast.Attribute)):
+ left, right = right, left
+ if not (isinstance(left, ast.Call) and isinstance(left.func, ast.Attribute)):
+ continue
+ holder = left.func.value
+ out = _lit(right, env) if not (isinstance(right, ast.Constant) and right.value is None) else None
+ qargs = tuple(_lit(a, env) for a in left.args)
+ if isinstance(holder, ast.Name) and holder.id in objs:
+ _real, run = objs[holder.id]
+ run["obs"].append((len(run["events"]), left.func.attr, qargs, out))
+ elif isinstance(holder, ast.Call) and isinstance(holder.func, ast.Name) and holder.func.id in classes:
+ mod, real = classes[holder.func.id]
+ d = found.setdefault(real, {"module": mod, "files": [], "ctor": len(holder.args), "mutators": [],
+ "runs": []})
+ d["runs"].append({"ctor": tuple(_lit(a, env) for a in holder.args), "events": [],
+ "obs": [(0, left.func.attr, qargs, out)]})
+ if str(rel) not in d["files"]:
+ d["files"].append(str(rel).replace(os.sep, "/"))
+ except Exception: # noqa: BLE001
+ continue
+ return found
+
+
+def _queries(d):
+ qs = []
+ for run in d["runs"]:
+ for _k, q, _qa, _o in run["obs"]:
+ if q not in qs:
+ qs.append(q)
+ return qs
+
+
+def _replay(init, trans, run, q):
+ """the query's state through the run's actions in order -> [(k, state)] at each observation, or None on an error"""
+ st = init(run["ctor"])
+ if st is ERR:
+ return None
+ out, k = [], 0
+ obs = sorted([(kk, o) for kk, qq, qa, o in run["obs"] if qq == q and not qa])
+ for kk, _o in obs:
+ while k < kk:
+ m, args = run["events"][k]
+ f = trans.get(m)
+ if f is None:
+ return None
+ st = f(st, args, run["ctor"])
+ if st is ERR:
+ return None
+ k += 1
+ out.append((kk, st))
+ return out
+
+
+def state_plan(cname, d, deadline):
+ """each query without arguments as a state carried through the ordered actions: an initial state from the fields, and a
+ transition for each action. Transitions shown directly (asked right before and right after one action) are composed as
+ goals of their own; the rest are searched together, every combination replayed through every ordered run. -> {q: plan}
+ or a reason"""
+ plans = {}
+ for q in _queries(d):
+ if any(qa for run in d["runs"] for _k, qq, qa, _o in run["obs"] if qq == q):
+ return None, "%s.%s takes arguments; its state through the actions is not one value" % (cname, q)
+ inits, direct = [], {m: [] for m in d["mutators"]}
+ for run in d["runs"]:
+ seen = {kk: o for kk, qq, _qa, o in run["obs"] if qq == q}
+ if 0 in seen:
+ inits.append((tuple(run["ctor"]), seen[0], None))
+ for kk, o in seen.items():
+ if kk >= 1 and kk - 1 in seen:
+ m, args = run["events"][kk - 1]
+ direct[m].append(((seen[kk - 1],) + tuple(args) + tuple(run["ctor"]), o, None))
+ plans[q] = {"inits": inits, "direct": direct}
+ return plans, None
+
+
+def compose_states(cname, d, job, deadline):
+ """compose every argument-free query of a class as a carried state -> (sources by query, imports, reason)"""
+ plans, why = state_plan(cname, d, deadline)
+ if plans is None:
+ return None, None, why
+ root = job["root"]
+ nf = d["ctor"]
+ fparams = param_names([(tuple(run["ctor"]), None, None) for run in d["runs"]])[:nf] if nf else []
+ out, imports = {}, set()
+ for q, pl in plans.items():
+ # the initial state: a constant, or composed from the fields
+ vals = {repr(o) for _a, o, _t in pl["inits"]}
+ if pl["inits"] and len(vals) == 1 and nf == 0:
+ init_v = pl["inits"][0][1]
+ init_src = repr(init_v)
+ consistent = all(same(o, init_v) for _a, o, _t in pl["inits"])
+ init_fn = (lambda c, v=init_v: v) if consistent else None
+ if nf and len({repr(a) for a, _o, _t in pl["inits"]}) > 1:
+ init_fn = None # different fields, one value: still try the fields below
+ else:
+ init_fn, init_src = None, None
+ if init_fn is None and nf and pl["inits"]:
+ g = {"name": "%s_start" % q, "params": fparams, "module": "m", "examples": pl["inits"], "module_text": "",
+ "root": root, "need": 0, "no_namewords": True}
+ r = compose_one(root, g, [], job.get("words", ""), [])
+ if r["status"] != "composed":
+ return None, None, "%s.%s right after it is made: %s" % (cname, q, r.get("gap"))
+ ns = {}
+ exec(compile("\n".join("import %s" % i for i in r["imports"]) + "\n" + r["source"], "init", "exec"), ns)
+ f0 = ns[g["name"]]
+ init_fn = lambda c, f0=f0: _ap(f0, *c)
+ init_src = "%s(%s)" % (g["name"], ", ".join(fparams))
+ imports |= set(r["imports"])
+ out.setdefault("_helpers", []).append(r["source"])
+ init_choices = None
+ if init_fn is None: # never asked right after it is made: starts tried with the rest
+ seen_t = ty_of_vals([o for run in d["runs"] for _k, qq, qa, o in run["obs"] if qq == q and not qa])
+ init_choices = [((lambda c, v=v: v), repr(v)) for v in (0, "", [], None)
+ if v is None or tyof(v) == seen_t or (is_num(tyof(v)) and is_num(seen_t)) or
+ (is_seq(tyof(v)) and is_seq(seen_t))] # only in the shape its answers have
+ init_choices += [((lambda c, i=i: c[i]), fparams[i]) for i in range(nf)
+ if all(tyof(run["ctor"][i]) == seen_t or (is_num(tyof(run["ctor"][i])) and is_num(seen_t))
+ for run in d["runs"])]
+ init_choices = [ic for ic in init_choices if ic[1] != "None"] or init_choices
+ init_fn, init_src = init_choices[0]
+ # transitions: composed from direct rows where the tests show them
+ trans, tsrc = {}, {}
+ missing = list(d["mutators"])
+ if missing:
+ found, why_ask = None, None
+ for ifn, isrc in (init_choices or [(init_fn, init_src)]):
+ f2, ask2 = _search_transitions(q, d, ifn, trans, missing, fparams, deadline, pl["direct"])
+ if ask2:
+ why_ask = ask2
+ if f2 is not None:
+ if found is not None:
+ why_ask = "%s.%s could start as %s or as %s; ask it right after the object is made" % (
+ cname, q, init_src, isrc)
+ break
+ found, init_fn, init_src = f2, ifn, isrc
+ if why_ask:
+ return None, None, why_ask
+ if found is None:
+ return None, None, ("the tests never show what %s does to %s.%s on its own, and no small transition for it "
+ "reproduces every ordered run; add an assert on %s after a %s" % (
+ ", ".join(missing), cname, q, q, missing[0]))
+ for m, (fn, src) in found.items():
+ trans[m] = fn
+ tsrc[m] = {"source": src, "imports": []}
+ for run in d["runs"]: # the whole plan replays every run, in order
+ got = _replay(init_fn, trans, run, q)
+ want = sorted([(kk, o) for kk, qq, qa, o in run["obs"] if qq == q and not qa])
+ if got is None or len(got) != len(want) or not all(same(a[1], b[1]) for a, b in zip(got, want)):
+ return None, None, "the state plan for %s.%s does not replay every run" % (cname, q)
+ out[q] = {"init": init_src, "trans": tsrc, "fparams": fparams}
+ return out, sorted(imports), None
+
+
+def _search_transitions(q, d, init_fn, trans, missing, fparams, deadline, direct=None):
+ """each action's transition: small programs of (state, the action's values, the fields). Where the tests show an action
+ on its own, its candidates are the programs that fit those rows; the rest come from states the runs pass through. The
+ combination is chosen by replaying every ordered run, the cheapest that reproduces every observation."""
+ direct = direct or {}
+ states, argsamp = [], {m: [] for m in missing}
+ for run in d["runs"]:
+ st = init_fn(run["ctor"])
+ if st is not ERR and st is not None and st not in states:
+ states.append(st)
+ for _k, qq, qa, o in run["obs"]:
+ if qq == q and not qa and o not in states:
+ states.append(o)
+ for m, a in run["events"]:
+ if m in argsamp and a not in argsamp[m]:
+ argsamp[m].append(a)
+ if not states:
+ return None, None
+ cands = {}
+ for m in missing:
+ drows = direct.get(m) or []
+ n = max((len(a) for a in argsamp[m]), default=0)
+ rows = [(r[0][0], tuple(r[0][1:1 + n])) for r in drows] # what the tests show of this action on its own
+ k_direct = len(rows)
+ rows += [(st, a) for st in states for a in (argsamp[m] or [()])][:40] # other states: so candidates stay apart
+ cb = Bank(len(rows), min(deadline, time.time() + 6), 20000, set(), [0, 1, -1, "", None, True, False, []], [],
+ namewords=[])
+ cb.add(X(("in", 0), [], tuple(st for st, _a in rows), 1, True, uses=1))
+ for i in range(n):
+ cb.add(X(("in", i + 1), [], tuple(a[i] for _st, a in rows), 1, True, uses=1 << (i + 1)))
+ for c in [0, 1, -1, "", None, True, False, []]:
+ cb.add(X(("const", c), [], tuple(c for _ in rows), 1, False))
+ for size in range(2, 5):
+ cb.grow(size)
+ want = [o for _r, o, _t in drows]
+ pool = sorted((x for x in cb.seen.values() if not x.dead and all(v is not ERR for v in x.val) and
+ all(same(v, o) for v, o in zip(x.val[:k_direct], want))), key=lambda x: x.cost)[:40]
+ if not pool:
+ return None, None
+ names = ["state"] + (["value"] if n == 1 else ["arg%d" % i for i in range(n)])
+ cands[m] = [((lambda st, a, c, x=x: evalx(x, [st] + list(a))),
+ "def %s_after_%s(%s):\n return %s\n" % (q, m, ", ".join(names + fparams), bare(code(x, names))), x)
+ for x in pool]
+ best, fits = None, []
+ for combo in itertools.product(*[cands[m] for m in missing]):
+ if time.time() > deadline:
+ break
+ tr = dict(trans)
+ for m, (fn, _src, _x) in zip(missing, combo):
+ tr[m] = fn
+ okc = True
+ for run in d["runs"]:
+ got = _replay(init_fn, tr, run, q)
+ want = sorted([(kk, o) for kk, qq, qa, o in run["obs"] if qq == q and not qa])
+ if got is None or len(got) != len(want) or not all(same(a[1], b[1]) for a, b in zip(got, want)):
+ okc = False
+ break
+ if okc:
+ cost = sum(x.cost for _f, _s, x in combo)
+ fits.append((cost, combo))
+ if best is None or cost < best[0]:
+ best = (cost, combo)
+ if best is None:
+ return None, None
+ # combinations that also fit and are as plain: replayed on new orders of the actions; a disagreement means ask
+ probes_ = []
+ for run in d["runs"]:
+ ev = run["events"]
+ for k in range(len(ev)):
+ probes_.append({"ctor": run["ctor"], "events": ev[:k] + ev[k + 1:] + ev[k:k + 1], "obs": [(len(ev), q, (), None)]})
+ probes_.append({"ctor": run["ctor"], "events": ev[::-1], "obs": [(len(ev), q, (), None)]})
+ probes_.append({"ctor": run["ctor"], "events": ev + ev, "obs": [(2 * len(ev), q, (), None)]})
+ def run_with(combo):
+ tr = dict(trans)
+ for m, (fn, _src, _x) in zip(missing, combo):
+ tr[m] = fn
+ return [(_replay(init_fn, tr, pr, q) or [(None, ERR)])[-1][1] for pr in probes_]
+ base = run_with(best[1])
+ for cost, combo in sorted(fits, key=lambda c: c[0]):
+ if combo is best[1] or cost > best[0] + AMBIG:
+ continue
+ if all(wraps(b_src.split("return ")[-1], o_src.split("return ")[-1]) for (_f, b_src, _x), (_g, o_src, _y) in zip(best[1], combo)):
+ continue # the same transitions with a wrapper added are not a rival
+ other = run_with(combo)
+ for pr, a, b in zip(probes_, base, other):
+ if a is not ERR and b is not ERR and not same(a, b):
+ srcs = [(s1, s2) for (_f1, s1, _x1), (_f2, s2, _x2) in zip(best[1], combo) if s1 != s2]
+ return None, ("the tests fit more than one way %s.%s changes: after %s it is %r one way and %r the other "
+ "(%s vs %s). Ask %s after an action the tests do not show on its own." % (
+ d.get("name", "the object"), q, ", ".join("%s(%s)" % (m, ", ".join(map(repr, a_)))
+ for m, a_ in pr["events"]), a, b,
+ srcs[0][0].split("return ")[-1].strip() if srcs else "?",
+ srcs[0][1].split("return ")[-1].strip() if srcs else "?", q))
+ return {m: (fn, src) for m, (fn, src, _x) in zip(missing, best[1])}, None
+
+
+def state_class_source(cname, d, plan):
+ """the class: each query's state set when it is made and changed by each action, in the order the actions come"""
+ fparams = next(iter(v["fparams"] for k, v in plan.items() if k != "_helpers"), [])
+ lines = []
+ for h in plan.get("_helpers", []):
+ lines += [h.rstrip("\n"), "", ""]
+ for q, pl in plan.items():
+ if q == "_helpers":
+ continue
+ for m, r in pl["trans"].items():
+ lines += [r["source"].rstrip("\n"), "", ""]
+ lines += ["class %s:" % cname, " def __init__(self%s):" % "".join(", " + f for f in fparams)]
+ for f in fparams:
+ lines.append(" self.%s = %s" % (f, f))
+ for q, pl in plan.items():
+ if q != "_helpers":
+ lines.append(" self._%s = %s" % (q, pl["init"]))
+ for m in d["mutators"]:
+ nargs = max((len(ev[1]) for run in d["runs"] for ev in run["events"] if ev[0] == m), default=0)
+ aparams = ["value"] if nargs == 1 else ["arg%d" % i for i in range(nargs)]
+ lines += ["", " def %s(self%s):" % (m, "".join(", " + a for a in aparams))]
+ for q, pl in plan.items():
+ if q != "_helpers" and m in pl["trans"]:
+ lines.append(" self._%s = %s_after_%s(self._%s%s%s)" % (
+ q, q, m, q, "".join(", " + a for a in aparams), "".join(", self." + f for f in fparams)))
+ if not any(q != "_helpers" and m in pl["trans"] for q, pl in plan.items()):
+ lines.append(" pass")
+ for q, pl in plan.items():
+ if q != "_helpers":
+ lines += ["", " def %s(self):" % q, " return self._%s" % q]
+ return "\n".join(lines) + "\n"
+
+
+def read_class_tests(root, only=None):
+ """{Class: {"module", "files", "ctor": arity, "mutators": [m...], "queries": {q: [(ctor args, {m: [args]}, q args, out)]}}}
+ from test files that make objects, call methods on them as statements (what is done to the object) and assert on what
+ other methods give (what it is asked)"""
+ root = Path(root)
+ found = {}
+ for p in sorted(root.rglob("*.py")):
+ rel = p.relative_to(root)
+ if any(part.startswith(".") or part in ("node_modules", "__pycache__", "venv", ".venv") for part in rel.parts):
+ continue
+ if not is_test_path(rel) or p.name.startswith("_hidden"):
+ continue
+ if only and p.name not in only and str(rel).replace(os.sep, "/") not in only:
+ continue
+ try:
+ tree = ast.parse(p.read_text(encoding="utf-8"))
+ except Exception: # noqa: BLE001
+ continue
+ classes = {}
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ImportFrom) and node.level == 0 and node.module and \
+ node.module.split(".")[0] not in sys.stdlib_module_names:
+ for a in node.names:
+ if a.name[:1].isupper():
+ classes[a.asname or a.name] = (node.module, a.name)
+ if not classes:
+ continue
+ bodies = [tree.body] + [n.body for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)]
+ for body in bodies:
+ objs, env = {}, {}
+ for st in body:
+ try:
+ if isinstance(st, ast.Assign) and len(st.targets) == 1 and isinstance(st.targets[0], ast.Name):
+ v = st.value
+ if isinstance(v, ast.Call) and isinstance(v.func, ast.Name) and v.func.id in classes and not v.keywords:
+ objs[st.targets[0].id] = (v.func.id, tuple(_lit(a, env) for a in v.args), {})
+ else:
+ try:
+ env[st.targets[0].id] = ast.literal_eval(v)
+ except Exception: # noqa: BLE001
+ pass
+ elif isinstance(st, ast.Expr) and isinstance(st.value, ast.Call) and \
+ isinstance(st.value.func, ast.Attribute) and isinstance(st.value.func.value, ast.Name) and \
+ st.value.func.value.id in objs:
+ _c, _ca, hist = objs[st.value.func.value.id]
+ args = tuple(_lit(a, env) for a in st.value.args)
+ hist.setdefault(st.value.func.attr, []).append(args[0] if len(args) == 1 else args)
+ elif isinstance(st, ast.Assert) and isinstance(st.test, ast.Compare) and len(st.test.ops) == 1 and \
+ isinstance(st.test.ops[0], (ast.Eq, ast.Is)):
+ left, right = st.test.left, st.test.comparators[0]
+ if not (isinstance(left, ast.Call) and isinstance(left.func, ast.Attribute)):
+ left, right = right, left
+ if not (isinstance(left, ast.Call) and isinstance(left.func, ast.Attribute)):
+ continue
+ holder = left.func.value
+ if isinstance(holder, ast.Name) and holder.id in objs:
+ cname, cargs, hist = objs[holder.id]
+ elif isinstance(holder, ast.Call) and isinstance(holder.func, ast.Name) and holder.func.id in classes:
+ cname, cargs, hist = holder.func.id, tuple(_lit(a, env) for a in holder.args), {}
+ else:
+ continue
+ out = _lit(right, env) if not (isinstance(right, ast.Constant) and right.value is None) else None
+ qargs = tuple(_lit(a, env) for a in left.args)
+ mod, real = classes[cname]
+ d = found.setdefault(real, {"module": mod, "files": [], "ctor": len(cargs), "mutators": [],
+ "queries": {}})
+ if str(rel) not in d["files"]:
+ d["files"].append(str(rel).replace(os.sep, "/"))
+ d["queries"].setdefault(left.func.attr, []).append(
+ (cargs, {m: list(v) for m, v in hist.items()}, qargs, out))
+ for m in hist:
+ if m not in d["mutators"]:
+ d["mutators"].append(m)
+ except Exception: # noqa: BLE001
+ continue
+ for d in found.values():
+ d["mutators"] = sorted(d["mutators"])
+ return found
+
+
+def _hist_name(m):
+ return m + ("_log" if m.endswith("s") else "s")
+
+
+def class_goals(cname, d):
+ """each query is a function of the object's fields and of the history of each thing done to it"""
+ goals = []
+ for q, rows in d["queries"].items():
+ ex = []
+ for cargs, hist, qargs, out in rows:
+ ex.append((tuple(cargs) + tuple(list(hist.get(m, [])) for m in d["mutators"]) + tuple(qargs), out, None))
+ if not ex or len({len(a) for a, _o, _t in ex}) != 1:
+ continue
+ nq = len(rows[0][2])
+ cparams = param_names([(tuple(r[0]), None, None) for r in rows]) if d["ctor"] else []
+ cparams = cparams[:d["ctor"]]
+ qparams = param_names([(tuple(r[2]), None, None) for r in rows]) if nq else []
+ qparams = [("%s_" % n if n in cparams else n) for n in qparams[:nq]]
+ params = cparams + [_hist_name(m) for m in d["mutators"]] + qparams
+ need = sum(1 << (len(params) - nq + i) for i in range(nq))
+ goals.append({"name": q, "params": params, "module": d["module"], "examples": ex, "module_text": "", "need": need,
+ "class": cname, "ctor_params": cparams, "query_params": qparams})
+ return goals
+
+
+def class_source(cname, d, goals, results):
+ """the class: its fields, a history for each thing done to it, and each query as composed"""
+ g0 = goals[0] if goals else {"ctor_params": [], "params": []}
+ cps = g0["ctor_params"]
+ lines = ["class %s:" % cname, " def __init__(self%s):" % "".join(", " + c for c in cps)]
+ for c in cps:
+ lines.append(" self.%s = %s" % (c, c))
+ for m in d["mutators"]:
+ lines.append(" self._%s = []" % _hist_name(m))
+ if not cps and not d["mutators"]:
+ lines.append(" pass")
+ for m in d["mutators"]:
+ lines += ["", " def %s(self, *args):" % m,
+ " self._%s.append(args[0] if len(args) == 1 else args)" % _hist_name(m)]
+ for g, r in zip(goals, results):
+ src = r["source"]
+ body = src.split("\n", 1)[1] if "\n" in src else ""
+ binds = ["%s = self.%s" % (c, c) for c in cps] + ["%s = self._%s" % (_hist_name(m), _hist_name(m)) for m in d["mutators"]]
+ lines += ["", " def %s(self%s):" % (g["name"], "".join(", " + q for q in g["query_params"]))]
+ lines += [" " + b for b in binds]
+ lines += [" " + ln if ln.strip() else ln for ln in body.rstrip("\n").split("\n")]
+ return "\n".join(lines) + "\n"
+
+
+def run_classes(job):
+ """compose every query of every class the tests use, then write each class whole (a class with a query not composed is
+ not written)"""
+ root = job["root"]
+ out = []
+ runs = read_object_runs(root, job.get("only"))
+ for cname, d in job["classes"].items():
+ rd = runs.get(cname)
+ if rd and len(rd["mutators"]) >= 2: # order between kinds of action matters: a state through them
+ plan, imports, why = compose_states(cname, rd, job, time.time() + 240)
+ if plan is None:
+ out.append({"class": cname, "status": "declined", "module": d["module"], "gap": why})
+ continue
+ out.append({"class": cname, "status": "composed", "module": d["module"], "imports": imports,
+ "source": state_class_source(cname, rd, plan), "mutators": rd["mutators"], "form": "state",
+ "queries": [{"name": q, "moves": ["state through %s" % ", ".join(rd["mutators"])], "size": None,
+ "examples": sum(1 for run in rd["runs"] for o in run["obs"] if o[1] == q),
+ "read_back": "replayed every ordered run"} for q in plan if q != "_helpers"]})
+ continue
+ goals = class_goals(cname, d)
+ if not goals:
+ out.append({"class": cname, "status": "declined", "gap": "the tests ask %s nothing I can read" % cname})
+ continue
+ r = run_goals({"root": root, "goals": goals, "words": job.get("words", ""), "exclude": [g["name"] for g in goals],
+ "net_scope": job.get("net_scope", [])})
+ res = r["results"]
+ bad = [x for x in res if x["status"] != "composed"]
+ if bad:
+ out.append({"class": cname, "status": "declined", "module": d["module"],
+ "gap": "; ".join("%s.%s: %s" % (cname, x["name"], x.get("gap", "")) for x in bad)})
+ continue
+ imports = sorted({i for x in res for i in x.get("imports", [])})
+ out.append({"class": cname, "status": "composed", "module": d["module"], "imports": imports,
+ "source": class_source(cname, d, goals, res),
+ "queries": [{"name": x["name"], "moves": x.get("moves"), "size": x.get("size"), "examples": x["examples"],
+ "read_back": x["read_back"]} for x in res],
+ "mutators": d["mutators"]})
+ return {"classes": out}
+
+
+# ================================================================ files and the network at the edge
+URL_RE = re.compile(r"^https?://[^\s/]+")
+EDGE_CAP = 2_000_000
+
+
+def _read_inside(root, p):
+ """a file of the project, read-only: inside the project, not a secret, not too large (else it raises)"""
+ if not isinstance(p, str) or not p or os.path.isabs(p) or ".." in Path(p).parts or SECRET.search(p):
+ raise ValueError("not a project file")
+ full = (Path(root) / p).resolve()
+ if not str(full).startswith(str(Path(root).resolve())) or not full.is_file() or full.stat().st_size > EDGE_CAP:
+ raise ValueError("not a project file")
+ return full.read_text(encoding="utf-8", errors="replace")
+
+
+EDGE_READS = ("readtext", "fetch") # the moves that read the world: their results are leaves for three-input moves
+
+
+def edge_leaves(goal, bank):
+ """an input that names files of the project: their text, lines or JSON, read once; an input of URLs inside the
+ conversation's network scope: the pages, fetched once each before the search (never during it)"""
+ ex = goal["examples"]
+ root = goal.get("root")
+ fetched = goal.get("fetched") or {}
+ leaves = {x.op[1]: x for x in bank.alive(1) if x.op[0] == "in"}
+ for i, leaf in leaves.items():
+ vals = [a[i] for a, _o, _t in ex]
+ if not all(isinstance(v, str) for v in vals):
+ continue
+ if root:
+ try:
+ texts = [_read_inside(root, v) for v in vals]
+ except Exception: # noqa: BLE001
+ texts = None
+ if texts is not None:
+ cache = dict(zip(vals, texts))
+
+ def rd(pth, cache=cache, root=root):
+ return cache[pth] if pth in cache else _read_inside(root, pth)
+ bank.add(X(("u", "readtext", "open({0}).read()", rd), [leaf], tuple(texts), 2, True,
+ bank.nw("file read open contents text whole")))
+ bank.add(X(("u", "readlines", "open({0}).read().splitlines()", lambda pth, rd=rd: rd(pth).splitlines()),
+ [leaf], tuple(t.splitlines() for t in texts), 2, True,
+ bank.nw("file lines line log read open each entries")))
+ try:
+ js = [json.loads(t) for t in texts]
+ bank.add(X(("u", "readjson", "json.load(open({0}))", lambda pth, rd=rd: json.loads(rd(pth))), [leaf],
+ tuple(js), 2, True, bank.nw("json load parse file records read"), ("json",)))
+ except Exception: # noqa: BLE001
+ pass
+ continue
+ if all(URL_RE.match(v) for v in vals) and all(v in fetched for v in vals):
+ def fe(u, fetched=fetched):
+ if u not in fetched:
+ raise ValueError("not fetched") # the search never reaches the network
+ return fetched[u]
+ bank.add(X(("u", "fetch", "urllib.request.urlopen({0}, timeout=10).read().decode()", fe), [leaf],
+ tuple(fetched[v] for v in vals), 2, True, bank.nw("page fetch download url web http get site read"),
+ ("urllib.request",)))
+
+
+def fetch_examples(g):
+ """the example URLs, fetched once each, only for hosts inside the conversation's network scope -> (pages, gap)"""
+ urls = []
+ for a, _o, _t in g["examples"]:
+ for v in a:
+ if isinstance(v, str) and URL_RE.match(v) and v not in urls:
+ urls.append(v)
+ if not urls:
+ return {}, None
+ from urllib.parse import urlparse
+ hosts = sorted({urlparse(u).hostname or "" for u in urls})
+ scope = set(g.get("net_scope") or [])
+ outside = [h for h in hosts if h not in scope]
+ if outside:
+ return None, ("this conversation has no network scope for %s, so nothing was fetched and nothing was written. Say "
+ "\"allow network to %s\" to let Oracle7 read the example pages (once each, while composing) and let this "
+ "project's runs reach that host." % (", ".join(outside), outside[0]))
+ import urllib.request
+ pages = {}
+ for u in urls[:12]:
+ try:
+ with urllib.request.urlopen(u, timeout=8) as r:
+ body = r.read(EDGE_CAP + 1)
+ if len(body) > EDGE_CAP:
+ return None, "the page %s is larger than %d bytes" % (u, EDGE_CAP)
+ pages[u] = body.decode("utf-8", errors="replace")
+ except Exception as e: # noqa: BLE001
+ return None, "the example page %s could not be read (%s)" % (u, str(e)[:80])
+ return pages, None
+
+
+def run_job(root, goals, words="", exclude=(), timeout=None, net_scope=(), classes=None):
+ """compose in a child process (the project's functions are imported there, never in the bench)"""
+ timeout = timeout or max(600, 150 + 220 * len(goals)) # each goal: its search, then its chains
+ job = {"root": str(root), "goals": goals, "words": words, "exclude": list(exclude), "net_scope": list(net_scope)}
+ if classes:
+ job["classes"] = classes
+ timeout = max(timeout, 150 + 220 * sum(len(d["queries"]) for d in classes.values()))
+ job["ends_at"] = time.time() + timeout # the job's own stop: a second (kept-part) pass must finish before it
+ with tempfile.TemporaryDirectory(prefix="o7job_") as d:
+ jp, op = os.path.join(d, "job.txt"), os.path.join(d, "out.txt")
+ open(jp, "w", encoding="utf-8").write(repr(job))
+ # 12.0 C14: the child is watched, not waited on blindly - a stop asked of the turn job that runs this (continuation's
+ # stop_requested) ends it at once, inside the stage, not after it
+ ct = sys.modules.get("continuation")
+ stop_asked = getattr(ct, "stop_requested", None)
+ # its output goes to files and the child is polled (pipes held open by the composer's own children would block a
+ # wait); it runs in its own process group, so a stop or a timeout ends the composer and everything it started
+ fo, fe = open(os.path.join(d, "stdout.txt"), "w"), open(os.path.join(d, "stderr.txt"), "w")
+ p = subprocess.Popen([sys.executable, "-I", str(Path(__file__).resolve()), jp, op], stdout=fo, stderr=fe, text=True,
+ cwd=d, env=__import__("runjail").env(root=d, PYTHONDONTWRITEBYTECODE="1", PYTHONHASHSEED="0", **_child_settings()),
+ start_new_session=(os.name != "nt"))
+
+ def _end():
+ try:
+ os.killpg(p.pid, 9) if os.name != "nt" else p.kill()
+ except (ProcessLookupError, PermissionError, OSError):
+ pass
+ p.wait()
+ fo.close()
+ fe.close()
+ t0 = time.time()
+ while p.poll() is None:
+ if stop_asked is not None and stop_asked():
+ _end()
+ return {"error": "stopped as asked, %.1f s into composing" % (time.time() - t0), "stopped": True}
+ if time.time() - t0 > timeout:
+ _end()
+ return {"error": "the composer ran past %d s" % timeout}
+ time.sleep(0.2)
+ fo.close()
+ fe.close()
+ r = subprocess.CompletedProcess(p.args, p.returncode, open(os.path.join(d, "stdout.txt")).read(),
+ open(os.path.join(d, "stderr.txt")).read())
+ if not os.path.exists(op):
+ if r.returncode < 0: # stopped by a signal: say which (9 is the system's memory stop)
+ return {"error": "the composer was stopped by signal %d%s" % (
+ -r.returncode, " (the system stops a process this way when memory runs out)" if r.returncode == -9 else "")}
+ return {"error": "the composer stopped (exit %d): %s" % (r.returncode, (r.stderr or "").strip()[-300:] or
+ "no message")}
+ return json.loads(open(op, encoding="utf-8").read())
+
+
+def _child_settings():
+ """round-3 R2: the composer's job child is Oracle7's own search, so it gets the settings it reads (its memory bound, the
+ formula organ, and the kept-parts store resolved here), and nothing else of Oracle7's state. Named gap: the child also
+ inspects project code, which can therefore see that one store file."""
+ import code_store
+ out = {k: os.environ[k] for k in ("O7_COMPOSE_MEM_MB", "ORACLE7_FORMULA_ORGAN") if k in os.environ}
+ out["ORACLE7_CODE_STORE"] = str(code_store.store_path())
+ return out
+
+
+def main():
+ # -I deliberately excludes the script directory. Reconnect the installed
+ # workbench before inspecting project code, so kept parts remain available
+ # and a project file named code_store.py cannot replace the native store.
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
+ import code_store as native_store
+ try:
+ import resource
+ cap = (MEM_MB + 1400) << 20
+ resource.setrlimit(resource.RLIMIT_AS, (cap, cap))
+ except (ImportError, ValueError, OSError):
+ pass
+ job = ast.literal_eval(open(sys.argv[1], encoding="utf-8").read())
+ out = run_classes(job) if job.get("classes") else run_goals(job)
+ out["connections"] = {"code_store": str(Path(native_store.__file__).resolve()),
+ "store_path": str(native_store.store_path())}
+ open(sys.argv[2], "w", encoding="utf-8").write(json.dumps(out))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/workbench/continuation.py b/workbench/continuation.py
new file mode 100644
index 0000000000000000000000000000000000000000..dcbae10a04a1d34003f9a2aa660d0f550fbafbee
--- /dev/null
+++ b/workbench/continuation.py
@@ -0,0 +1,696 @@
+"""continuation - the receive-and-continue specialist (12.0 C11). It takes part in every project turn of the bench: it receives
+the turn against the project of the environment that is open (never another's), decides whether going again can bring
+anything new, keeps the attempts and what each one showed, chooses a materially different next step when an attempt
+showed nothing new, runs a long turn as a job that stays observable and stoppable and survives a restart, and makes a
+checked capability of Oracle7's own discoverable, invokable and usable as a part of later projects.
+
+ WHAT IT TAKES IN the turn's words, the project kept for the open environment, the attempt record, the turn jobs,
+ Oracle7's code store and its registry of adopted capabilities
+ WHERE IT GOES the project's own record (.oracle7/project.json: attempts, the step chosen, the project id), the
+ bench's state (turn_jobs.json, capabilities.json), the reply's receipt (execution.continuation)
+
+THE ENVIRONMENT a project belongs to the environment it was received in (env key + a project id kept in its record);
+ opening another environment puts the project away under its own environment and brings back the one
+ kept for the new one. A project from another environment is never revised by this one's words.
+AN ATTEMPT every project turn is an attempt: its input fingerprint (the project's words, meanings, drops and
+ examples; the files it reads; the store and the registry) and its outcome signature (the state, the
+ holes, each requirement's status, what the judge saw). A retry whose inputs are the inputs of an
+ attempt that did not finish would show the same thing again: it is not run. A retry whose inputs
+ changed is run (a useful retry). A job whose log grows is progressing; one whose log is still is not.
+THE NEXT STEP when going again would show nothing new (or did), the next step is chosen from what the record shows,
+ never the step already taken for that same outcome: a part that fills the hole (a kept function, an
+ adopted capability that makes the missing file), a discriminating check (the command run and what it
+ printed against what the requirement wants), a changed hypothesis (a word read as the column it is
+ nearest to), a candidate repair (the traceback's line), and last a focused question naming the one hole.
+DONE is the judge's, requirement by requirement on what the program did; this module never says done.
+No language model."""
+import hashlib
+import json
+import os
+import re
+import shlex
+import subprocess
+import sys
+import threading
+import time
+import uuid
+from pathlib import Path
+
+NL = chr(10)
+WB = Path(__file__).resolve().parent
+
+
+def _home():
+ import bench
+ return bench.HOME
+
+
+def _sha(obj):
+ return hashlib.sha256(json.dumps(obj, sort_keys=True, default=str).encode()).hexdigest()[:16]
+
+
+def _load(p, default):
+ try:
+ return json.loads(Path(p).read_text(encoding="utf-8"))
+ except Exception: # noqa: BLE001
+ return default
+
+
+def _save(p, obj):
+ p = Path(p)
+ p.parent.mkdir(parents=True, exist_ok=True)
+ tmp = p.with_name(p.name + ".tmp%d.%d" % (os.getpid(), threading.get_ident()))
+ try:
+ tmp.write_text(json.dumps(obj, indent=1, default=str), encoding="utf-8")
+ # Windows can briefly deny replacement while a reader/scanner has the
+ # target open. Retry the same complete bytes, never a partial write.
+ for delay in (0, .01, .02, .04, .08, .16, .32, .64):
+ if delay:
+ time.sleep(delay)
+ try:
+ os.replace(tmp, p)
+ break
+ except PermissionError:
+ if os.name != "nt" or delay == .64:
+ raise
+ finally:
+ if tmp.exists():
+ try:
+ tmp.unlink()
+ except OSError:
+ pass
+
+
+# ---------------------------------------------------------------- the environment's project
+def switch(turn, new_env_d):
+ """called as an environment is opened: the project of the old environment is put away under it, the one kept for the
+ new environment (in this conversation) comes back; candidates of Oracle7 itself are not an environment's"""
+ import bench
+ old = turn.s.get("env")
+ projs = turn.s.setdefault("projects", {})
+ works = turn.s.setdefault("works", {})
+ focuses = turn.s.setdefault("environment_focus", {})
+ cur = turn.s.get("project")
+ if old:
+ old_key = bench.Env(old).key
+ if cur is not None:
+ projs[old_key] = cur
+ work = turn.s.get("work")
+ if work is not None and work.get("env") == old_key:
+ works[old_key] = work
+ if turn.s.get("focus") in ("project", "work"):
+ focuses[old_key] = turn.s["focus"]
+ key = bench.Env(new_env_d).key
+ turn.s["project"] = projs.get(key)
+ turn.s["work"] = works.get(key)
+ turn.s["focus"] = focuses.get(key) or ("project" if projs.get(key) else "work" if works.get(key) else None)
+ return turn.s["project"]
+
+
+def bind(turn, env):
+ """the project kept for this environment, or None; a project received in another environment is put away under it"""
+ cur = turn.s.get("project")
+ if cur is not None and cur.get("env") not in (None, env.key):
+ turn.s.setdefault("projects", {})[cur["env"]] = cur
+ turn.s["project"] = turn.s["projects"].get(env.key)
+ cur = turn.s["project"]
+ return cur
+
+
+def stamp(shape, env):
+ """the project's identity: its id (kept for its life) and the environment it belongs to"""
+ shape.setdefault("pid", uuid.uuid4().hex[:12])
+ shape["env"] = env.key
+ shape["env_root"] = env.root
+ return shape
+
+
+# ---------------------------------------------------------------- attempts
+def _files_of(shape, root):
+ names = set()
+ import project as PJ
+ for c in shape.get("clauses") or []:
+ names.update(PJ.DATA.findall(c))
+ if shape.get("module"):
+ names.add(shape["module"])
+ out = {}
+ for n in sorted(names):
+ p = Path(root) / n
+ try:
+ st = p.stat()
+ digest = hashlib.sha256()
+ with p.open("rb") as stream:
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
+ digest.update(chunk)
+ out[n] = [st.st_size, st.st_mtime_ns, digest.hexdigest()]
+ except OSError:
+ out[n] = None
+ return out
+
+
+def _store_mark():
+ try:
+ import code_store as CS
+ p = CS.store_path()
+ st = p.stat()
+ return [st.st_size, int(st.st_mtime)]
+ except Exception: # noqa: BLE001
+ return None
+
+
+def fingerprint(shape, root, authority=None):
+ """what an attempt depends on: the project's words and fills, the files it reads, the store, the registry, and the
+ authority it ran under (12.0 C31: which hosts it may reach, whether it may change files). A grant changes what the
+ same words can do, so it reopens the obligation; an unchanged retry still matches and is not run again."""
+ keep = {k: shape.get(k) for k in ("clauses", "dropped", "meanings", "examples", "use", "module", "entries",
+ "source_fills", "scope_fills")}
+ return _sha([keep, _files_of(shape, root), _store_mark(), _load(_reg_path(), []), authority or {}])
+
+
+def outcome_sig(reply, shape):
+ ex = reply.get("execution") or {}
+ holes = sorted(h.get("text", "")[:200] for h in (shape.get("holes_kept") or []))
+ reqs = sorted((r.get("id"), r.get("status")) for r in ex.get("requirements") or [])
+ judged = [ln for ln in (reply.get("response") or "").splitlines() if ln.startswith(" - ")][:20]
+ return _sha([ex.get("state"), holes, reqs, judged])
+
+
+def record(shape, text, reply, fp, cont=None):
+ """one attempt kept in the project's record, numbered by the project's own sequence (never by a window's length)"""
+ shape["seq"] = int(shape.get("seq") or 0) + 1
+ a = {"seq": shape["seq"], "t": time.time(), "text": text, "state": (reply.get("execution") or {}).get("state"),
+ "fp": fp, "sig": outcome_sig(reply, shape), "cont": cont}
+ shape.setdefault("attempts", []).append(a)
+ if len(shape["attempts"]) > 300: # the record keeps its first and its latest; the sequence goes on
+ shape["attempts"] = shape["attempts"][:20] + shape["attempts"][-280:]
+ return a
+
+
+UNFINISHED = ("missing", "failed", "interrupted", "blocked", "refused")
+
+
+def unchanged_retry(shape, root, text, authority=None):
+ """the attempt whose inputs this turn would repeat exactly, when that attempt did not finish; else None"""
+ import project as PJ
+ if not PJ.CONTINUE.match(text.strip()):
+ return None
+ att = shape.get("attempts") or []
+ if not att or att[-1].get("state") not in UNFINISHED:
+ return None
+ return att[-1] if att[-1].get("fp") == fingerprint(shape, root, authority) else None
+
+
+def same_outcome_run(shape):
+ """how many attempts in a row ended with the same outcome (1 = the latest is new)"""
+ att = shape.get("attempts") or []
+ n = 0
+ for a in reversed(att):
+ if att and a.get("sig") == att[-1].get("sig"):
+ n += 1
+ else:
+ break
+ return n
+
+
+# ---------------------------------------------------------------- the next step
+def _words(s):
+ return [w for w in re.findall(r"[a-z][a-z0-9_]+", (s or "").lower()) if len(w) > 2]
+
+
+def _near(word, options):
+ """the option nearest a word by shared letters in order (a column a word may have meant)"""
+ import difflib
+ m = difflib.get_close_matches(word.lower(), [o.lower() for o in options], n=1, cutoff=0.72)
+ if not m:
+ return None
+ return next(o for o in options if o.lower() == m[0])
+
+
+def _parts_for(hole, shape):
+ """a kept part that fills this hole: an adopted capability that makes the missing file, or a kept function whose words
+ meet the hole's words. -> (kind, record) or None"""
+ if hole.get("kind") == "world" and hole.get("file"):
+ for c in capabilities():
+ if hole["file"] in (c.get("outputs") or []):
+ return "capability", c
+ ws = set(hole.get("words") or []) | set(_words(hole.get("name", ""))) | set(_words(hole.get("col", "")))
+ if not ws:
+ return None
+ try:
+ import code_store as CS
+ best = None
+ for e in CS.load():
+ ew = set(_words(e.get("name", ""))) | {w.lower() for w in (e.get("words") or [])}
+ hit = len(ws & ew)
+ if hit and (best is None or hit > best[0]):
+ best = (hit, e)
+ if best:
+ return "function", best[1]
+ except Exception: # noqa: BLE001
+ pass
+ return None
+
+
+def _columns(shape, root):
+ import project as PJ
+ cols = []
+ for c in shape.get("clauses") or []:
+ for f in PJ.DATA.findall(c):
+ try:
+ t = PJ.read_table(root, f)
+ cols += list((t or {}).get("columns") or [])
+ except Exception: # noqa: BLE001
+ continue
+ return list(dict.fromkeys(cols))
+
+
+def _run_entry(shape, root, runenv=None):
+ """the project's first command run once, its exit and last lines: the discriminating check"""
+ ents = shape.get("entries") or {}
+ name = next((n for n, e in ents.items() if "PORT" not in e.get("args", [])), None)
+ if not name or not shape.get("module") or not (Path(root) / shape["module"]).is_file():
+ return None
+ cmd = [sys.executable, shape["module"], name] + list(ents[name].get("args") or [])
+ try:
+ r = subprocess.run(cmd, cwd=root, capture_output=True, text=True, timeout=60, env=runenv)
+ return {"cmd": " ".join(shlex.quote(x) for x in ["python3"] + cmd[1:]), "exit": r.returncode,
+ "out": (r.stdout + r.stderr).strip().splitlines()[-12:]}
+ except subprocess.TimeoutExpired:
+ return {"cmd": " ".join(cmd[1:]), "exit": None, "out": ["ran past 60 s and was stopped"]}
+
+
+def choose(turn, shape, root, reply, used=(), runenv=None):
+ """the next step when an attempt showed nothing new: the first kind the record supports that was not already taken for
+ this outcome. -> {"kind", "text", "do"?: what was done}"""
+ holes = list(shape.get("holes_kept") or [])
+ resp = reply.get("response") or ""
+ tried = set(used)
+ # 1. a part that fills a hole
+ if "part" not in tried:
+ for h in holes:
+ got = _parts_for(h, shape)
+ if not got:
+ continue
+ kind, rec = got
+ if kind == "capability" and turn is not None and turn.env is not None and turn.s.get("authority") == "change":
+ ran = invoke(rec, turn.env.root, why="the project's missing %s" % h["file"])
+ if ran["ok"]:
+ return {"kind": "part", "rerun": True,
+ "text": "%s was missing; my adopted capability %s makes it (sha %s, judged when it was adopted), so I "
+ "ran it here: %s, exit 0. Going on with the project." % (
+ h["file"], rec["name"], rec["sha256"][:12], ran["cmd"])}
+ return {"kind": "part", "text": "%s is missing; my capability %s makes it, but running it here failed (exit %s): %s" % (
+ h["file"], rec["name"], ran["exit"], " / ".join(ran["out"][-3:]))}
+ if kind == "function":
+ return {"kind": "part", "text": "For %s, my store keeps %s (sha %s, from %s), whose words meet this one's. If it is "
+ "what you mean, say \"%s means %s\" or give two examples." % (
+ h.get("req") or h.get("file") or "the hole", rec["name"], rec["sha256"][:12],
+ rec.get("project") or "earlier work",
+ (h.get("words") or [rec["name"]])[0], rec["name"].replace("_", " "))}
+ # 2. a discriminating check: the command run once, against what the judge wanted
+ if "check" not in tried and (reply.get("execution") or {}).get("state") == "failed":
+ r = _run_entry(shape, root, runenv)
+ if r:
+ want = [ln.strip() for ln in resp.splitlines() if ln.startswith(" - ")][:3]
+ return {"kind": "check", "text": "I ran `%s` once more to see what it does, not to retry: exit %s; it printed: %s. What the "
+ "requirements wanted and did not get: %s." % (
+ r["cmd"], r["exit"], " | ".join(r["out"][-6:]) or "nothing",
+ "; ".join(w.lstrip("- ") for w in want) or "see the judge lines above")}
+ # 3. a changed hypothesis: an unread word read as the column it is nearest to
+ if "hypothesis" not in tried:
+ cols = _columns(shape, root)
+ for h in holes:
+ for w in h.get("words") or []:
+ c = _near(w, cols)
+ if c and c.lower() != w.lower():
+ return {"kind": "hypothesis", "text": "A different reading: '%s' may be the column '%s' of the table (the "
+ "nearest by its letters). If so, say \"%s means %s\"; if not, say what "
+ "it means." % (w, c, w, c)}
+ # 4. a candidate repair: the traceback's own line
+ if "repair" not in tried:
+ tb = re.findall(r'File "([^"]+)", line (\d+)', resp)
+ if tb:
+ f, ln = tb[-1]
+ return {"kind": "repair", "text": "The program stopped at %s line %s. Say \"fix %s\" and I compose a repair for that line "
+ "against the failing requirement." % (os.path.basename(f), ln, os.path.basename(f))}
+ # 5. a focused question: the one hole first in line, and the forms an answer can take
+ if holes:
+ h = holes[0]
+ forms = {"unread": "\"%s means ...\" (rows, a column, an operation), or \"drop %s\"" % (
+ (h.get("words") or ["it"])[0], (h.get("req") or "R?")[1:]),
+ "world": "add %s to the folder and say \"it's there now\"" % (h.get("file") or "the table"),
+ "derive": "two or three examples (\"3 -> 9\")",
+ "compose": "examples of other kinds of value (a zero, a negative, a word)",
+ "outcome": "the file to write instead, or \"drop\" with its number"}.get(h.get("kind"), "what it means, or drop it")
+ return {"kind": "ask", "text": "One thing stands in the way: %s It can be answered as %s." % (
+ h.get("text", "").rstrip(".") + ".", forms)}
+ return {"kind": "ask", "text": "The project did not change and I have no new step to take; tell me what to look at."}
+
+
+def used_for(shape, sig):
+ """the steps already taken after attempts that ended with this outcome"""
+ return {a.get("cont") for a in shape.get("attempts") or [] if a.get("sig") == sig and a.get("cont")}
+
+
+# ---------------------------------------------------------------- turn jobs: long work observable, stoppable, kept
+_TJ = threading.RLock()
+_LIVE = {} # job id -> {"thread", "stop": Event, "result"}
+_LOCAL = threading.local()
+
+
+class Stopped(BaseException):
+ """a stop asked for (not an error: the routes' own error handling must not turn it into a reply)"""
+
+
+def _tj_path():
+ return _home() / "turn_jobs.json"
+
+
+def _tj_all():
+ with _TJ:
+ # An unreadable existing ledger is not an empty ledger. Treating it as
+ # empty could forget a running request or erase earlier completions.
+ for delay in (0, .01, .02, .04, .08, .16, .32, .64):
+ if delay:
+ time.sleep(delay)
+ try:
+ jobs = json.loads(_tj_path().read_text(encoding="utf-8"))
+ break
+ except FileNotFoundError:
+ jobs = []
+ break
+ except PermissionError:
+ if os.name != "nt" or delay == .64:
+ raise
+ if not isinstance(jobs, list):
+ raise ValueError("the turn receipt file is not a job list")
+ # A completed worker remains completed if its metadata write failed.
+ # Do not let a stale on-disk 'running' record block this process forever.
+ return [dict(_LIVE.get(j["id"], {}).get("terminal") or j) for j in jobs]
+
+
+def _tj_put(j):
+ with _TJ:
+ live = _LIVE.get(j["id"])
+ old = (live or {}).get("terminal")
+ if old and old.get("state") != "running" and j.get("state") == "running":
+ # A poll/stage snapshot taken before completion may only acknowledge
+ # it; it cannot resurrect a finished worker.
+ j = dict(old, **{key: j[key] for key in ("shown", "told", "resumed", "stop_asked") if key in j})
+ # Publish the known execution outcome before any filesystem operation,
+ # including the read needed to merge this receipt into the ledger.
+ if live is not None:
+ live["record"] = dict(j)
+ if j.get("state") != "running":
+ live["terminal"] = dict(j)
+ try:
+ existing = _tj_all()
+ old = next((x for x in existing if x["id"] == j["id"]), None)
+ if old and old.get("state") != "running" and j.get("state") == "running":
+ j = dict(old, **{key: j[key] for key in ("shown", "told", "resumed", "stop_asked") if key in j})
+ js = [x for x in existing if x["id"] != j["id"]] + [j]
+ js.sort(key=lambda entry: entry.get("t", 0))
+ _save(_tj_path(), js[-200:])
+ if live is not None:
+ live.pop("storage_error", None)
+ if isinstance(live.get("terminal"), dict): # 12.0 C29: a later save that succeeds clears the earlier warning
+ live["terminal"].pop("storage_error", None)
+ r = live.get("result")
+ if isinstance(r, dict) and (r.get("turn_receipt") or {}).get("saved") is False:
+ r["turn_receipt"] = {"saved": True}
+ r["response"] = str(r.get("response", "")).replace(_RECEIPT_NOTE, "")
+ except (OSError, ValueError) as error:
+ if live is None or j.get("state") == "running":
+ raise
+ # The execution outcome is known, but its durability is not. Keep
+ # that distinction visible instead of reporting a phantom worker.
+ live["storage_error"] = repr(error)
+ live["terminal"]["storage_error"] = repr(error)
+ return j
+
+
+_RECEIPT_NOTE = "\n\nThe work returned, but its turn receipt could not be saved. The completion is available in this running session."
+
+
+def _receipt_note(live):
+ r = live.get("result")
+ if r is not None and live.get("storage_error"):
+ if "turn_receipt" not in r:
+ r["response"] = str(r.get("response", "")) + _RECEIPT_NOTE
+ r["turn_receipt"] = {"saved": False, "error": live["storage_error"]}
+
+
+def _tj_mark_interrupted():
+ """on load: a turn job left running by an earlier process was interrupted by its end (said so, never 'running' forever)"""
+ try:
+ js = _tj_all()
+ except Exception: # noqa: BLE001
+ return
+ ch = False
+ for j in js:
+ if j.get("state") == "running" and j.get("pid") != os.getpid():
+ j["state"], j["t_end"], ch = "interrupted", time.time(), True
+ if ch:
+ _save(_tj_path(), js)
+
+
+def stage(name):
+ """the stage a turn job is at (shown by status); a stop asked for is honoured here, between stages"""
+ jid = getattr(_LOCAL, "jid", None)
+ if not jid:
+ return
+ live = _LIVE.get(jid)
+ if live and live["stop"].is_set():
+ raise Stopped(name)
+ j = next((x for x in _tj_all() if x["id"] == jid), None)
+ if j:
+ j["stage"], j["t_stage"] = name, time.time()
+ j.setdefault("stages", []).append([name, round(time.time() - j["t"], 2)])
+ _tj_put(j)
+
+
+def stop_requested():
+ """C14: has a stop been asked of the turn job this thread runs (for work inside a stage, like the composer's child)"""
+ live = _LIVE.get(getattr(_LOCAL, "jid", None) or "")
+ return bool(live and live["stop"].is_set())
+
+
+def active(sid):
+ """the conversation's newest turn job, if it is running or finished and not yet shown"""
+ js = [j for j in _tj_all() if j.get("sid") == sid]
+ if not js:
+ return None
+ j = max(js, key=lambda entry: entry.get("t", 0))
+ # C11b: a request cut off or stopped stays one to take up again until it is taken up ("resumed"); being told about it
+ # ("told") does not use that up (accept38 H8, first run: a status before "continue" lost the request)
+ if j["state"] == "running" or (j["state"] == "finished" and not j.get("shown")) or \
+ (j["state"] in ("interrupted", "stopped") and not j.get("resumed")):
+ return j
+ return None
+
+
+STATUSQ = re.compile(r"(?i)^\s*(?:ok(?:ay)?[\s,]*)?(?:status|where are we(?: at| now)?|how(?:'s| is) it going|is it done\??|"
+ r"what(?:'s| is) (?:happening|running)|progress)\s*[?.!]*$")
+STOPQ = re.compile(r"(?i)^\s*(?:stop|stop it|stop that|cancel(?: it| that| the job)?|abort|halt)\s*[.!]*$")
+
+
+def _job_text(j):
+ st = ", ".join("%s at %.1fs" % (s, t) for s, t in (j.get("stages") or [])[-6:])
+ return "job %s (\"%s\"): %s%s, started %ds ago%s" % (
+ j["id"], j["text"][:80], j["state"], (" at " + j["stage"]) if j.get("stage") else "", int(time.time() - j["t"]),
+ ("; stages: " + st) if st else "")
+
+
+def intercept(sid, text):
+ """before a turn: while this conversation has a turn job running, status and stop are answered from its record and any
+ other words wait (so two turns never change one project at once); a finished job's result is given once"""
+ j = active(sid)
+ if j is None:
+ return None
+ t = text.strip()
+ if j["state"] == "running":
+ if STOPQ.match(t):
+ live = _LIVE.get(j["id"])
+ if live:
+ live["stop"].set()
+ j["stop_asked"] = time.time()
+ _tj_put(j)
+ return {"status": "offered", "path": "turn:stop", "response": "Stopping %s at its next stage (it is at %s). What it "
+ "kept so far stays kept; \"continue\" goes on from there." % (j["id"], j.get("stage") or "its start"),
+ "execution": {"state": "running", "job": j["id"], "stop": True}}
+ return {"status": "offered", "path": "turn:running", "response": "Still working: %s. Say \"stop\" to stop it at its next "
+ "stage; other requests wait until it is done." % _job_text(j),
+ "execution": {"state": "running", "job": j["id"], "stage": j.get("stage")}}
+ import project as PJ
+ if j["state"] in ("interrupted", "stopped") and PJ.CONTINUE.match(t):
+ j["shown"] = j["resumed"] = True # the request that was cut off, taken up again from its own words
+ _tj_put(j)
+ return {"resume": j}
+ if j["state"] == "interrupted" and STATUSQ.match(t):
+ j["told"] = True
+ _tj_put(j)
+ return {"status": "hole", "path": "turn:interrupted", "response": "%s - it was cut off (the harness stopped while it ran), "
+ "so what it would have finished is not known. Say \"continue\" and I take that request up again from its "
+ "own words." % _job_text(j), "execution": {"state": "interrupted", "job": j["id"]}}
+ if j["state"] in ("finished", "stopped") and STATUSQ.match(t) and not j.get("told"):
+ j["shown"] = True
+ j["told"] = True
+ _tj_put(j)
+ r = dict(j.get("result") or {"status": "hole", "response": "(no result was kept)", "path": "turn:lost"})
+ r["response"] = "%s finished:%s%s" % (_job_text(j), NL, r.get("response", ""))
+ return r
+ return None
+
+
+def run_turn(fn, sid, text, deadline):
+ """a turn that may run long: started as a job; its reply if it ends within the deadline, else the job's id, and the
+ result kept for status"""
+ jid = uuid.uuid4().hex[:10]
+ j = {"id": jid, "sid": sid, "text": text, "t": time.time(), "state": "running", "pid": os.getpid(), "stage": "received"}
+ try:
+ _tj_put(j)
+ except (OSError, ValueError) as error:
+ return {"status": "hole", "path": "turn:storage", "response": "The work did not start because its turn receipt could not be saved: %s" % error,
+ "execution": {"state": "failed", "started": False}}
+ live = {"stop": threading.Event(), "result": None}
+ _LIVE[jid] = live
+
+ def work():
+ _LOCAL.jid = jid
+ try:
+ r = fn()
+ state = "finished"
+ except Stopped as e:
+ r = {"status": "hole", "path": "turn:stopped", "response": "Stopped at %s, as asked. The project is kept as it was "
+ "before that stage; \"continue\" goes on." % e, "execution": {"state": "interrupted", "job": jid}}
+ state = "stopped"
+ except Exception as e: # noqa: BLE001
+ r = {"status": "hole", "path": "turn:error", "response": "That did not complete: %r" % e, "execution": {"state": "failed"}}
+ state = "finished"
+ live["result"] = r
+ jj = dict(live.get("record") or j)
+ jj.update(state=state, t_end=time.time(), result=r)
+ _tj_put(jj)
+ _receipt_note(live)
+
+ th = threading.Thread(target=work, daemon=True)
+ th.start()
+ th.join(deadline)
+ if not th.is_alive():
+ jj = dict(live.get("terminal") or j)
+ jj["shown"] = True
+ _tj_put(jj)
+ _receipt_note(live)
+ return live["result"]
+ return {"status": "offered", "path": "turn:running", "response": "This is taking longer than %d s, so it goes on as job %s "
+ "(now at %s). Say \"status\" to see it or get its result, \"stop\" to stop it at its next stage." % (
+ deadline, jid, (next((x for x in _tj_all() if x["id"] == jid), j)).get("stage")),
+ "execution": {"state": "running", "job": jid}}
+
+
+try:
+ _tj_mark_interrupted()
+except Exception: # noqa: BLE001
+ pass
+
+
+# ---------------------------------------------------------------- capabilities of Oracle7's own (selfdev adopts, here kept)
+def _reg_path():
+ return WB / "self" / "capabilities.json"
+
+
+def capabilities():
+ return [c for c in _load(_reg_path(), []) if not c.get("retired")]
+
+
+def register(cap):
+ """a checked capability in the registry the head reads: what it is, how it is called, what it reads and makes, its source
+ sha, its dependencies, the checks it passed, and (later) each use"""
+ reg = [c for c in _load(_reg_path(), []) if c["name"] != cap["name"]]
+ cap.setdefault("uses", [])
+ cap["registered"] = time.time()
+ reg.append(cap)
+ _save(_reg_path(), reg)
+ return cap
+
+
+def _note_use(name, use):
+ reg = _load(_reg_path(), [])
+ for c in reg:
+ if c["name"] == name:
+ c.setdefault("uses", []).append(use)
+ c["uses"] = c["uses"][-200:]
+ _save(_reg_path(), reg)
+
+
+def invoke(cap, cwd, why=""):
+ """run a capability (its own command, in cwd: what it makes lands there); the use is recorded with its outcome"""
+ t = time.time()
+ try:
+ r = subprocess.run([sys.executable, cap["path"]] + cap["argv"], cwd=cwd, capture_output=True, text=True, timeout=300)
+ ok, code, out = r.returncode == 0, r.returncode, (r.stdout + r.stderr).strip().splitlines()
+ except subprocess.TimeoutExpired:
+ ok, code, out = False, None, ["ran past 300 s and was stopped"]
+ made = [f for f in cap.get("outputs") or [] if (Path(cwd) / f).is_file() and (Path(cwd) / f).stat().st_mtime >= t - 1]
+ _note_use(cap["name"], {"t": t, "cwd": str(cwd), "why": why, "exit": code, "made": made})
+ return {"ok": ok and all(f in made for f in cap.get("outputs") or []), "exit": code, "out": out[-40:], "made": made,
+ "cmd": "python3 %s %s" % (cap["path"], " ".join(cap["argv"]))}
+
+
+LISTQ = re.compile(r"(?i)\b(?:what|which)\b.*\b(?:have you (?:added|built|adopted) (?:to|into) yourself|capabilities (?:have )?you "
+ r"(?:built|added|adopted)|did you (?:add|build) (?:to|into) yourself|(?:own|adopted|new) capabilit(?:y|ies))\b")
+
+
+def capability_for(text, caps=None):
+ """the adopted capability this turn calls by its own words, or None; nothing is run (the conversation's ownership
+ check asks this before any receiver takes the turn)"""
+ caps = capabilities() if caps is None else caps
+ t = (text or "").strip()
+ import project as PJ
+ if PJ.BUILD.search(t) or PJ.ENTRY.search(t) or re.search(r"(?i)\b(?:in)?to\s+(?:yourself|oracle7)\b", t):
+ return None # C11c: a turn that builds (or rebuilds) is a project, not a call
+ tw = set(_words(t))
+ best = None
+ for c in caps:
+ key = set(c.get("words") or [])
+ if not key:
+ continue
+ hit = len(tw & key) / len(key)
+ named = c["name"].lower() in t.lower() or c["entry"].lower() in tw
+ if (hit >= 0.6 or (named and hit >= 0.3)) and (best is None or hit > best[0]):
+ best = (hit, c)
+ return best[1] if best else None
+
+
+def capability_turn(text, sid):
+ """the head's door to Oracle7's adopted capabilities: listed with their records, or one invoked by its own words"""
+ caps = capabilities()
+ t = text.strip()
+ if LISTQ.search(t):
+ if not caps:
+ return {"status": "answered", "path": "self:capabilities", "response": "I have adopted no capability of my own yet.",
+ "execution": {"state": "read"}}
+ lines = ["Capabilities I built into myself and adopted, each judged before it was adopted:"]
+ for c in caps:
+ lines.append("- %s: %s. Called by `%s %s`; reads %s; makes %s; source sha %s; checks: %s; used %d time%s%s." % (
+ c["name"], c["request"][:160], os.path.basename(c["path"]), " ".join(c["argv"]),
+ ", ".join(c.get("reads") or []) or "nothing", ", ".join(c.get("outputs") or []) or "printed lines",
+ c["sha256"][:12], "; ".join(c.get("checks") or []), len(c.get("uses") or []),
+ "" if len(c.get("uses") or []) == 1 else "s",
+ (" (last: %s)" % c["uses"][-1].get("why", "")[:80]) if c.get("uses") else ""))
+ return {"status": "answered", "path": "self:capabilities", "response": NL.join(lines),
+ "execution": {"state": "read", "capabilities": [c["name"] for c in caps]}}
+ c = capability_for(t, caps)
+ if c is None:
+ return None
+ import bench
+ cwd = bench.Turn(sid).s.get("env") or {}
+ cwd = cwd.get("root") if cwd.get("kind") == "folder" and bench.Turn(sid).s.get("authority") == "change" else str(WB / "self" / c["name"])
+ ran = invoke(c, cwd, why=t[:200])
+ body = NL.join(" " + x for x in ran["out"]) or " (nothing printed)"
+ return {"status": "answered" if ran["ok"] else "hole", "path": "self:capability:" + c["name"],
+ "response": "That is my capability %s (adopted, sha %s): `%s` in %s, exit %s.%s%s%s" % (
+ c["name"], c["sha256"][:12], ran["cmd"], cwd, ran["exit"], NL, body,
+ (NL + "It made: " + ", ".join(ran["made"])) if ran["made"] else ""),
+ "execution": {"state": "passed" if ran["ok"] else "failed", "capability": c["name"], "sha256": c["sha256"],
+ "files": ran["made"]}}
diff --git a/workbench/converse/__init__.py b/workbench/converse/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..256599fa62b3d9c1d33ad4ad7a5d24a56cba7577
--- /dev/null
+++ b/workbench/converse/__init__.py
@@ -0,0 +1,29 @@
+"""converse - 11.5: the turn loop inside the head's own chat (constitution art. 4: one front door).
+
+The head answers first. Where it declines, or where what it has is a lecture rather than an answer, the turn is read into
+forms (turn_kernel: K8 + the forms grown from the dialogue corpus), the nearest scenes are found by role-aware resonance on
+the seed algebra (resonance.py), and the reply is the scene's next move with its places bound and proved (compose_reply_v9),
+cited to the record it came from. An open place is a question back to the user (the named hole). No language model.
+Everything here was measured first in release115/PREREG_CONVERSATION.md.
+
+This package carries its own data (data/): the move index, the scenes, the induced forms, the scene programs and the
+dialogue acts it was measured on. Paths are set here so the modules find them wherever the pack is installed."""
+import os
+import sys
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+DATA = os.path.join(HERE, "data")
+TREE = os.path.abspath(os.path.join(HERE, "..", ".."))
+
+os.environ.setdefault("ORACLE7_MOVES", os.path.join(DATA, "moves.json"))
+os.environ.setdefault("ORACLE7_SCENES", os.path.join(DATA, "scenes.json"))
+os.environ.setdefault("ORACLE7_MOVES_SCENES", os.path.join(DATA, "moves_scenes.json"))
+os.environ.setdefault("ORACLE7_REL_LEXICON", os.path.join(DATA, "rel_lexicon.json"))
+os.environ.setdefault("ORACLE7_TK", os.path.join(DATA, "tk"))
+os.environ.setdefault("ORACLE7_TMP", os.path.join(DATA, "tk"))
+os.environ.setdefault("ORACLE7_RELSTORE_DIR", os.path.join(TREE, "root", "relstore"))
+os.environ.setdefault("ORACLE7_WT", os.path.join(TREE, "root", "wander-train"))
+os.environ.setdefault("ORACLE7_DAILYDIALOG", os.path.join(DATA, "dailydialog_raw.json"))
+for p in (HERE, os.path.join(TREE, "root", "wander-train")):
+ if p not in sys.path:
+ sys.path.insert(0, p)
diff --git a/workbench/converse/accord.py b/workbench/converse/accord.py
new file mode 100644
index 0000000000000000000000000000000000000000..93bc5e995326933b923d1822de60c80fb33d026e
--- /dev/null
+++ b/workbench/converse/accord.py
@@ -0,0 +1,826 @@
+#!/usr/bin/env python3
+"""accord - open talk planned backward from the turn (12.0 Amendment 8; the planner's shape pointed at a turn).
+
+The speaker before this chose a sentence shape first, was not allowed the turn's own words, and gave an empty place its most
+common filler: a guess. Here the reply is bound to the turn or it is not said:
+
+ world the turn, read: its own content words (kept in their surface and their lemma), its function-word frame, what it
+ does (act) and how it feels
+ forms reply forms induced from the exchanges of the corpus, not from single sentences: in every reply sentence the
+ words CARRIED from the turn it answers become places, everything else stays the form's own words. A form is
+ admitted with three or more donor dialogues (the M14 multi-donor rule, one order up). Nothing is written by hand.
+ bind a place takes only a word of this turn: one that stands in the turn where the donors' carried words stood (the
+ frame around it) and that resonates with the bundle of the words that filled the place. No default fill.
+ call a form is called by this turn's own evidence, each feature counted by its lift over the form's base rate,
+ shrunk for thin evidence: the turn's concepts, its frame, its act and feeling.
+ account every content word of the reply is a word of the turn or a word of a form this turn called by its own concepts.
+ A form whose own content words nothing in the turn calls is not said; what remains is the short form with no
+ content of its own ("I see.", "Really?"), chosen by act and feeling.
+No language model.
+usage: accord.py induce | eval [n] | say """
+import collections
+import json
+import math
+import os
+import random
+import re
+import sys
+import threading
+
+import numpy as np
+
+APOS = chr(39)
+TOKC = re.compile("[A-Za-z]+(?:" + APOS + "[a-z]+)?|[0-9]+(?:[.,:][0-9]+)*|[.?!,]")
+END = set(".?!")
+FUNC = set("the a an this that these those my your his her its our their i you he she it we they him them me us who whom what "
+ "which of in on at to for with by from as into over under about through and or but so because if then than while "
+ "although though yet nor is are was were be been being have has had do does did will would shall should can could "
+ "may might must not no yes oh well there here how why when where all some any very too just really please am "
+ "one ones mine yours ok okay yeah up out off down again also still even only now".split())
+K_SHRINK = 5.0
+REFER = set("he she him her his hers they them their theirs".split()) # words that point at someone: they need an owner in the turn
+MIN_DONORS = 3
+PLACE_TAGS = ("", "", "", "")
+TYPED = {"IsA", "PartOf", "HasA", "UsedFor", "CapableOf", "AtLocation", "Causes", "HasSubevent", "HasPrerequisite",
+ "MotivatedByGoal", "Desires", "MadeOf", "ReceivesAction", "HasProperty", "CausesDesire", "HasFirstSubevent",
+ "HasLastSubevent", "MannerOf", "Entails"}
+_RX1 = re.compile("\\s+" + APOS + "\\s*(s|re|m|ll|ve|d|t)\\b")
+_RX2 = re.compile("([.?!])(?=[A-Za-z])")
+_RX3 = re.compile("\\s+")
+_RXI = re.compile("\\bi\\b")
+
+
+def norm_text(u):
+ u = str(u or "").replace(chr(0x2019), APOS).replace(chr(0x2018), APOS)
+ u = _RX1.sub(APOS + "\\1", u)
+ u = _RX2.sub("\\1 ", u)
+ return _RX3.sub(" ", u).strip()
+
+
+def toks_of(u):
+ return TOKC.findall(norm_text(u))
+
+
+def sentences(toks):
+ out, cur = [], []
+ for t in toks:
+ cur.append(t)
+ if t in END:
+ out.append(cur)
+ cur = []
+ if cur:
+ out.append(cur)
+ return out
+
+
+class Words:
+ """the dictionary's readings, cached: the kind of a token, its lemma"""
+
+ def __init__(self, tree):
+ sys.path[:0] = [tree + "/workbench/converse", tree + "/workbench/swarm", tree + "/workbench"]
+ import converse # noqa: F401
+ self._tl = threading.local()
+ self._lem, self._kind, self._nb = {}, {}, {}
+ import sqlite3
+ self.cn = sqlite3.connect("file:%s/root/fable-content/oracle-m-series-2026-08-15/m13e5_conceptnet_build_a_v1/"
+ "conceptnet_specialist.sqlite3?mode=ro" % tree, uri=True, check_same_thread=False)
+
+ def nbrs(self, c):
+ """the words a concept reaches by a typed relation (the head's own ConceptNet store), with the edge's weight"""
+ if c not in self._nb:
+ out = {}
+ for rel, a, b, wt in self.cn.execute(
+ "select rel,start,end,weight from edge where (start=? or end=?) and dataset in "
+ "('/d/conceptnet/4/en','/d/wordnet/3.1','/d/verbosity','/d/opencyc','/d/wiktionary/en')", (c, c)):
+ if rel in TYPED:
+ o = b if a == c else a
+ if " " not in o and "_" not in o and o != c:
+ out[o] = max(out.get(o, 0.0), min(float(wt), 2.0))
+ self._nb[c] = out
+ return self._nb[c]
+
+ @property
+ def d(self):
+ """the dictionary store, opened once per thread (a sqlite connection stays in the thread that made it)"""
+ if not hasattr(self._tl, "d"):
+ from turn_reader import Dict, open_dict
+ self._tl.d = Dict(open_dict())
+ return self._tl.d
+
+ @staticmethod
+ def base(w):
+ return w.lower().split(APOS)[0]
+
+ def kind(self, tok, initial=False):
+ """F function word or punctuation, NUM, NAME, W content word, O other"""
+ if tok in END or tok == ",":
+ return "F"
+ if tok[0].isdigit():
+ return "NUM"
+ b = self.base(tok)
+ if b in FUNC or tok.lower() in FUNC:
+ return "F"
+ if tok[0].isupper() and not initial:
+ return "NAME"
+ if b not in self._kind:
+ p = self.d.pos(b)
+ self._kind[b] = "W" if (len(b) > 2 and any(x in p for x in ("noun", "verb", "adj", "adjective"))) else "O"
+ return self._kind[b]
+
+ def lem(self, w):
+ b = self.base(w)
+ if b not in self._lem:
+ try:
+ self._lem[b] = self.d.lemma(b)
+ except Exception: # noqa: BLE001
+ self._lem[b] = b
+ return self._lem[b]
+
+
+def read_turn(W, text):
+ """the world: the turn's tokens with their kinds, and its content words"""
+ flat = []
+ for s in sentences(toks_of(text)):
+ flat += [(t, W.kind(t, initial=(i == 0))) for i, t in enumerate(s)]
+ content = [(i, t, k) for i, (t, k) in enumerate(flat) if k in ("W", "NAME", "NUM")]
+ return {"flat": flat, "content": content}
+
+
+def frame(flat, carried=()):
+ """the turn's function-word frame: content abstracted to its kind, a carried position to """
+ out = [""]
+ for i, (t, k) in enumerate(flat):
+ out.append("" if i in carried else (t.lower() if k == "F" else k))
+ if t in END:
+ out.append("")
+ out.append("")
+ if out[-1] == "":
+ out.pop()
+ else:
+ out.append("")
+ return out
+
+
+def grams(fr, need_c=False):
+ """trigrams of a frame; with need_c only those through the carried position, otherwise only those without one"""
+ g = set()
+ for i in range(len(fr) - 2):
+ tri = fr[i:i + 3]
+ if ("" in tri) == need_c:
+ g.add(" ".join(tri))
+ return g
+
+
+def template(W, turn, reply_sent):
+ """a reply sentence as a form over the turn it answers: carried words -> places. -> (key tokens, [(turn index, mode)])"""
+ by_surf, by_lem = {}, {}
+ for i, t, k in turn["content"]:
+ by_surf.setdefault(t.lower(), i)
+ if k == "W":
+ by_lem.setdefault(W.lem(t), i)
+ key, binds = [], []
+ for j, t in enumerate(reply_sent):
+ k = W.kind(t, initial=(j == 0))
+ if k in ("W", "NAME", "NUM"):
+ if t.lower() in by_surf:
+ key.append("<%s>" % k)
+ binds.append((by_surf[t.lower()], "S", None))
+ continue
+ if k == "W" and W.lem(t) in by_lem and W.base(t) == W.lem(t):
+ key.append("")
+ binds.append((by_lem[W.lem(t)], "L", None))
+ continue
+ if k == "W" and W.base(t) == W.lem(t): # a word a word of the turn reaches by a typed relation
+ src = [(W.nbrs(c).get(W.lem(t), 0.0), i) for c, i in by_lem.items()]
+ src = [x for x in src if x[0] > 0]
+ if src:
+ key.append("")
+ binds.append((max(src)[1], "R", W.lem(t)))
+ continue
+ key.append(t.lower())
+ return key, binds
+
+
+def exchanges(raw, lo, hi):
+ for di in range(lo, hi):
+ dl = raw[di]
+ us = dl["utterances"]
+ for j in range(1, len(us)):
+ a = (dl.get("acts") or [0] * len(us))[j - 1]
+ e = (dl.get("emotions") or [0] * len(us))[j - 1]
+ yield di, us[j - 1], us[j], a, e
+
+
+def turn_feats(W, turn, a, e):
+ cs = {W.lem(t) for _i, t, k in turn["content"] if k == "W"} | {t.lower() for _i, t, k in turn["content"] if k == "NAME"}
+ f = [("c", c) for c in sorted(cs)] + [("a", str(a)), ("e", str(e)), ("ae", "%s/%s" % (a, e))]
+ f += [("g", g) for g in sorted(grams(frame(turn["flat"])))]
+ return f
+
+
+def induce(tree, ddpath, out):
+ W = Words(tree)
+ raw = json.load(open(ddpath))["train"]
+ ntr = int(0.9 * len(raw))
+ donors = collections.defaultdict(set)
+ nt = collections.Counter()
+ F = collections.defaultdict(collections.Counter) # feature -> form -> n
+ nf = collections.Counter()
+ B = collections.defaultdict(collections.Counter) # carried-frame trigram -> "form|place" -> n
+ nb = collections.Counter()
+ fill = collections.defaultdict(collections.Counter) # "form|place" -> filler lemma -> n
+ mode = collections.defaultdict(collections.Counter)
+ df = collections.Counter()
+ CW = collections.defaultdict(collections.Counter) # concept of the turn -> content word of the reply -> n
+ ncw, nw = collections.Counter(), collections.Counter()
+ seen_pair = set()
+ PAIR = collections.defaultdict(collections.Counter) # first sentence's form -> second sentence's form -> n
+ after_q = collections.Counter() # form -> times it replied to a turn that asked
+ opener = collections.defaultdict(lambda: [0, 0]) # first two words of a sentence -> [sentences, of them questions]
+ dir2 = collections.defaultdict(lambda: [0, 0]) # first two words of a turn's last sentence -> [n, directives]
+ dir1 = collections.defaultdict(lambda: [0, 0]) # its first word
+ verb0 = [0, 0] # last sentences opening on a bare verb -> [n, directives]
+ vf = collections.defaultdict(lambda: [0, 0]) # bare verb + this function word -> [n, directives]
+ tokc = collections.Counter()
+ for dl in raw[:ntr]:
+ for u in dl["utterances"]:
+ tokc.update(x.lower() for x in toks_of(u))
+
+ def bare_verb(tok):
+ b = W.base(tok)
+ return b not in FUNC and "verb" in W.d.pos(b) and W.lem(b) == b
+ for dl in raw[:ntr]:
+ acts = dl.get("acts") or []
+ for ui, u in enumerate(dl["utterances"]):
+ sts = sentences(toks_of(u))
+ for st in sts:
+ if len(st) >= 3:
+ o = opener[" ".join(x.lower() for x in st[:2])]
+ o[0] += 1
+ o[1] += st[-1] == "?"
+ if sts and ui < len(acts) and len(sts[-1]) >= 2 and sts[-1][-1] != "?":
+ st = sts[-1]
+ isd = acts[ui] == 3
+ for tab, key in ((dir2, " ".join(x.lower() for x in st[:2])), (dir1, st[0].lower())):
+ tab[key][0] += 1
+ tab[key][1] += isd
+ if bare_verb(st[0]):
+ verb0[0] += 1
+ verb0[1] += isd
+ if st[1].lower() in FUNC:
+ vf[st[1].lower()][0] += 1
+ vf[st[1].lower()][1] += isd
+ N = nturn = NW = 0
+ for di, tu, ru, a, e in exchanges(raw, 0, ntr):
+ turn = read_turn(W, tu)
+ if not turn["flat"]:
+ continue
+ pair = (norm_text(tu).lower(), norm_text(ru).lower())
+ if pair in seen_pair: # the corpus repeats whole dialogues: one exchange counts once
+ continue
+ seen_pair.add(pair)
+ feats = turn_feats(W, turn, a, e)
+ nturn += 1
+ cs = [f[1] for f in feats if f[0] == "c"]
+ for c in cs:
+ df[c] += 1
+ rws = set()
+ for rs in sentences(toks_of(ru))[:2]:
+ for j, t_ in enumerate(rs):
+ if t_.lower() in REFER or W.kind(t_, initial=(j == 0)) in ("W", "O"):
+ rws.add(t_.lower() if t_.lower() in REFER else W.lem(t_))
+ for w_ in rws:
+ nw[w_] += 1
+ NW += 1
+ for c in cs:
+ CW[c][w_] += 1
+ ncw[c] += 1
+ two = []
+ for rs in sentences(toks_of(ru))[:2]:
+ if len(rs) < 2 or len(rs) > 14 or rs[-1] not in END:
+ two.append(None)
+ continue
+ key, binds = template(W, turn, rs)
+ t = " ".join(key)
+ two.append(t)
+ N += 1
+ nt[t] += 1
+ donors[t].add(pair[0])
+ after_q[t] += pair[0].endswith("?")
+ for f in feats:
+ F[f][t] += 1
+ nf[f] += 1
+ for k, (ti, m, rw) in enumerate(binds):
+ pk = "%s|%d" % (t, k)
+ tok, kind = turn["flat"][ti]
+ fill[pk][rw if m == "R" else (W.lem(tok) if kind == "W" else kind)] += 1
+ mode[pk][m] += 1
+ for g in grams(frame(turn["flat"], carried=(ti,)), need_c=True):
+ B[g][pk] += 1
+ nb[g] += 1
+ if len(two) == 2 and two[0] and two[1]:
+ PAIR[two[0]][two[1]] += 1
+ keep = {t for t in nt if len(donors[t]) >= MIN_DONORS}
+ print("exchanges %d, reply sentences %d, forms seen %d, admitted (>= %d distinct donor turns) %d, covering %.1f%% of sentences" % (
+ nturn, N, len(nt), MIN_DONORS, len(keep), 100.0 * sum(nt[t] for t in keep) / max(1, N)), flush=True)
+ withp = [t for t in keep if any(x in PLACE_TAGS for x in t.split(" "))]
+ print("admitted forms with a carried place: %d, covering %.1f%% of sentences" % (
+ len(withp), 100.0 * sum(nt[t] for t in withp) / max(1, N)), flush=True)
+ wv = np.load(tree + "/workbench/converse/data/ladder/wordvec.npz", allow_pickle=True)
+ WV, WVI = wv["vec"], {w: i for i, w in enumerate(wv["words"])}
+ places = {}
+ for pk, cn in fill.items():
+ if pk.rsplit("|", 1)[0] not in keep:
+ continue
+ ws = [(w, n) for w, n in cn.items() if w in WVI]
+ rec = {"fill": dict(cn.most_common(40)), "mode": dict(mode[pk])}
+ if len(ws) >= 3:
+ vs = np.stack([WV[WVI[w]] for w, _ in ws]).astype(np.float32)
+ ns = np.array([n for _, n in ws], np.float32)
+ b = (vs * ns[:, None]).sum(0)
+ b /= (np.linalg.norm(b) + 1e-9)
+ rec["bundle"] = [round(float(x), 4) for x in b]
+ rec["floor"] = round(float(np.percentile(vs @ b, 25)), 4)
+ places[pk] = rec
+ data = {"N": N, "nturn": nturn, "forms": {t: [nt[t], len(donors[t])] for t in keep},
+ "F": {"%s\t%s" % f: {t: n for t, n in cn.items() if t in keep} for f, cn in F.items()},
+ "nf": {"%s\t%s" % f: n for f, n in nf.items()},
+ "B": {g: {pk: n for pk, n in cn.items() if pk.rsplit("|", 1)[0] in keep} for g, cn in B.items()},
+ "nb": dict(nb), "places": places, "df": {c: n for c, n in df.items() if n >= 2},
+ "CW": {c: {w_: n for w_, n in cn.items() if n >= 2} for c, cn in CW.items()}, "ncw": dict(ncw), "nw": dict(nw), "NW": NW}
+ data["CW"] = {c: cn for c, cn in data["CW"].items() if cn}
+ data["PAIR"] = {a: {b: n for b, n in cn.items() if b in keep and n >= 2} for a, cn in PAIR.items() if a in keep}
+ data["PAIR"] = {a: cn for a, cn in data["PAIR"].items() if cn}
+ data["answer_forms"] = sorted(t for t in keep if after_q[t] * 2 >= nt[t]) # said mostly in reply to a question
+ data["ask_openers"] = sorted(k for k, (n, q) in opener.items() if n >= 8 and q >= 0.6 * n)
+ data["tell_openers"] = sorted(k for k, (n, q) in dir2.items() if n >= 8 and q >= 0.5 * n)
+ data["tell_first"] = sorted(k for k, (n, q) in dir1.items() if n >= 8 and q >= 0.5 * n)
+ data["bare_verb_tells"] = [verb0[0], verb0[1]]
+ data["verb_then"] = sorted(k for k, (n, q) in vf.items() if n >= 8 and q >= 0.5 * n)
+ # "lets" -> "let's", "dont" -> "don't": restored where the corpus writes the apostrophe form more often than the bare one
+ data["apos"] = {w.replace(APOS, ""): w for w, n in tokc.items() if APOS in w and n >= 5 and n > 3 * tokc.get(w.replace(APOS, ""), 0)}
+ print("verb + function word openings that tell:", data["verb_then"], "| apostrophes restored:", len(data["apos"]), flush=True)
+ print("sentences opening on a bare verb: %d, of them directives %d; tell openers %d, first words %d" % (
+ verb0[0], verb0[1], len(data["tell_openers"]), len(data["tell_first"])), flush=True)
+ print("answer forms %d, openers of asking sentences %d" % (len(data["answer_forms"]), len(data["ask_openers"])), flush=True)
+ data["F"] = {f: cn for f, cn in data["F"].items() if cn}
+ data["B"] = {g: cn for g, cn in data["B"].items() if cn}
+ json.dump(data, open(out, "w"))
+ print("written %s (%.1f MB)" % (out, os.path.getsize(out) / 1e6), flush=True)
+
+
+class Accord:
+ RARE, OWN_LIFT, TAU, FACT_IDF = 5.0, 1.0, 7.0, 9.0
+ WEIGHTS = (1.5, 2.0, 0.5, 0.25, 0.5) # concepts, frame, act and feeling, binding, base rate
+
+ def __init__(self, tree, datapath, W=None):
+ self.W = W or Words(tree)
+ D = json.load(open(datapath))
+ self.N, self.nturn = D["N"], D["nturn"]
+ self.forms, self.F, self.nf, self.B, self.nb, self.places, self.df = (
+ D[k] for k in ("forms", "F", "nf", "B", "nb", "places", "df"))
+ wv = np.load(tree + "/workbench/converse/data/ladder/wordvec.npz", allow_pickle=True)
+ self.WV, self.WVI = wv["vec"], {w: i for i, w in enumerate(wv["words"])}
+ self.keys = {t: t.split(" ") for t in self.forms}
+ self.ptags = {t: [x for x in k if x in PLACE_TAGS] for t, k in self.keys.items()}
+ # a form's own content words (what must be called by the turn itself)
+ self.CW, self.ncw, self.nw, self.NW = D["CW"], D["ncw"], D["nw"], D["NW"]
+ self.PAIR = D.get("PAIR", {})
+ self.answer_forms = set(D.get("answer_forms", []))
+ self.ask_openers = set(D.get("ask_openers", []))
+ self.tell_openers = set(D.get("tell_openers", []))
+ self.tell_first = set(D.get("tell_first", []))
+ self.verb_then = set(D.get("verb_then", []))
+ self.apos = D.get("apos", {})
+ bv = D.get("bare_verb_tells", [1, 0])
+ self.bare_verb_tells = bv[1] * 2 >= bv[0] # the corpus itself says whether a bare-verb opening is a directive
+ self.own = {}
+ for t, k in self.keys.items():
+ o = []
+ for x in k:
+ if x in PLACE_TAGS:
+ continue
+ if x in REFER:
+ o.append(x)
+ elif self.W.kind(x) in ("W", "O", "NAME", "NUM"):
+ l = self.W.lem(x)
+ if self.widf(l) >= self.RARE: # a common word of talk needs no owner; a rarer one does
+ o.append(l)
+ self.own[t] = o
+ self.bund = {pk: (np.array(r["bundle"], np.float32), r["floor"]) for pk, r in self.places.items() if "bundle" in r}
+
+ def lift(self, n_ft, n_f, n_t, total):
+ if not n_ft:
+ return 0.0
+ return max(0.0, math.log((n_ft / n_f) / (n_t / total))) * n_ft / (n_ft + K_SHRINK)
+
+ def widf(self, w):
+ """how rare a word is among replies (log of exchanges per reply carrying it)"""
+ return math.log(self.nturn / (1.0 + self.nw.get(w, 0)))
+
+ def owned(self, w, lemmas, surf):
+ """is this word of a form accounted for by the turn: a word of the turn, a word one of its words reaches by a typed
+ relation, or a word that follows one of its concepts in replies far above its base rate"""
+ if w in lemmas or w in surf:
+ return True
+ for c in lemmas:
+ n = self.CW.get(c, {}).get(w, 0)
+ if n >= 3 and self.lift(n, self.ncw[c], self.nw.get(w, 1), self.NW) >= self.OWN_LIFT:
+ return True
+ return False
+
+ def idf(self, c):
+ return math.log(self.nturn / (1.0 + self.df.get(c, 0)))
+
+ def fits(self, pk, tok, kind, lemma=None):
+ """may this word enter the place: it filled it before, or it resonates with the words that did"""
+ rec = self.places.get(pk)
+ if rec is None:
+ return None
+ if kind != "W":
+ return 0.5 if kind in rec["fill"] else None
+ l = lemma or self.W.lem(tok)
+ if l in rec["fill"]:
+ return 1.0
+ if pk in self.bund and l in self.WVI:
+ b, floor = self.bund[pk]
+ c = float(self.WV[self.WVI[l]] @ b)
+ return (c - floor) if c >= floor else None
+ return None
+
+ def candidates(self, text, a, e, top=8):
+ W = self.W
+ turn = read_turn(W, text)
+ if not turn["flat"]:
+ return []
+ feats = turn_feats(W, turn, a, e)
+ cw = {f[1]: self.idf(f[1]) for f in feats if f[0] == "c"}
+ cz = sum(cw.values()) or 1.0
+ s_con, s_frm, s_act = collections.Counter(), collections.Counter(), collections.Counter()
+ ng = sum(1 for f in feats if f[0] == "g") or 1
+ for f in feats:
+ k = "%s\t%s" % f
+ cn = self.F.get(k)
+ if not cn:
+ continue
+ for t, n in cn.items():
+ lf = self.lift(n, self.nf[k], self.forms[t][0], self.N)
+ if not lf:
+ continue
+ if f[0] == "c":
+ s_con[t] += lf * cw[f[1]] / cz * len(cw) ** 0.5
+ elif f[0] == "g":
+ s_frm[t] += lf / ng ** 0.5
+ else:
+ s_act[t] += lf
+ # the places: for each word of the turn, the forms whose donors carried a word standing in such a frame
+ bsc = collections.defaultdict(dict) # "form|place" -> turn index -> lift
+ ngc = {}
+ own_l = {W.lem(t_) for _i, t_, k_ in turn["content"] if k_ == "W"}
+ own_s = {t_.lower() for t_, _k in turn["flat"]}
+ for i, tok, kind in turn["content"]:
+ gs = grams(frame(turn["flat"], carried=(i,)), need_c=True)
+ ngc[i] = len(gs) or 1
+ for g in gs:
+ cn = self.B.get(g)
+ if not cn:
+ continue
+ for pk, n in cn.items():
+ t = pk.rsplit("|", 1)[0]
+ lf = self.lift(n, self.nb[g], self.forms[t][0], self.N)
+ if lf:
+ bsc[pk][i] = bsc[pk].get(i, 0.0) + lf
+ out = []
+ pool = set(s_con) | set(s_frm) | set(s_act) | {pk.rsplit("|", 1)[0] for pk in bsc}
+ for t in pool:
+ tags = self.ptags[t]
+ binds, used, bscore, ok = [], set(), 0.0, True
+ for k, want in enumerate(tags):
+ pk = "%s|%d" % (t, k)
+ best = None
+ for i, tok, kind in turn["content"]:
+ if i in used:
+ continue
+ if want == "": # a word this turn's word reaches by a typed relation
+ if kind != "W":
+ continue
+ for o, wt in W.nbrs(W.lem(tok)).items():
+ if o in own_l:
+ continue
+ ft = self.fits(pk, o, "W", lemma=o)
+ if ft is None:
+ continue
+ sc = self.gnorm(bsc.get(pk, {}).get(i, 0.0), ngc[i]) + ft + 0.25 * wt
+ if best is None or sc > best[0]:
+ best = (sc, i, o, "R")
+ continue
+ if want != "<%s>" % kind:
+ continue
+ ft = self.fits(pk, tok, kind)
+ if ft is None:
+ continue
+ sc = self.gnorm(bsc.get(pk, {}).get(i, 0.0), ngc[i]) + ft
+ if best is None or sc > best[0]:
+ best = (sc, i, tok, kind)
+ if best is None:
+ ok = False # a place nothing of this turn can fill: the form is not said
+ break
+ used.add(best[1])
+ binds.append(best)
+ bscore += best[0]
+ if not ok:
+ continue
+ if tags:
+ bscore /= len(tags)
+ if any(not self.owned(w_, own_l, own_s) for w_ in self.own[t]):
+ continue # a word of the form nothing in this turn accounts for
+ comp = (s_con[t], s_frm[t], s_act[t], bscore, math.log(self.forms[t][0] / self.N))
+ total = sum(w * c for w, c in zip(self.WEIGHTS, comp))
+ out.append((total, t, binds, {"con": round(s_con[t], 2), "frm": round(s_frm[t], 2), "act": round(s_act[t], 2),
+ "bind": round(bscore, 2), "donors": self.forms[t][1],
+ "bound": bool(tags or self.own[t])}, comp))
+ out.sort(key=lambda x: -x[0])
+ return out[:top] if top else out
+
+ @staticmethod
+ def gnorm(x, n):
+ return x / n ** 0.5
+
+ def realise(self, t, binds):
+ out, k = [], 0
+ for x in self.keys[t]:
+ if x in PLACE_TAGS:
+ _sc, _i, tok, kind = binds[k]
+ m = self.places["%s|%d" % (t, k)]["mode"]
+ if kind == "R":
+ out.append(tok)
+ elif kind == "W":
+ out.append(self.W.lem(tok) if m.get("L", 0) > m.get("S", 0) else tok.lower())
+ else:
+ out.append(tok)
+ k += 1
+ else:
+ out.append(x)
+ s = ""
+ for x in out:
+ s += x if (x in END or x == ",") else ((" " + x) if s else x)
+ s = _RXI.sub("I", s)
+ return s[:1].upper() + s[1:]
+
+ def fix(self, text):
+ """apostrophes people leave out, put back the way the corpus writes them (lets -> let's, whats -> what's)"""
+ return " ".join(self.apos.get(w.lower(), w) if w.lower() in self.apos else w for w in str(text or "").split())
+
+ def asks(self, text):
+ """does the turn ask something, whatever its punctuation: its last sentence ends with a question mark or opens the
+ way sentences that ask open ("do we", "can you", "where are": learned from the corpus's own question marks)"""
+ st = sentences(toks_of(self.fix(text)))
+ if not st:
+ return False
+ for x in st:
+ if x[-1] == "?":
+ return True
+ low = [y.lower() for y in x]
+ for i in range(0, min(4, len(low) - 1)): # past a leading "okay so", "and", a name
+ if " ".join(low[i:i + 2]) in self.ask_openers:
+ return True
+ return False
+
+ def tells(self, text):
+ """does the turn tell me to do something: a sentence of it opens the way directives open in the corpus (its own act
+ labels), or on a bare verb where the corpus says such openings are directives"""
+ for x in sentences(toks_of(self.fix(text))):
+ low = [y.lower() for y in x]
+ for i in range(0, min(3, len(low))):
+ if " ".join(low[i:i + 2]) in self.tell_openers or (i == 0 and low[0] in self.tell_first):
+ return True
+ for i in range(0, min(2, len(low) - 1)): # "run it", "yes get the rest done"
+ b = self.W.base(low[i])
+ if b not in FUNC and "verb" in self.W.d.pos(b) and self.W.lem(b) == b and (
+ self.bare_verb_tells or low[i + 1] in self.verb_then):
+ return True
+ return False
+
+ def about(self, text, reply):
+ """is the reply about something the turn names: one of the turn's rarer words, or a name in it, is in the reply"""
+ turn = read_turn(self.W, self.fix(text))
+ rl = {self.W.lem(t) for t in toks_of(str(reply)[:600])} | {t.lower() for t in toks_of(str(reply)[:600])}
+ for _i, tok, kind in turn["content"]:
+ if kind == "NAME" and tok.lower() in rl:
+ return True
+ if kind == "W" and self.idf(self.W.lem(tok)) >= self.RARE and self.W.lem(tok) in rl:
+ return True
+ return False
+
+ def subject(self, text):
+ """the turn's most distinctive thing: a name, or a noun rare in talk (for the head to say what it holds about it)"""
+ turn = read_turn(self.W, text)
+ best = None
+ names, run_ = {}, [] # a name of several words is one subject
+ for i, (tok, kind) in enumerate(turn["flat"]):
+ if kind == "NAME":
+ run_.append((i, tok))
+ else:
+ if len(run_) > 1:
+ for j, _t in run_:
+ names[j] = " ".join(t for _j, t in run_)
+ run_ = []
+ if len(run_) > 1:
+ for j, _t in run_:
+ names[j] = " ".join(t for _j, t in run_)
+ for i, tok, kind in turn["content"]:
+ if kind == "NAME":
+ sc, word = 20.0 + (1.0 if i in names else 0.0), names.get(i, tok)
+ elif kind == "W" and "noun" in self.W.d.pos(self.W.lem(tok)) and len(tok) > 3:
+ word = self.W.lem(tok)
+ sc = self.idf(word)
+ else:
+ continue
+ if sc >= self.FACT_IDF and (best is None or sc > best[0]):
+ best = (sc, word)
+ return best[1] if best else None
+
+ def parts(self, text, a, e):
+ c = [x for x in self.candidates(text, a, e, top=0) if x[1] not in self.answer_forms] # nothing was asked: no answers
+ plain = next((x for x in c if not x[3]["bound"]), None)
+ w = self.WEIGHTS
+ key = lambda x: w[0] * x[4][0] + w[1] * x[4][1] + w[2] * x[4][2] + w[3] * x[4][3]
+ bound = max((x for x in c if x[3]["bound"]), key=key, default=None)
+ return plain, bound, (key(bound) if bound is not None else 0.0)
+
+ def say(self, text, a=1, e=0):
+ """the short form the turn calls, then the form bound to the turn's own content when one is called strongly enough"""
+ if self.asks(text) or self.tells(text):
+ return None, None # a turn that asks or tells is not talk: the door's other parts take it
+ text = self.fix(text)
+ plain, bound, spec = self.parts(text, a, e)
+ if bound is not None and spec < self.TAU:
+ bound = None
+ parts = [x for x in (plain, bound) if x is not None]
+ if not parts:
+ return None, None
+ if plain is not None and bound is not None and not self.PAIR.get(plain[1], {}).get(bound[1]):
+ parts = [bound] # the two are said together only where replies said them together
+ said = " ".join(self.realise(x[1], x[2]) for x in parts)
+ top_ = parts[-1]
+ return said, dict(top_[3], form=" + ".join(x[1] for x in parts), score=round(top_[0], 2))
+
+
+class Speaker:
+ """the door's open talk: solve(text) -> (reply, None, how). Everything it needs is inside the tree."""
+
+ def __init__(self, tree):
+ self.A = Accord(tree, os.path.join(tree, "workbench", "converse", "data", "accord", "accord.json"))
+ self.ins = instrument()
+
+ def solve(self, text):
+ a, e = self.ins(text)
+ said, why = self.A.say(text, a, e)
+ return said, None, ("accord" if said else None)
+
+ def asks(self, text):
+ return self.A.asks(text)
+
+ def tells(self, text):
+ return self.A.tells(text)
+
+ def about(self, text, reply):
+ return self.A.about(text, reply)
+
+ def subject(self, text):
+ return self.A.subject(text)
+
+
+def instrument():
+ from relational_instrument_v1 import act_of, emotion_of, ACTS, EMOS
+ an, en = {v: k for k, v in ACTS.items()}, {v: k for k, v in EMOS.items()}
+ return lambda text: (an.get(act_of(text), 1), en.get(emotion_of(text), 0))
+
+
+if __name__ == "__main__":
+ mode_ = sys.argv[1]
+ if mode_ == "induce":
+ induce(sys.argv[2], sys.argv[3], sys.argv[4])
+ elif mode_ == "eval":
+ tree, ddpath, datapath = sys.argv[2:5]
+ n = int(sys.argv[5]) if len(sys.argv) > 5 else 400
+ A = Accord(tree, datapath)
+ raw = json.load(open(ddpath))["train"]
+ ntr = int(0.9 * len(raw))
+ ex = [x for x in exchanges(raw, ntr, len(raw)) if not norm_text(x[1]).endswith("?")]
+ random.Random(12).shuffle(ex)
+ ex = ex[:n]
+ res = collections.Counter()
+ shown = 0
+ for q, (di, tu, ru, a, e) in enumerate(ex):
+ turn = read_turn(A.W, tu)
+ rs = sentences(toks_of(ru))
+ if not rs or not turn["flat"]:
+ continue
+ res["n"] += 1
+ truth = {" ".join(template(A.W, turn, s)[0]) for s in rs[:2]}
+ res["admitted"] += bool(truth & set(A.forms))
+ for name, txt in (("system", tu), ("mutant", ex[(q + 1) % len(ex)][1])):
+ ts = [x[1] for x in A.candidates(txt, a, e, top=5)]
+ res[name + "_top1"] += bool(ts[:1] and ts[0] in truth)
+ res[name + "_top5"] += bool(set(ts) & truth)
+ res[name + "_said"] += bool(ts)
+ if shown < 60:
+ said, why = A.say(tu, a, e)
+ print("%-70s -> %-40s | human: %-50s %s" % (norm_text(tu)[:70], said, norm_text(ru)[:50],
+ ("[%s]" % ", ".join("%s %s" % kv for kv in why.items() if kv[0] != "form")) if why else ""))
+ shown += 1
+ print(dict(res))
+ elif mode_ == "tune": # weights read on the first half of the held-out tenth of train
+ tree, ddpath, datapath = sys.argv[2:5]
+ A = Accord(tree, datapath)
+ raw = json.load(open(ddpath))["train"]
+ ntr = int(0.9 * len(raw))
+ mid = ntr + (len(raw) - ntr) // 2
+ half = sys.argv[5] if len(sys.argv) > 5 else "a"
+ lo, hi = (ntr, mid) if half == "a" else (mid, len(raw))
+ rows = []
+ for di, tu, ru, a, e in exchanges(raw, lo, hi):
+ if norm_text(tu).endswith("?"):
+ continue
+ turn = read_turn(A.W, tu)
+ rs = sentences(toks_of(ru))
+ if not rs or not turn["flat"]:
+ continue
+ truth = {" ".join(template(A.W, turn, s)[0]) for s in rs[:2]} & set(A.forms)
+ if not truth:
+ rows.append(None)
+ continue
+ c = A.candidates(tu, a, e, top=0)
+ rows.append((np.array([x[4] for x in c], np.float32).reshape(-1, 5), np.array([x[1] in truth for x in c])))
+ adm = [r for r in rows if r is not None]
+ print("statement exchanges %d, human reply form admitted %d" % (len(rows), len(adm)), flush=True)
+
+ def score(w):
+ t1 = t5 = 0
+ for comp, hit in adm:
+ if not len(comp) or not hit.any():
+ continue
+ o = np.argsort(-(comp @ np.array(w, np.float32)))[:5]
+ t1 += bool(hit[o[0]])
+ t5 += bool(hit[o].any())
+ return t1, t5
+ if half == "a":
+ best = None
+ for wc in (0.5, 1.0, 1.5, 2.5):
+ for wf in (0.5, 1.0, 2.0):
+ for wa in (0.25, 0.5, 1.0, 2.0):
+ for wb in (0.25, 0.5, 1.0, 2.0):
+ for wp in (0.0, 0.25, 0.5, 1.0):
+ t1, t5 = score((wc, wf, wa, wb, wp))
+ if best is None or (t1 + 0.3 * t5) > best[0]:
+ best = (t1 + 0.3 * t5, t1, t5, (wc, wf, wa, wb, wp))
+ print("best weights", best[3], "top1 %d top5 %d of %d" % (best[1], best[2], len(adm)))
+ print("default", A.WEIGHTS, score(A.WEIGHTS), "base rate only", score((0, 0, 0, 0, 1)))
+ else:
+ w = tuple(float(x) for x in sys.argv[6].split(","))
+ print("weights", w, "top1 %d top5 %d of %d admitted (%d exchanges)" % (score(w) + (len(adm), len(rows))))
+ print("default", A.WEIGHTS, score(A.WEIGHTS), "base rate only", score((0, 0, 0, 0, 1)))
+ elif mode_ == "calib": # how often the bound form is the human's own, by how strongly called
+ tree, ddpath, datapath = sys.argv[2:5]
+ A = Accord(tree, datapath)
+ raw = json.load(open(ddpath))["train"]
+ ntr = int(0.9 * len(raw))
+ mid = ntr + (len(raw) - ntr) // 2
+ lo, hi = (ntr, mid) if sys.argv[5] == "a" else (mid, len(raw))
+ bk = collections.defaultdict(lambda: [0, 0])
+ pl = [0, 0]
+ ex_ = collections.defaultdict(list)
+ for di, tu, ru, a, e in exchanges(raw, lo, hi):
+ if norm_text(tu).endswith("?"):
+ continue
+ turn = read_turn(A.W, tu)
+ rs = sentences(toks_of(ru))
+ if not rs or not turn["flat"]:
+ continue
+ truth = {" ".join(template(A.W, turn, s_)[0]) for s_ in rs[:2]}
+ plain, bound, spec = A.parts(tu, a, e)
+ if plain is not None:
+ pl[0] += 1
+ pl[1] += plain[1] in truth
+ if bound is not None:
+ b = min(12, int(spec))
+ bk[b][0] += 1
+ bk[b][1] += bound[1] in truth
+ if len(ex_[b]) < 6:
+ ex_[b].append("%s -> %s" % (norm_text(tu)[:60], A.realise(bound[1], bound[2])))
+ print("plain form is the human's: %d of %d" % (pl[1], pl[0]))
+ for b in sorted(bk):
+ print("bound, called %2d..: %4d said, %3d the human's (%.0f%%)" % (b, bk[b][0], bk[b][1], 100.0 * bk[b][1] / bk[b][0]))
+ for x in ex_[b]:
+ print(" ", x)
+ elif mode_ == "say":
+ tree, datapath, turns = sys.argv[2:5]
+ A = Accord(tree, datapath)
+ ins = instrument()
+ for line in open(turns, encoding="utf-8"):
+ line = line.strip()
+ if line:
+ a, e = ins(line)
+ said, why = A.say(line, a, e)
+ print("%-70s -> %-28s asks=%s tells=%s subject=%s" % (line[:70], said, A.asks(line), A.tells(line), A.subject(line)))
diff --git a/workbench/converse/builder.py b/workbench/converse/builder.py
new file mode 100644
index 0000000000000000000000000000000000000000..a882915470b4057ad4ec9f9ba1afc58f314177b2
--- /dev/null
+++ b/workbench/converse/builder.py
@@ -0,0 +1,183 @@
+"""converse.builder - the build door inside the turn loop (directive Phase 1, the dew point).
+
+A turn the head's own operation head resolves to `build` (or `compose`) opens an obligation whose places are example questions:
+the swarm's builder (workbench/swarm/run.py) reads 3-6 of them, names the gap, builds the part from its sources and examines it.
+Fewer than three bound -> the open places are asked back (the named hole, cited to the operation). Three or more -> the dew
+point: run.build is called, and the reply is its receipt (outcome, gap named, exam verdict, where the part lives). Nothing here
+decides by keyword: the operation is chosen by the head's catalogue resonance (op_head), the examples are the user's own questions.
+"""
+import re
+import sys
+import time
+
+Q = re.compile(r"\?\s*$")
+
+
+class Builder:
+ def __init__(self, router):
+ self.r = router
+ self.state = {} # session -> {"op": cmd, "qs": [...], "turn": n, "built": [...]}
+
+ def pending(self, session):
+ return self.state.get(session)
+
+ # ---- Amendment 14 (4): the builder PROPOSES during candidate generation and nothing changes until the reply is delivered.
+ # step() records what it would do in self.proposal[session]; commit() applies it (and runs the swarm, once) only when the
+ # delivered reply is the builder's own; a discarded candidate leaves no trace. Examples bind only when they fit the task.
+ STOPFIT = set("build specialist specialists make that knows know about famous world world's worlds what how which who where "
+ "when the a an of in on is are long tell me please".split())
+
+ def _stems(self, text):
+ return {w[:5] for w in re.findall(r"[a-z]+", str(text).lower()) if len(w) > 3 and w not in self.STOPFIT}
+
+ def fits(self, st, turn):
+ """an example fits the open task when it shares a content stem with the request (its topic) or an earlier example"""
+ want = set(st.get("topic") or set())
+ for x in st["qs"]:
+ want |= self._stems(x)
+ return bool(want & self._stems(turn)) if want else True
+
+ def step(self, turn, fr, session, q):
+ """-> (act, text, substantive) or None; a PROPOSAL, applied by commit() only if this reply is delivered"""
+ self.proposal = getattr(self, "proposal", {})
+ self.proposal.pop(session, None)
+ st = self.state.get(session)
+ n = len(self.r.turns[session])
+ # 1. a question while a build is pending binds one example place, if it fits the task
+ if st and Q.search(turn.strip()) and not st.get("done") and self.fits(st, turn):
+ k = len(st["qs"]) + 1
+ if k < 3:
+ text = "Kept as example %d [turn:%d]. %d more example question%s and I build it [op:%s]." % (
+ k, n, 3 - k, "s" if 3 - k != 1 else "", st["op"])
+ self.proposal[session] = {"kind": "example", "q": turn.strip(), "text": text}
+ return "hole", text, True
+ text = "Building from your 3 examples [op:%s]." % st["op"]
+ self.proposal[session] = {"kind": "build", "q": turn.strip(), "text": text}
+ return "plan", text, True
+ # 2. a new request the operation head resolves to build / compose
+ mood = fr.get("mood")
+ # the reader names moods directive / inform / commissive / question; the first end-to-end (2026-11-08) showed a build
+ # request read as "directive" never reaching the operation head because only the older names were listed here.
+ if mood not in ("request", "directive", "statement", "inform", "commitment", "commissive", "question"):
+ return None
+ op = self.operation(fr, q)
+ if not op:
+ return None
+ fit, kind, cmd, usage, desc = op
+ if cmd not in ("build", "compose"):
+ return None
+ if st and not st.get("done") and st["op"] == cmd:
+ return "hole", "Still open [turn:%d]: %d example question%s so far; give me %d more and I build it [op:%s]." % (
+ st["turn"], len(st["qs"]), "s" if len(st["qs"]) != 1 else "", 3 - len(st["qs"]), cmd), True
+ text = ("I can build that [op:%s]: %s. The places I need are three to six example questions it should answer, "
+ "one per turn; from them the swarm names what it needs and builds it from its sources." % (cmd, desc[:140].rstrip(".")))
+ self.proposal[session] = {"kind": "open", "state": {"op": cmd, "qs": [], "turn": n, "done": False,
+ "topic": sorted(self._stems(turn))}, "text": text}
+ return "hole", text, True
+
+ def commit(self, session, delivered_text):
+ """apply this turn's proposal iff the delivered reply is the builder's; returns the receipt text for a build, else None"""
+ p = getattr(self, "proposal", {}).pop(session, None)
+ if not p or p["text"] not in str(delivered_text):
+ return None
+ if p["kind"] == "open":
+ self.state[session] = p["state"]
+ self.r.stats["build_open"] += 1
+ return None
+ st = self.state.get(session)
+ if st is None or st.get("done"):
+ return None
+ st["qs"].append(p["q"])
+ if p["kind"] == "build":
+ return self.build(session, st)[1]
+ return None
+
+ def operation(self, fr, q):
+ """Amendment 13 (2026-11-08): the operation is read from what the turn asks, the frame's verb and object, not from the
+ whole turn, whose topic words outweigh it (the probe: "Build me a specialist that knows how long the world's famous
+ bridges are" put specialist.rel-bridges first and build at 0.27, under tau). The topic stays with the places. When the
+ frame names no verb or object, the whole turn is used as before. No threshold changes."""
+ def words_of(k):
+ v = fr.get(k)
+ return [str(x) for x in (v if isinstance(v, (list, tuple)) else [v]) if x]
+ verb = " ".join(words_of("verb")).strip().lower()
+ # 1. the turn NAMES the operation: its verb is a command of the catalogue (build, compose, ...). Exact, no threshold.
+ if verb:
+ for row in self.r.op_rows:
+ if str(row[1]).lower() == verb:
+ return (1.0,) + tuple(row)
+ # 2. the turn DESCRIBES the operation: resonance of the verb and object against the catalogue, under the same tau as
+ # any request (the second probe: build 0.26, compose 0.30 on these two words alone; under tau, so this rarely fires)
+ try:
+ from compose_reply_v8 import content_words, unit
+ opw = [w for w in content_words(" ".join(words_of("verb") + words_of("object"))) if w]
+ except Exception: # noqa: BLE001
+ opw = []
+ if opw:
+ q2 = unit(self.r.text_vec(opw, {w: 1.0 for w in opw}))
+ op = self.r.op_head(q2, words=opw) or self.r.op_head(q2)
+ if op:
+ return op
+ # 3. the whole turn, as before
+ return self.r.op_head(q)
+
+ def evidence(self, qs):
+ """Amendment 14 (4): the store's evidence for the examples, read the way the answer path reads it: each example's entity
+ and the relation the question asks for; the relation every example's entity holds is what the task asks about"""
+ r = self.r
+ from compose_reply_v8 import content_words, unit
+ per = []
+ for q in qs:
+ ents = r.link(q)
+ if not ents:
+ continue
+ span, e, _ = ents[0]
+ names = set(content_words(span))
+ rest = [w for w in content_words(q) if w not in names]
+ if not rest:
+ continue
+ asked = "number" if re.match(r"\s*how (many|much|long|old|far|tall|high|big|deep|wide|heavy)", q.lower()) else None
+ rels, _ = r.relations(e, unit(r.text_vec(rest, {w: 1.0 for w in rest})), asked)
+ per.append((e, [(p, lab) for p, lab, _v, _f in rels[:3]]))
+ if len(per) < 2:
+ return None
+ common = None
+ for _e, rels in per:
+ ps = {p for p, _l in rels}
+ common = ps if common is None else common & ps
+ if not common:
+ return None
+ p = next(pp for pp, _l in per[0][1] if pp in common)
+ lab = next(l for pp, l in per[0][1] if pp == p)
+ return {"pid": "P%d" % p, "label": lab, "entities": ["Q%d" % e for e, _ in per]}
+
+ def build(self, session, st):
+ try:
+ import run as swarm_run
+ except Exception as e: # noqa: BLE001
+ return "hole", "The builder is not on this install's path [none]: %s." % repr(e)[:80], False
+ t0 = time.time()
+ try:
+ ev = self.evidence(st["qs"])
+ except Exception: # noqa: BLE001
+ ev = None
+ st["evidence"] = ev
+ try:
+ try:
+ r = swarm_run.build(st["qs"], None, anyway=False, evidence=ev)
+ except TypeError:
+ r = swarm_run.build(st["qs"], None, anyway=False)
+ except Exception as e: # noqa: BLE001
+ st["done"] = True
+ return "hole", "The build raised %s [op:%s]; the %d examples are kept [turn:%d]." % (repr(e)[:100], st["op"], len(st["qs"]), st["turn"]), False
+ st["done"] = True
+ st["result"] = {k: v for k, v in r.items() if k != "build"}
+ self.r.stats["build_run"] += 1
+ b = r.get("brief") or {}
+ parts = ["Built from your %d examples [op:%s] in %d s." % (len(st["qs"]), st["op"], time.time() - t0)]
+ if b:
+ parts.append("The swarm read them as %s%s%s." % (
+ b.get("type") or "a task", (", near " + ", ".join(b.get("neighbors") or [])) if b.get("neighbors") else "",
+ ("; the gap it named: " + str(b["gap"])) if b.get("gap") else ""))
+ parts.append(str(r.get("message", "")).strip())
+ return ("plan" if r.get("outcome") == "error" else "answer"), " ".join(p for p in parts if p), True
diff --git a/workbench/converse/claim_discussion.py b/workbench/converse/claim_discussion.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd6fc6a1cc337a4edb61342a4b428c30c0e87086
--- /dev/null
+++ b/workbench/converse/claim_discussion.py
@@ -0,0 +1,390 @@
+"""Develop received claims in the existing conversation thread.
+
+Reasons and definitions fill the same held claim; corrections make versions.
+The reply is composed from received parts and explicit discussion rules, then
+read back by a separate judge. Requests remain available to the work receiver.
+"""
+import copy
+import json
+import re
+import time
+import uuid
+
+from claim_shape import ClaimReader, atom
+import claim_judge
+from turn_meaning import literals, outside_literals
+
+
+def _quote(value):
+ return json.dumps(value, ensure_ascii=False)
+
+
+def clause(node):
+ subject = node["subject"]
+ if node.get("replacements"):
+ pieces = ([node["focus"]["text"]] if node.get("focus") else []) + [subject["text"], node["predicate"]["text"]]
+ for c in node["complements"]:
+ pieces += ([c["marker"]] if c.get("marker") else []) + [c["text"]]
+ return " ".join(pieces)
+ if subject.get("source") == node["source"] and node["span"][0] <= subject.get("span", [-1])[0] < node["span"][1]:
+ return node["text"]
+ return subject["text"] + " " + node["text"]
+
+
+def compose(graph, act="receive", dictionary=None):
+ checked = claim_judge.shape(graph, dictionary)
+ segments = []
+ nodes = {n["id"]: n for n in graph["nodes"]}
+ def add(role, text, ids=(), **extra):
+ segments.append(dict(role=role, text=text, nodes=list(ids), **extra))
+ alternative_members = {x[k] for x in graph["links"] if x["kind"] == "alternative" for k in ("from", "to")}
+ for rid in graph["roots"]:
+ if rid in alternative_members:
+ continue
+ n = nodes[rid]
+ attr, own = n["attribution"], _quote(clause(n))
+ if n.get("role_reading", {}).get("status") == "unresolved":
+ add("unresolved_roles", "The subject and action in %s are not yet settled." % own, [rid])
+ elif attr["speaker"] == "unresolved":
+ add("unattributed", "The speaker for %s is not yet settled." % own, [rid])
+ elif attr["speaker"] != "user" and attr["stance"] == "withheld_belief":
+ add("reported_withheld", "You're reporting that %s withholds belief in %s." % (_quote(attr["speaker"]), own), [rid])
+ elif attr["speaker"] != "user":
+ add("reported", "You're reporting %s's view: %s." % (_quote(attr["speaker"]), own), [rid])
+ elif attr["stance"] == "withheld_belief":
+ add("withheld", "You're withholding belief in %s." % own, [rid])
+ elif attr["stance"] == "tentative":
+ add("tentative", "Your view is %s." % own, [rid])
+ else:
+ add("assertion", "You're saying %s." % own, [rid])
+ if n.get("role_reading", {}).get("status") == "selected":
+ add("selected_roles", "You clarified that the subject is %s and the action is %s." % (_quote(n["subject"]["text"]), _quote(n["predicate"]["text"])), [rid])
+ if n["subject"].get("binding"):
+ explicit = n["subject"]["binding"]["basis"] == "explicit reference fill"
+ add("explicit_binding" if explicit else "binding", ("You clarified that %s refers to %s." if explicit else "Here, %s refers to %s from the preceding claim.") %
+ (_quote(n["subject"]["text"]), _quote(n["subject"]["binding"]["target"]["text"])), [rid])
+ for link in graph["links"]:
+ if act in ("conditions", "actuality", "consequence", "limits") and link["kind"] in ("reason", "purpose"):
+ continue
+ if act == "reason" and link["kind"] not in ("reason", "condition", "alternative", "contrast"):
+ continue
+ a, b = nodes[link["from"]], nodes[link["to"]]
+ qa, qb, ids = _quote(clause(a)), _quote(clause(b)), [a["id"], b["id"]]
+ if link.get("scope") == "unresolved" or any(x.get("role_reading", {}).get("status") == "unresolved" for x in (a, b)):
+ add("unresolved_link", "The connection between %s and %s is not yet settled." % (qa, qb), ids)
+ elif link["kind"] == "condition":
+ add("condition", "You place that claim in the situation %s, introduced by %s. That does not by itself say the situation causes the outcome." % (qa, _quote(link["mode"])), ids)
+ elif link["kind"] == "reason":
+ if link.get("scope") == "belief":
+ add("belief_reason", "You give %s as your reason for withholding belief in %s." % (qa, qb), ids)
+ elif link.get("scope") == "claim" and b["attribution"]["stance"] == "withheld_belief":
+ add("withheld_reason", "Inside the claim you withhold, %s is offered as a reason for %s." % (qa, qb), ids)
+ else:
+ add("reason", "You give %s as a reason for %s. That is the connection you supplied; its support still needs to be assessed." % (qa, qb), ids)
+ elif link["kind"] == "contrast":
+ add("contrast", "You contrast %s with %s." % (qa, qb), ids)
+ elif link["kind"] == "coordination":
+ add("coordination", "Both %s and %s belong to your account." % (qa, qb), ids)
+ elif link["kind"] == "alternative":
+ add("alternative", "You leave %s and %s as alternatives." % (qa, qb), ids)
+ elif link["kind"] == "sequence":
+ add("sequence", "Your account puts %s before %s." % (qa, qb), ids)
+ elif link["kind"] == "purpose":
+ add("purpose", "You give %s as the purpose of %s, not as a demonstrated result." % (qa, qb), ids)
+ if act in ("definition", "meaning", "receive"):
+ for i, definition in enumerate(graph.get("definitions", [])):
+ add("definition", "For this discussion, %s means %s." % (_quote(definition["term"]["text"]), _quote(definition["content"]["text"])), definition=i)
+ for i, hole in enumerate(graph["holes"]):
+ add("clarify", "I kept %s. %s" % (_quote(hole["text"]), _quote(hole["need"])), hole=i)
+ if not graph["holes"] and graph["roots"]:
+ n = nodes[graph["roots"][-1]]
+ own, rid, modal = _quote(clause(n)), n["id"], n.get("modal")
+ reasons = [x for x in graph["links"] if x["kind"] == "reason" and x["to"] == rid]
+ if act == "reason":
+ if not reasons: add("missing_reason", "What reason supports %s?" % own, [rid])
+ elif act in ("conditions", "actuality"):
+ conditions = [x for x in graph["links"] if x["kind"] == "condition" and x["to"] == rid]
+ if not conditions:
+ add("missing_condition", "What situation should %s apply to?" % own, [rid])
+ elif act == "actuality":
+ for condition in conditions:
+ parent = nodes[condition["from"]]
+ add("condition_actuality", "The conditional claim alone does not establish %s as true now." % _quote(clause(parent)), [parent["id"], rid])
+ elif act == "challenge":
+ add("challenge", "A challenge would need evidence against %s within its stated scope. I have not established such a counterexample." % own, [rid])
+ elif act in ("consequence", "limits"):
+ conditions = [x for x in graph["links"] if x["kind"] == "condition" and x["to"] == rid]
+ for condition in conditions:
+ parent = nodes[condition["from"]]
+ if condition["mode"] == "only if":
+ add("necessary_limit", "Your only-if condition %s is necessary in this account; satisfying it alone does not establish %s." % (_quote(clause(parent)), own), [parent["id"], rid])
+ else:
+ add("conditional_limit", "The link from %s to %s does not by itself establish the reverse link." % (_quote(clause(parent)), own), [parent["id"], rid])
+ if n["attribution"]["stance"] == "withheld_belief":
+ add("withheld_limit", "Withholding belief in %s does not establish its opposite." % own, [rid])
+ elif modal and modal["kind"] == "obligation":
+ add("obligation", "Treating %s as a requirement does not establish that it is already true." % own, [rid])
+ elif modal and modal["kind"] in ("possibility", "possibility_or_permission", "ability_or_possibility"):
+ add("possible", "The possibility in %s leaves room for it to happen without saying it happens every time." % own, [rid])
+ elif n["polarity"] == "negative":
+ add("negative_limit", "The negation in %s does not establish a different positive account." % own, [rid])
+ else:
+ add("premise_limit", "If we accept %s for this discussion, it is a premise; further causes or consequences need another supporting claim." % own, [rid])
+ elif act not in ("definition", "revision", "reason_fill", "meaning", "reference_fill", "scope_fill", "role_fill"):
+ if modal and modal["kind"] == "obligation" and n["attribution"]["stance"] != "withheld_belief":
+ if n["predicate"]["lemma"] == "be" and n["complements"] and not graph.get("definitions"):
+ add("norm_question", "What would count as %s for %s in practice?" % (_quote(n["complements"][0]["text"]), _quote(n["subject"]["text"])), [rid])
+ else:
+ add("behavior_question", "What observable result would show that %s is being met?" % own, [rid])
+ elif modal and modal["kind"] in ("possibility", "possibility_or_permission", "ability_or_possibility"):
+ add("possible", "The possibility in %s leaves room for it to happen without saying it happens every time." % own, [rid])
+ else:
+ add("open_question", "What would you like to examine about %s?" % own, [rid])
+ plan = {"graph_id": graph["id"], "version": graph["revision"], "truth": "unverified", "act": act, "segments": segments}
+ reply = "\n\n".join(s["text"] for s in segments)
+ delivery = claim_judge.delivery(graph, plan, reply)
+ check = {"passed": checked["passed"] and delivery["passed"], "shape": checked, "delivery": delivery}
+ if not check["passed"]:
+ return {"status": "hole", "path": "converse:claim:judge", "response": "I kept your wording, but the received parts did not pass their meaning check: " + "; ".join(checked["errors"] + delivery["errors"]), "meaning_graph": graph, "meaning_check": check}
+ return {"status": "hole" if graph["holes"] else "answered", "path": "converse:claim:" + act, "response": reply,
+ "meaning_graph": graph, "meaning_check": check, "meaning_plan": plan,
+ "basis": {"source": "received conversation claims", "truth": "unverified", "rules": [s["role"] for s in segments]}}
+
+
+def _merge(prior, addition):
+ graph = copy.deepcopy(prior)
+ rename = {n["id"]: "P%d" % (len(graph["nodes"]) + i + 1) for i, n in enumerate(addition["nodes"])}
+ for n in addition["nodes"]:
+ n = copy.deepcopy(n); n["id"] = rename[n["id"]]; graph["nodes"].append(n)
+ for link in addition["links"]:
+ link = copy.deepcopy(link); link["from"], link["to"] = rename[link["from"]], rename[link["to"]]; graph["links"].append(link)
+ for source in addition["sources"]:
+ if source not in graph["sources"]: graph["sources"].append(source)
+ graph["syntax"] += addition["syntax"]
+ graph["holes"] += addition["holes"]
+ graph["revision"] += 1
+ graph["latest"] = addition["original"]
+ return graph, [rename[r] for r in addition["roots"]]
+
+
+def _normal(text):
+ return re.sub(r"^(?:(?:the|a|an|all)\s+)+", "", text.strip().lower())
+
+
+def _move(text, prior, reader):
+ """Discourse roles refer to a held claim; new named topics stay outside."""
+ from priority_claims import _act
+ if any(x["kind"] in ("file", "code") for x in literals(text)):
+ return None
+ low = outside_literals(text).lower().strip()
+ if re.match(r"(?:please\s+)?(?:do not|don't)\b", low):
+ return None
+ if re.search(r"\bunderstand\b.*\b(?:saying|said|mean)\b", low) and re.search(r"\b(?:me|i|my)\b", low):
+ return "meaning"
+ if re.search(r"\b(?:believe|belief|withhold|withheld)\b", low) and re.match(r"what\b", low):
+ speakers = {n["attribution"]["speaker"].lower() for n in prior["nodes"]}
+ if any(re.search(r"\b" + re.escape(s) + r"\b", low) for s in speakers - {"user"}) or re.search(r"\b(?:i|my)\b", low):
+ return "meaning"
+ act = _act(text, reader)
+ self_recall = re.search(r"\b(?:reason|condition|claim|thought|view)\b", low) and re.search(r"\b(?:i|my|we|our)\b", low)
+ reference = re.search(r"\b(?:it|that|this|they|them|claim|idea|thought|view)\b", low)
+ if not act or not (self_recall or reference or low.rstrip("?.! ") == "why"):
+ return None
+ # A move about a held claim asks or requests something of it. A declarative
+ # turn with its own clause ("It bothers me when a tool forgets why I asked
+ # ...") is a new statement: its "it" and embedded "why" do not point back.
+ if not self_recall and not low.rstrip().endswith("?") and low.rstrip("?.! ") != "why":
+ try:
+ mood = reader.read(text).get("mood")
+ except Exception: # noqa: BLE001
+ mood = None
+ if mood == "statement" and not re.search(r"\b(?:that|this|the)\s+(?:claim|idea|thought|view|reason)\b", low):
+ return None
+ # A demonstrative followed by an unrelated noun introduces a new subject.
+ for m in re.finditer(r"\b(?:this|that)\s+(\w+)", low):
+ word = m.group(1)
+ if "noun" in reader.d.pos(word) and word not in {"claim", "idea", "thought", "view", "condition", "reason"} and word not in prior["original"].lower().split():
+ if not reader.d.pos(word) & {"verb", "adv"}: return None
+ if re.search(r"\b(?:already|actually occurred|has happened)\b", low) and any(x["kind"] == "condition" for x in prior["links"]):
+ return "actuality"
+ return act
+
+
+def _amend(prior, text):
+ graph = copy.deepcopy(prior)
+ graph["revision"] += 1
+ graph["latest"] = text
+ if text not in graph["sources"]: graph["sources"].append(text)
+ graph["syntax"].append(atom(text, 0, len(text), kind="explicit clarification"))
+ return graph
+
+
+def _fill(prior, text):
+ """Fill a named role or replace one existing part; keep its other joins."""
+ prefix = r"\s*(?:(?:actually|no)[,\s]+)?"
+ boundary = re.fullmatch(prefix + r"(?:the\s+)?subject\s+is\s+(.+?)\s*[.]?\s*", text, re.I)
+ if boundary:
+ choices = [(n["id"], i) for n in prior["nodes"] if n.get("role_reading", {}).get("status") == "unresolved"
+ for i, c in enumerate(n["role_reading"]["candidates"]) if _normal(c["subject"]["text"]) == _normal(boundary.group(1))]
+ if len(choices) == 1:
+ graph = _amend(prior, text)
+ nid, index = choices[0]
+ n = next(n for n in graph["nodes"] if n["id"] == nid)
+ n.update(copy.deepcopy(n["role_reading"]["candidates"][index]))
+ n["role_reading"].update(status="selected", index=index, evidence=atom(text, 0, len(text)))
+ graph["holes"] = [h for h in graph["holes"] if not (h["kind"] == "role_boundary" and h.get("node") == nid)]
+ return graph, "role_fill"
+ ref = re.fullmatch(prefix + r"(?:by\s+)(it|that|this|they|them)[,\s]+I mean\s+(.+?)\s*[.]?\s*", text, re.I)
+ if ref and any(h["kind"] == "reference" and h["text"].lower() == ref.group(1).lower() for h in prior["holes"]):
+ graph = _amend(prior, text)
+ target = atom(text, ref.start(2), ref.end(2))
+ for n in graph["nodes"]:
+ for part in [n["subject"]] + n["complements"]:
+ if part["text"].lower() == ref.group(1).lower():
+ part["binding"] = {"target": target, "basis": "explicit reference fill"}
+ graph["holes"] = [h for h in graph["holes"] if not (h["kind"] == "reference" and h["text"].lower() == ref.group(1).lower())]
+ return graph, "reference_fill"
+ change = re.fullmatch(prefix + r"I (?:mean|meant)\s+(.+?)\s+(?:rather than|instead of|not)\s+(.+?)\s*[.]?\s*", text, re.I)
+ if change:
+ old = _normal(change.group(2))
+ targets = [(n["id"], "subject", None, n["subject"]) for n in prior["nodes"] if _normal(n["subject"]["text"]) == old]
+ targets += [(n["id"], "complement", i, c) for n in prior["nodes"] for i, c in enumerate(n["complements"]) if _normal(c["text"]) == old]
+ graph = _amend(prior, text)
+ if len(targets) != 1:
+ graph["holes"].append(atom(text, 0, len(text), kind="correction_scope", need="Name the claim and the part you want this correction to replace."))
+ graph["pending_correction"] = {"new": atom(text, change.start(1), change.end(1)), "old": atom(text, change.start(2), change.end(2))}
+ return graph, "clarify"
+ nid, role, index, before = targets[0]
+ n = next(n for n in graph["nodes"] if n["id"] == nid)
+ after = dict(before, **atom(text, change.start(1), change.end(1)))
+ after.pop("binding", None)
+ if role == "subject": n["subject"] = after
+ else: n["complements"][index] = after
+ n.setdefault("replacements", []).append({"role": role, "index": index, "before": before, "after": after})
+ graph["revises"] = {"id": prior["id"], "revision": prior["revision"], "instruction": text}
+ return graph, "revision"
+ ownership = re.fullmatch(r"\s*(?:(?:that|the (?:second|contrasting) (?:clause|claim))\s+(?:is|was|belongs to)\s+(mine|my (?:claim|view)|me)|(.+?)\s+(?:said|believes|owns)\s+both)\s*[.]?\s*", text, re.I)
+ if ownership and sum(h["kind"] == "attribution_scope" for h in prior["holes"]) == 1:
+ owner = "user" if ownership.group(1) else ownership.group(2).strip()
+ candidates = {c for n in prior["nodes"] for c in n["attribution"].get("candidates", [])}
+ if owner == "user" or owner.lower() in {x.lower() for x in candidates}:
+ graph = _amend(prior, text)
+ for n in graph["nodes"]:
+ if n["attribution"]["speaker"] == "unresolved":
+ n["attribution"].update(speaker=owner, stance="asserted" if owner == "user" else "reported", basis="explicit attribution fill", evidence=atom(text, 0, len(text)))
+ graph["holes"] = [h for h in graph["holes"] if h["kind"] != "attribution_scope"]
+ return graph, "scope_fill"
+ reason_owner = re.fullmatch(r"\s*(?:the reason|that|it)\s+(?:is|explains|concerns|applies to|belongs to)\s+(.+?)\s*[.]?\s*", text, re.I)
+ if reason_owner and sum(h["kind"] == "reason_scope" for h in prior["holes"]) == 1:
+ body = reason_owner.group(1).lower()
+ scope = "belief" if re.search(r"\b(?:belief|withhold|withholding)\b", body) else "claim" if re.search(r"\bclaim\b", body) else None
+ if scope:
+ graph = _amend(prior, text)
+ for link in graph["links"]:
+ if link["kind"] == "reason" and link.get("scope") == "unresolved":
+ link.update(scope=scope, scope_evidence=atom(text, 0, len(text)))
+ graph["holes"] = [h for h in graph["holes"] if h["kind"] != "reason_scope"]
+ return graph, "scope_fill"
+ selector = re.fullmatch(r"\s*(?:I meant\s+)?(?:the\s+)?(subject|object|property)(?:\s+of\s+(?:the\s+)?(first|second|third)\s+claim)?\s*[.]?\s*", text, re.I)
+ if selector and prior.get("pending_correction"):
+ roots = prior["roots"]
+ if selector.group(2):
+ ordinal = {"first": 0, "second": 1, "third": 2}[selector.group(2).lower()]
+ roots = roots[ordinal:ordinal + 1]
+ targets = []
+ for n in prior["nodes"]:
+ if n["id"] not in roots: continue
+ if selector.group(1).lower() == "subject": targets.append((n["id"], "subject", None, n["subject"]))
+ else:
+ targets += [(n["id"], "complement", i, c) for i, c in enumerate(n["complements"]) if c["role"] == selector.group(1).lower()]
+ if len(targets) == 1:
+ graph = _amend(prior, text)
+ nid, role, index, before = targets[0]
+ n = next(n for n in graph["nodes"] if n["id"] == nid)
+ after = dict(before, **graph["pending_correction"]["new"])
+ after.pop("binding", None)
+ if role == "subject": n["subject"] = after
+ else: n["complements"][index] = after
+ n.setdefault("replacements", []).append({"role": role, "index": index, "before": before, "after": after})
+ graph.pop("pending_correction", None)
+ graph["holes"] = [h for h in graph["holes"] if h["kind"] != "correction_scope"]
+ return graph, "revision"
+ return None
+
+
+def handle(text, sid, reader, allow_statement=True):
+ import reflect
+ record = reflect.load(sid)
+ prior = next((x.get("graph") for x in reversed(record.get("thread", [])) if x.get("kind") == "received_claim"), None)
+ ledger = record.get("ledger") or []
+ focused = bool(prior and ledger and str(ledger[-1].get("path", "")).startswith("converse:claim:"))
+ graph, act = None, "receive"
+ filled = _fill(prior, text) if prior and (focused or re.search(r"\b(?:I mean|I meant)\b", text, re.I)) else None
+ if filled:
+ graph, act = filled
+ alias = re.fullmatch(r"\s*([A-Za-z][\w-]*)\s+means\s+([A-Za-z][\w-]*)\s*[.]?\s*", text, re.I)
+ if graph is None and focused and alias and any(h["kind"] == "predicate" for h in prior["holes"]):
+ word, meaning = alias.group(1).lower(), alias.group(2).lower()
+ if "verb" in reader.d.pos(meaning):
+ meanings = dict(prior.get("word_meanings", {}))
+ meanings[word] = {"meaning": meaning, "evidence": atom(text, 0, len(text))}
+ graph = ClaimReader(reader, meanings).read(prior["original"])
+ graph.update(id=prior["id"], revision=prior["revision"] + 1, word_meanings=meanings, latest=text)
+ graph["sources"].append(text); graph["syntax"].append(atom(text, 0, len(text), kind="received word meaning"))
+ graph["definitions"] = [{"term": atom(text, alias.start(1), alias.end(1)), "content": atom(text, alias.start(2), alias.end(2))}]
+ act = "definition"
+ if focused:
+ reason = re.match(r"\s*because\s+", text, re.I)
+ definition = re.fullmatch(r"\s*by\s+(.+?)[,\s]+I mean\s+(.+?)\s*[.]?\s*", text, re.I)
+ if graph is not None:
+ pass
+ elif reason:
+ addition = ClaimReader(reader).read(text, content_span=(reason.end(), len(text)))
+ graph, ids = _merge(prior, addition)
+ for nid in ids:
+ for root in graph["roots"]:
+ graph["links"].append({"kind": "reason", "mode": "because", "from": nid, "to": root, "connector": atom(text, reason.start(), reason.end())})
+ act = "reason_fill"
+ elif definition:
+ term = definition.group(1).strip(" ,")
+ targets = [(n, c) for n in prior["nodes"] for c in [n["subject"]] + n["complements"] if c["text"].lower() == term.lower()]
+ if len(targets) == 1:
+ addition = ClaimReader(reader).read(text, previous=prior, content_span=(definition.start(2), definition.end(2)))
+ graph, ids = _merge(prior, addition)
+ graph.setdefault("definitions", []).append({"term": atom(text, definition.start(1), definition.end(1)),
+ "content": atom(text, definition.start(2), definition.end(2)), "target": targets[0][0]["id"], "nodes": ids})
+ act = "definition"
+ else:
+ move = _move(text, prior, reader)
+ if move:
+ return compose(prior, move, reader.d)
+ elif prior and graph is None and re.search(r"\b(?:did I|my (?:claim|reason)|understand me)\b", text, re.I):
+ move = _move(text, prior, reader)
+ if move:
+ return compose(prior, move, reader.d)
+ if graph is None:
+ if not allow_statement:
+ return None
+ graph = ClaimReader(reader, (prior or {}).get("word_meanings") if focused else None).read(text, previous=prior if focused else None)
+ words = re.findall(r"[A-Za-z]+", outside_literals(text))
+ if graph["act"] != "statement" or (not graph["nodes"] and not focused and (len(words) < 3 or "intj" in reader.d.pos(words[0].lower()))):
+ return None
+ # A quoted literal or social fragment is not enough to establish a new
+ # proposition; failed reading stays with the existing head.
+ if graph.get("correction") and focused:
+ if not graph["roots"] or graph["holes"]:
+ held = _amend(prior, text)
+ held["holes"].append(atom(text, 0, len(text), kind="correction_scope", need="Name the part of the existing claim this correction replaces."))
+ graph = held
+ graph["id"], graph["revision"] = prior["id"], prior["revision"] + 1
+ graph["revises"] = {"id": prior["id"], "revision": prior["revision"]}
+ act = "revision"
+ else:
+ graph["id"], graph["revision"] = uuid.uuid4().hex[:12], 1
+ graph["t"] = time.time()
+ result = compose(graph, act, reader.d)
+ if result["meaning_check"]["passed"]:
+ record.setdefault("thread", []).append({"kind": "received_claim", "t": graph["t"], "graph": graph})
+ record["thread"] = record["thread"][-40:]
+ reflect.save(sid, record)
+ return result
diff --git a/workbench/converse/claim_judge.py b/workbench/converse/claim_judge.py
new file mode 100644
index 0000000000000000000000000000000000000000..a087191fa3fc0d4a644ed1a9167935d67b7c4c39
--- /dev/null
+++ b/workbench/converse/claim_judge.py
@@ -0,0 +1,271 @@
+"""Check a received shape and read every delivered discussion part back.
+
+No receiver or writer is called here. Source positions, clause direction,
+attribution, modal/negative scope and the small allowed discussion rules are
+checked independently. Holding a user's sentence does not certify its truth.
+"""
+import json
+import re
+
+WORDS = re.compile(r"[A-Za-z0-9_]+(?:['’-][A-Za-z0-9_]+)*")
+NEG = re.compile(r"\b(?:not|never|cannot)\b|n't\b", re.I)
+MODALS = {"should": "obligation", "must": "obligation", "shall": "obligation", "may": "possibility_or_permission", "might": "possibility",
+ "could": "possibility", "can": "ability_or_possibility", "will": "future", "would": "conditional"}
+Q = r'"(?:[^"\\]|\\.)*"'
+
+
+def _atoms(value):
+ if isinstance(value, dict):
+ if "source" in value and "span" in value and "text" in value:
+ yield value
+ for key, child in value.items():
+ if key not in ("source", "span", "text"):
+ yield from _atoms(child)
+ elif isinstance(value, list):
+ for child in value:
+ yield from _atoms(child)
+
+
+def shape(graph, dictionary=None):
+ errors, covered = [], {}
+ nodes = {n["id"]: n for n in graph.get("nodes", [])}
+ sources = set(graph.get("sources", []))
+ owned = list(graph.get("syntax", [])) + list(graph.get("holes", [])) + list(graph.get("definitions", [])) + list(graph.get("reference_context", [])) + list(graph.get("links", []))
+ for n in nodes.values():
+ owned += [v for k, v in n.items() if k not in ("text", "span", "source", "id", "kind")]
+ if n.get("truth") != "unverified":
+ errors.append("received assertion promoted to world truth")
+ predicate = n["predicate"]
+ if (n["polarity"] == "negative") != bool(NEG.search(predicate["text"])):
+ errors.append("predicate negation changed")
+ modal = n.get("modal")
+ if modal and modal.get("kind") != MODALS.get(modal.get("lemma")):
+ errors.append("modal force changed")
+ if dictionary is not None:
+ actual = {dictionary.lemma(w.lower(), "verb") for w in WORDS.findall(predicate["text"])}
+ if predicate["lemma"] == "be":
+ if not re.search(r"\b(?:am|is|are|was|were|be|been|being)\b|\b(?:isn't|aren't|wasn't|weren't)\b", predicate["text"], re.I):
+ errors.append("property relation has no received copula")
+ elif predicate["lemma"] not in actual and not predicate.get("meaning"):
+ errors.append("predicate does not follow dictionary form")
+ subj = n["subject"]
+ if subj.get("source") == n["source"] and n["span"][0] <= subj["span"][0] <= n["span"][1] and subj["span"][1] > predicate["span"][0]:
+ errors.append("subject crosses received predicate")
+ for c in n.get("complements", []):
+ if c["source"] == predicate["source"] and c["span"][0] < predicate["span"][1]:
+ errors.append("complement moved before its predicate")
+ if c.get("marker"):
+ before = c["source"][:c["span"][0]].rstrip()
+ if not before.lower().endswith(c["marker"].lower()):
+ errors.append("preposition changed")
+ attr = n["attribution"]
+ if attr.get("wording"):
+ wording = attr["wording"]["text"]
+ is_user = bool(re.match(r"(?:I|we)\b", wording, re.I))
+ if attr.get("basis") == "explicit attribution fill":
+ evidence = attr.get("evidence", {}).get("text", "")
+ if attr["speaker"] == "user":
+ if not re.search(r"\b(?:mine|my (?:claim|view)|me)\b", evidence, re.I): errors.append("user ownership lacks explicit fill")
+ elif not re.search(r"\b" + re.escape(attr["speaker"]) + r"\b", evidence, re.I): errors.append("named ownership lacks explicit fill")
+ elif attr["speaker"] != "unresolved" and is_user != (attr["speaker"] == "user"):
+ errors.append("reported speaker changed")
+ if bool(NEG.search(wording)) != (attr["stance"] == "withheld_belief"):
+ errors.append("withheld belief changed")
+ if subj.get("implicit") and n["speech_act"] != "request":
+ errors.append("implicit requested actor presented as assertion")
+ reading = n.get("role_reading")
+ if reading:
+ choices = reading.get("candidates", [])
+ if len(choices) < 2: errors.append("role ambiguity lacks competing readings")
+ for choice in choices:
+ s, p = choice["subject"], choice["predicate"]
+ if s["source"] != n["source"] or p["source"] != n["source"] or not (n["span"][0] <= s["span"][0] < s["span"][1] <= p["span"][0] < p["span"][1] <= n["span"][1]):
+ errors.append("role candidate leaves received clause")
+ if n["source"][s["span"][1]:p["span"][0]].strip(): errors.append("role boundary skips source words")
+ if dictionary and dictionary.lemma(p["text"].lower(), "verb") != p["lemma"]: errors.append("role candidate has no held verb form")
+ held = {k: n[k] for k in ("subject", "predicate", "complements")}
+ if held not in choices: errors.append("received roles differ from retained choices")
+ if reading["status"] == "unresolved":
+ if not any(h["kind"] == "role_boundary" and h.get("node") == n["id"] for h in graph["holes"]): errors.append("ambiguous roles lost their owned hole")
+ elif reading["status"] == "selected":
+ index = reading.get("index")
+ if not isinstance(index, int) or not 0 <= index < len(choices) or held != choices[index]: errors.append("selected roles differ from held choice")
+ evidence = reading.get("evidence", {}).get("text", "")
+ selected = re.fullmatch(r"\s*(?:(?:actually|no)[,\s]+)?(?:the\s+)?subject\s+is\s+(.+?)\s*[.]?\s*", evidence, re.I)
+ normal = lambda value: re.sub(r"^(?:(?:the|a|an|all)\s+)+", "", value.strip().lower())
+ if not selected or normal(selected.group(1)) != normal(n["subject"]["text"]): errors.append("role selection lacks explicit subject clarification")
+ else: errors.append("unknown role-reading status")
+ for item in _atoms(owned):
+ source, span = item["source"], item["span"]
+ if source not in sources or len(span) != 2 or not 0 <= span[0] <= span[1] <= len(source) or source[slice(*span)] != item["text"]:
+ errors.append("source span does not hold")
+ continue
+ covered.setdefault(source, []).append(span)
+ for source in sources:
+ if source in graph.get("context_sources", []):
+ continue
+ for word in WORDS.finditer(source):
+ if not any(a <= word.start() and word.end() <= b for a, b in covered.get(source, [])):
+ errors.append("unowned source words: " + word.group())
+ for link in graph.get("links", []):
+ if link["from"] not in nodes or link["to"] not in nodes:
+ errors.append("link refers to absent claim")
+ if link.get("mode", "").lower() != link["connector"]["text"].lower() and link["kind"] not in ("relative", "definition"):
+ errors.append("link wording changed")
+ mode = link["connector"]["text"].lower()
+ expected_kind = {"because": "reason", "so that": "purpose", "in order to": "purpose", "but": "contrast", "although": "contrast",
+ "and": "coordination", "or": "alternative", "then": "sequence", "and then": "sequence",
+ "that": "relative", "which": "relative", "who": "relative"}.get(mode, "condition" if mode in ("if", "when", "unless", "only if", "provided that", "while", "after", "before") else None)
+ if expected_kind != link["kind"]:
+ errors.append("connector changed to another relation kind")
+ if link["from"] in nodes and link["to"] in nodes:
+ a, b, c = nodes[link["from"]], nodes[link["to"]], link["connector"]
+ if a["source"] == b["source"] == c["source"]:
+ if expected_kind in ("coordination", "alternative", "sequence") or (expected_kind == "contrast" and mode == "but"):
+ order = a["span"][1] <= c["span"][0] and c["span"][1] <= b["span"][0]
+ else:
+ suffix = b["span"][1] <= c["span"][0] and c["span"][1] <= a["span"][0]
+ comma = c["source"].find(",", c["span"][1])
+ prefix = c["span"][1] <= a["span"][0] and a["span"][1] <= comma < b["span"][0]
+ order = suffix or prefix
+ if not order: errors.append("received link direction changed")
+ elif not (expected_kind == "reason" and a["source"] == c["source"] and
+ not c["source"][:c["span"][0]].strip() and c["span"][1] <= a["span"][0]):
+ errors.append("unowned cross-turn relation")
+ if link.get("scope") in ("belief", "claim"):
+ ev = link.get("scope_evidence", {}).get("text", "")
+ if not re.search(r"\b(?:belief|withhold|withholding)\b" if link["scope"] == "belief" else r"\bclaim\b", ev, re.I):
+ errors.append("reason scope lacks explicit fill")
+ if not all(root in nodes for root in graph.get("roots", [])):
+ errors.append("absent root claim")
+ return {"passed": not errors, "errors": list(dict.fromkeys(errors)), "claims": len(nodes), "sources": len(sources),
+ "holes": len(graph.get("holes", [])), "coverage": "source words, roles, links, modal/negative scope and attribution"}
+
+
+def _clause(n):
+ subject = n["subject"]
+ if n.get("replacements"):
+ fields = ([n["focus"]["text"]] if n.get("focus") else []) + [subject["text"], n["predicate"]["text"]]
+ for c in n["complements"]:
+ if c.get("marker"): fields.append(c["marker"])
+ fields.append(c["text"])
+ return " ".join(fields)
+ if subject.get("source") == n["source"] and n["span"][0] <= subject.get("span", [-1])[0] < n["span"][1]:
+ return n["text"]
+ return subject["text"] + " " + n["text"]
+
+
+def delivery(graph, plan, reply):
+ errors = []
+ nodes = {n["id"]: n for n in graph["nodes"]}
+ if reply != "\n\n".join(s.get("text", "") for s in plan.get("segments", [])):
+ errors.append("unread delivered text")
+ if plan.get("truth") != "unverified" or plan.get("graph_id") != graph.get("id") or plan.get("version") != graph.get("revision", 1):
+ errors.append("wrong graph, version or claim truth")
+ grammar = {
+ "assertion": r"You're saying (" + Q + r")\.",
+ "tentative": r"Your view is (" + Q + r")\.",
+ "withheld": r"You're withholding belief in (" + Q + r")\.",
+ "reported": r"You're reporting (" + Q + r")'s view: (" + Q + r")\.",
+ "reported_withheld": r"You're reporting that (" + Q + r") withholds belief in (" + Q + r")\.",
+ "unresolved_roles": r"The subject and action in (" + Q + r") are not yet settled\.",
+ "selected_roles": r"You clarified that the subject is (" + Q + r") and the action is (" + Q + r")\.",
+ "unattributed": r"The speaker for (" + Q + r") is not yet settled\.",
+ "unresolved_link": r"The connection between (" + Q + r") and (" + Q + r") is not yet settled\.",
+ "condition": r"You place that claim in the situation (" + Q + r"), introduced by (" + Q + r")\. That does not by itself say the situation causes the outcome\.",
+ "reason": r"You give (" + Q + r") as a reason for (" + Q + r")\. That is the connection you supplied; its support still needs to be assessed\.",
+ "belief_reason": r"You give (" + Q + r") as your reason for withholding belief in (" + Q + r")\.",
+ "withheld_reason": r"Inside the claim you withhold, (" + Q + r") is offered as a reason for (" + Q + r")\.",
+ "contrast": r"You contrast (" + Q + r") with (" + Q + r")\.",
+ "coordination": r"Both (" + Q + r") and (" + Q + r") belong to your account\.",
+ "alternative": r"You leave (" + Q + r") and (" + Q + r") as alternatives\.",
+ "sequence": r"Your account puts (" + Q + r") before (" + Q + r")\.",
+ "purpose": r"You give (" + Q + r") as the purpose of (" + Q + r"), not as a demonstrated result\.",
+ "norm_question": r"What would count as (" + Q + r") for (" + Q + r") in practice\?",
+ "behavior_question": r"What observable result would show that (" + Q + r") is being met\?",
+ "open_question": r"What would you like to examine about (" + Q + r")\?",
+ "possible": r"The possibility in (" + Q + r") leaves room for it to happen without saying it happens every time\.",
+ "obligation": r"Treating (" + Q + r") as a requirement does not establish that it is already true\.",
+ "withheld_limit": r"Withholding belief in (" + Q + r") does not establish its opposite\.",
+ "negative_limit": r"The negation in (" + Q + r") does not establish a different positive account\.",
+ "conditional_limit": r"The link from (" + Q + r") to (" + Q + r") does not by itself establish the reverse link\.",
+ "necessary_limit": r"Your only-if condition (" + Q + r") is necessary in this account; satisfying it alone does not establish (" + Q + r")\.",
+ "premise_limit": r"If we accept (" + Q + r") for this discussion, it is a premise; further causes or consequences need another supporting claim\.",
+ "missing_reason": r"What reason supports (" + Q + r")\?",
+ "challenge": r"A challenge would need evidence against (" + Q + r") within its stated scope\. I have not established such a counterexample\.",
+ "definition": r"For this discussion, (" + Q + r") means (" + Q + r")\.",
+ "binding": r"Here, (" + Q + r") refers to (" + Q + r") from the preceding claim\.",
+ "explicit_binding": r"You clarified that (" + Q + r") refers to (" + Q + r")\.",
+ "missing_condition": r"What situation should (" + Q + r") apply to\?",
+ "condition_actuality": r"The conditional claim alone does not establish (" + Q + r") as true now\.",
+ "clarify": r"I kept (" + Q + r")\. (" + Q + r")",
+ }
+ seen = set()
+ for segment in plan.get("segments", []):
+ role = segment.get("role")
+ match = re.fullmatch(grammar.get(role, r"(?!)"), segment.get("text", ""))
+ if not match:
+ errors.append("unread discussion segment: " + str(role)); continue
+ try:
+ values = [json.loads(v) for v in match.groups()]
+ ids = segment.get("nodes", [])
+ own = [nodes[i] for i in ids]
+ n = own[0] if own else None
+ expected = []
+ unsettled = any(x.get("role_reading", {}).get("status") == "unresolved" for x in own)
+ if unsettled and role not in ("unresolved_roles", "unresolved_link"):
+ errors.append("unresolved roles presented as settled meaning")
+ if role in ("assertion", "tentative", "withheld", "reported", "reported_withheld", "unattributed", "unresolved_roles"):
+ expected = [_clause(n)]
+ attr = n["attribution"]
+ correct = ("unresolved_roles" if n.get("role_reading", {}).get("status") == "unresolved" else "unattributed" if attr["speaker"] == "unresolved" else
+ "reported_withheld" if attr["speaker"] != "user" and attr["stance"] == "withheld_belief" else "reported" if attr["speaker"] != "user" else
+ "withheld" if attr["stance"] == "withheld_belief" else "tentative" if attr["stance"] == "tentative" else "assertion")
+ if role in ("reported", "reported_withheld"): expected.insert(0, attr["speaker"])
+ if role != correct: errors.append("delivered speaker or stance changed")
+ seen.add(n["id"])
+ elif role == "selected_roles":
+ expected = [n["subject"]["text"], n["predicate"]["text"]]
+ if n.get("role_reading", {}).get("status") != "selected": errors.append("unreceived role clarification")
+ elif role in ("condition", "reason", "contrast", "coordination", "alternative", "sequence", "purpose", "conditional_limit", "necessary_limit", "unresolved_link", "belief_reason", "withheld_reason"):
+ link = next((x for x in graph["links"] if x["from"] == ids[0] and x["to"] == ids[1]), None)
+ if not link: raise ValueError("no owned link")
+ expected = [_clause(own[0]), _clause(own[1])]
+ if role == "condition": expected = [_clause(own[0]), link["mode"]]
+ allowed = {"conditional_limit": "condition", "necessary_limit": "condition", "belief_reason": "reason", "withheld_reason": "reason"}.get(role, role)
+ if role == "unresolved_link":
+ if link.get("scope") != "unresolved" and not unsettled: errors.append("settled link declared unresolved")
+ elif link["kind"] != allowed or link.get("scope") == "unresolved": errors.append("link kind or scope changed in discussion")
+ if role in ("belief_reason", "withheld_reason") and (link.get("scope") != ("belief" if role == "belief_reason" else "claim") or own[1]["attribution"]["stance"] != "withheld_belief"):
+ errors.append("withheld reason attached to wrong scope")
+ if role == "necessary_limit" and link["mode"] != "only if": errors.append("condition made necessary")
+ seen.update(ids)
+ elif role == "norm_question":
+ expected = [n["complements"][0]["text"], n["subject"]["text"]]
+ if not n.get("modal") or n["modal"]["kind"] != "obligation": errors.append("nonrequirement worded as requirement")
+ elif role in ("behavior_question", "open_question", "possible", "obligation", "withheld_limit", "negative_limit", "premise_limit", "missing_reason", "challenge", "missing_condition"):
+ expected = [_clause(n)]
+ if role == "possible" and (not n.get("modal") or n["modal"]["kind"] not in ("possibility", "possibility_or_permission", "ability_or_possibility")): errors.append("unsupported possibility rule")
+ if role in ("obligation", "behavior_question") and (not n.get("modal") or n["modal"]["kind"] != "obligation"): errors.append("unsupported obligation rule")
+ if role == "withheld_limit" and n["attribution"]["stance"] != "withheld_belief": errors.append("unsupported withheld-belief rule")
+ if role == "negative_limit" and n["polarity"] != "negative": errors.append("unsupported negative rule")
+ if role == "missing_reason" and any(x["kind"] == "reason" and x["to"] == n["id"] for x in graph["links"]): errors.append("held reason declared missing")
+ if role == "missing_condition" and any(x["kind"] == "condition" and x["to"] == n["id"] for x in graph["links"]): errors.append("held condition declared missing")
+ elif role == "condition_actuality":
+ expected = [_clause(n)]
+ if not any(x["kind"] == "condition" and x["from"] == ids[0] and x["to"] == ids[1] for x in graph["links"]): errors.append("actuality limit has no conditional source")
+ elif role in ("binding", "explicit_binding"):
+ expected = [n["subject"]["text"], n["subject"]["binding"]["target"]["text"]]
+ if (role == "explicit_binding") != (n["subject"]["binding"]["basis"] == "explicit reference fill"): errors.append("binding source changed")
+ elif role == "definition":
+ definition = graph["definitions"][segment["definition"]]
+ expected = [definition["term"]["text"], definition["content"]["text"]]
+ elif role == "clarify":
+ hole = graph["holes"][segment["hole"]]
+ expected = [hole["text"], hole["need"]]
+ if values != expected: errors.append("delivered argument, condition or source wording changed")
+ except (ValueError, KeyError, TypeError, IndexError):
+ errors.append("discussion part lacks received support")
+ if graph.get("nodes") and not set(graph.get("roots", [])) <= seen:
+ errors.append("a main received claim is absent from the reply")
+ return {"passed": not errors, "errors": list(dict.fromkeys(errors)), "coverage": "every delivered part and its received support"}
diff --git a/workbench/converse/claim_shape.py b/workbench/converse/claim_shape.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcd69b3b15e97b303f7776387669b0413f17e70b
--- /dev/null
+++ b/workbench/converse/claim_shape.py
@@ -0,0 +1,394 @@
+"""Receive a claim as owned parts and joins, retaining every source span.
+
+The native dictionary supplies open words and their forms. The small closed
+grammar below supplies joins, attribution and modal scope; it contains no
+project domains or example answers. A received claim is not a verified fact.
+"""
+import copy
+import json
+import re
+
+from turn_meaning import outside_literals, literals, _ExactWords
+
+WORD = re.compile(r"[A-Za-z0-9_]+(?:['’-][A-Za-z0-9_]+)*")
+COPULA = {"am", "is", "are", "was", "were", "be", "been", "being"}
+MODAL = {"should": "obligation", "must": "obligation", "shall": "obligation", "may": "possibility_or_permission",
+ "might": "possibility", "could": "possibility", "can": "ability_or_possibility", "will": "future", "would": "conditional"}
+AUXILIARY = {"do", "does", "did", "have", "has", "had"}
+NEGATED_AUX = {"don't": "do", "doesn't": "does", "didn't": "did", "isn't": "is", "aren't": "are", "wasn't": "was",
+ "weren't": "were", "can't": "can", "cannot": "can", "couldn't": "could", "shouldn't": "should",
+ "mustn't": "must", "won't": "will", "wouldn't": "would", "hasn't": "has", "haven't": "have", "hadn't": "had"}
+DETERMINERS = {"a", "an", "the", "my", "your", "our", "their", "his", "her", "its", "this", "that", "these", "those", "every", "each", "some", "any", "no"}
+PREPOSITIONS = {"to", "from", "with", "without", "in", "on", "at", "for", "by", "like", "as", "into", "onto", "through", "across", "under", "over", "above", "below", "beside", "between", "around", "against", "within", "beyond", "before", "after", "until", "during"}
+REPORT = re.compile(r"^(?PI|we|[A-Z][\w-]*(?:\s+[A-Z][\w-]*)?)\s+"
+ r"(?P(?:(?:do not|don't|does not|doesn't)\s+)?(?:(?:personally|really|strongly|honestly)\s+)?"
+ r"(?:think|thinks|believe|believes|feel|feels|suspect|suspects|hope|hopes|say|says|said|claim|claims|argue|argues))\b\s*(?:that\s+)?", re.I)
+PREFIX = re.compile(r"^(only if|provided that|because|if|when|unless|while|although|after|before)\b\s*", re.I)
+SUFFIX = re.compile(r"\b(because|only if|provided that|unless|when|if|so that|in order to)\b", re.I)
+COORD = re.compile(r"\b(and then|and|but|or|then)\b", re.I)
+
+
+def atom(source, start, end, **fields):
+ while start < end and source[start].isspace():
+ start += 1
+ while end > start and (source[end - 1].isspace() or source[end - 1] in ".?!,;"):
+ end -= 1
+ return dict(text=source[start:end], span=[start, end], source=source, **fields)
+
+
+class ClaimReader:
+ def __init__(self, reader, meanings=None):
+ from turn_reader import Reader
+ self.native = Reader(reader.d, _ExactWords())
+ self.d = reader.d
+ self.meanings = meanings or {}
+
+ def _verb(self, word):
+ low = word.lower()
+ if low in DETERMINERS or low in PREPOSITIONS or low in {"and", "or", "but", "if", "when", "that", "which", "who", "i", "we", "you", "they", "it"}:
+ return None
+ target = self.meanings.get(low, {}).get("meaning", low)
+ lemma = self.d.lemma(target, "verb")
+ if "verb" in self.d.pos(target):
+ return lemma
+ try:
+ explicit = self.d.db.execute("SELECT 1 FROM forms WHERE form=? AND pos='verb' LIMIT 1", (target,)).fetchone()
+ except Exception:
+ explicit = None
+ return lemma if explicit and "verb" in self.d.pos(lemma) else None
+
+ def _tokens(self, start, end):
+ tokens = [(m.group(), m.start(), m.end()) for m in WORD.finditer(self.mask, start, end)]
+ tokens += [(x["text"], *x["span"]) for x in self.g["literals"] if start <= x["span"][0] and x["span"][1] <= end]
+ return sorted(tokens, key=lambda x: x[1])
+
+ def _syntax(self, start, end, kind):
+ self.g["syntax"].append(atom(self.text, start, end, kind=kind))
+
+ def _hole(self, text, start, end, kind="reading"):
+ h = atom(self.text, start, end, kind=kind, need=text)
+ self.g["holes"].append(h)
+ return []
+
+ def _predicate(self, tokens, inherited=False, request=False):
+ if not tokens:
+ return None
+ if inherited and self._verb(tokens[0][0]):
+ return 0
+ # Closed grammatical markers locate the finite phrase without guessing
+ # a noun/verb sense from an incidental word in a dictionary definition.
+ for i, (word, _, _) in enumerate(tokens):
+ low = word.lower()
+ if i and (low in COPULA or low in MODAL or low in AUXILIARY or low in NEGATED_AUX):
+ return i
+ if request and self._verb(tokens[0][0]):
+ counts = {pos: sum(len(gs) for p, gs in self.d.entries(tokens[0][0].lower()) if p == pos) for pos in ("noun", "adj", "verb")}
+ if counts["verb"] >= max(counts["noun"], counts["adj"]):
+ return 0
+ for i, (word, _, _) in enumerate(tokens):
+ if not i or not self._verb(word) or word.lower().endswith("ing"):
+ continue
+ before = tokens[i - 1][0].lower()
+ if before in DETERMINERS or before in PREPOSITIONS:
+ continue
+ # A following verb-only word cannot be the apparent object head.
+ if i + 1 < len(tokens) and self._verb(tokens[i + 1][0]) and self.d.pos(tokens[i + 1][0].lower()) <= {"verb"} and not tokens[i + 1][0].lower().endswith("ing"):
+ continue
+ return i
+ return None
+
+ def _role_boundaries(self, tokens):
+ """Retain competing finite boundaries allowed by noun forms/agreement.
+
+ This is a conservative ambiguity check, not a likelihood ranking of
+ dictionary senses. Closed auxiliaries already locate a finite phrase.
+ """
+ if any(w.lower() in COPULA | set(MODAL) | AUXILIARY | set(NEGATED_AUX) for w, _, _ in tokens):
+ return []
+ candidates = []
+ for i, (word, _, _) in enumerate(tokens):
+ if not i or not self._verb(word): continue
+ if i + 1 < len(tokens) and self._verb(tokens[i + 1][0]) and self.d.pos(tokens[i + 1][0].lower()) <= {"verb"}:
+ continue
+ prefix = [w.lower() for w, _, _ in tokens[:i]]
+ if prefix[-1] in DETERMINERS | PREPOSITIONS: continue
+ # All pre-head words must remain possible nominal modifiers.
+ if any(w in PREPOSITIONS or (self.d.pos(w) and not self.d.pos(w) & {"noun", "adj", "name", "proper noun", "det"} and w not in DETERMINERS)
+ for w in prefix): continue
+ number = self._number({"text": prefix[-1]})
+ if number is None: continue
+ try:
+ forms = [set(json.loads(r[0])) for r in self.d.db.execute("SELECT tags_json FROM forms WHERE form=? AND pos='verb'", (word.lower(),))]
+ except (ValueError, TypeError):
+ forms = []
+ # Base forms take plural subjects; third-person singular forms take
+ # singular subjects. Past tense is number-neutral. Participles alone
+ # do not supply the finite verb for this received class.
+ finite = any("past" in tags and "participle" not in tags for tags in forms)
+ finite |= number == "singular" and any("third-person" in tags for tags in forms)
+ finite |= number == "plural" and word.lower() == self._verb(word)
+ if finite: candidates.append(i)
+ return candidates
+
+ def _has_clause(self, start, end, inherited=False):
+ return self._predicate(self._tokens(start, end), inherited=inherited) is not None
+
+ def _complements(self, start, end, lemma):
+ result = []
+ cursor, role, marker = start, "property" if lemma == "be" else "object", None
+ markers = [(word, a, z) for word, a, z in self._tokens(start, end) if word.lower() in PREPOSITIONS]
+ markers += [(m.group(), m.start(), m.end()) for m in re.finditer(r"\bregardless of\b", self.mask, re.I) if start <= m.start() < end]
+ for word, a, z in sorted(markers, key=lambda x: x[1]):
+ if a > cursor: result.append(atom(self.text, cursor, a, role=role, marker=marker))
+ marker = word.lower()
+ self._syntax(a, z, "preposition")
+ cursor, role = z, "preposition"
+ if cursor < end: result.append(atom(self.text, cursor, end, role=role, marker=marker))
+ return result
+
+ def read(self, text, previous=None, content_span=None):
+ self.text = str(text or "")
+ self.mask = outside_literals(self.text)
+ self.previous = previous
+ native = self.native.read(self.text)
+ self.g = {"version": 1, "original": self.text, "sources": [self.text], "act": native["mood"], "nodes": [], "roots": [],
+ "links": [], "syntax": [], "holes": [], "literals": literals(self.text), "correction": None,
+ "basis": "native dictionary + received clause parts", "truth": "unverified", "context_sources": []}
+ start, end = content_span or (0, len(self.text))
+ if content_span:
+ if start:
+ self._syntax(0, start, "received envelope")
+ if end < len(self.text):
+ self._syntax(end, len(self.text), "received envelope")
+ revised = re.match(r"\s*(?:(?:actually|no|rather|instead)[,\s]+|I meant\s+)", self.mask, re.I) if not content_span else None
+ if revised:
+ self.g["correction"] = atom(self.text, revised.start(), revised.end(), kind="replacement")
+ self._syntax(revised.start(), revised.end(), "correction")
+ start = revised.end()
+ # A direct modal question/request is not a received assertion.
+ if self.text.rstrip().endswith("?"):
+ self.g["act"] = "request" if re.match(r"\s*(?:can|could|would|will)\s+you\b", self.mask, re.I) else "question"
+ elif PREFIX.match(self.mask.strip()) and "," in self.mask:
+ self.g["act"] = "statement"
+ roots = self._read(start, end, attribution={"speaker": "user", "stance": "asserted"}, speech_act=self.g["act"])
+ self.g["roots"] = roots
+ if roots and self.g["act"] not in ("question", "social"):
+ self.g["act"] = "request" if any(n["speech_act"] == "request" for n in self.g["nodes"] if n["id"] in roots) else "statement"
+ self._bind_references()
+ return self.g
+
+ def _read(self, start, end, attribution, speech_act, inherited=None, depth=0):
+ part = atom(self.text, start, end)
+ start, end = part["span"]
+ if start >= end:
+ return []
+ if depth > 12:
+ return self._hole("Name the clauses separately; this nesting has not been received.", start, end)
+ mask = self.mask[start:end]
+ # Every independent sentence gets a part; punctuation inside literal
+ # source/code remains data.
+ cuts = list(re.finditer(r"[;.!?](?=\s|$)", mask))
+ if cuts:
+ result, cursor = [], start
+ for cut in cuts:
+ result += self._read(cursor, start + cut.start(), attribution, speech_act, inherited, depth + 1)
+ cursor = start + cut.end()
+ result += self._read(cursor, end, attribution, speech_act, inherited, depth + 1)
+ return result
+ # An attribution owns its embedded claim, never the user's endorsement.
+ report = REPORT.match(self.text[start:end])
+ if report and self._has_clause(start + report.end(), end):
+ speaker = report.group("speaker")
+ own = speaker.lower() in ("i", "we")
+ stance = "withheld_belief" if re.search(r"\bnot\b|n't\b", report.group("stance"), re.I) else "tentative" if own else "reported"
+ attr = {"speaker": "user" if own else speaker, "stance": stance,
+ "wording": atom(self.text, start, start + report.end())}
+ return self._read(start + report.end(), end, attr, "statement", inherited, depth + 1)
+ # Prefix situations bind to their whole main clause, not to one noun.
+ pre = PREFIX.match(mask)
+ if pre:
+ comma = mask.find(",", pre.end())
+ if comma < 0:
+ return self._hole("Supply the main clause after this condition.", start, end, "main_clause")
+ condition = self._read(start + pre.end(), start + comma, attribution, "statement", None, depth + 1)
+ main = self._read(start + comma + 1, end, attribution, speech_act, inherited, depth + 1)
+ self._join(pre.group(1).lower(), condition, main, start, start + pre.end())
+ return main
+ # Reasons and conditions are links between received clauses. No link
+ # here promotes the reason to a proven causal account.
+ suffix = SUFFIX.search(mask)
+ if suffix:
+ main = self._read(start, start + suffix.start(), attribution, speech_act, inherited, depth + 1)
+ linked = self._read(start + suffix.end(), end, attribution, "statement", None, depth + 1)
+ self._join(suffix.group(1).lower(), linked, main, start + suffix.start(), start + suffix.end())
+ if suffix.group(1).lower() == "because" and attribution.get("stance") == "withheld_belief":
+ for link in self.g["links"]:
+ if link["from"] in linked and link["to"] in main:
+ link["scope"] = "unresolved"
+ self.g["holes"].append(atom(self.text, start + suffix.start(), end, kind="reason_scope",
+ need="Does this explain why you withhold belief, or is it the reason inside the claim you are withholding?"))
+ return main
+ # A relative clause receives the referenced object as its subject.
+ relative = re.search(r"\b(that|which|who)\b", mask, re.I)
+ if relative and self._has_clause(start + relative.end(), end, inherited=True):
+ main = self._read(start, start + relative.start(), attribution, speech_act, inherited, depth + 1)
+ parent = next((n for n in self.g["nodes"] if main and n["id"] == main[-1]), None)
+ target = next((c for c in (parent or {}).get("complements", []) if c["role"] == "object"), None)
+ if target:
+ child = self._read(start + relative.end(), end, attribution, "requirement" if parent["speech_act"] == "request" else "statement", target, depth + 1)
+ self._join("relative", child, main, start + relative.start(), start + relative.end())
+ return main
+ return self._hole("Name what this relative clause describes.", start + relative.start(), end, "reference") + main
+ # Coordination splits only where a following clause/predicate is read;
+ # object lists such as 'salt and pepper' stay one object.
+ for join in COORD.finditer(mask):
+ after = start + join.end()
+ if not self._has_clause(after, end, inherited=True):
+ continue
+ first = self._read(start, start + join.start(), attribution, speech_act, inherited, depth + 1)
+ parent = next((n for n in self.g["nodes"] if first and n["id"] == first[-1]), None)
+ tokens = self._tokens(after, end)
+ shared = parent["subject"] if parent and tokens and self._verb(tokens[0][0]) else None
+ second = self._read(after, end, attribution, speech_act, shared, depth + 1)
+ self._join(join.group().lower(), first, second, start + join.start(), start + join.end())
+ explicit_new_speaker = REPORT.match(self.text[after:end].lstrip())
+ if join.group().lower() == "but" and attribution.get("wording") and not shared and not explicit_new_speaker:
+ for node in self.g["nodes"]:
+ if node["id"] in second:
+ node["attribution"]["candidates"] = [attribution["speaker"], "user"]
+ node["attribution"]["speaker"] = "unresolved"
+ self.g["holes"].append(atom(self.text, after, end, kind="attribution_scope",
+ need="Does this contrasting clause belong to the reported view too, or is it your separate claim?", candidates=[attribution["speaker"], "user"]))
+ return first + second
+ # Polite action envelopes are grammar, not part of a subject.
+ envelope = re.match(r"(?:(?:can|could|would|will)\s+you\s+(?:please\s+)?|please\s+|let(?:'s| us)\s+)", mask, re.I)
+ if envelope:
+ self._syntax(start, start + envelope.end(), "request_envelope")
+ start += envelope.end()
+ speech_act = "request"
+ focus = re.match(r"(?:even|also|only)\s+", self.mask[start:end], re.I)
+ focus_atom = None
+ if focus:
+ focus_atom = atom(self.text, start, start + focus.end(), kind="focus")
+ start += focus.end()
+ tokens = self._tokens(start, end)
+ request = bool(tokens and speech_act == "request" and not attribution.get("wording") and self._verb(tokens[0][0]))
+ pi = self._predicate(tokens, inherited is not None, request)
+ if pi is None:
+ return self._hole("Name the action or property relating the subject to the rest of this clause.", start, end, "predicate")
+ boundaries = self._role_boundaries(tokens) if pi and inherited is None else []
+ if boundaries:
+ pi = boundaries[0]
+ if pi == 0:
+ subject = copy.deepcopy(inherited) if inherited else {"text": "you", "implicit": "requested actor"}
+ if not inherited:
+ speech_act = "request"
+ else:
+ subject = atom(self.text, start, tokens[pi][1])
+ if speech_act == "request" and not re.match(r"(?:i|we)\s+(?:want|need)\b", self.mask[start:end], re.I):
+ speech_act = "statement" # a third-party 'should' is a claim, not permission to act
+ j, modal, negatives, auxiliaries = pi, None, [], []
+ while j < len(tokens):
+ word, a, z = tokens[j]
+ low = word.lower()
+ base = NEGATED_AUX.get(low, low)
+ if low in NEGATED_AUX:
+ negatives.append(atom(self.text, a, z))
+ if base in MODAL:
+ modal = atom(self.text, a, z, kind=MODAL[base], lemma=base)
+ auxiliaries.append(atom(self.text, a, z)); j += 1
+ elif base in COPULA or base in AUXILIARY:
+ auxiliaries.append(atom(self.text, a, z)); j += 1
+ elif low in ("not", "never"):
+ negatives.append(atom(self.text, a, z)); j += 1
+ else:
+ break
+ base = NEGATED_AUX.get(tokens[pi][0].lower(), tokens[pi][0].lower())
+ copular = bool(auxiliaries and any(NEGATED_AUX.get(x["text"].lower(), x["text"].lower()) in COPULA for x in auxiliaries))
+ modifiers = []
+ while j + 1 < len(tokens) and "adv" in self.d.pos(tokens[j][0].lower()) and any(self._verb(x[0]) for x in tokens[j + 1:]):
+ modifiers.append(atom(self.text, tokens[j][1], tokens[j][2])); j += 1
+ lexical = self._verb(tokens[j][0]) if j < len(tokens) else None
+ # An adjective after be is a property, even if another dictionary sense
+ # is a verb. A by-agent or -ing form makes the action reading explicit.
+ # A determiner between be and the next word ("is a river", "was the capital") opens a noun phrase: the word after
+ # it is the complement's head, not a verb, even when the store also lists a verb sense ("to river").
+ gap = self.text[auxiliaries[-1]["span"][1]:tokens[j][1]].lower().split() if (copular and j < len(tokens)) else []
+ nominal = any(w.strip(",;:") in DETERMINERS for w in gap)
+ if copular and j < len(tokens) and (nominal or "adj" in self.d.pos(tokens[j][0].lower()) or not lexical) and not tokens[j][0].lower().endswith("ing"):
+ lemma, p_end = "be", tokens[j - 1][2]
+ elif lexical:
+ lemma, p_end = lexical, tokens[j][2]
+ j += 1
+ elif copular:
+ lemma, p_end = "be", tokens[j - 1][2]
+ else:
+ return self._hole("The verb after this auxiliary is not held by the dictionary; supply its meaning.", tokens[pi][1], end, "predicate")
+ predicate = atom(self.text, tokens[pi][1], p_end, lemma=lemma)
+ if tokens[max(pi, j - 1)][0].lower() in self.meanings:
+ predicate["meaning"] = copy.deepcopy(self.meanings[tokens[j - 1][0].lower()])
+ tail_start = tokens[j][1] if j < len(tokens) else end
+ complements = self._complements(tail_start, end, lemma)
+ node = {"id": "P%d" % (len(self.g["nodes"]) + 1), "kind": "claim", "text": part["text"], "span": part["span"], "source": self.text,
+ "subject": subject, "predicate": predicate, "complements": complements, "modal": modal,
+ "polarity": "negative" if negatives else "positive", "negatives": negatives, "auxiliaries": auxiliaries,
+ "attribution": copy.deepcopy(attribution), "speech_act": speech_act, "truth": "unverified", "focus": focus_atom, "modifiers": modifiers}
+ self.g["nodes"].append(node)
+ if len(boundaries) > 1:
+ candidates = []
+ for boundary in boundaries:
+ word, a, z = tokens[boundary]
+ candidates.append({"subject": atom(self.text, start, a),
+ "predicate": atom(self.text, a, z, lemma=self._verb(word)),
+ "complements": self._complements(z, end, self._verb(word))})
+ node["role_reading"] = {"status": "unresolved", "candidates": candidates}
+ choices = " or ".join(repr(c["subject"]["text"]) for c in candidates)
+ self.g["holes"].append(atom(self.text, start, end, kind="role_boundary", node=node["id"],
+ need="Which is the subject: %s? You can say 'The subject is ...'." % choices))
+ return [node["id"]]
+
+ def _join(self, word, origins, targets, start, end):
+ kind = ("reason" if word == "because" else "purpose" if word in ("so that", "in order to") else
+ "contrast" if word in ("but", "although") else "sequence" if word in ("then", "and then") else
+ "alternative" if word == "or" else "coordination" if word == "and" else "relative" if word == "relative" else "condition")
+ connector = atom(self.text, start, end)
+ self.g["syntax"].append(dict(connector, kind="join"))
+ for origin in origins:
+ for target in targets:
+ self.g["links"].append({"kind": kind, "mode": word, "from": origin, "to": target, "connector": connector})
+
+ def _bind_references(self):
+ prior_nodes = (self.previous or {}).get("nodes", [])
+ prior_roots = (self.previous or {}).get("roots", [])
+ prior_parts = [part for n in prior_nodes if n["id"] in prior_roots and n.get("role_reading", {}).get("status") != "unresolved" for part in [n["subject"]] +
+ [c for c in n["complements"] if c["role"] == "object"]]
+ unique = {x["text"].lower(): x for x in prior_parts}
+ self.g["reference_context"] = list(unique.values())
+ for source in (self.previous or {}).get("sources", []):
+ if source not in self.g["sources"]:
+ self.g["sources"].append(source); self.g["context_sources"].append(source)
+ for node in self.g["nodes"]:
+ for subject in [node["subject"]] + node["complements"]:
+ if subject["text"].lower() not in ("it", "they", "this", "that", "these", "those", "them"):
+ continue
+ plural = subject["text"].lower() in ("they", "these", "those", "them")
+ candidates = [x for x in unique.values() if self._number(x) in (None, "plural" if plural else "singular")]
+ if len(candidates) == 1:
+ subject["binding"] = {"target": copy.deepcopy(candidates[0]), "basis": "previous received referent"}
+ else:
+ self.g["holes"].append(dict(subject, kind="reference", need="Name which thing this pronoun refers to.", candidates=[x["text"] for x in candidates]))
+
+ def _number(self, part):
+ words = WORD.findall(part["text"].lower())
+ if not words: return None
+ head = words[-1]
+ try:
+ rows = self.d.db.execute("SELECT tags_json FROM forms WHERE form=? AND pos='noun'", (head,)).fetchall()
+ if any("plural" in row[0] for row in rows): return "plural"
+ except Exception:
+ pass
+ return "singular" if "noun" in self.d.pos(head) else None
+
+
+def receive(text, reader, previous=None, meanings=None):
+ return ClaimReader(reader, meanings).read(text, previous)
diff --git a/workbench/converse/compose_reply_v8.py b/workbench/converse/compose_reply_v8.py
new file mode 100644
index 0000000000000000000000000000000000000000..07c70fa61605fd2cc53bf1a31888abd08df1da4e
--- /dev/null
+++ b/workbench/converse/compose_reply_v8.py
@@ -0,0 +1,750 @@
+#!/usr/bin/env python3
+"""COMPOSE ROUTER v8 (round 9): the transformer of Oracle7's parts GENERATES THE PROGRAM UNDER THE SURFACE.
+
+Ben, 2026-11-05: "it must generate the symbolic logic (typed terms / programs) under the surface, not surface text;
+realizer + law handle surface; never pad with filler caveats." Ben, 2026-11-07: "it needs to be broad."
+
+Rounds 3-8 attended over Oracle7's own record sentences and copied the best-fitting one. v8 attends over the BROAD store
+and composes typed terms; every term carries its source; the surface is rendered from the terms and nothing is copied:
+
+ query the turn's demand (reader frame; the HRR REF head of v6 binds what "it"/"that" points at)
+ keys ENTITY names (names_v1: 14.1M), the RELATIONS an entity holds (prop labels + aliases), the OPERATIONS
+ (v7's head), the SCENES (roles mined from DailyDialog), the LEDGER, the DICTIONARY
+ attention cosine fit of demand to key, HRR word vectors (v6), masked by what the store actually holds for the entity
+ program ACT x TERMS: answer(E, R, V) | describe(E) | define(w) | yes/no(E, R, V) | do(op, receipt) | plan(op) |
+ play(scene, move) | ack(E) + relate(E, R, V) | judge(ledger) | hole(missing, filler, question-back) | social
+ render own clauses from the terms, each with its citation: [wd:Q.. P..] [dict:w] [ledger:n] [op:cmd] [scene:id]
+ [turn:k] [none]
+usage: module (ComposeRouterV8(..., reader=Reader), same constructor as v4-v7)"""
+from __future__ import annotations
+
+import collections
+import json
+import os
+import re
+import sqlite3
+
+import numpy as np
+
+from squircle_reply import content_words
+from squircle_reply_v4 import GENERIC
+from squircle_reply_v6 import SquircleRouterV6, unit, D
+from squircle_reply_v7 import SquircleRouterV7
+
+OP_TAU = 0.42
+
+_HERE = os.path.dirname(os.path.abspath(__file__))
+_TREE = os.path.abspath(os.path.join(_HERE, "..", ".."))
+REL_ROOT = os.environ.get("ORACLE7_RELSTORE_DIR", os.path.join(_TREE, "root", "relstore")) # the release's own store
+SCENES = os.environ.get("ORACLE7_SCENES", os.path.join(_HERE, "data", "scenes.json"))
+MOVES = os.environ.get("ORACLE7_MOVES", os.path.join(_HERE, "data", "moves.json"))
+MOVER_TAU = 0.45 # superseded: the tau now lives in moves.json, read off the dev-slice eval (conv_mover.py eval)
+REL_TAU = 0.24
+LEX_W = 0.35 # the learned lexicon's vote, added to the declared-name fit # a relation must fit the demand this well to be the asked one
+SCENE_TAU = 0.45 # a scene must fit this well to be played
+MAX_ENT = 3
+SKIP_P = {31, 279, 373, 646, 214, 227, 244, 213, 268, 269, 349, 434, 435, 436, 18, 109, 94, 154, 242, 158, 1442, 910, 1151,
+ 2959, 5008, 1343, 1889, 4224, 3450, 1464, 1465, 1792, 2354, 7867, 1424} # ids, images, categories
+PLACE_P = {17, 131, 276, 159, 19, 20, 30, 706, 36, 150, 47}
+TIME_TYPES = {"Time"}
+NUM_TYPES = {"Quantity"}
+STOPW = set("a an the of in on at to for by with from and or is was were are be been being i you he she it we they me him her us "
+ "them my your his its our their this that these those there here please thanks thank yes no not so very just like would "
+ "could can will shall may might must do does did have has had am get got go going come want need let say said tell ask "
+ "know think sure ok okay well oh hi hello good sir madam miss mr mrs ms excuse sorry much many some any".split())
+CANCEL = re.compile(r"\b(ignore that|never ?mind|forget (it|that)|scratch that|wrong (chat|window|channel|char))\b")
+AGREE = re.compile(r"^(?:(?:yes|yeah|yep|ok|okay|sure|right|alright|good|great|fine|please|do it|go ahead|go|lets|let\x27s)[ ,.!]*){1,4}"
+ r"(?:(?:do|try|run|go with|get on with|start|build) (?:that|it|this|those|them|one|first))?[ .!]*$")
+DEFQ = re.compile(r"^(?:so |ok |okay )?(?:what|whats|what's|what is|what are|what does|define|meaning of)\s+(?:a |an |the )?([a-z\-']+(?: [a-z\-']+)?)\s*(?:mean|means)?\s*\??$")
+DEF_NOT = {"plan", "status", "eta", "progress", "goal", "point", "deal", "matter", "idea", "problem", "issue", "next", "news", "time",
+ "difference", "result", "answer", "verdict", "score", "count", "number", "price", "cost", "name", "date", "year"}
+
+
+def defq_word(core, d=None):
+ """the word a definition question asks about, or None: one noun (or noun noun), not a status word, not modified"""
+ m = DEFQ.match(core)
+ if not m:
+ return None
+ ws = m.group(1).split()
+ if ws[-1] in DEF_NOT or ws[0] in ("full", "whole", "current", "next", "new", "best", "right", "real", "actual", "exact"):
+ return None
+ if d is not None and len(ws) == 2 and ("noun" not in d.pos(ws[0]) or "adj" in d.pos(ws[0])):
+ return None
+ return ws[-1]
+TITLES = {"mr", "mrs", "ms", "miss", "dr", "prof", "sir", "madam", "mister", "doctor", "professor", "captain", "officer"}
+HUMAN = re.compile(r"\b(\d{4}\)|\(born|player|actor|actress|politician|writer|singer|footballer|musician|painter|poet|author|"
+ r"composer|scientist|businessman|businesswoman|journalist|director|producer|athlete|physician|lawyer|"
+ r"american|british|canadian|german|french|chinese|japanese|english|australian|indian|italian|spanish|russian)\b")
+SCENE_OPEN = re.compile(r"^(hello|hi|hey|good (morning|afternoon|evening)|excuse me|welcome|this is|may i|can i|could i)\b")
+OPENERS = re.compile(r"^(?:(?:hello|hi|hey|good (?:morning|afternoon|evening)|excuse me|sorry|welcome|please|sir|madam|miss|"
+ r"mr\.? \w+|mrs\.? \w+|ms\.? \w+|dr\.? \w+|oh|well|um|er|so|okay|ok)[,.!? ]+)+", re.I)
+COMPARE = re.compile(r"\b(difference|differences|compare|comparison|versus|vs|similarit(y|ies)|between)\b")
+STATUS = re.compile(r"\b(where are we|where we are|whats been done|what's been done|whats left|what's left|is it (all )?(finished|done|built)|eta\b|status\b|how far (are|along)|progress\b|what did you (do|run))")
+OTHER_OFFER = re.compile(r"\b(can|could|may) i help( you)?\b|\bwhat can i do for you\b|\bhow can i (help|be of service)\b")
+SCENE_STOP = {"him", "her", "them", "service", "server", "previous", "single", "time", "day", "today", "way", "thing", "people", "work", "home", "line"}
+OFFER = re.compile(r"^(?:can|could|may|shall|should) i\b")
+SELFQ = re.compile(r"^(?:what|who) (?:do|are|can) (?:you|u)\b|^what(?:'s| is) (?:this|oracle7|oracle 7)\b|^who are you")
+EVAL = {"huge", "great", "better", "worse", "good", "bad", "amazing", "wrong", "broken", "slow", "fast", "dark", "nice", "cool",
+ "awesome", "terrible", "fine", "perfect", "big", "small", "important", "significant"}
+
+
+def norm(s):
+ import unicodedata
+ s = unicodedata.normalize("NFKD", str(s)).encode("ascii", "ignore").decode("ascii")
+ return " ".join(re.sub(r"[^a-z0-9 ]+", " ", s.lower()).split())
+
+
+class ComposeRouterV8(SquircleRouterV7):
+ def __init__(self, *a, **k):
+ super().__init__(*a, **k)
+ self.rel = sqlite3.connect("file:%s/relations_v2.sqlite3?mode=ro&immutable=1" % REL_ROOT, uri=True, check_same_thread=False)
+ self.names = sqlite3.connect("file:%s/names_v1.sqlite3?mode=ro&immutable=1" % REL_ROOT, uri=True, check_same_thread=False)
+ self.ptype, self.plabel = {}, {}
+ for p, t, lab, n, g in self.rel.execute("SELECT p, type, label, facts, global FROM prop_src"):
+ self.ptype[p], self.plabel[p] = t, lab
+ self.palias = {}
+ try:
+ al = json.load(open(REL_ROOT + "/prop_aliases_v1.json"))
+ for p, v in al.items():
+ p = int(p)
+ self.palias[p] = v.get("aliases", [])[:12]
+ if v.get("label"):
+ self.plabel.setdefault(p, v["label"])
+ dt = (v.get("datatype") or "").lower()
+ if "time" in dt:
+ self.ptype.setdefault(p, "Time")
+ elif "quantity" in dt:
+ self.ptype.setdefault(p, "Quantity")
+ elif "item" in dt:
+ self.ptype.setdefault(p, "WikibaseItem")
+ elif dt:
+ self.ptype.setdefault(p, dt)
+ except Exception: # noqa: BLE001
+ pass
+ self._pk = {}
+ self.mover, self.played_m = None, {}
+ if os.path.exists(MOVES):
+ from conv_mover import Mover
+ self.mover = Mover(MOVES)
+ self.scenes = []
+ if os.path.exists(SCENES):
+ self.scenes = json.load(open(SCENES))
+ self.SK = np.zeros((len(self.scenes), D), dtype=np.float32)
+ for i, s in enumerate(self.scenes):
+ self.SK[i] = unit(self.text_vec(s["key"]))
+ self.lex = {"words": {}, "asked": {}}
+ lp = os.environ.get("ORACLE7_REL_LEXICON", "/opt/o7conv/rel_lexicon.json")
+ if os.path.exists(lp):
+ try:
+ self.lex = json.load(open(lp))
+ except Exception: # noqa: BLE001
+ pass
+ self.played = {} # session -> (scene index, moves used)
+ self.role_turns = collections.defaultdict(list) # session -> what the role said (its replies, or a transcript it was given)
+ self.mover_last = {} # session -> (dialogue, step) of the last move the mover played (scene continuity)
+ self.lastprog = {} # session -> (act, text) of the last composed program
+ self.dbg = []
+ self.stats.clear()
+
+ # ---------------- the broad store: entities and their relations
+ def link(self, turn, wh_about=True, want_p=None):
+ """entity spans of the turn: longest first, by the name table's link count; the original case is kept.
+ want_p: relations the demand asks for; among a span's candidates the first that HOLDS one of them wins."""
+ words = re.findall(r"[A-Za-z0-9][A-Za-z0-9'\-]*", turn)
+ taken, out = set(), []
+ self._ltrace = []
+ for n in (6, 5, 4, 3, 2, 1):
+ for i in range(len(words) - n + 1):
+ if any(j in taken for j in range(i, i + n)):
+ continue
+ span = words[i:i + n]
+ low = [w.lower() for w in span]
+ if n > 3 and not (span[0][:1].isupper() and span[-1][:1].isupper()):
+ continue
+ if (low[0] in STOPW and not (n > 1 and span[0][:1].isupper() and i > 0)) or low[-1] in STOPW or all(w in STOPW for w in low):
+ continue
+ caps = any(w[:1].isupper() for w in span)
+ before = words[i - 1].lower().rstrip(".") if i > 0 else ""
+ if before in TITLES:
+ taken.update(range(i, i + n))
+ continue # "Mr Jackson", "Dr Steward": a person in the room
+ if n == 1:
+ w = low[0]
+ ps = self.reader.d.pos(w)
+ if len(w) < 3 or w in GENERIC or self.reader.is_closed(w) or not caps:
+ continue
+ if i == 0 and (ps & {"noun", "verb", "adj", "adv", "intj"}) and "name" not in ps:
+ continue # sentence-initial common word ("How", "Is", "Mom")
+ elif not caps:
+ if all("noun" in self.reader.d.pos(w) or self.reader.is_closed(w) for w in low):
+ continue # "computer file", "one way ticket": words, not a name
+ elif not (span[0][:1].isupper() and span[-1][:1].isupper()):
+ continue # "live in Tokyo": the name is Tokyo
+ cands = self.names.execute("SELECT qid, links FROM name WHERE norm=? ORDER BY links DESC LIMIT 6", (norm(" ".join(span)),)).fetchall()
+ cands = [c for c in cands if not ((not caps and c[1] < 120) or (n == 1 and c[1] < 60))]
+ if not cands:
+ self._ltrace.append((" ".join(span), "no candidate"))
+ continue
+ sp = norm(" ".join(span))
+ good = [c for c in cands if norm(self.label(int(c[0])) or "") == sp or norm(self.label(int(c[0])) or "").startswith(sp + " ")]
+ if not good and n > 1:
+ good = cands[:1] # a multiword alias with no exact label: the best-linked one
+ if not good:
+ self._ltrace.append((" ".join(span), "no label match"))
+ continue
+ r = good[0]
+ if want_p:
+ for c in good[:4]:
+ if any(self.rel.execute("SELECT 1 FROM fact WHERE s=? AND p=? LIMIT 1", (int(c[0]), p)).fetchone() for p in want_p):
+ r = c
+ break
+ if n == 1:
+ ps = self.reader.d.pos(low[0])
+ if ("noun" in ps or "verb" in ps or "adj" in ps) and "name" not in ps:
+ self._ltrace.append((span[0], "common word"))
+ continue # Jack, Dick, Horde, Mechanics: words first
+ dsc = (self.descr(int(r[0])) or "").lower()
+ if want_p and any(self.rel.execute("SELECT 1 FROM fact WHERE s=? AND p=? LIMIT 1", (int(r[0]), p)).fetchone() for p in want_p):
+ pass # it holds the asked relation: it is the thing asked about
+ elif re.search(r"\b(given name|family name|surname|male name|female name)\b", dsc) or (
+ r[1] < 150 and re.search(r"\b(river|village|hamlet|album|song|film|band|genus|family of|species)\b", dsc)
+ and "name" in self.reader.d.pos(low[0])):
+ continue
+ if not wh_about:
+ dsc = (self.descr(int(r[0])) or "").lower()
+ if HUMAN.search(dsc):
+ taken.update(range(i, i + n))
+ continue # a person named in a scene stays a person in the scene
+ out.append((" ".join(span), int(r[0]), int(r[1])))
+ taken.update(range(i, i + n))
+ out.sort(key=lambda x: (-len(x[0].split()), -x[2]))
+ return out[:MAX_ENT]
+
+ def label(self, qid):
+ r = self.rel.execute("SELECT label, enwiki FROM entity WHERE qid=?", (qid,)).fetchone()
+ return (r[0] or r[1]) if r else None
+
+ def descr(self, qid):
+ r = self.rel.execute("SELECT text FROM descr WHERE qid=?", (qid,)).fetchone()
+ return r[0] if r else None
+
+ def pkey(self, p):
+ if p not in self._pk:
+ ws = content_words(self.plabel.get(p, "") + " " + " ".join(self.palias.get(p, [])))
+ self._pk[p] = unit(self.text_vec([w for w in ws if w not in STOPW])) if ws else np.zeros(D, dtype=np.float32)
+ return self._pk[p]
+
+ def fmt_lit(self, lit):
+ m = re.match(r"^([+-]?\d{1,5})-(\d\d)-(\d\d)", str(lit))
+ if m:
+ return m.group(1).lstrip("+")
+ s = str(lit)
+ return s[:60]
+
+ def relations(self, qid, q, asked):
+ """the RELATION head: softmax over the relations this entity holds, keyed by their declared names"""
+ rows = self.rel.execute("SELECT p, o, lit FROM fact WHERE s=? LIMIT 3000", (qid,)).fetchall()
+ byp = {}
+ for p, o, lit in rows:
+ if p in SKIP_P or p not in self.plabel or self.ptype.get(p, "").lower() in (
+ "externalid", "external-id", "commonsmedia", "url", "string", "math", "globecoordinate", "globe-coordinate",
+ "monolingualtext", "wikibase-lexeme", "wikibase-form", "wikibase-sense", "wikibase-property", "tabular-data",
+ "geo-shape", "musical-notation"):
+ continue
+ byp.setdefault(p, []).append((o, lit))
+ if not byp:
+ return [], []
+ ps = list(byp)
+ K = np.stack([self.pkey(p) for p in ps])
+ fit = K @ q
+ # the relation lexicon, learned from the loop's own tests: which demand words (and asked forms) mean which relation
+ qw = getattr(self, "_qwords", None) or []
+ lw = self.lex.get("words", {})
+ if lw and qw:
+ votes = collections.Counter()
+ for w in qw:
+ for pp, c in lw.get(w, {}).items():
+ votes[int(pp)] += c
+ if votes:
+ top = max(votes.values())
+ fit = fit + np.array([LEX_W * votes.get(p, 0) / top for p in ps], dtype=np.float32)
+ aw = self.lex.get("asked", {}).get(getattr(self, "_asked_form", "") or "", {})
+ if aw:
+ top = max(aw.values())
+ fit = fit + np.array([0.5 * LEX_W * aw.get(str(p), 0) / top for p in ps], dtype=np.float32)
+ if asked == "time":
+ fit = np.where([self.ptype.get(p) in TIME_TYPES for p in ps], fit + 0.15, fit - 0.2)
+ elif asked == "number":
+ fit = np.where([self.ptype.get(p) in NUM_TYPES for p in ps], fit + 0.15, fit - 0.2)
+ elif asked == "place":
+ fit = np.where([p in PLACE_P for p in ps], fit + 0.15, fit)
+ order = np.argsort(-fit)
+ out = []
+ for j in order[:3]:
+ if fit[j] < REL_TAU:
+ break
+ p = ps[j]
+ vals = []
+ for o, lit in byp[p][:3]:
+ v = self.label(o) if o is not None else self.fmt_lit(lit)
+ if v:
+ vals.append(v)
+ if vals:
+ out.append((p, self.plabel.get(p, "P%d" % p), vals, float(fit[j])))
+ if not out and asked in ("time", "number"):
+ # Amendment 14 (1): a typed place is filled by type. The question asks for a date (or a number) and the entity holds
+ # relations of that type: the best of them fills it, named, so the reply says which relation answered (11-08:
+ # "When did he paint it?" -> "I hold no date for Mona Lisa ... What I do hold: inception, ...")
+ types = TIME_TYPES if asked == "time" else NUM_TYPES
+ typed = [j for j in order if self.ptype.get(ps[j]) in types]
+ if len(typed) == 1:
+ j = typed[0]
+ p = ps[j]
+ vals = [v for v in ((self.label(o) if o is not None else self.fmt_lit(lit)) for o, lit in byp[p][:3]) if v]
+ if vals:
+ out.append((p, self.plabel.get(p, "P%d" % p), vals, float(fit[j])))
+ held = [self.plabel.get(ps[j], "") for j in order[:6] if self.plabel.get(ps[j])]
+ return out, held
+
+ def asked(self, fr):
+ wh, core = fr.get("wh"), fr["fixed"].lower()
+ if wh == "yes/no" or re.search(r"\b(no|right|yes|correct|isn't it|isnt it|innit|ok|okay)\s*\?\s*$", core):
+ return "yesno"
+ if wh == "when" or re.search(r"\b(what|which) year\b", core[:40]):
+ return "time"
+ if re.match(r"\s*how (many|much|long|old|far|tall|high)", core):
+ return "number"
+ if wh in ("who", "whom", "whose"):
+ return "name"
+ if wh == "where":
+ return "place"
+ return "noun"
+
+ # ---------------- scenes: the PLAY act
+ def scene(self, session, q, words):
+ said = set(words)
+ if self.mover is not None:
+ T = self.turns.get(session) or []
+ R = self.role_turns.get(session) or []
+ hit = self.mover.query(T[-1] if T else " ".join(words), T[-2] if len(T) > 1 else None, R[-1] if R else None,
+ last=self.mover_last.get(session))
+ if hit:
+ e, sim = hit
+ self.dbg.append(("mover", round(sim, 3), e["id"], e["wh"], e["slot"]))
+ used = self.played_m.setdefault(session, set())
+ if sim >= self.mover.tau and e["id"] not in used and not (e["slot"] and e["slot"] in said):
+ used.add(e["id"])
+ self.mover_last[session] = (e["dlg"], e["step"])
+ return ({"id": e["id"], "key": e["ctx"][:8]}, {"act": "question", "text": e["text"], "wh": e["wh"], "slot": e["slot"]}, float(sim))
+ if not self.scenes or float(np.linalg.norm(q)) == 0:
+ return None
+ best, j = 0.0, -1
+ for i, sc in enumerate(self.scenes):
+ key = sc["key"]
+ shared = [k for k in key if k in said]
+ if not shared or (len(shared) < 2 and (max(self.idf(k) for k in shared) < 6.0 or len(said) > 6
+ or shared[0] in SCENE_STOP or "noun" not in self.reader.d.pos(shared[0]))):
+ continue
+ cov = sum(self.idf(k) for k in shared) / max(1e-6, sum(self.idf(k) for k in key))
+ f = cov * (0.6 + 0.4 * min(1.0, len(shared) / 2.0))
+ if f > best:
+ best, j = f, i
+ fit = {j: best} if j >= 0 else {}
+ self.dbg.append(("scene", round(best, 3), self.scenes[j]["key"][:3] if j >= 0 else None))
+ if j < 0 or best < SCENE_TAU:
+ return None
+ cur = self.played.get(session)
+ if cur and cur[0] != j and any(k in said for k in self.scenes[cur[0]]["key"]):
+ j = cur[0]
+ used = cur[1] if cur and cur[0] == j else set()
+ s = self.scenes[j]
+ for k, m in enumerate(s["moves"]):
+ if k in used:
+ continue
+ if m["act"] == "question" and m["slot"] and m["slot"] in said:
+ used.add(k) # the obligation is already bound by what was said
+ continue
+ if len(m["text"].split()) > 28:
+ used.add(k)
+ continue
+ if k == 0 or m["act"] == "question":
+ used.add(k)
+ self.played[session] = (j, used)
+ return s, m, float(fit[j])
+ return None
+
+ # ---------------- render: own clauses from typed terms
+ def r_fact(self, e, p, lab, vals):
+ return "%s's %s is %s [wd:Q%d P%d]" % (self.label(e), lab, ", ".join(vals[:2]), e, p)
+
+ def r_play(self, sc, key, descrs, n_turn):
+ s_, m, fit = sc
+ # the premise check: a move may ASK anything; it may ASSERT only what it can cite. Sentences without a "?" are cut.
+ sents = [x for x in re.split(r"(?<=[.!?])\s+", m["text"].strip()) if x.strip()]
+ kept = [x for x in sents if "?" in x] or sents[-1:]
+ text = " ".join(kept)
+ cite = " [scene:%s%s]" % (s_["id"], (":" + m["slot"]) if m.get("slot") else "")
+ ack = (descrs[0] + ". ") if descrs else "" # a move asks; it asserts only what the store holds
+ return ack + text + cite
+
+ def r_descr(self, e):
+ d = self.descr(e)
+ if not d:
+ return None
+ d = d.rstrip(".")
+ first = d.split()[0]
+ ps = self.reader.d.pos(first.lower())
+ if first[:1].islower() and first not in ("a", "an", "the") and (("noun" in ps and not first.endswith("s")) or ("adj" in ps and len(d.split()) > 1)):
+ d = ("an " if first[0] in "aeiou" else "a ") + d
+ return "%s is %s [wd:Q%d]" % (self.label(e), d, e)
+
+ def op_head(self, q, tau=None, words=None):
+ """v7's operations head with a lexical gate: the request and the operation must share one content word"""
+ if self.OK.shape[0] == 0 or float(np.linalg.norm(q)) == 0:
+ return None
+ fit = self.OK @ q
+ order = np.argsort(-fit)[:8]
+ tau = OP_TAU if tau is None else tau
+ for j in order:
+ if fit[j] < tau:
+ return None
+ kind, cmd, usage, desc = self.op_rows[j]
+ if words is not None:
+ ow = set(content_words(desc + " " + cmd.replace("-", " ").replace(".", " ").replace("_", " ")))
+ if not (ow & {w for w in words if w not in GENERIC and self.idf(w) >= 2.5}):
+ continue
+ return (float(fit[j]),) + self.op_rows[j]
+ return None
+
+ def program(self, turn, fr, session, wts, h, q, ref_words):
+ """compose the typed terms for this turn; returns (act, text, substantive)"""
+ mood = fr["mood"]
+ core0 = fr["fixed"].strip().lower()
+ words = list(fr.get("_own") or wts)
+ wh_about = mood == "question" and fr.get("wh") not in (None, "yes/no") and not SCENE_OPEN.search(core0)
+ want_p = []
+ if mood == "question":
+ votes = collections.Counter()
+ for w in words:
+ for pp, c in self.lex.get("words", {}).get(w, {}).items():
+ votes[int(pp)] += c
+ hm0 = re.match(r"^\W*(when|where|who|how many|how much|how long|how old|how tall|what year|which|what)", core0)
+ for pp, c in self.lex.get("asked", {}).get(hm0.group(1) if hm0 else "", {}).items():
+ votes[int(pp)] += 0.5 * c
+ want_p = [p for p, _ in votes.most_common(3)]
+ ents = self.link(fr["fixed"] if fr["changes"] else turn, wh_about=wh_about, want_p=want_p)
+ self.dbg.append(("link", want_p, self._ltrace[:4]))
+ if not ents and ref_words and fr["refs"]:
+ ents = self.link(" ".join(ref_words).title())
+ self.dbg.append(("ents", [(e[0], e[1]) for e in ents], "ref", ref_words[:3]))
+ asked = self.asked(fr) if mood == "question" else None
+ self._qwords = [w for w in words if w not in GENERIC]
+ hm = re.match(r"^\W*(when|where|who|how many|how much|how long|how old|how tall|what year|which|what)", fr["fixed"].lower())
+ self._asked_form = hm.group(1) if hm else ""
+ qrel = q
+ if ents:
+ ew = set(w for e in ents for w in content_words(e[0]))
+ rest = [w for w in words if w not in ew]
+ qrel = unit(self.text_vec(rest, wts)) if rest else q
+ facts, descrs, helds = [], [], []
+ for span, e, _ in ents:
+ rels, held = self.relations(e, qrel, asked)
+ self.stats["ent"] += 1
+ for p, lab, vals, fit in rels[:1 if mood != "question" else 2]:
+ facts.append((e, p, lab, vals, fit))
+ d = self.r_descr(e)
+ if d:
+ descrs.append(d)
+ helds.append((e, held))
+ key = h
+ if not key or key in GENERIC:
+ key = next((w for w in reversed(fr["object"]) if w.isalpha() and w not in GENERIC and not self.reader.is_closed(w)
+ and "noun" in self.reader.d.pos(w)), None)
+ if key in ("no", "yes", "one", "thing", "something", "anything", "lot", "bit", "kind", "sort"):
+ key = None
+ if not key:
+ key = next((w for w in reversed(words) if w.isalpha() and w not in GENERIC and not self.reader.is_closed(w)
+ and "noun" in self.reader.d.pos(w) and w not in ("no", "yes", "one", "thing")), None)
+ if not key and ref_words and fr["refs"]:
+ key = ref_words[0]
+ self.dbg.append(("key", key, "obj", fr["object"][:4], "h", h))
+ core = fr["fixed"].strip().lower()
+ n_turn = len(self.turns[session])
+ # ----- the acts
+ if CANCEL.search(core):
+ self.stats["cancel"] += 1
+ return "cancel", "Ignored; I drop that turn and keep the earlier ones [turn:%d]." % n_turn, True
+ if mood in ("request", "commitment", "social", "statement") and AGREE.match(core):
+ last = self.lastprog.get(session)
+ self.stats["agree"] += 1
+ if last and last[0] == "plan":
+ return "plan", "On your go, then: " + last[1], True
+ if last and last[0] == "play":
+ return "play", last[1], True
+ if last and last[0] == "hole":
+ return "hole", "Agreed, but it is still the hole I named: " + last[1], False
+ L = self.ledger.get(session) or []
+ if L and L[-1]["open"]:
+ return "plan", "Then I would run `%s` [ledger:%d]; say the word and I run it and keep the receipt." % (L[-1]["cmd"], L[-1]["turn"]), True
+ return "hole", "Agreed [turn:%d], but nothing of mine is pending from the last turn. What should I do first?" % n_turn, False
+ if mood == "social":
+ return "social", "Hello. Ask me something I can check, or tell me what to run, and I'll show the working.", True
+ if STATUS.search(core) and mood in ("question", "request", "statement"):
+ self.stats["status"] += 1
+ L = self.ledger.get(session) or []
+ done = [e for e in L if not e["open"]][-3:]
+ open_ = [e for e in L if e["open"]][-2:]
+ parts = []
+ if done:
+ parts.append("Run here: " + "; ".join("`%s` -> %s [ledger:%d]" % (e["cmd"], (e["receipt"] or "no result")[:60], e["turn"]) for e in done) + ".")
+ if open_:
+ parts.append("Waiting on your go: " + "; ".join("`%s` [ledger:%d]" % (e["cmd"], e["turn"]) for e in open_) + ".")
+ prev = [t for t in self.turns[session][:-1] if not STATUS.search(t.lower())]
+ if prev:
+ pw = " ".join(w for w in content_words(prev[-1]) if w not in GENERIC)[:70]
+ parts.append("The last thing asked of me was about %s [turn:%d]%s" % (
+ pw or "the previous turn", len(self.turns[session]) - 1,
+ "; nothing of mine ran for it, so that is the open item." if not L else "."))
+ if not parts:
+ parts.append("Nothing of mine has run in this conversation [ledger:0], and nothing was asked before this; what do you want checked first?")
+ return "answer", " ".join(parts), True
+ if OTHER_OFFER.search(core):
+ self.stats["accept"] += 1
+ return "answer", ("Yes, please: I check claims against records I can cite and run my own operations, so give me one "
+ "claim or one question and I show the working [turn:%d]." % n_turn), True
+ if mood == "question" and len(ents) >= 2 and COMPARE.search(core):
+ a, b = ents[0], ents[1]
+ da, db = self.r_descr(a[1]), self.r_descr(b[1])
+ if da and db:
+ ca = {o for o, _ in self.rel.execute("SELECT o, lit FROM fact WHERE s=? AND p=31", (a[1],)) if o}
+ cb = {o for o, _ in self.rel.execute("SELECT o, lit FROM fact WHERE s=? AND p=31", (b[1],)) if o}
+ both = [self.label(x) for x in (ca & cb)][:2]
+ tail = (" Both are %s [wd:Q%d P31]." % (" and ".join(both), a[1])) if both else " My records give them no common class."
+ self.stats["compare"] += 1
+ return "answer", da + ". " + db + "." + tail, True
+ if mood == "question":
+ if OFFER.match(core):
+ self.stats["offer"] += 1
+ return "answer", "Yes, gladly%s: tell me what to check, or what to run, and I show the working [turn:%d]." % (
+ (", " + key) if key else "", n_turn), True
+ if SELFQ.match(core):
+ self.stats["selfq"] += 1
+ cmds = ", ".join(c for c, _, _ in self.rep[:8])
+ return "answer", ("I am Oracle7 [op:help]: I answer from records I can cite, run my own operations (%s and %d more) and "
+ "say what I lack when I lack it." % (cmds, max(0, len(self.rep) - 8))), True
+ ev = [w for w in words if w in EVAL]
+ if asked == "yesno" and ev and not ents:
+ L = self.ledger.get(session) or []
+ if L:
+ e = L[-1]
+ return "answer", "I can't say yes or no beyond my last receipt: `%s`: %s [ledger:%d]." % (
+ e["cmd"], (e["receipt"] or "no result")[:100], e["turn"]), True
+ return "answer", ("I can't say yes or no [turn:%d]: '%s' is a judgement, and I hold no measure for it here. "
+ "What should I measure it by?" % (n_turn, ev[0])), True
+ if re.match(r"^(?:so |ok |okay )?how (?:do|can|could|would|should|to|does one|might) (?:i|we|you|one)?\b", core):
+ op = self.op_head(q)
+ if op and not facts:
+ fit, kind, cmd, usage, desc = op
+ self.stats["howto"] += 1
+ return "answer", "That is `oracle7.py %s` [op:%s]: %s." % (usage if kind == "command" else cmd, cmd, desc[:160].rstrip(".")), True
+ if asked == "yesno":
+ if facts:
+ e, p, lab, vals, _ = facts[0]
+ hit = any(norm(v) in norm(turn) for v in vals)
+ return ("answer", ("Yes: " if hit else "No, not by my records: ") + self.r_fact(e, p, lab, vals) + ".", True)
+ if descrs:
+ return ("answer", "I can't say yes or no from what I hold. %s. What about %s should I check?" % (
+ descrs[0], self.label(ents[0][1])), True)
+ else:
+ if facts:
+ e, p, lab, vals, _ = facts[0]
+ txt = self.r_fact(e, p, lab, vals) + "."
+ if descrs and len(facts) == 1:
+ txt = descrs[0] + ". " + txt
+ self.stats["answer"] += 1
+ return "answer", txt, True
+ if descrs and asked == "noun":
+ self.stats["describe"] += 1
+ return "answer", descrs[0] + ".", True
+ if ents and helds and helds[0][1]:
+ e, held = helds[0]
+ self.stats["hole_rel"] += 1
+ return ("hole", "I hold no %s for %s [none]; a record of it would fill that. What I do hold on %s: %s [wd:Q%d]. "
+ "Which of those do you want?" % ({"yesno": "yes or no", "time": "date", "number": "number", "name": "name",
+ "place": "place"}.get(asked, "answer"), self.label(e), self.label(e),
+ ", ".join(held[:5]), e), False)
+ dw = defq_word(core, self.reader.d)
+ if dw:
+ w = dw
+ g = self.ffn_define(w)
+ if g:
+ self.stats["define"] += 1
+ return "answer", g.rstrip(".") + " [dict:%s]." % w, True
+ sc = self.scene(session, unit(self.text_vec(words, wts)) if words else q, words)
+ if sc:
+ self.stats["play"] += 1
+ return "play", self.r_play(sc, key, descrs if ents and ents[0][0].lower() in core else [], n_turn), True
+ if key:
+ return ("hole", "I hold no record that names %s [none]; a record of %s would fill that. Which %s do you mean?" % (
+ key, key, key), False)
+ return "hole", "I hold nothing that answers that [none]. What is it about?", False
+ if mood in ("request", "commitment"):
+ verb, thing, top = self.understood(fr, h)
+ m = re.search(r"\b(?:like|want|need|love)\s+to\s+([a-z]+)\s+(.*)$", core)
+ if m and (verb in ("like", "want", "need", "love", None) or not thing):
+ verb = m.group(1)
+ thing = " ".join(w for w in content_words(m.group(2)) if w not in GENERIC and not self.reader.is_closed(w))[:60] or thing
+ if not fr["object"] and ref_words and thing == " ".join(fr.get("bound", [])[:2]):
+ thing = "" # a referent is not the thing to act on unless the turn says so
+ want = " ".join(x for x in [verb, thing, ("on " + top) if top else ""] if x).strip() or "that"
+ op = self.op_head(q, words=words)
+ lead = ""
+ if descrs and ents and ents[0][0].lower() in core:
+ lead = descrs[0] + ". "
+ if op:
+ fit, kind, cmd, usage, desc = op
+ self.stats["plan"] += 1
+ return ("plan", lead + "I would run `oracle7.py %s` [op:%s]: %s. Shall I?" % (
+ usage if kind == "command" else cmd, cmd, desc[:140].rstrip(".")), True)
+ sc = self.scene(session, unit(self.text_vec(words, wts)), words) if not op else None
+ if sc:
+ self.stats["play"] += 1
+ return "play", self.r_play(sc, thing or key, descrs if ents and ents[0][0].lower() in core else [], n_turn), True
+ self.stats["hole_op"] += 1
+ if verb in GENERIC or not verb or "verb" not in self.reader.d.pos(verb):
+ want = "do that ('%s')" % " ".join(re.sub(r"\s+", " ", core).split()[:6])
+ near = ""
+ op2 = self.op_head(q, tau=0.25, words=[w for w in words if self.idf(w) >= 4.0])
+ if op2:
+ fit, kind, cmd, usage, desc = op2
+ near = " The nearest I have is `oracle7.py %s` [op:%s]: %s." % (usage if kind == "command" else cmd, cmd, desc[:110].rstrip("."))
+ elif len(self.turns[session]) > 1:
+ pw = " ".join(w for w in content_words(self.turns[session][-2]) if w not in GENERIC)[:60]
+ near = " It follows what you asked about %s [turn:%d]." % (pw or "before", n_turn - 1)
+ return ("hole", lead + "I can't %s [none]: no operation of mine acts on %s; a part that does would fill it.%s "
+ "What would count as done?" % (want, thing or "that", near), False)
+ # statement
+ parts = []
+ own = [e for e in ents if e[0].lower() in core]
+ if descrs and own:
+ parts.append(descrs[0] + ".")
+ if facts and own:
+ e, p, lab, vals, _ = facts[0]
+ parts.append(self.r_fact(e, p, lab, vals) + ".")
+ ev = [w for w in words if w in EVAL]
+ if ev:
+ L = self.ledger.get(session) or []
+ prev = self.turns[session][-2] if len(self.turns[session]) > 1 else None
+ if L:
+ e = L[-1]
+ parts.append("By my last receipt it is `%s`: %s [ledger:%d]." % (e["cmd"], (e["receipt"] or "no result")[:100], e["turn"]))
+ elif prev and fr["refs"]:
+ pw = " ".join(w for w in content_words(prev) if w not in GENERIC)[:60]
+ parts.append("You mean what we had on %s [turn:%d]: '%s'. No operation of mine changes that; the part that renders it would. "
+ "Which element?" % (pw or "the last turn", n_turn - 1, ev[0]))
+ else:
+ parts.append("I have no measure of my own for '%s' here [turn:%d]; what should I measure it by?" % (ev[0], n_turn))
+ sc = None
+ if not parts or (self.mover is not None and not ev):
+ sc = self.scene(session, unit(self.text_vec(words, wts)) if words else q, words)
+ if sc:
+ self.stats["play"] += 1
+ return "play", self.r_play(sc, key, [p.rstrip(".") for p in parts[:1]], n_turn), True
+ if parts:
+ self.stats["ack"] += 1
+ about = (" ".join(ref_words[:3]) if ref_words and not h else key) or (ents[0][0] if ents else "that")
+ return "ack", "Noted on %s. %s" % (about, " ".join(parts)), True
+ L = self.ledger.get(session) or []
+ if key:
+ if L:
+ e = L[-1]
+ return "ack", "Noted on %s. My last receipt here is `%s`: %s [ledger:%d]. What came of it on your side?" % (
+ key, e["cmd"], (e["receipt"] or "no result")[:80], e["turn"]), True
+ return "hole", "Noted on %s [turn:%d]. I hold no record of it and no receipt of my own; tell me what came of it and I keep it." % (
+ key, n_turn), False
+ return "hole", "Noted [turn:%d]. What should I do with that?" % n_turn, False
+
+ def candidates(self, turn, fr, session, cg, head):
+ out = super(SquircleRouterV6, self).candidates(turn, fr, session, cg, head) # v4's ports: head, ledger, essay, run, commit
+ out = [c for c in out if c[1] not in ("hole", "records")] # no copied record sentences, no v4 hole
+ kept = []
+ for c in out:
+ if c[1].startswith("head"):
+ hp, nw = c[4], len(str(c[2]).split())
+ self.dbg.append(("head", hp[:60], nw))
+ if hp.startswith("help") or "lecture" in hp or hp.startswith("wordnet") or (nw > 90 and fr["mood"] == "question"):
+ continue # a help lecture is not an answer
+ kept.append(c)
+ out = kept
+ wts, h = self.demand(turn, fr)
+ words = list(wts)
+ q = unit(self.text_vec(words, wts)) if words else np.zeros(D, dtype=np.float32)
+ own = [w for w in sorted(wts, key=lambda x: -wts[x])][:6]
+ fr["_own"] = list(wts)
+ q_own = q
+ q, ref_words = self.ref_head(session, q, fr, wts) if words or self.hist[session] else (q, [])
+ for w in ref_words:
+ wts.setdefault(w, 1.0)
+ fr["bound"] = list(dict.fromkeys(fr.get("bound", []) + ref_words))[:6]
+ ran = any(sub in ("run", "commit", "essay") and text for _, sub, text, _, _ in out)
+ try:
+ act, text, subst = self.program(turn, fr, session, wts, h, q, ref_words)
+ except Exception as e: # noqa: BLE001
+ self.stats["program_error"] += 1
+ self.dbg.append(("error", repr(e)[:200]))
+ act, text, subst = "hole", "I can't compose a reply to that [none]. What is it about?", False
+ self.lastprog[session] = (act, text)
+ if ran and act in ("plan", "hole"):
+ pass # v4 already did the work; its receipt wins
+ else:
+ port = "hole" if act == "hole" else ("commissive" if act in ("plan", "play") else "inform")
+ out.append((port, "c8:" + act, text, subst, ""))
+ self.stats["act_" + act] += 1
+ self.hist[session].append((q_own if float(np.linalg.norm(q_own)) > 0 else np.zeros(D, dtype=np.float32) + 1e-6, own))
+ return out
+
+ def prime(self, user_turn, role_turn, session="convo"):
+ """record one exchange of a transcript (what the user said, what the role said) without composing anything"""
+ self.turns[session].append(user_turn)
+ self.role_turns[session].append(role_turn)
+ self.reader.sp.observe(user_turn)
+
+ def reply(self, turn, session="convo"):
+ """v4's act (forward ports, inverted read-back), with one change: a composed program is read back by its own terms
+ (its citations), so it is not dropped for lacking the turn's words"""
+ from squircle_reply_v4 import MOOD_ACT, LECTURE, COVER
+ self._cur = turn
+ self.turns[session].append(turn)
+ self.reader.sp.observe(turn)
+ cg = self.common[session]
+ self.receive(cg, turn)
+ stripped = OPENERS.sub("", turn, count=1).strip() or turn
+ fr = self.bind(session, self.reader.read(stripped if len(stripped.split()) >= 2 else turn))
+ fr["turn"] = turn
+ u = MOOD_ACT.get(fr["mood"], "inform")
+ head = self.head_chat(turn, session)
+ cands = self.candidates(turn, fr, session, cg, head)
+ self.frames[session].append(fr)
+ scored = []
+ for port, sub, text, substantive, hpath in cands:
+ if not text:
+ continue
+ fit, agree, act_c = self.inverse(fr, u, text)
+ if sub.startswith("head") and fr["mood"] == "question" and hpath and not LECTURE.match(hpath):
+ agree = max(agree, COVER)
+ if sub.startswith("c8:") and "[" in text:
+ agree = max(agree, COVER)
+ if agree < COVER and port != "hole":
+ continue
+ bonus = 0.5 if sub.startswith("c8:") and substantive else 0.0
+ scored.append((agree + fit + (1.0 if substantive else 0.0) + bonus, port, sub, text, act_c, round(agree, 2)))
+ frame = {k: fr[k] for k in ("mood", "verb", "object", "topic", "status", "keys", "bound", "changes", "wh")}
+ if not scored:
+ return {"status": "declined", "response": "I can't reply to that with anything I can check.",
+ "path": "compose8:%s>none" % u, "act_in": u, "frame": frame}
+ scored.sort(key=lambda x: -x[0])
+ s, port, sub, text, act_c, agree = scored[0]
+ self.role_turns[session].append(text)
+ return {"status": "answered", "response": text, "path": "compose8:%s>%s:%s" % (u, port, sub), "act_in": u,
+ "act_out": act_c, "agree": agree, "frame": frame,
+ "considered": [(round(x[0], 2), x[1] + ":" + x[2], x[5]) for x in scored[:5]]}
diff --git a/workbench/converse/compose_reply_v9.py b/workbench/converse/compose_reply_v9.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6d51b1c4b5fddb69a31159d7eaa6dd9d707179d
--- /dev/null
+++ b/workbench/converse/compose_reply_v9.py
@@ -0,0 +1,409 @@
+#!/usr/bin/env python3
+"""compose_reply_v9 - the turn governed by the loop (PLAN_CONVERSATION_115 S2 + S3), on V8.
+
+Connection 1: the turn is READ into programs by the turn kernel (K8 for store sentences, induced conversational rules
+for the rest). Connection 2: a conversation is a scene with obligations. Each user clause the kernel reads is an
+obligation the user bound (its slots are the givens). The reply's FORM comes from the corpus scene index (what the role
+said next after this form, counted over DailyDialog train), and its places are bound: carried from the user's own turn
+where the corpus carries them (reflect), bound from the head's record where the slot is a name the store links (fill),
+otherwise open. The reply is said only at the dew point: every place bound. Said = the skeleton refilled; proved = the
+second reading (the reply read back is the program it was said from). An open place is a named hole (C4). Nothing about
+the data is written by hand: forms, their order and the carrying of places are all counted off the corpus.
+
+Store answers keep precedence (quality): where V8 composes a cited fact, that reply stands. The learned move replaces V8's
+hand ports (social, ack, hole-without-record) and the next-question predictor."""
+import collections
+import json
+import os
+import re
+import sys
+
+from compose_reply_v8 import ComposeRouterV8, content_words
+
+_HERE = os.path.dirname(os.path.abspath(__file__)) # the package itself: its K8 reader, its data
+_TREE = os.path.abspath(os.path.join(_HERE, "..", "..")) # the release this package ships in
+TK_DIR = os.environ.get("ORACLE7_TK", os.path.join(_HERE, "data", "tk"))
+WT = os.environ.get("ORACLE7_WT", os.path.join(_TREE, "root", "wander-train"))
+for p in (WT, _HERE): # the package's own modules first; nothing outside the release
+ if p not in sys.path:
+ sys.path.insert(0, p)
+from turn_kernel import TurnKernel, Induced, toks # noqa: E402
+
+CARRY_MIN = 0.5 # a role place is carried from the user's turn when the corpus carries it at least this often
+MOVE_MIN = 2 # a (user form -> role form) pair must occur at least this often to be a move
+AUX = re.compile(r"^(do|does|did|is|are|was|were|can|could|would|will|shall|should|have|has|had|may|might)$", re.I)
+WH = re.compile(r"^(what|who|where|when|why|how|which|whose)$", re.I)
+
+
+class SceneIndex:
+ """counted off scene_programs.json: for each user form, the role's next forms, and how their places are carried"""
+
+ def __init__(self, path, rules):
+ self.rule = {r["rule_id"]: r for r in rules}
+ self.next = collections.defaultdict(collections.Counter) # user rule -> Counter(role rule)
+ self.next_given = collections.defaultdict(collections.Counter) # (user rule, one of the user's own words) -> Counter(role rule)
+ self.carry = collections.defaultdict(collections.Counter) # (user rule, role rule, role slot k) -> Counter(user slot m | "new")
+ self.fill = collections.defaultdict(collections.Counter) # (user rule, role rule, role slot k) -> Counter(word the role brought)
+ self.fill_given = collections.defaultdict(collections.Counter) # (..., k, a user slot value) -> Counter(word the role brought)
+ self.pairs = collections.Counter()
+ scenes = json.load(open(path))
+ for dl in scenes:
+ for j in range(len(dl) - 1):
+ ups = [p for p in dl[j] if p]
+ rps = [p for p in dl[j + 1] if p]
+ if not ups or not rps:
+ continue
+ u = ups[-1] # the last thing the user said is what the role answers
+ for r in rps[:1]: # the role's first clause is its move
+ self.next[u["rule"]][r["rule"]] += 1
+ self.pairs[(u["rule"], r["rule"])] += 1
+ us = {int(k): v.lower() for k, v in u["slots"].items()}
+ for uv in set(us.values()):
+ self.next_given[(u["rule"], uv)][r["rule"]] += 1
+ for k, v in r["slots"].items():
+ src = next((m for m, uv in us.items() if uv == v.lower()), "new")
+ self.carry[(u["rule"], r["rule"], int(k))][src] += 1
+ if src == "new": # the role brought this word: the scene's own vocabulary
+ self.fill[(u["rule"], r["rule"], int(k))][v] += 1
+ for uv in us.values():
+ self.fill_given[(u["rule"], r["rule"], int(k), uv)][v] += 1
+ # the scene ids the judge reads: one per (user form, role form) pair that is a move
+ self.scene_of = {}
+ self.scenes = []
+ for (ur, rr), n in self.pairs.most_common():
+ if n < MOVE_MIN:
+ break
+ sid = "p%d" % len(self.scenes)
+ self.scene_of[(ur, rr)] = sid
+ skel = self.rule[rr]["skeleton_tokens"]
+ text = " ".join(skel)
+ lead = [s for s in skel if not s.startswith("<")]
+ wh = "yes/no" if lead and AUX.match(lead[0]) else next((s for s in lead if WH.match(s)), None)
+ key = [w for w in content_words(" ".join(s for s in self.rule[ur]["skeleton_tokens"] + skel if not s.startswith("<")))]
+ self.scenes.append({"id": sid, "key": key[:8], "n": n, "user_form": ur, "role_form": rr,
+ "moves": [{"act": "question" if skel and skel[-1] == "?" else "statement", "text": text,
+ "wh": wh, "slot": None}]})
+
+ def opens(self, rr):
+ """a move opens an obligation: it asks, or it brings a name or a number. A bare acknowledgement is not a move."""
+ skel = self.rule[rr]["skeleton_tokens"]
+ return (skel and skel[-1] == "?") or any(s in ("", "") for s in skel)
+
+ def moves(self, user_rule, user_slots=None):
+ """the role's next forms after this form: given one of the user's own words where the corpus counted that (>= MOVE_MIN),
+ then by the form alone; only forms that open an obligation"""
+ out, seen = [], set()
+ for uv in (user_slots or {}).values():
+ for rr, n in self.next_given.get((user_rule, uv.lower()), {}).most_common():
+ if n >= MOVE_MIN and rr not in seen and self.opens(rr):
+ out.append((rr, n)); seen.add(rr)
+ for rr, n in self.next.get(user_rule, {}).most_common():
+ if n >= MOVE_MIN and rr not in seen and self.opens(rr):
+ out.append((rr, n)); seen.add(rr)
+ return out
+
+ def filler(self, ur, rr, k, user_slots):
+ """the word the role brings at this place, counted off the scene: given the user's own words first, else overall"""
+ for uv in user_slots.values():
+ c = self.fill_given.get((ur, rr, k, uv.lower()))
+ if c and c.most_common(1)[0][1] >= 2:
+ return c.most_common(1)[0][0]
+ c = self.fill.get((ur, rr, k))
+ return c.most_common(1)[0][0] if c else None
+
+ def carried(self, ur, rr, k):
+ c = self.carry.get((ur, rr, k))
+ if not c:
+ return None
+ src, n = c.most_common(1)[0]
+ return src if src != "new" and n / sum(c.values()) >= CARRY_MIN else None
+
+
+class ComposeRouterV9(ComposeRouterV8):
+ def __init__(self, *a, **k):
+ super().__init__(*a, **k)
+ from stage5m13e9_kernel_k8 import ConstructionKernelK8
+ self.tk = TurnKernel(ConstructionKernelK8(compositional=True), TK_DIR)
+ self.index = SceneIndex(os.path.join(TK_DIR, "scene_programs.json"), self.tk.ind.rules)
+ self.scene_programs = json.load(open(os.path.join(TK_DIR, "scene_programs.json"))) # train dialogue -> turn -> programs
+ self.obl = collections.defaultdict(list) # session -> obligations: {rule, slots, by, turn}
+ try: # the build door (converse/builder.py): present in the pack, optional in the harness
+ from builder import Builder
+ self.builder = Builder(self)
+ except Exception: # noqa: BLE001
+ self.builder = None
+ self.played9 = collections.defaultdict(set) # session -> role forms already used
+ self.holes9 = collections.Counter() # the typed holes this router leaves (S5 reads them)
+ out_dir = os.environ.get("ORACLE7_TMP", TK_DIR)
+ os.makedirs(out_dir, exist_ok=True)
+ json.dump(self.index.scenes, open(os.path.join(out_dir, "program_scenes.json"), "w"), ensure_ascii=False)
+ # the resonator (resonance.py): role-aware resonance over the scene memory ranks the scenes in place of the mover's cosine
+ self.resonator = None
+ if os.environ.get("ORACLE7_RESONANCE", "1") == "1" and self.mover is not None:
+ from resonance import Resonator
+ self.resonator = Resonator(os.environ.get("ORACLE7_MOVES", "/opt/o7conv/moves.json"))
+ self.res_cfg = dict(L=int(os.environ.get("RES_L", 1)), p=int(os.environ.get("RES_P", 2)), sq=int(os.environ.get("RES_SQ", 1)))
+
+ # ---------------- the loop over obligations
+ def bind_turn(self, turn, session):
+ """read the turn; every clause read is an obligation the user bound. -> programs (None where unread)"""
+ ps = self.tk.compile(turn)
+ n = len(self.turns[session])
+ for p in ps:
+ if p and p["kind"] == "rule":
+ self.obl[session].append({"rule": p["rule"], "slots": p["slots"], "by": "user", "turn": n})
+ self.dbg.append(("read", [(p["kind"], p.get("rule")) if p else None for p in ps]))
+ if not ps or not any(ps):
+ self.holes9["unread"] += 1
+ elif not all(ps):
+ self.holes9["part_read"] += 1
+ return ps
+
+ def scene_move(self, turn, session, ents):
+ """the scenes nearest in CONTENT (the mover's neighbours over what was said, the user's previous turn and the role's), read
+ as programs: the role's next form in each, voted by similarity; its places bound (carried from the turn, the store's name,
+ or the scene's own word); only a form that opens an obligation; said at the dew point and proved by the second reading"""
+ if self.mover is None or not hasattr(self, "scene_programs"):
+ return None
+ T = self.turns.get(session) or []
+ R = self.role_turns.get(session) or []
+ if getattr(self, "resonator", None) is not None:
+ sc = self.resonator.rank(T[-1] if T else turn, T[-2] if len(T) > 1 else None, R[-1] if R else None, **self.res_cfg)
+ else:
+ sc = self.mover.scored(T[-1] if T else turn, T[-2] if len(T) > 1 else None, R[-1] if R else None)
+ n = len(self.turns[session])
+ tw = {t.lower() for t in toks(turn)}
+ names = [self.label(e) for _, e, _ in ents][:3]
+ # the read-out order IS the choice (the standalone measurement's 37.8%): the first pooled scene whose reply opens an
+ # obligation and was not played. If its reply reads as a form, the form is refilled (places carried from the turn, the
+ # store's name, else the scene's own word) and proved by the second reading; if it does not read, or the second reading
+ # fails, the reply is the LITERAL form (the corpus's own words): no open place, proved by identity.
+ for sim, i in sc[:20]:
+ e = self.mover.entries[i]
+ if getattr(self, "resonator", None) is None and sim < self.mover.tau:
+ break
+ if getattr(self, "resonator", None) is not None and sim < self.resonator.tau():
+ break # below the read-off tau: no move; the hole or the head's reply stands
+ if e["id"] in self.played9[session] or "?" not in e["text"]:
+ continue
+ # (round 25) the 'slot already said' skip is removed: the corpus role often asks about the word just said
+ di, j = int(e["dlg"][1:]), int(e["id"].split("_")[1])
+ try:
+ progs = [p for p in self.scene_programs[di][j + 1] if p]
+ except (IndexError, KeyError):
+ progs = []
+ cite_scene = " [scene:%s%s]" % (e["id"], (":" + e["slot"]) if e.get("slot") else "")
+ text, cites, how = None, [], "literal"
+ for p in progs:
+ rr = p["rule"]
+ if not self.index.opens(rr):
+ continue
+ skel = self.index.rule[rr]["skeleton_tokens"]
+ slots, cs = {}, []
+ for k, s_ in enumerate(skel):
+ if not s_.startswith("<"):
+ continue
+ own = p["slots"].get(str(k))
+ if own and own.lower() in tw:
+ slots[k] = own; cs.append("[turn:%d]" % n)
+ elif s_ == "" and names:
+ slots[k] = names[0]; cs.append("[wd:Q%d]" % ents[0][1])
+ elif own:
+ slots[k] = own
+ else:
+ slots = None
+ break
+ if slots is None:
+ continue
+ prog = {"kind": "rule", "rule": rr, "slots": slots, "skeleton": skel}
+ t = Induced.realize(prog)
+ if self.tk.same(prog, t):
+ text, cites, how = t, cs, "form:" + rr
+ self.obl[session].append({"rule": rr, "slots": slots, "by": "role", "turn": n})
+ else:
+ self.holes9["second_reading"] += 1
+ break
+ if text is None:
+ text = e["text"]
+ self.holes9["literal_move"] += 1
+ self.played9[session].add(e["id"])
+ self.mover_last[session] = (e["dlg"], e["step"])
+ self.dbg.append(("scene_move", e["id"], round(sim, 3), how, text[:60]))
+ return "play", (text + " " + " ".join(dict.fromkeys(cites)) + cite_scene).replace(" ", " "), True
+ return None
+
+ def move(self, turn, ps, session, ents):
+ """the role's next form after the user's last read form, its places bound; said at the dew point only"""
+ sm = self.scene_move(turn, session, ents)
+ if sm:
+ return sm
+ last = next((p for p in reversed(ps) if p and p["kind"] == "rule"), None)
+ if not last:
+ return None
+ ur = last["rule"]
+ n = len(self.turns[session])
+ names = [self.label(e) for _, e, _ in ents][:3]
+ open_need = None
+ for rr, cnt in self.index.moves(ur, last["slots"]):
+ if rr in self.played9[session]:
+ continue
+ skel = self.index.rule[rr]["skeleton_tokens"]
+ slots, cites, open_ = {}, [], []
+ for k, s in enumerate(skel):
+ if not s.startswith("<"):
+ continue
+ typ = s[1:-1]
+ m = self.index.carried(ur, rr, k)
+ if m is not None and m in last["slots"]:
+ slots[k] = last["slots"][m] # reflected from the user's own turn
+ cites.append("[turn:%d]" % n)
+ elif typ == "NAME" and names:
+ slots[k] = names[0] # filled from the store's linked name
+ cites.append("[wd:Q%d]" % ents[0][1])
+ elif typ == "NUM" and any(t.isdigit() for t in toks(turn)):
+ slots[k] = next(t for t in toks(turn) if t.isdigit())
+ cites.append("[turn:%d]" % n)
+ else:
+ w = self.index.filler(ur, rr, k, last["slots"]) # bound from the scene's own record (S3 fill, hole class open_place)
+ if w is not None and (typ != "NAME" or not names):
+ slots[k] = w
+ cites.append("[scene:%s]" % self.index.scene_of.get((ur, rr), "p0"))
+ else:
+ open_.append(typ)
+ if open_:
+ if open_need is None:
+ open_need = (rr, open_)
+ continue
+ prog = {"kind": "rule", "rule": rr, "slots": slots, "skeleton": skel}
+ text = Induced.realize(prog)
+ if not self.tk.same(prog, text):
+ self.holes9["second_reading"] += 1
+ self.dbg.append(("second_reading_failed", rr, text[:60]))
+ continue
+ self.played9[session].add(rr)
+ sid = self.index.scene_of.get((ur, rr), "p0")
+ self.obl[session].append({"rule": rr, "slots": slots, "by": "role", "turn": n})
+ act = "play" if skel and skel[-1] == "?" else "answer"
+ # a question is a move and cites its scene; a statement is said only from what it carries (the turn, the store)
+ cite = " ".join(dict.fromkeys(cites)) + ((" [scene:%s]" % sid) if act == "play" else "")
+ self.dbg.append(("move", ur, "->", rr, cnt, text[:60]))
+ return act, text + " " + cite, True
+ if open_need:
+ rr, open_ = open_need
+ self.holes9["open_place:" + open_[0]] += 1
+ sid = self.index.scene_of.get((ur, rr), "p0")
+ return "hole", "The next thing to say here needs a %s I don't hold [scene:%s]; give me the %s and I go on." % (
+ open_[0].lower(), sid, open_[0].lower()), False
+ self.holes9["no_move"] += 1
+ return None
+
+ # ---------------- the plug: store facts first, then the learned move, then V8's remaining ports
+ COMPARE = re.compile(r"\b(compare|compared|comparison|longer|shorter|taller|bigger|larger|smaller|older|newer|heavier|higher)\b", re.I)
+
+ def compare(self, turn, session, asked):
+ """Amendment 14 (1): a comparison binds two entities (this turn's, else the most recent one the conversation named) and
+ one relation, read from the store for both; both values are stated with their citations. The judgement is made only
+ when the values are comparable; the relational store keeps quantities without units, so a quantity is never judged."""
+ ents = [e for _s, e, _ in self.link(turn)]
+ if len(ents) < 2:
+ for prev in reversed(self.turns[session][:-1]):
+ if self.COMPARE.search(prev):
+ continue # the referent of "it" is the thing asked about, not an earlier comparison's other side
+ for _s, e, _ in self.link(prev):
+ if e not in ents:
+ ents.append(e)
+ break
+ if len(ents) >= 2:
+ break
+ if len(ents) < 2:
+ return None
+ a, b = ents[0], ents[1]
+ prevq = " ".join([t for t in self.turns[session][:-1] if t.rstrip().endswith("?")][-3:]) or turn
+ from compose_reply_v8 import content_words, unit as _unit
+ names = set(w for e in (a, b) for w in content_words(self.label(e) or ""))
+ rest = [w for w in content_words(prevq + " " + turn) if w not in names and not self.COMPARE.search(w)]
+ # a comparative names its quantity by its base ("longer" -> long, "taller" -> tall, "older" -> old)
+ rest += [m.lower()[:-3] if m.lower().endswith("ier") else m.lower()[:-2] for m in self.COMPARE.findall(turn) if m.lower().endswith("er")]
+ if self.COMPARE.search(turn) and asked in (None, "noun", "yesno"):
+ asked = "number"
+ qv = _unit(self.text_vec(rest, {w: 1.0 for w in rest})) if rest else None
+ if qv is None:
+ return None
+ ra, _ = self.relations(a, qv, asked or "number")
+ if not ra:
+ return None
+ pa, lab, va, _f = ra[0]
+ rb, _ = self.relations(b, qv, asked or "number")
+ vb = next((v for pp, _l, v, _f in rb if pp == pa), None)
+ if vb is None:
+ return ("hole", "%s. I hold no %s for %s [none]; a record of it would let me compare them." % (
+ self.r_fact(a, pa, lab, va), lab, self.label(b)), False)
+ txt = "%s, and %s." % (self.r_fact(a, pa, lab, va), self.r_fact(b, pa, lab, vb))
+ num = lambda v: float(v[0]) if v and re.match(r"^[+-]?\d+(\.\d+)?$", str(v[0])) else None
+ if num(va) is not None and num(vb) is not None:
+ txt += " My records keep these without their units, so I won't say which is greater until a source gives the unit."
+ return "answer", txt, True
+
+ def program(self, turn, fr, session, wts, h, q, ref_words):
+ if self.COMPARE.search(turn) and (fr.get("mood") == "question" or turn.rstrip().endswith("?")):
+ try:
+ c = self.compare(turn, session, self.asked(fr))
+ except Exception as e: # noqa: BLE001
+ c = None
+ self.dbg.append(("compare_error", repr(e)[:120]))
+ if c:
+ self.stats["compare"] = self.stats.get("compare", 0) + 1
+ return c
+ ps = self.bind_turn(turn, session)
+ if self.builder is not None: # a build request, or an example question binding one of its places
+ try:
+ b = self.builder.step(turn, fr, session, q)
+ except Exception as e: # noqa: BLE001
+ b = None
+ self.dbg.append(("builder_error", repr(e)[:120]))
+ if b:
+ return b
+ act, text, subst = super().program(turn, fr, session, wts, h, q, ref_words)
+ if act == "answer" and "[wd:" in text and " P" in text:
+ return act, text, subst # a cited fact from the store stands (quality)
+ if act in ("cancel", "plan") or (act == "answer" and "[ledger:" in text) or (act == "answer" and "[op:" in text):
+ return act, text, subst # the work ledger and the head's own operations stand
+ ents = getattr(self, "_ents9", []) or []
+ mv = self.move(turn, ps, session, ents) if any(ps) else self.scene_move(turn, session, ents)
+ # 12.0 step 3, the Tiferet rule: a question the head declined and the store did not fill is met by the hole that names
+ # the open place, never by a scene move (the 11.5 end-to-end answered a bridge length with a scene about dancing)
+ # the class (wake run 11-08: the first rule only caught a play replacing a hole): on a QUESTION the head declined, a
+ # play is never the reply; a hole or a cited answer stands, otherwise the hole names what is open
+ if mv and mv[0] == "play" and (fr.get("mood") == "question" or turn.rstrip().endswith("?")):
+ self.stats["hole_over_play"] = self.stats.get("hole_over_play", 0) + 1
+ if act == "hole" or (act == "answer" and "[" in str(text)):
+ return act, text, subst
+ keys = [str(k) for k in (fr.get("keys") or []) if k][:4]
+ need = (" What I would need: a record of " + ", ".join(keys) + ".") if keys else ""
+ return "hole", "I cannot answer that from anything I can check [turn:%d].%s" % (len(self.turns[session]), need), False
+ if mv:
+ self.stats["move9"] += 1
+ return mv
+ if act == "play" and (fr.get("mood") == "question" or turn.rstrip().endswith("?")):
+ # the same class on the older composer's own play (wake run: "What would you build next" got a recorded line)
+ self.stats["hole_over_play"] = self.stats.get("hole_over_play", 0) + 1
+ keys = [str(k) for k in (fr.get("keys") or []) if k][:4]
+ need = (" What I would need: a record of " + ", ".join(keys) + ".") if keys else ""
+ return "hole", "I cannot answer that from anything I can check [turn:%d].%s" % (len(self.turns[session]), need), False
+ return act, text, subst
+
+ def link(self, turn, wh_about=True, want_p=None):
+ ents = super().link(turn, wh_about=wh_about, want_p=want_p)
+ self._ents9 = ents
+ return ents
+
+ def prime(self, user_turn, role_turn, session="convo"):
+ super().prime(user_turn, role_turn, session)
+ n = len(self.turns[session])
+ for p in self.tk.compile(user_turn):
+ if p and p["kind"] == "rule":
+ self.obl[session].append({"rule": p["rule"], "slots": p["slots"], "by": "user", "turn": n})
+ for p in self.tk.compile(role_turn):
+ if p and p["kind"] == "rule":
+ self.obl[session].append({"rule": p["rule"], "slots": p["slots"], "by": "role", "turn": n})
+ self.played9[session].add(p["rule"])
diff --git a/workbench/converse/compose_writing.py b/workbench/converse/compose_writing.py
new file mode 100644
index 0000000000000000000000000000000000000000..b480c652a073d93869451b52c9e8605656404d54
--- /dev/null
+++ b/workbench/converse/compose_writing.py
@@ -0,0 +1,989 @@
+"""compose_writing - writing that answers its question, shaped as asked (revised 12.0, 2026-11-17).
+
+The single-subject writer answers "write about X". A request that asks something of its writing ("Explain how a key
+opens a pin-tumbler lock", "Compare owls and hawks as hunters: four sections with headings ...", "Describe how paper is
+made, numbered steps", "Using only these two notes, compare ...") needs three things that writer does not do:
+
+ 1. read what the writing must accomplish: the question's own words, the structure asked (paragraphs, named sections,
+ numbered steps, bullets), the size, and any passage or note the user supplies;
+ 2. find the pages that answer it through the store's own full-text index over every held sentence, ranked by how many
+ of the question's terms their sentences carry; the user's supplied text is kept as their premise;
+ 3. take the run of consecutive sentences that carries the question best, sized to the request: a passage in its
+ source's own order is coherent because its source wrote it so. One run per heading for sections.
+
+Every sentence keeps its kind: a held sentence is cited by its record and reads back; a supplied sentence is marked as
+the user's. Nothing is said that no record holds. What the held passages cannot fill is a counted hole that keeps the
+request for a fill.
+
+Would not solve: an explanation, argument or verdict that no held passage gives (only held and supplied sentences are
+said); connecting passages from different sources into one line of reasoning.
+"""
+import hashlib
+import re
+
+NL = chr(10)
+NL2 = NL + NL
+
+QUOTED = re.compile(r"[\"‘“']([^\"‘’“”]{40,}?)[\"’”'](?=\s|$|[.,;:])")
+STRUCTURE_WORDS = {"paragraph", "paragraphs", "section", "sections", "heading", "headings", "step", "steps", "numbered",
+ "bullet", "bullets", "takeaway", "takeaways", "word", "words", "sentence", "sentences", "short",
+ "long", "total", "between", "across", "per", "within", "into", "about", "around", "exactly", "each", "under", "most", "least", "more",
+ "less", "than", "only", "using", "write", "explain", "describe", "compare", "argue", "give", "make",
+ "someone", "who", "has", "have", "used", "life", "all", "never", "still", "same", "one", "two",
+ "three", "four", "five", "six", "seven", "eight", "nine", "ten", "first", "then", "with", "for", "and",
+ "that", "this", "these", "those", "into", "from", "how", "why", "what", "when", "where", "which",
+ "should", "would", "could", "can", "does", "did", "do", "is", "are", "was", "were", "the", "a", "an",
+ "of", "in", "on", "to", "by", "as", "or", "but", "not", "it", "its", "their", "they", "them", "you",
+ "your", "me", "my", "i", "we", "our", "us", "please", "verdict", "conclusion", "side", "takes",
+ "wondered", "ordinary", "common", "some", "like", "order", "stage", "stages", "per", "much", "many",
+ "roughly", "make", "made", "makes", "change", "changes", "easier", "harder", "answer", "argued"}
+
+
+def _lemmas(text, reader):
+ out = set()
+ for w in re.findall(r"[a-z]{3,}", text.lower()):
+ if w in STRUCTURE_WORDS:
+ 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 else w)
+ return out
+
+
+def _number(word, reader):
+ if word is None:
+ return None
+ if word.isdigit():
+ return int(word)
+ import size
+ return size.value(word, reader.d) if reader is not None else None
+
+
+def _split(text):
+ return [s.strip() for s in re.split(r"(?<=[.!?])\s+(?=[A-Z0-9\"'])", text) if len(s.strip()) > 3]
+
+
+APPROX = r"(?:about|around|roughly|approximately|some|or so|more or less|circa)"
+AT_MOST = r"(?:no more than|not more than|at most|up to|under|below|fewer than|less than|within|a maximum of|max(?:imum)?)"
+AT_LEAST = r"(?:at least|no fewer than|not less than|no less than|over|more than|a minimum of|min(?:imum)?)"
+
+
+def _bounded(s, body, structure):
+ """a word size with the bound its own wording gives it. An exact count stays exact; "about N" is N within a fifth;
+ "no more than N" / "under N" is anything up to N (from a third of it); "at least N" runs from N to half as much
+ again; "each ..." in a sectioned piece is per section, so the whole is that many times it."""
+ lo, hi = s.get("min", s["n"]), s.get("max", s["n"])
+ begin = s.get("span", [0, 0])[0]
+ before = body[max(0, begin - 28):begin].lower()
+ after = body[s.get("span", [0, 0])[1]:][:12].lower()
+ if lo == hi:
+ n = hi
+ if re.search(AT_MOST + r"\s*$", before):
+ lo, hi = max(1, n // 3), n
+ elif re.search(AT_LEAST + r"\s*$", before):
+ lo, hi = n, n + n // 2
+ elif re.search(APPROX + r"\s*$", before) or re.match(r"\s*or so", after):
+ lo, hi = n - n // 5, n + n // 5
+ if structure.get("sections") and re.search(r"(?i)\beach\b[^.]{0,24}$", body[max(0, begin - 40):begin]):
+ k = len(structure["sections"])
+ lo, hi = lo * k, hi * k
+ return (lo, hi)
+
+
+def _words(items):
+ return sum(len(x["sentence"].split()) for x in items)
+
+
+def _extend(chosen, pages, lo, hi):
+ """a passage shorter than the size asked is continued from where it stands: the sentences that follow it on its own
+ page, then those before it, then the same from the next pages, until the size is met (never past its upper bound).
+ What is added is the passage's own context, so the piece stays one account instead of stopping short."""
+ if not chosen or not lo:
+ return chosen
+ have = {x["claim"] for x in chosen}
+ for page in sorted(pages, key=lambda pg: 0 if pg and pg[0].get("page") == chosen[0].get("page") else 1):
+ if not page:
+ continue
+ at = [i for i, x in enumerate(page) if x["claim"] in have]
+ start = (max(at) + 1) if at else 0
+ for x in page[start:]:
+ if _words(chosen) >= lo:
+ return chosen
+ if x["claim"] not in have and (not hi or _words(chosen) + len(x["sentence"].split()) <= hi):
+ chosen.append(x)
+ have.add(x["claim"])
+ for x in reversed(page[:min(at)] if at else []):
+ if _words(chosen) >= lo:
+ return chosen
+ if x["claim"] not in have and (not hi or _words(chosen) + len(x["sentence"].split()) <= hi):
+ chosen.insert(0, x)
+ have.add(x["claim"])
+ return chosen
+
+
+def read_request(text, reader):
+ """-> the writing's obligation: the question's words, the structure, the size, supplied passages"""
+ supplied = [m.group(1).strip() for m in QUOTED.finditer(text)]
+ body = QUOTED.sub(" ", text)
+ structure = {"kind": "paragraphs", "count": None, "sections": [], "steps": None, "bullets": None}
+ m = re.search(r"(?i)sections?\s+with\s+headings?\s*:\s*(.+?)(?:\.\s|\.$|$)", body)
+ if m:
+ heads = [h.strip(" .;") for h in re.split(r",\s*(?:and\s+)?|\s+and\s+", m.group(1)) if h.strip(" .;")]
+ structure.update(kind="sections", sections=[re.sub(r"(?i)^(?:a|an|the)\s+(?:short\s+)?", "", h) for h in heads])
+ elif re.search(r"(?i)\ba section for\b.*\ba section against\b", body):
+ structure.update(kind="sections", sections=["For", "Against", "Conclusion"])
+ m = re.search(r"(?i)numbered steps(?:,\s*(\w+)\s+to\s+(\w+))?", body)
+ if m:
+ lo, hi = _number(m.group(1), reader), _number(m.group(2), reader)
+ structure.update(kind="steps", steps=(lo or 3, hi or lo or 9))
+ m = re.search(r"(?i)\b(\w+)\s+bullet", body)
+ if m and _number(m.group(1), reader):
+ structure["bullets"] = _number(m.group(1), reader)
+ import size
+ sizes = size.sizes_of(body, reader.d) if reader is not None else []
+ words = sentences = None
+ for s in sizes:
+ if s.get("unit") == "paragraph" and structure["kind"] == "paragraphs":
+ structure["count"] = s["n"]
+ if s.get("unit") == "word":
+ words = _bounded(s, body, structure)
+ if s.get("unit") == "sentence":
+ sentences = (s.get("min", s["n"]), s.get("max", s["n"]))
+ m = re.search(r"(?i)no more than\s+(\d+)\s+words", body)
+ if m and not words:
+ words = (int(m.group(1)) // 3, int(m.group(1)))
+ head = re.split(r"(?<=[.?!])\s", body.strip())[0] # the question is its first sentence; the rest shapes it
+ return {"content": _lemmas(head, reader), "question": head, "structure": structure, "words": words,
+ "sentences": sentences, "supplied": supplied, "only_supplied": bool(re.search(r"(?i)\busing only\b", body))}
+
+
+def _stem(word):
+ """a word's stem for matching held text ("senses" ~ "sense", "fjords" ~ "fjord", "hunts" ~ "hunt")"""
+ for end in ("ies", "es", "s"):
+ if len(word) > 4 and word.endswith(end) and not word.endswith("ss"):
+ return word[: -len(end)] + ("y" if end == "ies" else "")
+ return word
+
+
+def _terms(obligation):
+ words = [_stem(w) for w in re.findall(r"[a-z]{3,}", obligation["question"].lower()) if w not in STRUCTURE_WORDS]
+ return list(dict.fromkeys(words))[:12]
+
+
+def _store():
+ import sqlite3
+ import prosefold.options as PO
+ path = PO._deep_store()
+ return sqlite3.connect("file:%s?mode=ro" % path, uri=True) if path else None
+
+
+def _page(con, page_id):
+ rows = con.execute("select c.c0, c.c1, ps.sentence_ordinal from page_sentence ps join source_rows_content c "
+ "on c.id = ps.source_rowid where ps.page_id = ? order by ps.sentence_ordinal", (page_id,)).fetchall()
+ title = (con.execute("select title from article where page_id = ?", (page_id,)).fetchone() or [page_id])[0]
+ out = []
+ for claim, fact, ordinal in rows:
+ t = " ".join(str(fact).split())
+ if len(t) >= 20:
+ out.append({"sentence": t, "claim": claim, "title": title, "page": page_id, "ordinal": int(ordinal or 0),
+ "kind": "sourced"})
+ return out
+
+
+def weights(con, terms):
+ """each term's weight is how rare it is among held sentences (the store's own index counts): the rarest content
+ term anchors the passage, a common word ("coasts", "Norway") cannot carry it alone"""
+ import math
+ total = max(1, (con.execute("select count(*) from page_sentence").fetchone() or [1])[0])
+ out = {}
+ for t in terms:
+ try:
+ df = con.execute("select count(*) from source_rows where source_rows match ?", ('"%s"' % t,)).fetchone()[0]
+ except Exception: # noqa: BLE001
+ df = 0
+ if df:
+ out[t] = math.log(total / df)
+ return out
+
+
+def titled_pages(con, question):
+ """pages whose title is a noun phrase of the question itself ("pin tumbler lock", "fjords", "common frog"), longest
+ phrase first: the page about exactly what is asked is the first source for it"""
+ words = re.findall(r"[a-z][a-z'-]*", question.lower().replace("-", " "))
+ found = []
+ for n in (4, 3, 2, 1):
+ for i in range(len(words) - n + 1):
+ chunk = words[i:i + n]
+ if chunk[0] in STRUCTURE_WORDS or chunk[-1] in STRUCTURE_WORDS or (n == 1 and len(chunk[0]) < 4):
+ continue
+ for key in (" ".join(chunk), " ".join(chunk).rstrip("s"), "_".join(chunk)):
+ row = con.execute("select page_id from title_alias where normalized_title = ?", (key,)).fetchone()
+ if row and row[0] not in found:
+ found.append(row[0])
+ break
+ return found
+
+
+def candidate_pages(con, terms, limit=6):
+ """pages ranked by how many distinct question terms their sentences carry (the store's own full-text index)"""
+ if not terms:
+ return []
+ query = " OR ".join('"%s"' % t.replace('"', "") for t in terms)
+ hits = {}
+ for page_id, fact in con.execute("select page_id, fact from source_rows where source_rows match ? "
+ "order by bm25(source_rows) limit 800", (query,)):
+ low = str(fact).lower()
+ found = {t for t in terms if t in low}
+ if len(found) >= 2:
+ hits.setdefault(page_id, set()).update(found)
+ w = terms if isinstance(terms, dict) else {t: 1.0 for t in terms}
+ ranked = sorted(hits.items(), key=lambda kv: -sum(w.get(t, 1.0) for t in kv[1]))
+ return [page for page, _found in ranked[:limit]]
+
+
+def best_window(sentences, terms, size, need=None):
+ """the run of `size` consecutive sentences that carries the most distinct question terms (and one of `need`)"""
+ best, score = [], -1
+ need = set(need or ())
+ for i in range(0, max(1, len(sentences) - size + 1)):
+ window = sentences[i:i + size]
+ text = " ".join(x["sentence"].lower() for x in window)
+ covered = {t for t in terms if t in text}
+ if need and not {t for t in need if t in text}:
+ continue
+ w = terms if isinstance(terms, dict) else {t: 1.0 for t in terms}
+ carrying = sum(1 for x in window if any(t in x["sentence"].lower() for t in terms))
+ k = 2 * sum(w.get(t, 1.0) for t in covered) + carrying - (len(window) - carrying)
+ if k > score:
+ best, score = window, k
+ return best, score
+
+
+def _carries(window, terms, anchor=None):
+ """the test a chosen passage must pass before it is used: it carries the question's subject and at least half of
+ the question's content terms by weight (and two of them). A page that shares one stray word does not."""
+ w = terms if isinstance(terms, dict) else {t: 1.0 for t in terms}
+ if not window or not w:
+ return bool(window)
+ said = " ".join(x["sentence"].lower() for x in window)
+ starts = set()
+ for word in re.findall(r"[a-z]+", said): # a term is carried by a word that begins with it, not by a
+ for k in range(3, len(word) + 1): # chance run of letters inside another word
+ starts.add(word[:k])
+ carried = {t for t in w if t in starts}
+ share = sum(w[t] for t in carried) / max(1e-9, sum(w.values()))
+ # What a question asks is in its distinctive words, subject and what is asked of it alike ("volcanic", "chains",
+ # "Hawaii"; "price", "fifteenth"). A passage that carries the subject but not what is asked of it is on the
+ # subject and does not answer. So the rarer half of the question's terms must be carried, one miss allowed when
+ # that half has three or more.
+ ranked = sorted(w, key=lambda t: -w[t])
+ rare = ranked[:-(-len(ranked) // 2)]
+ missed = [t for t in rare if t not in carried]
+ return (share >= 0.5 and len(carried) >= min(2, len(w)) and len(missed) <= (1 if len(rare) >= 3 else 0)
+ and not (anchor and anchor in w and anchor not in carried))
+
+
+KIND_MARKERS = {
+ # the forms an answer of each kind takes in held prose: a reason is said with its connective, a method with its
+ # means. Weighted with what is asked, so a passage that gives the reason outranks one that only names the subject.
+ "reason": ("because", "due to", "caused by", "causes", "as a result", "so that", "which means", "leads to", "results in", "which is why",
+ "this is why", "that is why", "makes it", "so the "),
+ "method": (" by ", " using ", " through ", " when ", " then ", "first", "after "),
+}
+
+
+def _asked_kind(question):
+ q = re.sub(r"(?i)^\s*(?:please\s+)?(?:explain|describe|tell me|say|show|outline)\s+", "", question.strip())
+ first = (re.findall(r"[a-z]+", q.lower()) or [""])[0]
+ if first == "how" and re.match(r"(?i)how\s+(?:many|much)\b", q):
+ return "number"
+ return {"why": "reason", "how": "method", "when": "time", "where": "place"}.get(first)
+
+
+def _subject_and_asked(con, question, terms, ids):
+ """what a question is about and what it asks of it. The subject is the question's own phrase that names a held page
+ ("Dead Sea", "printing press", "monarch butterfly"); what is asked is the rest of its content words: the predicate
+ ("salty", "form in chains", "price", "life cycle"). A passage answers when it carries what is asked, not when it
+ only names the subject."""
+ subject = set()
+ for pid in ids:
+ row = con.execute("select normalized_title from title_alias where page_id = ? limit 1", (pid,)).fetchone()
+ if row:
+ words = {_stem(w) for w in re.findall(r"[a-z]{3,}", str(row[0]).lower())}
+ if len(words) >= 2 or not subject: # the longest titled phrases first: the subject's own name
+ subject |= words & set(terms)
+ if len(subject) >= 2:
+ break
+ asked = [t for t in terms if t not in subject]
+ return subject, asked
+
+
+def _answers(window, subject, asked, kind):
+ """the test a passage must pass before it is used: what is asked is carried (half of its words, at least one), and
+ for a reason or a method, said in the form such an answer takes; the subject is the page's or the passage's own"""
+ if not window:
+ return False
+ said = " ".join(x["sentence"].lower() for x in window)
+ starts = set()
+ for word in re.findall(r"[a-z]+", said):
+ for k in range(3, len(word) + 1):
+ starts.add(word[:k])
+ if asked:
+ carried = [t for t in asked if t in starts]
+ if len(carried) < max(1, -(-len(asked) // 2)):
+ return False
+ if kind in KIND_MARKERS and not any(m in " " + said + " " for m in KIND_MARKERS[kind]):
+ return False
+ return True
+
+
+def _from_pages(text, reader, obligation, sid=None):
+ """the page composer: passages from the held pages that answer the question, shaped as asked"""
+ st = obligation["structure"]
+ lo, hi = obligation["words"] or (None, None)
+ if obligation["sentences"]:
+ size = obligation["sentences"][1]
+ elif st["kind"] == "steps":
+ size = st["steps"][1]
+ elif hi:
+ size = max(2, hi // 24)
+ else:
+ size = 3 * (st["count"] or 2)
+ terms = _terms(obligation)
+ anchor = None
+ supplied = [{"sentence": s, "kind": "premise", "claim": "you:" + hashlib.sha256(s.encode()).hexdigest()[:12],
+ "title": "your text", "ordinal": i}
+ for i, s in enumerate(x for p in obligation["supplied"] for x in _split(p))]
+ pages, about = [], set()
+ subject, asked = set(), []
+ kind = _asked_kind(obligation["question"])
+ if not obligation["only_supplied"]:
+ con = _store()
+ if con is not None:
+ weighted = weights(con, terms)
+ terms = weighted or {t: 1.0 for t in terms}
+ ids = titled_pages(con, obligation["question"])
+ about = set(ids) # the pages that are about the question's own subject
+ # The anchor is the question's subject: the head word of the page titled with the question's own phrase
+ # ("paper", "frog", "lock"); with no titled page, the rarest content term.
+ title = (con.execute("select normalized_title from title_alias where page_id = ? limit 1", (ids[0],)).fetchone()
+ if ids else None)
+ head = re.findall(r"[a-z]+", str(title[0]).lower())[-1] if title else None
+ anchor = _stem(head) if head else (max(weighted, key=weighted.get) if weighted else None)
+ subject, asked = _subject_and_asked(con, obligation["question"], terms, ids)
+ ids += [pid for pid in candidate_pages(con, terms) if pid not in ids]
+ pages = [p for p in (_page(con, pid) for pid in ids[:8]) if p]
+ if anchor: # a passage must carry the question's rarest content term
+ pages = [p for p in pages if any(anchor in x["sentence"].lower() for x in p)] or pages
+ if supplied:
+ pages = [supplied] + pages
+ if not pages:
+ return None
+ blocks, holes = [], []
+ if st["kind"] == "sections":
+ per = max(2, min(4, size // max(1, len(st["sections"]))))
+ for head in st["sections"]:
+ head_terms = [_stem(w) for w in re.findall(r"[a-z]{4,}", head.lower()) if w not in STRUCTURE_WORDS]
+ chosen = []
+ for page in pages[:4]:
+ window, score = best_window(page, dict(terms, **{h: 1.0 for h in head_terms}) if isinstance(terms, dict) else terms + head_terms, min(per, len(page)), need=head_terms or None)
+ if window and score > 0:
+ chosen = window
+ break
+ if chosen and lo:
+ share_lo, share_hi = lo // len(st["sections"]), (hi // len(st["sections"])) if hi else None
+ chosen = _extend(list(chosen), [pg for pg in pages[:4] if pg and pg[0].get("page") == chosen[0].get("page")
+ and (pg[0].get("page") in about or pg[0].get("kind") == "premise")],
+ share_lo, share_hi)
+ blocks.append((head[:1].upper() + head[1:], chosen))
+ if not chosen:
+ holes.append('no held passage bears on "%s"' % head)
+ else:
+ # The page titled as the question's own subject leads; later pages only continue it where it is shorter than
+ # the size asked, so what follows extends the core passage instead of replacing it.
+ best, best_score = [], -1
+ # what is asked weighs three times the subject's own words, and an answer's form (a reason's connective) counts
+ w0 = terms if isinstance(terms, dict) else {t: 1.0 for t in terms}
+ top = max(w0.values()) if w0 else 1.0
+ ranked = {t: v * (3.0 if t in asked else 1.0) for t, v in w0.items()}
+ ranked.update({m: top for m in KIND_MARKERS.get(kind, ())})
+ for page in pages:
+ if page[0].get("kind") == "premise":
+ window, score = best_window(page, terms, min(size, len(page)), need=[anchor] if anchor else None)
+ ok = bool(window) and score > 0
+ else:
+ window, score = best_window(page, ranked, min(size, len(page)))
+ ok = (bool(window) and score > 0 and _answers(window, subject, asked, kind)
+ and _carries(window, terms, anchor))
+ if ok:
+ best, best_score = list(window), score
+ if page[0].get("kind") != "premise" and len(best) > 1:
+ # the answer first: the sentence that carries most of what is asked (in an answer's form) leads, the
+ # rest keep the page's order after it
+ def bears(x):
+ low = " " + x["sentence"].lower() + " "
+ return (sum(1 for t in asked if t in low) + sum(1 for m in KIND_MARKERS.get(kind, ()) if m in low))
+ lead = max(best, key=bears)
+ if bears(lead) > bears(best[0]):
+ best = [lead] + [x for x in best if x is not lead]
+ break
+ for page in pages:
+ if len(best) >= size or (hi and sum(len(x["sentence"].split()) for x in best) >= (lo or hi)):
+ break
+ if best and page and page[0].get("page") == best[0].get("page"):
+ continue
+ more, score = best_window(page, ranked, min(size - len(best), len(page)))
+ if more and score > 0 and best and (page[0].get("kind") == "premise" or (
+ _answers(more, subject, asked, kind) and _carries(more, terms, anchor))):
+ best += [x for x in more if x["claim"] not in {b["claim"] for b in best}]
+ if not best:
+ return None # nothing here carries it: the request's own writer takes it
+ if st["kind"] != "steps" and lo and _words(best) < lo:
+ # continued only on the page the core passage itself came from
+ best = _extend(best, [pg for pg in pages if pg and pg[0].get("page") == best[0].get("page")
+ and (pg[0].get("page") in about or pg[0].get("kind") == "premise")], lo, hi)
+ if st["kind"] == "steps":
+ blocks.append((None, best))
+ if len(best) < st["steps"][0]:
+ holes.append("%d steps are held in one passage; %d to %d were asked" % (len(best), st["steps"][0], st["steps"][1]))
+ else:
+ n = st["count"] or (1 if len(best) <= 5 else 2)
+ per = max(1, -(-len(best) // n))
+ for p in range(n):
+ blocks.append((None, best[p * per:(p + 1) * per]))
+ if st.get("bullets"):
+ rest = [x for page in pages for x in page if x not in best][:st["bullets"]]
+ blocks.append(("Takeaways", rest))
+ total = sum(len(it["sentence"].split()) for _h, items in blocks for it in items)
+ if hi and total > hi:
+ for _h, items in reversed(blocks):
+ while items and total > hi:
+ total -= len(items.pop()["sentence"].split())
+ if lo and total < lo:
+ holes.append("the held passage that answers it comes to %d words; %d to %d were asked" % (total, lo, hi))
+ if not any(items for _h, items in blocks):
+ return None
+ # The test before the saying: the passages chosen must carry what the question asks. They are chosen by shared
+ # words, so a page about something else can win on one stray word ("chains" -> a page on supernovae; "take" -> a
+ # page on film takes). A piece is written only when the chosen sentences carry the question's subject and at least
+ # half of its content terms by weight (rare terms count most); otherwise the hole is said and nothing is written
+ # from pages that are about something else.
+ w = terms if isinstance(terms, dict) else {t: 1.0 for t in terms}
+ said = " ".join(it["sentence"].lower() for _h, items in blocks for it in items if it.get("kind") != "premise")
+ held = [it for _h, items in blocks for it in items if it.get("kind") != "premise"]
+ if held and w:
+ carried = {t for t in w if t in said}
+ share = sum(w[t] for t in carried) / max(1e-9, sum(w.values()))
+ if share < 0.5 or len(carried) < min(2, len(w)) or (anchor and anchor in w and anchor not in said):
+ return None # nothing here carries it: the request's own writer takes it
+ return _finish(blocks, holes, st, obligation, text, sid)
+
+
+# ---------------------------------------------------------------- one rendering, one kept draft
+
+def _drafts_path():
+ import os
+ from pathlib import Path
+ base = Path(os.environ.get("ORACLE7_STATE") or Path.home() / ".oracle7")
+ base.mkdir(parents=True, exist_ok=True)
+ return base / "compose_drafts.json"
+
+
+def load_draft(sid):
+ import json
+ try:
+ return (json.load(open(_drafts_path(), encoding="utf-8")) or {}).get(str(sid))
+ except (OSError, ValueError):
+ return None
+
+
+def save_draft(sid, draft):
+ import json
+ if sid is None:
+ return
+ try:
+ allv = json.load(open(_drafts_path(), encoding="utf-8"))
+ except (OSError, ValueError):
+ allv = {}
+ allv[str(sid)] = draft
+ tmp = _drafts_path().with_suffix(".tmp")
+ json.dump(allv, open(tmp, "w", encoding="utf-8"), ensure_ascii=False)
+ tmp.replace(_drafts_path())
+
+
+def _finish(blocks, holes, st, obligation, text, sid, note=None, path="converse:compose_writing"):
+ lo, hi = obligation.get("words") or (None, None)
+ total = sum(len(it["sentence"].split()) for _h, items in blocks for it in items)
+ if hi and total > hi:
+ for _h, items in reversed(blocks):
+ while len(items) > 1 and total > hi:
+ total -= len(items.pop()["sentence"].split())
+ if lo and total < lo and not any("words" in h for h in holes):
+ holes.append("the held passage that answers it comes to %d words; %d to %d were asked" % (total, lo, hi))
+ if not any(items for _h, items in blocks):
+ return None
+ refs, out, index = [], [], {}
+ numbered = st.get("kind") == "steps"
+ for head, items in blocks:
+ lines = []
+ for k, it in enumerate(items, 1):
+ if it.get("kind") == "deduction":
+ lines.append(it["sentence"] + " (my weighing of the points above, not a held fact)")
+ continue
+ if it["claim"] not in index:
+ index[it["claim"]] = len(index) + 1
+ refs.append("%d. %s (%s)" % (index[it["claim"]], it["title"], it["claim"]))
+ mark = "[%d]" % index[it["claim"]] if it["kind"] == "sourced" else "(your text [%d])" % index[it["claim"]]
+ lines.append(("%d. " % k if numbered else ("- " if head == "Takeaways" else "")) + it["sentence"] + " " + mark)
+ if head:
+ out.append("### " + head)
+ out.append(("\n" if numbered or head == "Takeaways" else " ").join(lines) if lines else "(No held passage bears on this.)")
+ response = "\n\n".join(out) + ("\n\n### Sources\n\n" + "\n".join(refs) if refs else "")
+ if note:
+ response = note + "\n\n" + response
+ if holes:
+ response = ("The held passages do not fill everything asked: " + "; ".join(holes) +
+ ". A source you give me fills the rest of this same request.\n\n") + response
+ save_draft(sid, {"obligation": {k: (sorted(v) if isinstance(v, set) else v) for k, v in obligation.items()},
+ "structure": st, "blocks": [[h, items] for h, items in blocks], "request": text, "holes": holes})
+ return {"status": "answered" if not holes else "hole", "path": path, "response": response,
+ "records": [it["claim"] for _h, items in blocks for it in items if it.get("claim")],
+ "writing": {"holes": holes, "blocks": [[h, [it.get("claim") for it in items]] for h, items in blocks],
+ "structure": st},
+ "execution": {"state": "read" if not holes else "not_run", "takes": ["a source for: " + h for h in holes]}}
+
+
+# ---------------------------------------------------------------- the user's own text
+
+def _centrality(sentences, reader):
+ """how much of the passage's own content each sentence carries (its words shared with the rest of the passage)"""
+ from collections import Counter
+ bags = [_lemmas(x["sentence"], reader) for x in sentences]
+ freq = Counter(w for b in bags for w in b)
+ return [sum(freq[w] - 1 for w in b) / (1 + len(b)) ** 0.5 for b in bags]
+
+
+def _from_supplied(text, reader, obligation, supplied, sid=None):
+ st = obligation["structure"]
+ lo, hi = obligation["words"] or (None, None)
+ holes, blocks = [], []
+ notes = re.findall(r"(?i)\bnote\s+([a-z])\s*:\s*[\"'\u2018\u201c]", text)
+ if re.search(r"(?i)\b(?:compare|recommend)\b", obligation["question"]) and len(obligation["supplied"]) >= 2:
+ # compare the supplied notes side by side, then recommend by the condition the request names
+ for i, passage in enumerate(obligation["supplied"]):
+ name = "Note %s" % (notes[i].upper() if i < len(notes) else chr(65 + i))
+ items = [x for x in supplied if x.get("passage") == i]
+ blocks.append((name, items))
+ rec = _recommend(text, obligation, supplied, reader)
+ if rec:
+ blocks.append(("Recommendation", [rec]))
+ return _finish(blocks, holes, {"kind": "sections"}, obligation, text, sid)
+ scores = _centrality(supplied, reader)
+ ranked = sorted(range(len(supplied)), key=lambda i: -scores[i])
+ chosen, words = [], 0
+ for i in ranked:
+ n = len(supplied[i]["sentence"].split())
+ if hi and words + n > hi:
+ continue
+ chosen.append(i)
+ words += n
+ if lo and words >= lo:
+ break
+ body = [supplied[i] for i in sorted(chosen)]
+ blocks.append(("Abstract" if re.search(r"(?i)\babstract|summar", text) else None, body))
+ if st.get("bullets"):
+ rest = [supplied[i] for i in ranked if i not in chosen][:st["bullets"]]
+ if len(rest) < st["bullets"]:
+ rest += [supplied[i] for i in ranked if supplied[i] not in rest][:st["bullets"] - len(rest)]
+ blocks.append(("Takeaways", rest))
+ if lo and words < lo:
+ holes.append("your text gives %d words of its main points; %d to %d were asked" % (words, lo, hi))
+ return _finish(blocks, holes, {"kind": "paragraphs"}, obligation, text, sid)
+
+
+def _recommend(text, obligation, supplied, reader, condition=None):
+ """the note whose sentences share most with the condition the request names ("someone whose income changes every
+ month"), said as a deduction from the notes, never as a held fact"""
+ m = re.search(r"(?i)\bfor\s+(someone|a person|people|anyone)\s+(.+?)(?:[.?!]|$)", condition or obligation["question"])
+ if not m:
+ return None
+ cond = _lemmas(m.group(2), reader)
+ best, score = None, -1
+ for i, passage in enumerate(obligation["supplied"]):
+ k = len(cond & _lemmas(passage, reader))
+ if k > score:
+ best, score = i, k
+ if best is None:
+ return None
+ letters = re.findall(r"(?i)\bnote\s+([a-z])\s*:", text)
+ name = "note %s" % (letters[best].upper() if best < len(letters) else chr(65 + best))
+ return {"sentence": "For someone %s, the method in %s fits better, since its own words speak to that condition "
+ "(%s)." % (m.group(2).strip(), name, ", ".join(sorted(cond & _lemmas(obligation["supplied"][best], reader))[:4]) or "its terms"),
+ "kind": "deduction", "claim": None, "title": "deduction"}
+
+
+# ---------------------------------------------------------------- arguing a question
+
+def _leans(sentence, reader, part=None):
+ """+1 a held sentence speaks of a gain, -1 of a harm, 0 neither: read from the store's definitions of its words"""
+ good, bad = 0, 0
+ for w in re.findall(r"[a-z]{4,}", sentence.lower()):
+ glosses = " ".join(g for _pos, gs in reader.d.entries(w) for g in gs[:2]).lower() if reader else ""
+ if re.search(r"\b(?:improve|benefit|help|advantage|good|better|increase in (?:health|learning))\b", glosses):
+ good += 1
+ if re.search(r"\b(?:harm|damage|problem|disadvantage|bad|worse|distract|danger|risk)\b", glosses):
+ bad += 1
+ return (good > bad) - (bad > good)
+
+
+def _argument(text, reader, obligation, sid=None):
+ built = _from_pages(text, reader, dict(obligation, structure={"kind": "paragraphs", "count": 1, "sections": [],
+ "steps": None, "bullets": None}), sid=None)
+ draft = load_draft(None) or {}
+ pool = []
+ if built:
+ for _h, items in (built.get("_blocks") or []):
+ pool += items
+ con = _store()
+ terms = _terms(obligation)
+ pages = []
+ if con is not None:
+ ids = titled_pages(con, obligation["question"]) + candidate_pages(con, terms)
+ pages = [p for p in (_page(con, pid) for pid in list(dict.fromkeys(ids))[:6]) if p]
+ found = [x for page in pages for x in page if sum(t in x["sentence"].lower() for t in terms) >= 2]
+ pro = [x for x in found if _leans(x["sentence"], reader) > 0][:3]
+ con_ = [x for x in found if _leans(x["sentence"], reader) < 0][:3]
+ holes = []
+ if not pro:
+ holes.append("no held sentence argues for it")
+ if not con_:
+ holes.append("no held sentence argues against it")
+ side = "for" if len(pro) > len(con_) else "against" if len(con_) > len(pro) else None
+ verdict = ({"sentence": "On the held points above, %d weigh %s and %d %s, so the case %s is the stronger here." % (
+ max(len(pro), len(con_)), side, min(len(pro), len(con_)), "against" if side == "for" else "for", side),
+ "kind": "deduction", "claim": None, "title": "deduction"} if side else
+ {"sentence": "The held points weigh evenly, so they do not settle it either way.", "kind": "deduction",
+ "claim": None, "title": "deduction"})
+ blocks = [("For", pro), ("Against", con_), ("Conclusion", [verdict])]
+ return _finish(blocks, holes, {"kind": "sections"}, obligation, text, sid)
+
+
+# ---------------------------------------------------------------- the entry
+
+REFERS = re.compile(r"(?i)\b(?:your|the|that|this|those|these)\s+(?:(?:first|second|third|fourth|fifth|sixth|last|final|"
+ r"weakest|strongest|next|previous|same|two|three|four)\s+){0,2}(?:paragraph|sentence|step|section|"
+ r"takeaway|draft|piece|abstract|verdict|conclusion|recommendation|example|stage|point|answer)s?\b|"
+ r"\b(?:rewrite|shorten|cut|trim|expand|merge|swap|replace|reorder|move)\s+(?:it|them|that|this)\b")
+
+
+def compose(text, reader, sid=None):
+ """-> a reply dict, or None when nothing held bears on the request"""
+ if sid and REFERS.search(text) and not QUOTED.search(text) and load_draft(sid):
+ # the turn names a part of the piece this conversation keeps (reached here only when no revision operation took
+ # it): it is about that piece. A question is answered from the piece's pages if they carry it; otherwise the
+ # missing operation is said. A new piece is never started from the turn's stray words.
+ answered = follow_up(text, sid, reader) if text.strip().endswith("?") else None
+ return answered or {
+ "status": "hole", "path": "converse:compose_writing:revise",
+ "response": "That is about the piece I wrote, which is kept as it was. I have no operation yet that does "
+ "this to it: \"%s\". What I can do to a kept piece: answer what a part rests on, replace or add "
+ "a section, combine steps, put the answer first, change its size, expand a named part, use a "
+ "source you give, or ask it again for another reader." % text.strip()[:160],
+ "execution": {"state": "not_run"}}
+ obligation = read_request(text, reader)
+ supplied = []
+ for i, passage in enumerate(obligation["supplied"]):
+ for k, x in enumerate(_split(passage)):
+ supplied.append({"sentence": x, "kind": "premise", "passage": i, "ordinal": k, "title": "your text",
+ "claim": "you:" + hashlib.sha256(x.encode()).hexdigest()[:12]})
+ if supplied and (obligation["only_supplied"] or re.search(r"(?i)\b(?:abstract|summar\w*|takeaways?|of this)\b", text)):
+ return _from_supplied(text, reader, obligation, supplied, sid)
+ if [h.lower() for h in obligation["structure"].get("sections") or []] == ["for", "against", "conclusion"]:
+ return _argument(text, reader, obligation, sid)
+ built = _from_pages(text, reader, obligation, sid)
+ # what the question's own words are and do to one another comes first (holon_explain); the held passage follows
+ # Off unless ORACLE7_HOLON_EXPLAIN=1: on questions it was not shaped on, the engine's shallow reading of definitions
+ # states false relations ("A sail boats a boat") marked as definition-sourced (measured 2026-11-17), which the law
+ # does not allow in a reply. It stays a development part until definitions are read by the claim reader.
+ import os
+ if os.environ.get("ORACLE7_HOLON_EXPLAIN") == "1" and re.search(r"(?i)\b(?:explain|why|how|what)\b", obligation["question"]):
+ try:
+ import holon_explain
+ own = holon_explain.explain(obligation["question"], reader)
+ except Exception: # noqa: BLE001
+ own = None
+ if own and own.get("answer"):
+ # the answer is the definitions said whole and what follows from them; what each sentence rests on is kept
+ # beside it (the definition records and the joins), so the reply is offered, never marked answered
+ lead = own["answer"]
+ holon = {"parts": own["parts"], "joins": own["joins"], "basis": own["sentences"]}
+ if built:
+ built = dict(built, response=lead + NL2 + "From held pages:" + NL2 + built["response"], holon=holon)
+ else:
+ built = {"status": "offered", "path": "converse:compose_writing:holon", "response": lead,
+ "holon": holon, "execution": {"state": "read"}}
+ return built
+
+
+# ---------------------------------------------------------------- the kept draft: follow-ups and revisions
+
+def follow_up(text, sid, reader):
+ """A question asked after a piece was written is about that piece's subject first: it is answered from the pages the
+ kept draft was written from (and any page titled with the question's own words), by the passage that carries the
+ question's own terms. The kept draft is left as it is. None when no passage on those pages carries at least two of
+ the question's terms beyond the subject's own name: then the turn goes on to the rest of the head."""
+ draft = load_draft(sid)
+ if not draft or not text.strip().endswith("?"):
+ return None
+ con = _store()
+ if con is None:
+ return None
+ obligation = read_request(text, reader)
+ terms = _terms(obligation)
+ ids = []
+ for _h, items in draft.get("blocks") or []:
+ for it in items:
+ if it.get("page") and it["page"] not in ids:
+ ids.append(it["page"])
+ subject = set()
+ for pid in ids:
+ row = con.execute("select normalized_title from title_alias where page_id = ? limit 1", (pid,)).fetchone()
+ subject |= {_stem(w) for w in re.findall(r"[a-z]{3,}", str(row[0]).lower())} if row else set()
+ ids += [pid for pid in titled_pages(con, obligation["question"]) if pid not in ids]
+ asked = [t for t in terms if t not in subject]
+ if not ids or len(asked) < 2:
+ return None
+ best, best_cover = [], 0
+ for pid in ids[:6]:
+ page = _page(con, pid)
+ if not page:
+ continue
+ window, _score = best_window(page, asked, min(3, len(page)))
+ low = " ".join(x["sentence"].lower() for x in window)
+ cover = len({t for t in asked if t in low})
+ if cover > best_cover:
+ best, best_cover = window, cover
+ if best_cover < 2:
+ return None
+ refs, lines = [], []
+ for k, it in enumerate(best, 1):
+ refs.append("%d. %s (%s)" % (k, it["title"], it["claim"]))
+ lines.append("%s [%d]" % (it["sentence"], k))
+ return {"status": "answered", "path": "converse:compose_writing:follow",
+ "response": "From the pages this piece was written from:" + NL2 + " ".join(lines) + NL2 + "### Sources" + NL2 + NL.join(refs),
+ "records": [it["claim"] for it in best], "execution": {"state": "read"}}
+
+
+def _items(draft):
+ return [it for _h, items in draft["blocks"] for it in items]
+
+
+def _page_of(item):
+ """the held page a kept sentence came from, or None"""
+ if not item.get("page"):
+ return None
+ try:
+ con = _store()
+ return _page(con, item["page"]) if con is not None else None
+ except Exception: # noqa: BLE001
+ return None
+
+
+def _redo(draft, blocks, text, sid, note):
+ ob = dict(draft["obligation"])
+ ob["content"] = set(ob.get("content") or [])
+ lo, hi = ob.get("words") or (None, None)
+ # a revision that leaves the piece shorter than the size it was asked at is continued from its own pages, the same
+ # way the first writing is
+ if lo and sum(_words(items) for _h, items in blocks) < lo:
+ for b in reversed(blocks):
+ if not b[1]:
+ continue
+ page = _page_of(b[1][0])
+ if page:
+ rest = sum(_words(items) for h2, items in blocks if items is not b[1])
+ b[1] = _extend(list(b[1]), [page], lo - rest, (hi - rest) if hi else None)
+ break
+ return _finish(blocks, [], draft.get("structure") or {}, ob, text, sid, note=note, path="converse:compose_writing:revise")
+
+
+def revise(text, sid, reader):
+ """A turn about the kept draft: a question about it is answered from the draft itself (its order, its kinds, its
+ sources); a revision is an operation on it (replace or add a section, combine steps, put the answer first, reshape
+ to a size, recommend under a new condition, replace a takeaway, a simpler source). The rest of the draft and its
+ purpose are kept. None when the turn is not about the draft."""
+ draft = load_draft(sid)
+ if not draft or not draft.get("blocks"):
+ return None
+ low = text.lower().strip()
+ blocks = [[h, list(items)] for h, items in draft["blocks"]]
+ items = _items(draft)
+ # the same request again with one thing changed ("Same, but for a swimming coach"): the kept request is asked again
+ # with the new reader or case in the place of the old one
+ m = re.match(r"(?:the )?same(?: again| thing)?,? but (for|to|about|with|in) (.+?)[.!]?$", low) or \
+ re.match(r"(?:now|again),? (?:do it |the same )?(for|to|about) (.+?)[.!]?$", low)
+ if m and draft.get("request"):
+ prep, new = m.group(1), m.group(2)
+ old = re.search(r"(?i)\b(?:to|for) (?:an? |the )?[a-z][a-z -]{2,30}?(?=,|\.|$| with| using| in )", draft["request"])
+ again = (draft["request"][:old.start()] + "%s %s" % (prep, new) + draft["request"][old.end():]) if old \
+ else draft["request"].rstrip(". ") + " %s %s." % (prep, new)
+ redone = compose(again, reader, sid)
+ if redone:
+ return dict(redone, response="The same request, now %s %s:" % (prep, new) + NL2 + str(redone.get("response", "")),
+ path="converse:compose_writing:revise")
+ # more about one named part ("Explain step 2 in more detail", "expand the second paragraph"): that part is
+ # continued from its own page; the rest is kept
+ ORD = {"first": 1, "second": 2, "third": 3, "fourth": 4, "fifth": 5, "sixth": 6, "seventh": 7, "eighth": 8, "ninth": 9,
+ "last": -1}
+ m = re.search(r"\b(?:step|paragraph|section|point|takeaway)\s+(\d+)\b", low) or \
+ re.search(r"\bthe (%s) (?:step|paragraph|section|point|takeaway)\b" % "|".join(ORD), low)
+ if m and re.search(r"\b(?:more|detail\w*|expand|elaborat\w*|longer|further|unpack)\b", low):
+ k = int(m.group(1)) if m.group(1).isdigit() else ORD[m.group(1)]
+ numbered = (draft.get("structure") or {}).get("kind") == "steps"
+ unit = items if numbered else [x for b in blocks for x in b[1][:1]] # a step is a sentence; else a block's lead
+ target = unit[k - 1] if 0 < k <= len(unit) else (unit[-1] if k == -1 and unit else None)
+ page = _page_of(target) if target else None
+ if target and page:
+ more = _extend([target], [page], _words([target]) + 60, _words([target]) + 140)
+ if len(more) > 1:
+ refs = ["%d. %s (%s)" % (i, it["title"], it["claim"]) for i, it in enumerate(more, 1)]
+ body = " ".join("%s [%d]" % (it["sentence"], i) for i, it in enumerate(more, 1))
+ return {"status": "answered", "path": "converse:compose_writing:revise",
+ "response": "More on that part, from the page it came from (the piece itself is kept as it was):" + NL2 +
+ body + NL2 + "### Sources" + NL2 + NL.join(refs),
+ "records": [it["claim"] for it in more], "execution": {"state": "read"}}
+ # a source the user adds fills the kept draft where its words bear, attributed to them
+ quoted = [m.group(1).strip() for m in QUOTED.finditer(text)]
+ if quoted and re.search(r"(?i)\b(?:use|from|here'?s|source|panel|survey|this)\b", text):
+ added = [{"sentence": x, "kind": "premise", "title": "your text", "ordinal": k,
+ "claim": "you:" + hashlib.sha256(x.encode()).hexdigest()[:12]}
+ for k, x in enumerate(s2 for q in quoted for s2 in _split(q))]
+ words = set().union(*(_lemmas(a["sentence"], reader) for a in added))
+ at = max(range(len(blocks)), key=lambda i: len(words & set().union(set(), *(_lemmas(x["sentence"], reader)
+ for x in blocks[i][1]))))
+ blocks[at][1] = blocks[at][1] + added
+ return _redo(draft, blocks, text, sid, "Your source is used where it bears, marked as yours; the rest is kept.")
+ # questions about the draft
+ m = re.search(r"\bwhy did you (?:put|explain|start with|begin with|write)\s+(?:the\s+)?(.+?)\s+before\s+(?:the\s+)?(.+?)[?.!]*$", low)
+ if m:
+ first = next((i for i, it in enumerate(items) if any(w in it["sentence"].lower() for w in m.group(1).split()[-2:])), None)
+ second = next((i for i, it in enumerate(items) if any(w in it["sentence"].lower() for w in m.group(2).split()[-2:])), None)
+ where = items[first]["title"] if first is not None else "its source"
+ if first is not None and (second is None or first < second):
+ say = ("I kept the order of the held passage I drew it from (%s): there, what you name first comes earlier, "
+ "and I said nothing between them that the passage does not say." % where)
+ else:
+ say = "In the draft I gave, that is not the order: the passage I drew from (%s) has them the other way." % where
+ return {"status": "answered", "path": "converse:compose_writing:about", "response": say,
+ "execution": {"state": "read"}}
+ if re.search(r"\b(?:least certain|weakest|record or reasoning|leans hardest|which (?:claim|sentence|takeaway))\b", low):
+ kinds = {"sourced": "a held record I cite", "premise": "your own text", "deduction": "my weighing, not a held fact"}
+ lines = ["- %s ... : %s%s" % (it["sentence"][:70], kinds.get(it["kind"], it["kind"]),
+ " (%s)" % it["title"] if it["kind"] == "sourced" else "") for it in items[:8]]
+ target = next((it for it in items if it["kind"] == "deduction"), None) or (items[-1] if items else None)
+ lead = ("The least settled part is the one that is my own weighing: \"%s\"." % target["sentence"][:120]
+ if target and target["kind"] == "deduction" else
+ "Every sentence is a held record or your own text; the one resting on the fewest of the question's words "
+ "is the last: \"%s\"." % (target["sentence"][:120] if target else ""))
+ return {"status": "answered", "path": "converse:compose_writing:about", "response": lead + "\n\nWhat each part rests on:\n" + "\n".join(lines),
+ "execution": {"state": "read"}}
+ # revisions
+ m = re.search(r"\bcombine the first (two|three|2|3) steps\b", low)
+ if m and draft.get("structure", {}).get("kind") == "steps":
+ n = {"two": 2, "three": 3}.get(m.group(1), int(m.group(1)) if m.group(1).isdigit() else 2)
+ steps = blocks[0][1]
+ merged = dict(steps[0], sentence=" ".join(x["sentence"] for x in steps[:n]))
+ blocks[0][1] = [merged] + steps[n:]
+ return _redo(draft, blocks, text, sid, "The first %d steps combined; the order and the rest are kept." % n)
+ m = re.search(r"\b(?:replace|swap) the (\w+)(?: section)? (?:with|for) (?:a section on |one about |a section about )?(.+?)[.!]?$", low)
+ if m:
+ old, topic = m.group(1), m.group(2)
+ con = _store()
+ new_items = []
+ if con is not None:
+ q = draft["obligation"].get("question", "") + " " + topic
+ terms = _terms({"question": q})
+ pages = [p for p in (_page(con, pid) for pid in titled_pages(con, q) + candidate_pages(con, terms)) if p][:4]
+ for page in pages:
+ window, score = best_window(page, terms, 3, need=[_stem(w) for w in re.findall(r"[a-z]{4,}", topic)] or None)
+ if window and score > 0:
+ new_items = window
+ break
+ for b in blocks:
+ if b[0] and old in b[0].lower():
+ b[0], b[1] = topic[:1].upper() + topic[1:], new_items
+ return _redo(draft, blocks, text, sid, "The %s section is replaced; the others are as they were." % old)
+ for b in blocks: # a takeaway or paragraph named by its place
+ if b[0] == "Takeaways" and b[1]:
+ pool = [x for x in _items(draft)] + [x for p in [] for x in p]
+ b[1][-1] = next((x for x in new_items), b[1][-1])
+ return _redo(draft, blocks, text, sid, "The weakest takeaway is replaced; the other two are unchanged.")
+ m = re.search(r"\badd (?:a )?(?:short )?(?:\w+ )?(?:paragraph|section) on (.+?)(?:;|,|\.|$)", low)
+ if m:
+ topic = m.group(1)
+ con = _store()
+ new_items = []
+ if con is not None:
+ q = draft["obligation"].get("question", "") + " " + topic
+ terms = _terms({"question": q})
+ for page in [p for p in (_page(con, pid) for pid in titled_pages(con, q) + candidate_pages(con, terms)) if p][:4]:
+ window, score = best_window(page, terms, 3, need=[_stem(w) for w in re.findall(r"[a-z]{4,}", topic)] or None)
+ if window and score > 0:
+ new_items = window
+ break
+ if "before the conclusion" in low:
+ at = next((i for i, b in enumerate(blocks) if (b[0] or "").lower() == "conclusion"), len(blocks))
+ blocks.insert(at, ["Counter-argument" if "counter" in low else topic.title(), new_items])
+ else:
+ blocks.append([topic[:1].upper() + topic[1:] if draft.get("structure", {}).get("kind") == "sections" else None, new_items])
+ return _redo(draft, blocks, text, sid, "Added; everything before it is unchanged.")
+ if re.search(r"\bmake the first sentence the answer\b", low):
+ q = re.sub(r"(?i)^.*?answer to\s+", "", text)
+ words = _lemmas(q, reader)
+ flat = _items(draft)
+ best = max(flat, key=lambda it: len(words & _lemmas(it["sentence"], reader))) if flat else None
+ if best:
+ for b in blocks:
+ if best in b[1]:
+ b[1].remove(best)
+ blocks[0][1].insert(0, best)
+ return _redo(draft, blocks, text, sid, "The sentence that answers it now comes first; the rest is kept.")
+ m = re.search(r"\bone paragraph of (?:about |around )?(\d+) words\b", low)
+ if m:
+ n = int(m.group(1))
+ flat = [it for it in _items(draft) if it.get("kind") != "deduction"]
+ keep, words = [], 0
+ for it in flat:
+ if words >= n * 0.9:
+ break
+ keep.append(it)
+ words += len(it["sentence"].split())
+ ob = dict(draft["obligation"], words=[int(n * 0.8), int(n * 1.2)])
+ draft2 = dict(draft, obligation=ob, structure={"kind": "paragraphs"})
+ return _redo(draft2, [[None, keep]], text, sid, "One paragraph; the cause and the order are kept.")
+ m = re.search(r"\bnow recommend for (.+?)[.!]?$", low)
+ if m and draft["obligation"].get("supplied"):
+ ob = dict(draft["obligation"])
+ rec = _recommend(text, ob, [], reader, condition="for " + m.group(1))
+ if rec:
+ for b in blocks:
+ if (b[0] or "").lower() == "recommendation":
+ b[1] = [rec]
+ return _redo(draft, blocks, text, sid, "The same comparison; the recommendation is made for the new case.")
+ if re.search(r"\b(?:rewrite|explain|say it)\b.*\bfor (?:a |an )?(?:\w+[- ]year[- ]old|child|kids?|beginner)", low):
+ # a younger reader: the same subject from the plainer held source (Simple English pages), same structure
+ con = _store()
+ if con is not None:
+ q = draft["obligation"].get("question", "")
+ terms = _terms({"question": q})
+ simple = [p for p in (_page(con, pid) for pid in titled_pages(con, q) + candidate_pages(con, terms)) if p
+ and str(p[0].get("page", "")).startswith("sw")]
+ if simple:
+ n = max(1, len([1 for b in blocks if b[1]]))
+ window, _score = best_window(simple[0], terms, max(3, len(items)))
+ per = max(1, -(-len(window) // n))
+ new_blocks = [[b[0], window[i * per:(i + 1) * per]] for i, b in enumerate(blocks)]
+ return _redo(draft, new_blocks, text, sid, "The same explanation from the plainer source (Simple English "
+ "Wikipedia), in the same number of paragraphs.")
+ return None
diff --git a/workbench/converse/context_record.py b/workbench/converse/context_record.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc6bee87ad5c638478ee1186f03e76c450ef601c
--- /dev/null
+++ b/workbench/converse/context_record.py
@@ -0,0 +1,48 @@
+"""Recover received context and complete open requests from the delivered ledger.
+
+This part reads records. It never invokes a work part or replays an effect.
+"""
+import hashlib
+import time
+
+
+def entries(sid, limit=12):
+ import reflect
+ return list(reflect.load(sid).get('ledger') or [])[-limit:]
+
+
+def open_requests(sid):
+ import reflect
+ return [item['original'] for item in reflect.load(sid).get('open_requests', [])
+ if item.get('state') == 'open']
+
+
+def record(text, sid, reply, reading=None):
+ """Keep unfinished instructions whole; retire only exact checked obligations."""
+ import reflect
+ state = reflect.load(sid)
+ obligations = state.setdefault('open_requests', [])
+ execution = reply.get('execution') or {}
+ performed = execution.get('state') in ('checked', 'changed-checked', 'sent', 'done') and not execution.get('holes')
+ completed = {r.get('text') for r in execution.get('requirements', [])
+ if r.get('status') in ('passed', 'met')}
+ if performed:
+ completed.add(text)
+ for item in obligations:
+ if item['original'] in completed:
+ item.update(state='done', completed=time.time(), receipt=reply.get('path'))
+ asks_work = bool(reply.get('_open_request') or (reading or {}).get('outcomes'))
+ # A checked conversational answer or a writer's own durable obligation
+ # belongs to its owner, not to this record of otherwise unperformed work.
+ pending = asks_work and not performed and not reply.get('writing') and reply.get('status') != 'answered'
+ if pending:
+ identity = hashlib.sha256((sid + '\0' + text).encode('utf-8')).hexdigest()[:24]
+ item = next((x for x in obligations if x['id'] == identity), None)
+ if item is None:
+ item = {'id': identity, 'original': text, 'created': time.time(), 'state': 'open'}
+ obligations.append(item)
+ item.update(last_seen=time.time(), path=reply.get('path'), missing=execution.get('holes') or [],
+ reading=reading, state='open')
+ reflect.save(sid, state)
+ reply.pop('_open_request', None)
+ return reply
diff --git a/workbench/converse/conv_mover.py b/workbench/converse/conv_mover.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0979935ded43aaaee51d547afb0e1f292dede43
--- /dev/null
+++ b/workbench/converse/conv_mover.py
@@ -0,0 +1,366 @@
+#!/usr/bin/env python3
+"""THE MOVER: the role's next move in a scene, learned from the corpus, with no hand-written keys.
+
+Ben, 2026-11-07: "we have everything we need". The corpus (DailyDialog train, 11,118 dialogues) holds, for every user turn,
+the move the role actually made next. The mover indexes every (what the role just said, what the user said before, what the
+user says now -> the role's next question) and, for a new turn, takes the nearest corpus turns and lets them vote on the move's
+kind (wh, slot). Nothing here is set by hand: the weights of the three context fields, k, and the vote rule are READ OFF a
+held-out slice of train (dialogues i % 10 == 0 are left out of the index and made into tests); validation is measured after.
+
+ build --out moves.json [--hold 10 0] [--cfg '{...}'] train split ONLY (validation = the test set;
+ test is never read). --hold M R leaves the
+ dialogues i % M == R out (the dev slice).
+ sweep --moves moves_dev.json grid over the config; the best is written
+ INTO the moves file as "cfg" (and printed)
+ eval [--moves moves.json] pass by step, pass by similarity bin, the
+ random-move baseline, and the tau read-off
+ judge --out moves_scenes.json the index in the judge's scene format
+"""
+import collections
+import json
+import math
+import os
+import random
+import re
+import sys
+
+WORD = re.compile(r"[a-z][a-z'\-]+")
+STOP = set("the a an and or but of to in on at for with from by as is are was were be been being am do does did have has had "
+ "it its this that these those i you he she we they me him her us them my your his our their mine yours not no yes so "
+ "if then than too very just can could will would shall should may might must about into over up down out off here "
+ "there what which who whom whose when where why how all any some more most much many few one two first last also".split())
+MOVES = os.environ.get("ORACLE7_MOVES", "/opt/o7conv/moves.json")
+DEFAULT_CFG = {"k": 5, "w_prev": 0.2, "w_role": 0.0, "vote": "kind", "use_nb": 0, "lam": 0.0, "w_cont": 0.0}
+POOL = 20 # neighbours pooled for the elicitation evidence (what similar users went on to say)
+
+
+def feats(turn, prev=None, role_prev=None):
+ return words(turn) + ["r:" + w for w in words(role_prev)] + ["p:" + w for w in words(prev)]
+
+
+def words(text):
+ return [w for w in WORD.findall((text or "").lower()) if w not in STOP and len(w) > 2]
+
+
+def clean(u):
+ return re.sub(r"\s+", " ", re.sub(r"\s+([.,?!'])", r"\1", u.strip()))
+
+
+class Mover:
+ def __init__(self, path=MOVES, cfg=None):
+ d = json.load(open(path))
+ self.entries = d["entries"]
+ self.idf = d["idf"]
+ self.cfg = dict(DEFAULT_CFG, **(d.get("cfg") or {}), **(cfg or {}))
+ self.tau = float(d.get("tau") or 0.45) # read off the dev eval (the lowest similarity bin that beats a random move)
+ self.nb = d.get("nb") # the yes/no-vs-wh class model, counted off train
+ self.inv = collections.defaultdict(list) # ctx word -> entries
+ self.rinv = collections.defaultdict(list) # role-prev word -> entries
+ self.norm, self.rnorm = [], []
+ for i, e in enumerate(self.entries):
+ c = collections.Counter(e["ctx"])
+ self.norm.append(math.sqrt(sum((self.idf.get(w, 0) * k) ** 2 for w, k in c.items())) or 1.0)
+ for w in c:
+ self.inv[w].append(i)
+ r = collections.Counter(e.get("role") or [])
+ self.rnorm.append(math.sqrt(sum((self.idf.get(w, 0) * k) ** 2 for w, k in r.items())) or 1.0)
+ for w in r:
+ self.rinv[w].append(i)
+
+ def _cos(self, q, qn, inv, field, norms, acc):
+ for w, c in q.items():
+ iw = self.idf.get(w, 0)
+ if iw <= 0:
+ continue
+ for i in inv.get(w, ()):
+ acc[i] += iw * c * iw * (self.entries[i].get(field) or []).count(w) / (qn * norms[i])
+
+ def scored(self, turn, prev=None, role_prev=None, cfg=None, exclude=None, last=None):
+ """every candidate entry with its similarity: (1 - wp - wr) * cos(ctx) + wp * jaccard(prev) + wr * cos(role)
+ (+ w_cont when the entry is the NEXT step of the dialogue the last played move came from: scene continuity)"""
+ cfg = cfg or self.cfg
+ wp, wr = cfg["w_prev"], cfg["w_role"]
+ wc = cfg.get("w_cont", 0.0)
+ q = collections.Counter(words(turn))
+ if not q:
+ return []
+ qn = math.sqrt(sum((self.idf.get(w, 0) * c) ** 2 for w, c in q.items())) or 1.0
+ acc = collections.defaultdict(float)
+ self._cos(q, qn, self.inv, "ctx", self.norm, acc)
+ for i in list(acc):
+ acc[i] *= (1.0 - wp - wr)
+ if wr > 0 and role_prev:
+ r = collections.Counter(words(role_prev))
+ rn = math.sqrt(sum((self.idf.get(w, 0) * c) ** 2 for w, c in r.items())) or 1.0
+ racc = collections.defaultdict(float)
+ self._cos(r, rn, self.rinv, "role", self.rnorm, racc)
+ for i, s in racc.items():
+ acc[i] += wr * s
+ pw = set(words(prev)) if (wp > 0 and prev) else set()
+ out = []
+ for i, s in acc.items():
+ e = self.entries[i]
+ if exclude and e["dlg"] == exclude:
+ continue
+ if pw and e.get("prev"):
+ ep = set(e["prev"])
+ s += wp * len(pw & ep) / max(1, len(pw | ep))
+ if wc > 0 and last and e["dlg"] == last[0] and e["step"] == last[1] + 1:
+ s += wc
+ out.append((s, i))
+ out.sort(reverse=True)
+ return out
+
+ def classify(self, turn, prev=None, role_prev=None):
+ """yes/no or wh: multinomial naive Bayes over the turn, the role's previous turn and the user's previous turn"""
+ nb = self.nb
+ if not nb:
+ return None
+ lo = math.log((nb["n_yn"] + 1.0) / (nb["n_wh"] + 1.0))
+ vy, vw = nb["t_yn"] + nb["v"], nb["t_wh"] + nb["v"]
+ for f in feats(turn, prev, role_prev):
+ lo += math.log((nb["yn"].get(f, 0) + 1.0) / vy) - math.log((nb["wh"].get(f, 0) + 1.0) / vw)
+ return "yes/no" if lo > 0 else "wh"
+
+ def vote(self, scored, cfg=None, turn="", prev=None, role_prev=None):
+ cfg = cfg or self.cfg
+ if not scored:
+ return None
+ pool = scored[:max(POOL, cfg["k"])]
+ tw = {w[:5] for w in words(turn)}
+ # the elicitation evidence: what the users of the pooled neighbours went on to say (weighted by similarity)
+ said = collections.defaultdict(float)
+ if cfg["lam"] > 0:
+ for sim, i in pool:
+ for w in self.entries[i].get("next") or []:
+ if len(w) > 3 and w[:5] not in tw:
+ said[w[:5]] += sim
+ tot = sum(said.values()) or 1.0
+ cand = pool
+ if cfg["use_nb"]:
+ cls = self.classify(turn, prev, role_prev)
+ same = [(s, i) for s, i in pool if (self.entries[i]["wh"] == "yes/no") == (cls == "yes/no")]
+ cand = same or pool
+ top = []
+ for sim, i in cand[:cfg["k"]]:
+ e = self.entries[i]
+ el = sum(said.get(w[:5], 0.0) for w in set(words(e["text"])) if len(w) > 3 and w[:5] not in tw) / tot if cfg["lam"] > 0 else 0.0
+ top.append((sim + cfg["lam"] * el, sim, i))
+ top.sort(reverse=True)
+ if cfg["vote"] == "top1":
+ return self.entries[top[0][2]], float(top[0][1])
+ key = (lambda e: (e["wh"], e["slot"])) if cfg["vote"] == "kind" else (lambda e: e["wh"])
+ votes = collections.defaultdict(float)
+ for sc, sim, i in top:
+ votes[key(self.entries[i])] += sc
+ kind = max(votes.items(), key=lambda kv: kv[1])[0]
+ for sc, sim, i in top:
+ e = self.entries[i]
+ if key(e) == kind:
+ return e, float(sim)
+ return None
+
+ def query(self, turn, prev=None, role_prev=None, k=None, exclude=None, last=None, cfg=None):
+ """-> (entry, similarity) of the winning move, or None. last = (dlg, step) of the move played before (continuity)."""
+ cfg = dict(cfg or self.cfg, k=k) if k else (cfg or self.cfg)
+ return self.vote(self.scored(turn, prev, role_prev, cfg, exclude, last), cfg, turn, prev, role_prev)
+
+ def chain(self, it, cfg=None):
+ """replay the test's earlier exchanges through the mover to find where continuity would stand: -> last (dlg, step)"""
+ cfg = cfg or self.cfg
+ if cfg.get("w_cont", 0.0) <= 0:
+ return None
+ hist, rh = it.get("history") or [], it.get("role_history") or []
+ last = None
+ for i, h in enumerate(hist):
+ hit = self.query(h, hist[i - 1] if i else None, rh[i - 1] if i else None, exclude=it.get("scene"), last=last, cfg=cfg)
+ last = (hit[0]["dlg"], hit[0]["step"]) if hit else None
+ return last
+
+
+def build(src, out, hold=None, cfg=None, tau=None):
+ sys.path[:0] = ["/opt/o7conv"]
+ from scene_miner import slot # noqa: E402
+ from turn_reader import Dict, open_dict # noqa: E402
+ d = Dict(open_dict())
+ dd = json.load(open(src))
+ entries = []
+ for i, r in enumerate(dd["train"]):
+ if hold and i % hold[0] == hold[1]:
+ continue
+ u, a = r["utterances"], r["acts"]
+ for j in range(0, len(u) - 1, 2):
+ move = clean(u[j + 1])
+ if not (a[j + 1] == 2 or "?" in move):
+ continue
+ wh, sl = slot(move, d)
+ if not wh:
+ continue
+ sents = [x for x in re.split(r"(?<=[.!?])\s+", move) if x.strip()]
+ qs = [x for x in sents if "?" in x]
+ text = " ".join(qs[:2]) if qs else sents[-1]
+ if len(text.split()) > 28:
+ continue
+ ctx = words(u[j])
+ if not ctx:
+ continue
+ entries.append({"id": "m%d_%d" % (i, j), "dlg": "t%d" % i, "step": j // 2, "ctx": ctx,
+ "prev": words(u[j - 2]) if j >= 2 else [], "role": words(u[j - 1]) if j >= 1 else [],
+ "next": words(u[j + 2]) if j + 2 < len(u) else [], "text": text, "wh": wh, "slot": sl})
+ n = len(entries)
+ # the class model: yes/no vs wh, counted off the same entries (features: turn words, r: role-prev words, p: user-prev words)
+ cy, cw = collections.Counter(), collections.Counter()
+ ny = nw = 0
+ for e in entries:
+ fs = e["ctx"] + ["r:" + w for w in e["role"]] + ["p:" + w for w in e["prev"]]
+ if e["wh"] == "yes/no":
+ cy.update(fs); ny += 1
+ else:
+ cw.update(fs); nw += 1
+ nb = {"yn": {f: c for f, c in cy.items() if c >= 2}, "wh": {f: c for f, c in cw.items() if c >= 2}, "n_yn": ny, "n_wh": nw,
+ "t_yn": sum(cy.values()), "t_wh": sum(cw.values()), "v": len(set(cy) | set(cw))}
+ df = collections.Counter(w for e in entries for w in set(e["ctx"]) | set(e["role"]))
+ idf = {w: math.log(n / k) for w, k in df.items() if k / n < 0.05}
+ json.dump({"entries": entries, "idf": idf, "cfg": cfg or {}, "hold": hold, "tau": tau, "nb": nb}, open(out, "w"), ensure_ascii=False)
+ print("moves", n, "dialogues", len({e["dlg"] for e in entries}), "with slot", sum(1 for e in entries if e["slot"]),
+ "idf words", len(idf), "held out", hold, "cfg", cfg, "->", out)
+
+
+def to_scenes(path, out):
+ d = json.load(open(path))
+ idf = d["idf"]
+ sc = []
+ for e in d["entries"]:
+ key = sorted(set(e["ctx"]), key=lambda w: -idf.get(w, 0))[:8]
+ sc.append({"id": e["id"], "key": key, "opener": " ".join(e["ctx"]), "moves": [{"act": "question", "text": e["text"], "wh": e["wh"], "slot": e["slot"]}]})
+ json.dump(sc, open(out, "w"), ensure_ascii=False)
+ print("scenes for the judge", len(sc), "->", out)
+
+
+def _truth():
+ sys.path[:0] = ["/opt/o7conv"]
+ from conv_propagate import truth # noqa: E402
+ return truth
+
+
+def _ctx(it):
+ hist, rh = it.get("history") or [], it.get("role_history") or []
+ return it["turn"], (hist[-1] if hist else None), (rh[-1] if rh else None)
+
+
+def sweep_cont(tests, path):
+ """the continuity weight alone, around the stored config (a second, smaller grid; stated in PREREG amendment 7)"""
+ truth = _truth()
+ m = Mover(path)
+ items = json.load(open(tests))
+ table = []
+ for wc in (0.0, 0.1, 0.2, 0.4, 0.8):
+ cfg = dict(m.cfg, w_cont=wc)
+ p = 0
+ for it in items:
+ hit = m.query(*_ctx(it), exclude=it.get("scene"), last=m.chain(it, cfg), cfg=cfg)
+ if hit and truth(it, hit[0]["text"]) == "pass":
+ p += 1
+ table.append((p / max(1, len(items)), cfg))
+ print(" w_cont %.1f: %.3f" % (wc, table[-1][0]))
+ table.sort(key=lambda x: (-round(x[0] * 100), x[1]["w_cont"], -x[0]))
+ d = json.load(open(path))
+ d["cfg"] = table[0][1]
+ json.dump(d, open(path, "w"), ensure_ascii=False)
+ print("cfg written to", path, d["cfg"])
+
+
+def sweep(tests, path):
+ """grid over the config on the DEV slice; writes the best into the moves file. Nothing is chosen by hand."""
+ truth = _truth()
+ m = Mover(path)
+ items = json.load(open(tests))
+ grid_w = [(wp, wr) for wp in (0.0, 0.1, 0.2, 0.3) for wr in (0.0, 0.15, 0.3, 0.45) if wp + wr < 1.0]
+ ks, votes = (1, 3, 5, 10, 20), ("kind", "wh", "top1")
+ table = []
+ for wp, wr in grid_w:
+ cfg0 = {"w_prev": wp, "w_role": wr}
+ sc = [m.scored(*_ctx(it), cfg=dict(DEFAULT_CFG, **cfg0), exclude=it.get("scene")) for it in items]
+ for k in ks:
+ for v in votes:
+ for nb in (0, 1):
+ for lam in (0.0, 0.5, 1.0, 2.0):
+ cfg = dict(DEFAULT_CFG, k=k, vote=v, use_nb=nb, lam=lam, **cfg0)
+ p = 0
+ for it, s in zip(items, sc):
+ hit = m.vote(s, cfg, *_ctx(it))
+ if hit and truth(it, hit[0]["text"]) == "pass":
+ p += 1
+ table.append((p / max(1, len(items)), cfg))
+ # ties within one point go to the simplest config (fewest parts switched on); stated in PREREG amendment 7
+ simple = lambda c: (c["use_nb"] != 0) + (c["lam"] != 0) + (c["w_role"] != 0) + (c["w_prev"] != 0) + (c["vote"] != "top1")
+ table.sort(key=lambda x: (-round(x[0] * 100), simple(x[1]), -x[0]))
+ print("SWEEP n %d configs %d" % (len(items), len(table)))
+ for r, cfg in table[:10]:
+ print(" %.3f %s" % (r, json.dumps(cfg)))
+ print(" ... worst %.3f %s" % (table[-1][0], json.dumps(table[-1][1])))
+ base = next(r for r, c in table if c == DEFAULT_CFG)
+ print(" default %.3f -> best %.3f" % (base, table[0][0]))
+ d = json.load(open(path))
+ d["cfg"] = table[0][1]
+ json.dump(d, open(path, "w"), ensure_ascii=False)
+ print("cfg written to", path, d["cfg"])
+ return table[0][1]
+
+
+def evaluate(tests, path=MOVES):
+ truth = _truth()
+ m = Mover(path)
+ items = json.load(open(tests))
+ rng = random.Random(1)
+ rows, by, base = [], collections.Counter(), 0
+ for it in items:
+ hit = m.query(*_ctx(it), exclude=it.get("scene"), last=m.chain(it))
+ sl = (it.get("expected_slot") or "").lower()
+ if not hit:
+ tr, sim = "no_move", 0.0
+ else:
+ e, sim = hit
+ tr = truth(it, e["text"])
+ rnd = m.entries[rng.randrange(len(m.entries))]
+ base += truth(it, rnd["text"]) == "pass"
+ rows.append((it.get("step"), tr, sim, it["turn"][:80], it.get("expected_wh"), sl, hit[0]["text"][:80] if hit else None))
+ by[(it.get("step"), tr)] += 1
+ n = len(rows)
+ p = sum(1 for r in rows if r[1] == "pass")
+ print("MOVER cfg", json.dumps(m.cfg), "n %d pass %d (%.1f%%) random-move baseline %.1f%%" % (n, p, 100.0 * p / max(1, n), 100.0 * base / max(1, n)))
+ for st in sorted({r[0] for r in rows}):
+ s = [r for r in rows if r[0] == st]
+ print(" step %s: n %d pass %.1f%% %s" % (st, len(s), 100.0 * sum(1 for r in s if r[1] == "pass") / len(s),
+ dict(collections.Counter(r[1] for r in s))))
+ # the tau read-off: the lowest bin whose pass rate still beats the random-move baseline
+ edges = (0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 1.01)
+ tau = None
+ for lo, hi in zip(edges, edges[1:]):
+ s = [r for r in rows if lo <= r[2] < hi]
+ if s:
+ pr = 100.0 * sum(1 for r in s if r[1] == "pass") / len(s)
+ print(" sim [%.1f,%.1f): n %d pass %.1f%%" % (lo, hi, len(s), pr))
+ if tau is None and pr > 100.0 * base / max(1, n) * 1.5 and len(s) >= 10:
+ tau = lo
+ print(" TAU read-off (lowest bin > 1.5x random, n>=10): %s" % tau)
+ for r in rows[:10]:
+ print(" ", r[0], r[1], "%.2f" % r[2], "|", r[3], "| want", r[4], r[5], "| got", r[6])
+
+
+if __name__ == "__main__":
+ a = sys.argv[1:]
+ out = a[a.index("--out") + 1] if "--out" in a else None
+ mv = a[a.index("--moves") + 1] if "--moves" in a else MOVES
+ if a[0] == "build":
+ hold = (int(a[a.index("--hold") + 1]), int(a[a.index("--hold") + 2])) if "--hold" in a else None
+ cfg = json.loads(a[a.index("--cfg") + 1]) if "--cfg" in a else None
+ build(a[1], out or MOVES, hold, cfg, float(a[a.index("--tau") + 1]) if "--tau" in a else None)
+ elif a[0] == "sweep":
+ sweep(a[1], mv)
+ elif a[0] == "sweep_cont":
+ sweep_cont(a[1], mv)
+ elif a[0] == "eval":
+ evaluate(a[1], mv)
+ elif a[0] == "judge":
+ to_scenes(a[1], out or "/opt/o7conv/moves_scenes.json")
diff --git a/workbench/converse/data/accord/accord.json b/workbench/converse/data/accord/accord.json
new file mode 100644
index 0000000000000000000000000000000000000000..bf81a32de6205ba21049ce951e0b353d7ce3b54c
--- /dev/null
+++ b/workbench/converse/data/accord/accord.json
@@ -0,0 +1 @@
+{"N": 80080, "nturn": 61029, "forms": {"show me the fastest way to get there .": [3, 3], "okay then .": [3, 3], "you're right !": [5, 5], "do you have an appointment ?": [5, 5], "oh , really .": [3, 3], "four .": [3, 3], "great , thanks .": [4, 4], "i don't so .": [4, 4], "that's good .": [39, 39], "that would be nice .": [5, 5], "do you know where that is ?": [4, 4], "but i .": [4, 4], "oh , all right .": [3, 3], "that sounds like a good idea .": [6, 6], "so long .": [3, 3], "what of would you ?": [3, 3], "thank you , dad .": [3, 3], "it was great .": [4, 4], "that's a great idea .": [10, 10], "is it far ?": [4, 4], "white .": [8, 8], "i'm afraid .": [4, 4], "ha , ha , ha !": [3, 3], "take your time .": [4, 4], "working .": [3, 3], "nice to meet you , .": [9, 9], "too bad .": [3, 3], "wow .": [32, 31], "that sounds ok .": [3, 3], "oh , i'm so sorry .": [3, 3], "i'm terribly sorry .": [3, 3], "what do you with ?": [3, 3], "do you have any other questions ?": [6, 6], "you're kidding !": [10, 10], "that is true .": [5, 5], "who won ?": [3, 3], "look at this one .": [3, 3], "may i have your name , please ?": [10, 10], "oh !": [40, 39], "thanks for telling me .": [3, 3], "what happened ?": [57, 57], "are you ready ?": [3, 3], "you're lucky .": [5, 5], "i so .": [10, 10], "you are right .": [23, 23], "how can you be so sure ?": [3, 3], "that will be all .": [4, 4], "what do you ?": [6, 6], "no , it isn't .": [7, 7], "i get it .": [5, 5], "i .": [9, 9], "absolutely not !": [6, 5], "no problem .": [161, 158], "fine !": [17, 17], "it's very nice of you .": [3, 3], "i'm not surprised .": [4, 4], "here's my .": [5, 4], "oh , is that right ?": [3, 3], "are you crazy ?": [7, 7], "bye .": [35, 33], "yes , i know .": [17, 16], "hold the line , please .": [3, 3], "you're kidding .": [6, 6], "will that be all ?": [5, 5], "hi !": [5, 5], "thank you , sir .": [16, 15], "oh , i don't know .": [6, 5], "well , that's fine .": [3, 3], "yes , she does .": [3, 3], "i like .": [4, 4], "that's perfect .": [7, 7], "i don't like it .": [3, 3], "oh , i see it .": [3, 3], "wait .": [5, 5], "yes , there is .": [7, 7], "how much is this going to cost ?": [3, 3], "wilson .": [7, 7], "correct !": [3, 3], "thank you for saying that .": [5, 5], "how much do they cost ?": [3, 3], "how about these ?": [3, 3], "it's okay .": [4, 4], "i haven't decided yet .": [5, 5], "hello .": [3, 3], "i've got it .": [6, 6], "i won't do it again .": [3, 3], "i'm really sorry .": [6, 6], "i'm so sorry to hear that .": [3, 3], "is that ok ?": [5, 5], "why not ?": [89, 89], "oh , i .": [20, 19], "so what about you ?": [3, 3], "which one do you recommend ?": [3, 3], "absolutely .": [35, 34], "i'm pretty good .": [3, 3], "what do you do there ?": [5, 5], "how do you know ?": [5, 5], "i wonder why .": [3, 3], "good gracious !": [3, 3], "i'm glad to hear that .": [11, 11], "ok , thank you .": [18, 18], "and now ?": [3, 3], "yes , certainly .": [10, 10], "yes , you .": [3, 3], "that's fantastic .": [4, 4], "yeah , me too .": [4, 3], "that's convenient .": [4, 4], "pardon ?": [7, 7], "this one ?": [4, 4], "you can say that again !": [3, 3], "i guess .": [3, 3], "you got it !": [5, 5], "yes , i will .": [13, 13], "wait a second , please .": [3, 3], "of course , here you are .": [3, 3], "never !": [4, 4], "i can't wait !": [6, 6], "what do you mean by that ?": [7, 7], "i was .": [3, 3], "see you !": [4, 4], "how about this one ?": [32, 32], "got it .": [22, 22], "no , i'm not sure .": [3, 3], "i know what you mean .": [13, 13], "huh ?": [14, 14], "sounds interesting .": [6, 6], "sure , i'd love to .": [3, 3], "what can i help you with ?": [6, 6], "is it urgent ?": [3, 3], "what size do you wear ?": [5, 4], "oh , really ?": [40, 40], "very good !": [4, 4], "ok , .": [3, 3], "perhaps .": [3, 3], "what do you think ?": [13, 13], "here it is .": [44, 43], "right ?": [3, 3], "yes , you can .": [5, 4], "no at all .": [5, 5], "only ?": [3, 3], "i got it .": [15, 15], "that's a secret .": [3, 3], "no , please .": [3, 3], "it's very interesting .": [4, 3], "i'll take it .": [29, 28], "how do you like it ?": [9, 9], "what's the problem ?": [22, 22], "quite a lot .": [3, 3], "you too .": [11, 11], "sounds great .": [6, 6], "emory .": [7, 7], "ok ?": [5, 5], "can i ?": [3, 3], "pardon me ?": [3, 3], "that's okay .": [13, 13], "not a problem .": [9, 9], "great !": [72, 71], "which season do you like best ?": [3, 3], "i'll take one .": [6, 6], "what about the commission ?": [3, 3], "glad to meet you .": [5, 5], "how about this .": [3, 3], "may i have your name ?": [3, 3], "yeah , i know what you mean .": [3, 3], "michael .": [3, 3], "c'mon .": [3, 3], "that sounds like fun .": [9, 9], "why do you say so ?": [6, 6], "it suits us fine .": [3, 3], "right !": [7, 7], "everything will be fine .": [4, 4], "talk to you then .": [3, 3], "what about these ?": [5, 5], "sure , what's up ?": [5, 5], "after a while .": [3, 3], "nothing much .": [6, 6], "don't worry about that .": [8, 7], "that's amazing !": [6, 6], "how do you do , .": [3, 3], "yes , sir ?": [3, 3], "of course , i will .": [4, 4], "what do you need ?": [7, 7], "that depends .": [6, 6], "oh , very good .": [3, 3], "give it to me .": [5, 5], "i forgot .": [5, 5], "oh , good .": [14, 14], "oh , that's great .": [3, 3], "how was it ?": [8, 8], "thanks very much .": [16, 16], "that's good !": [3, 3], "please !": [4, 4], "here is the .": [5, 5], "nothing special .": [8, 8], "and you ?": [32, 31], "i'm ready .": [3, 3], "whew !": [3, 3], "yeah .": [244, 238], "yes , that's true .": [6, 6], "have you ever been there ?": [3, 3], "how much is the rent ?": [5, 5], "let's order something to eat .": [3, 3], "okay , thank you .": [3, 3], "i'm very sorry .": [8, 7], "nice to meet you .": [12, 12], "maybe next weekend .": [3, 3], "how much do you charge ?": [5, 5], " !": [29, 29], " .": [70, 66], "oh , yes !": [6, 6], "it's delicious .": [5, 5], "of course not .": [28, 28], "ok , thanks .": [10, 10], "you ve been very helpful .": [3, 3], "well , i .": [3, 3], "that's not a bad idea .": [3, 3], "yikes !": [3, 3], "i will .": [58, 58], "certainly , sir .": [16, 16], "i'm in a hurry .": [4, 4], "oh , no .": [50, 48], "yes , it has .": [6, 6], "i quite agree with you .": [3, 3], "that sounds pretty good .": [4, 4], "i'll try my best .": [5, 5], "no , i haven't .": [15, 15], "where are you going now ?": [4, 4], "hi , tom .": [3, 3], "i don't understand .": [10, 10], "what a pity !": [15, 15], "really ?": [396, 394], "this way , please .": [12, 12], "your name , please ?": [6, 6], "so did i .": [5, 4], "jones .": [5, 5], "what does he look like ?": [3, 3], "yep .": [18, 18], "i understand that .": [4, 4], "no , don't bother .": [3, 3], "a minute , please .": [3, 3], "you must be joking !": [3, 3], "nothing .": [24, 23], "i bet .": [4, 4], "are you sure ?": [34, 33], "mm .": [3, 3], "oh , thanks a lot .": [3, 3], " , please .": [3, 3], "yes , i was .": [5, 5], "for here or to go ?": [3, 3], "yes , it did .": [3, 3], "yes , here it is .": [7, 7], "i suppose .": [4, 4], "that's .": [11, 11], "whatever .": [7, 6], "i appreciate your help .": [6, 6], " !": [15, 15], "excuse me , miss .": [3, 3], "that's good to know .": [4, 4], "yes , i know that .": [3, 3], "that sucks .": [3, 3], "hey !": [21, 21], "how long can i keep the ?": [4, 4], "where is the ?": [3, 3], " you then .": [8, 8], "i hope you it .": [3, 3], "sounds nice .": [3, 3], "sorry , sir .": [14, 14], "very well .": [23, 21], "that makes sense .": [12, 12], "what's the difference ?": [11, 11], "where did you go ?": [7, 7], "that sounds reasonable .": [5, 5], "well , no .": [4, 4], "you're very welcome .": [3, 3], "please sign your name here .": [4, 4], "let's .": [5, 5], "really .": [5, 5], "i've had enough .": [6, 4], " go .": [8, 8], "excuse me .": [8, 8], "can you the ?": [3, 3], "good !": [17, 17], "come on .": [46, 45], "this one looks nice .": [3, 3], "i what you mean .": [4, 4], "oh , ok .": [6, 6], "tomorrow .": [3, 3], "it's beautiful .": [4, 4], "we'll see you then .": [3, 3], "how are you doing ?": [6, 6], "yes , that's it .": [3, 3], "that's easy .": [7, 6], "what would you like ?": [4, 4], " ?": [3, 3], "let's call it a deal .": [3, 3], " a ?": [3, 3], "same here .": [9, 8], "do you think you are introverted or extroverted ?": [5, 5], "are you kidding ?": [28, 27], "not today .": [4, 4], " , .": [4, 4], "what did he say ?": [4, 4], "where do you want to go ?": [5, 5], " you .": [3, 3], "yes , madam .": [9, 9], "let me check .": [13, 12], "what bad luck !": [3, 3], "i'd to .": [9, 9], "no , i'm not .": [14, 14], "oh , sure .": [9, 9], "don't you know ?": [3, 3], "what size are you ?": [3, 3], "well , sir .": [4, 4], "what are you doing ?": [10, 10], "ha !": [6, 5], "by .": [3, 3], "yes , she is .": [3, 3], "not too .": [4, 4], "sounds good to me .": [4, 4], "let's keep in touch .": [3, 3], "here we go .": [4, 4], "for what ?": [8, 8], "anyway .": [4, 4], "yes , i .": [10, 10], "don't mention it .": [39, 38], "umm .": [9, 9], "again ?": [5, 5], "now you're talking .": [3, 3], "is there a problem ?": [7, 7], "single or return ?": [3, 3], "thank you very much !": [4, 4], "how can i help you ?": [12, 12], "what ?": [6, 6], "mmmm .": [12, 11], "just ?": [5, 4], "that would be great !": [8, 8], "be careful .": [4, 4], "yes , what can i do for you ?": [3, 3], "no , of course not .": [7, 7], "what else do you have ?": [3, 3], "ok , let's go .": [5, 5], "yes , i agree .": [7, 6], "wait for a moment .": [3, 3], "it isn't .": [4, 4], "what can i do now ?": [3, 3], " .": [3, 3], "what is a ?": [3, 3], "what are you going to do ?": [9, 9], "thank you so much .": [32, 30], "you are so kind .": [4, 4], "yes , thanks .": [5, 5], "oh , well .": [5, 5], "i'm surprised .": [4, 4], "well done !": [4, 4], "just a moment , please .": [16, 16], "so what happened ?": [4, 4], "where would you like to go ?": [4, 4], "exactly !": [7, 6], "how do you do , mr .": [3, 3], "oh , thank you .": [14, 14], "how do you ?": [3, 3], "what is the rate ?": [4, 4], "maybe you're right .": [8, 8], "so do i .": [13, 13], "sounds great !": [4, 4], "hold on , please .": [6, 6], "you did ?": [8, 8], "all right , ma'am .": [3, 3], "i'll see you then !": [4, 4], "by all means .": [5, 5], "sounds perfect .": [3, 3], "is that right ?": [28, 27], "anything else , sir ?": [5, 5], "come on !": [21, 20], "i am sorry to hear that .": [5, 5], "uh huh .": [7, 7], "what makes you say that ?": [3, 3], "yes , i think so .": [18, 17], "tell me !": [4, 3], "cool !": [20, 20], "ok .": [673, 656], "i can do that .": [7, 7], "now .": [3, 3], "i it !": [3, 3], "yes , we did .": [3, 3], "you're .": [5, 4], "didn't i ?": [3, 3], "i'm sorry .": [83, 83], "welcome .": [3, 3], "thank you , i will .": [3, 3], "hello ?": [3, 3], "here you are .": [176, 174], "i'll be there .": [4, 4], "excuse me ?": [5, 5], "that'll be fine .": [9, 9], "just one .": [3, 3], "what's the matter ?": [22, 22], "sounds good .": [38, 37], "that will be fine .": [10, 10], "k .": [21, 21], "no .": [311, 304], "i'm afraid you're going in the opposite direction .": [3, 3], "thanks a lot !": [4, 4], "thanks for your help .": [18, 18], "i'll do my best .": [4, 4], "how do you like your ?": [3, 3], " to you too .": [11, 9], "remember ?": [5, 5], "unfortunately not .": [3, 3], "alright , alright .": [4, 4], "did i ?": [4, 3], "i sure did .": [4, 4], "wow !": [75, 75], "that's ok .": [27, 27], "all right , then .": [3, 3], "how old is she ?": [10, 9], "yes , he does .": [6, 5], "alright , sir .": [5, 4], "ok , no problem .": [6, 6], "what do you think of it ?": [4, 4], "yeah , you're right .": [6, 6], "i sure did !": [3, 3], "i can't believe it .": [13, 13], " you , sir .": [3, 3], "how's that ?": [3, 3], "not much .": [13, 13], "interesting .": [9, 9], "how's it going ?": [3, 3], "5 .": [3, 3], "a .": [3, 3], "ah .": [11, 11], "i .": [5, 3], "i .": [30, 29], "are you ok ?": [5, 5], "got it !": [3, 3], "i sure do .": [3, 3], "indeed .": [9, 6], "how about thursday ?": [3, 3], "it doesn't matter .": [25, 25], "that's interesting .": [12, 12], "oh , cheer up .": [3, 3], "i know .": [101, 99], "what's wrong with that ?": [3, 3], "yeah , you are right .": [5, 5], "but why ?": [3, 3], "no , i'm afraid not .": [3, 3], "which ?": [12, 12], "i'm leaving tomorrow .": [3, 3], "hello , .": [4, 4], "well , i don't .": [3, 3], "com .": [3, 3], "that's the point .": [4, 4], "oh , i almost forgot .": [4, 4], "how was your flight ?": [3, 3], "is there anything else i can do for you ?": [3, 3], "it's all right .": [4, 4], "how much should i pay ?": [3, 3], "sure , go ahead .": [3, 3], "yes , it is .": [70, 67], "hang in there .": [3, 3], "my pleasure .": [24, 24], "who cares ?": [3, 3], "that's stupid .": [3, 3], " , mary .": [3, 3], "let me .": [3, 3], "that's cool .": [10, 10], "is that true ?": [11, 9], "not so well .": [3, 3], "that sounds fine .": [10, 10], "calm down , sir .": [3, 3], "you can't expect a close relationship with a dishonest .": [3, 3], "yes .": [1056, 1007], "is it very interesting ?": [3, 3], "that's not bad .": [6, 6], "see you soon .": [4, 4], "it's a pleasure .": [8, 8], "yes , they are .": [10, 10], "yes , you do .": [4, 4], "well , that's true .": [3, 3], "speaking .": [15, 15], "oh , come on !": [5, 5], "i don't like it very much .": [3, 3], "see ?": [6, 6], "anything else ?": [51, 50], "i can see that .": [3, 3], "i'd like to .": [3, 3], "it's too late .": [3, 3], "so how have you been ?": [3, 3], "it's very kind of you .": [12, 12], "that's terrific !": [4, 4], "i it .": [4, 4], "two .": [3, 3], "hurry up !": [3, 3], "i'll try .": [9, 9], "i don't know !": [3, 3], "that shouldn't be a problem .": [5, 5], "what are they ?": [12, 12], "that's it .": [15, 15], "you are quite right .": [4, 4], "oh , i know .": [5, 5], "three .": [5, 5], "what do you do ?": [6, 6], "is there anything else ?": [11, 11], "what about this ?": [4, 4], "ok , i .": [4, 3], "it's perfect .": [3, 3], "you're welcome .": [79, 71], "yes , sure .": [9, 9], "are you kidding me ?": [8, 8], "haha .": [7, 7], "do you really think so ?": [4, 4], "i couldn't agree more .": [6, 6], "just so so .": [7, 7], "er .": [10, 10], "it sure is .": [10, 10], "ok , here you are .": [16, 16], "is everything ok ?": [3, 3], "yes and no .": [4, 4], "sir .": [10, 10], "good night .": [6, 5], "do you have anything to declare ?": [11, 10], "i am .": [3, 3], "what's going on ?": [9, 9], "here is the money .": [10, 10], "you can say that again .": [9, 9], "that's right .": [136, 132], "let me try .": [3, 3], "where should we meet ?": [3, 3], "what do you mean ?": [63, 63], "what can i do for you today ?": [6, 6], "certainly !": [5, 5], "here is your key .": [3, 3], "i'm very sorry i can't .": [3, 3], "have a good one .": [3, 3], " you very much .": [5, 4], "thank you all the same .": [3, 3], "oh yes .": [6, 6], "what do you have in mind ?": [3, 3], "i am sorry , sir .": [9, 9], "okay .": [139, 139], "i can't agree more .": [4, 4], "forget it !": [5, 5], "i don't know .": [88, 87], "sounds pretty .": [4, 4], "sorry , i can't .": [5, 4], "it's easy .": [6, 6], "here's your .": [3, 3], "do you have your receipt ?": [3, 3], "that's great news !": [3, 3], "yes , here you are .": [15, 15], "trust me .": [5, 5], "that's correct .": [11, 11], "what does it say ?": [6, 6], "no , he doesn't .": [3, 3], "that's alright .": [10, 10], "have a nice day !": [4, 4], "what ?": [4, 4], "how come ?": [21, 21], "uh .": [12, 12], "please .": [8, 8], "i didn't .": [4, 4], "ah !": [10, 10], "yes , it's very .": [3, 3], "it sounds good .": [5, 5], "what about saturday ?": [3, 3], "oh , certainly .": [6, 6], "i don't think so .": [32, 29], "take it easy .": [12, 12], "i know that .": [8, 8], "well , that's something i've never heard of .": [3, 3], "ah , yes .": [4, 3], "oh , great !": [5, 5], "i .": [86, 84], "see you tomorrow .": [6, 6], "thanks for asking .": [4, 4], "thank you , mr .": [13, 13], "no , i can't .": [4, 4], "it's too expensive .": [3, 3], "ok , see you then .": [3, 3], "i am not sure .": [9, 9], "pretty well .": [3, 3], "what's wrong ?": [22, 22], "of course .": [186, 185], "that's strange .": [4, 3], "i guess you are right .": [6, 5], "that's true .": [71, 70], "how far is it ?": [3, 3], "ouch !": [3, 3], "not at all !": [5, 5], "what's new with you ?": [4, 4], "good .": [118, 115], "have a nice day .": [9, 9], "exactly .": [33, 32], "you're .": [3, 3], "how old are you ?": [5, 5], "wonderful !": [7, 7], "of course not !": [6, 6], "oh , i .": [8, 7], "that's incredible .": [3, 3], "that's terrible .": [8, 8], "that won't be a problem .": [3, 3], "you'll have the same time for .": [3, 3], "great minds think alike .": [4, 4], "nope .": [7, 7], "what are the ?": [4, 4], "i guess you're right .": [9, 9], "of course , you can .": [4, 4], "not always .": [7, 7], "here .": [17, 17], "oh , no !": [16, 16], "it's friday .": [3, 3], "geez !": [3, 3], "it's great !": [9, 8], "i'm sorry to hear that .": [28, 27], "there's a possibility .": [3, 3], "that sounds perfect .": [3, 3], "gee !": [4, 4], "look .": [4, 4], "that's no problem .": [18, 17], " worry .": [25, 24], "that's good advice .": [3, 3], "did you have a fight ?": [3, 3], "do you ?": [9, 9], "i'd totally die if she turned me down .": [3, 3], "how much do you want ?": [4, 4], "hum .": [3, 3], "nothing really .": [6, 6], "is she really ?": [3, 3], "do you have your passport with you ?": [4, 4], " !": [5, 5], "i see what you mean .": [3, 3], "how long does it take ?": [3, 3], "unbelievable !": [4, 4], "that's a .": [3, 3], "how so ?": [5, 5], "just a moment .": [10, 10], "what else do i have to do ?": [3, 3], "that's not a problem .": [9, 8], "i hope not .": [7, 6], "i don't .": [16, 16], "let me have a .": [5, 5], "i am .": [9, 8], "anything i can do for you ?": [4, 4], "all right , sir .": [9, 9], "please wait a moment .": [5, 5], "what's the ?": [7, 7], "yes , that's fine .": [4, 4], "thank you .": [595, 582], "what is the matter ?": [3, 3], "never .": [4, 4], "thanks for letting me know .": [5, 5], " you then .": [3, 3], "what's it about ?": [5, 5], " , please .": [26, 25], "really !": [8, 8], "no thanks .": [7, 6], "what's that ?": [34, 34], "where are you going ?": [9, 9], "i love going out and making new friends .": [3, 3], "what for ?": [17, 17], " , .": [5, 5], "thank you for your .": [3, 3], "fine , thanks .": [13, 13], "oh , i'm sorry .": [13, 12], "i have it right here .": [3, 3], "right here .": [7, 7], "where is it ?": [9, 9], "i'd love to .": [8, 8], "how long will it take me to get there ?": [3, 3], "i really appreciate it .": [8, 8], "where to ?": [5, 5], "why ?": [190, 188], "black .": [4, 4], "a .": [8, 8], "how do you know that ?": [5, 5], " so .": [3, 3], "as soon as possible .": [4, 4], "i never thought about it that way .": [3, 3], "of course i .": [3, 3], "you are very welcome .": [5, 5], "what have you learned from the jobs you have had ?": [3, 3], "ms .": [10, 10], "please take a seat .": [3, 3], "how long have you had it ?": [3, 3], "no , not at all .": [16, 14], "what's wrong with it ?": [14, 14], "where are we ?": [3, 3], "i suppose you're right .": [4, 4], "i'm glad to hear it .": [4, 4], "that'll be all .": [4, 4], "see you later .": [14, 14], "hello .": [16, 16], " you , too .": [3, 3], "you need to prepare for it .": [3, 3], "believe me .": [4, 4], "not particularly .": [3, 3], "who ?": [7, 6], "yes , that's .": [11, 11], "does she wear glasses ?": [3, 3], "no , sir .": [19, 19], "very nice .": [4, 4], "definitely .": [19, 19], "let me show you .": [4, 4], "what are you about ?": [3, 3], "yup .": [7, 7], "how much do i owe you ?": [5, 5], "smith .": [19, 19], "bye bye .": [7, 7], "i'm afraid not .": [20, 19], "are you american ?": [3, 3], "there .": [5, 5], "what's up ?": [26, 25], "oh , dear .": [8, 8], "thank you for inviting me .": [5, 5], "good for you !": [7, 7], "it's still early .": [3, 3], "oh , yeah ?": [7, 7], "no kidding !": [13, 13], "i'm just asking .": [4, 4], "what do you ?": [3, 3], "that sounds great .": [21, 21], "how ?": [4, 4], "that sounds fair .": [3, 3], " ?": [4, 4], "that doesn't sound too bad .": [4, 3], "nah !": [3, 3], "let's see .": [25, 24], "i'm ok .": [7, 7], " .": [5, 4], "may i help you ?": [13, 12], "absolutely !": [10, 10], "thanks a lot .": [82, 82], "this way please .": [3, 3], "go ahead , please .": [4, 4], "will there be anything else ?": [7, 7], "no , why ?": [4, 4], "nice to meet you !": [6, 6], "i love it .": [4, 4], "not yet .": [30, 29], "yes , we do .": [26, 26], "how did you do that ?": [3, 3], "oh , .": [3, 3], "what a good idea !": [3, 3], "for example ?": [7, 7], "sit down , please .": [3, 3], " is my favorite .": [5, 3], "i'm impressed .": [4, 4], " ?": [38, 38], "pretty good .": [12, 12], "what are those ?": [3, 3], "would you like to come ?": [5, 5], "yes , me too .": [4, 4], "yes , it does .": [8, 8], "yes , ma'am .": [3, 3], "that's what i thought .": [3, 3], "do you have any hobbies ?": [4, 4], "all right .": [221, 217], "that's everything .": [4, 4], "not exactly .": [4, 4], "well , it depends .": [3, 3], "no , mom .": [3, 3], "yes , i am .": [36, 34], "with pleasure .": [6, 6], "hello , mr .": [3, 3], "yes , there are .": [3, 3], "single or double ?": [3, 3], "i don't know yet .": [4, 4], "when ?": [14, 14], "no , thank you .": [39, 39], "yep !": [5, 5], "that's very nice of you .": [4, 4], "oh no .": [5, 5], "how about you ?": [54, 52], "i think so .": [36, 34], "terrific !": [6, 6], "it's on me .": [3, 3], "do you have a ?": [4, 4], "how old is he ?": [4, 4], "certainly .": [129, 126], " ?": [115, 113], "i apologize .": [3, 3], "probably .": [4, 4], "forget it .": [7, 7], "what kind of is it ?": [3, 3], "yes , he is .": [6, 6], "not very much .": [3, 3], "almost .": [6, 6], "are you all right ?": [5, 5], "i couldn't agree with you more .": [4, 4], "tomorrow morning .": [3, 3], "how have you been ?": [5, 5], "suit yourself .": [3, 3], "what kind of are you looking for ?": [3, 3], "yes , i do .": [67, 63], "oh , okay .": [3, 3], "not very .": [3, 3], "wow , good for you .": [3, 3], "what about ?": [3, 3], "well , that depends .": [4, 4], "i hope so .": [44, 43], "yes , i did .": [32, 31], "so what did you do ?": [3, 3], "i'm afraid you can't .": [5, 5], "that's very kind of you .": [8, 8], "what have you been doing ?": [4, 4], "what did you do ?": [13, 13], "easier said than done .": [4, 4], "of course you can .": [4, 4], "that's too bad .": [28, 28], "oh , dear !": [8, 7], "and ?": [6, 6], "i heard about that .": [3, 3], "yes ?": [23, 22], "it's .": [4, 4], "that's a long time .": [3, 3], "the same to you .": [4, 4], "no , i'm sorry .": [5, 5], " you .": [22, 22], "i doubt it .": [3, 3], "do you like it ?": [9, 9], "see you there !": [3, 3], "i promise .": [6, 6], "i'll be right back .": [7, 7], "i do .": [7, 7], "no , you don't have to .": [5, 3], "where ?": [15, 15], "it's hard to say .": [10, 10], "how are things with you ?": [3, 3], "oh , is it ?": [5, 5], "my ?": [6, 6], "oh , come on .": [5, 5], "i'm very sorry , sir .": [3, 3], "now what ?": [3, 3], "yeah ?": [13, 13], "not really .": [61, 60], "see you .": [11, 11], "that's too bad !": [4, 4], "it was my pleasure .": [3, 3], "hi .": [4, 4], "thank you , ma'am .": [4, 4], "i sure will .": [3, 3], "please have a seat .": [4, 4], "what are your strengths and weaknesses ?": [3, 3], "hi , steven .": [3, 3], " !": [7, 7], "yes , i so .": [5, 5], "i like it .": [5, 5], "awesome .": [3, 3], "well , yes .": [8, 8], "may i you ?": [4, 3], "just about .": [4, 4], "4 .": [3, 3], "this is mr .": [5, 5], "oh , i see .": [48, 48], "of course i'm .": [3, 3], "ha ha .": [9, 9], "let's go and have a drink .": [3, 3], "does that mean i'll have to pay duty on it ?": [3, 3], "yeah , fine .": [3, 3], "is there anything i can do for you ?": [4, 4], "but .": [7, 7], "it's very nice .": [5, 4], "no , really .": [3, 3], "what's he like ?": [4, 4], "give me a break .": [3, 3], "how much would you to ?": [3, 3], "you're absolutely right .": [4, 4], "you do ?": [6, 6], "excellent !": [7, 6], "what do you suggest ?": [3, 3], "ok , i can do that .": [3, 3], "how about your family ?": [3, 3], "here they are .": [12, 12], "that's fine .": [73, 73], "oh ?": [10, 10], "thanks for reminding me .": [8, 8], "wait a minute .": [14, 14], "i'm really not sure .": [3, 3], "ok , i see .": [6, 6], "many thanks .": [3, 3], "anytime .": [5, 5], "i'm afraid so .": [4, 4], "why not !": [6, 5], "oh , right .": [9, 9], "thanks for everything .": [4, 4], "i agree with you .": [9, 9], "i am fine .": [3, 3], "let me have a look .": [12, 10], "may i try it on ?": [8, 8], "that's better .": [5, 5], "so cool .": [3, 3], "oh , thanks .": [3, 3], "here you go .": [46, 46], "that is fine .": [3, 3], "and then ?": [6, 6], "i liked it .": [3, 3], "good for you .": [7, 7], "i'll talk to you later .": [5, 5], "thank you for saying so .": [4, 4], "that's it ?": [3, 3], "yes , i see .": [8, 7], "chen .": [3, 3], "what is it ?": [53, 53], "damn it !": [3, 3], "do you have a