oracle7 / workbench /language_bridge.py
psiloceyeben's picture
Release 12.0 (full): one browser harness that converses, writes from held sources and builds what you describe, keeping each request through corrections and restarts. No language model. (part 5)
d9b105f verified
Raw History Blame Contribute Delete
21.1 kB
"""Connect the existing turn grammar to work, and word work from its receipts.
The original turn accompanies every changed reading. A request envelope may be
removed; its payload stays exact. Spelling is suggested only for a named hole.
No reply here adds a fact beyond the project's saved shape or execution receipt.
"""
import re
import sys
from pathlib import Path
def _grammar():
# In the installed pack this module is in workbench/converse, whose path is
# set by Converse. The development overlay supplies release115 on sys.path.
try:
from turn_reader import REQUEST, WH, AUX
return REQUEST, WH, AUX
except ImportError:
local = Path(__file__).resolve().parent / "converse"
if (local / "turn_reader.py").is_file() and str(local) not in sys.path:
sys.path.insert(0, str(local))
return _grammar()
return None, (), ()
_ENVELOPE = re.compile(
r"\s*(?:(?:ok(?:ay)?|well|so|now)[,\s]+)*"
r"(?:(?:can|could|would|will)\s+(?:you|we|u)(?:\s+please)?(?:\s+just)?|"
r"please|let'?s|lets|let us|(?:we|i)\s+(?:need|want)(?:\s+to)?|"
r"need\s+to|make\s+sure(?:\s+that)?|go\s+ahead\s+and|"
r"i'?d\s+like(?:\s+you)?(?:\s+to)?)\s+", re.I)
_CORRECTION = re.compile(
r"^\s*(?:(?:sorry|no|oh|wait)[,\s]+)*(?:i\s+meant|i\s+mean)\s+(.+)$", re.I | re.S)
def code_context(text, native, env, turn=None):
"""Read local-code discussion through the same source and receipt boundary."""
local = str(Path(__file__).resolve().parent / "converse")
if local not in sys.path:
sys.path.insert(0, local)
import code_discussion
return code_discussion.handle(text, native, env, turn)
def request_reading(text, active_project=False, active_work=False):
"""A conservative reading using the native request grammar, with evidence.
The native REQUEST searches within a turn; the envelope check requires its
complete prefix to be a request marker, so quoted requests and questions
about a request do not turn into actions.
"""
original = str(text or "")
payload = original
steps = []
request, _wh, _aux = _grammar()
if request is not None:
found = request.match(payload)
if found and _ENVELOPE.fullmatch(payload[:found.start(1)]):
body = payload[found.start(1):found.end(1)]
prefix = payload[:found.start(1)]
# "I need a program that ..." receives a desired object. Removing
# "I need" leaves a noun fragment, not an equivalent imperative.
nominal = bool(re.search(r"\b(?:need|want|like)\b", prefix, re.I) and
re.match(r"\s*(?:a|an|the|some|my|our)\b", body, re.I))
if body and not nominal:
steps.append({"part": "turn_reader.REQUEST", "prefix": payload[:found.start(1)],
"body_start": found.start(1), "body_end": found.end(1)})
payload = body
if active_project or active_work:
correction = _CORRECTION.match(payload)
if correction:
body = payload[correction.start(1):correction.end(1)]
# C15: the revision marker is added only when the correction does not already carry one ("I meant it above
# 10 instead" stays as said; it was read as "instead it above 10 instead")
mark = "" if re.search(r"(?i)\b(?:instead|rather|change|changed|update|revise)\b", body) else "instead "
steps.append({"part": "work.REVISE" if active_work else "project.REVISE", "prefix": payload[:correction.start(1)],
"replacement": mark, "body_start": correction.start(1),
"body_end": correction.end(1)})
payload = mark + body
return {"original": original, "reading": payload, "steps": steps}
def asks_about(text):
"""A question/account is not an instruction to revise the active project."""
reading = request_reading(text)
if reading["steps"]:
return asks_about(reading["reading"])
_request, wh, aux = _grammar()
words = re.findall(r"[A-Za-z]+(?:'[A-Za-z]+)?", str(text or "").lower())
while words and words[0] in {"okay", "ok", "so", "well", "now", "and", "hey"}:
words.pop(0)
if len(words) > 1 and words[0] in {"do", "does", "did"} and words[1] == "not":
return False
if words and words[0] in set(wh) | set(aux):
return True
return bool(re.match(r"^\s*(?:explain|describe|tell me about|tell me why|tell me how)\b", str(text or ""), re.I))
_STATE_QUESTIONS = (
("holes", re.compile(r"(?:what(?:'s| is) (?:still )?(?:missing|left|needed|blocking(?: it| this project)?)|"
r"what (?:else |still )?(?:needs to be done|remains)|"
r"why (?:is|was) (?:it|this project|the project) (?:blocked|stuck|unfinished)|"
r"why (?:can't|cannot|didn't|did not) (?:it|this project|the project) (?:finish|complete))", re.I)),
("inputs", re.compile(r"(?:what (?:are|were) (?:the |its )?(?:inputs|sources)(?: (?:for|of) (?:this |the )?project)?|"
r"(?:what|which) (?:files|tables|sources|inputs) (?:does|did|will) (?:it|this project|the project) (?:read|use)|"
r"(?:show|tell) me (?:the |its )?(?:inputs|sources)(?: (?:for|of) (?:this |the )?project)?)", re.I)),
)
def _files(source):
if not isinstance(source, dict):
return []
if source.get("op") == "read":
return [source["file"]] if source.get("file") else []
children = source.get("inputs", ()) if source.get("op") == "union" else (source.get("left"), source.get("right"))
return list(dict.fromkeys(f for child in children for f in _files(child)))
# C15: a question about the project is read by what it refers to and what it asks about, not by a fixed list of phrasings.
# Each aspect is a part of the saved record; a question naming none of them, or not referring to the project, is not taken.
_ASPECTS = (
("holes", r"missing|left|needs?|needed|blocking|blocked|stuck|unfinished|waiting|holes?|gaps?"),
("inputs", r"sources?|inputs?|tables?|reads?|combines?|combined|joins?|joined|stack(?:s|ed)?|lookups?|look up|merges?|"
r"merged|come from|data"),
("outputs", r"outputs?|writes?|written|produces?|produced|makes?|saves?|saved|result files?|creates?"),
("status", r"done|finished|built|work(?:s|ing|ed)?|pass(?:ed|es)?|status|state|succeed(?:ed)?|complete(?:d)?|ready"),
("requirements", r"requirements?|obligations?|asked for|supposed to do|what (?:does|will) it do"),
("history", r"tried|attempts?|history|changes?|changed|corrections?|revisions?|so far"),
)
_REFERS = r"\b(?:project|it|its|it's|this|that|the build|the program|the job)\b"
def _aspect(q, shape):
# Quoted examples (including JSON keys/values) are data, not the aspect
# being asked about. A key named "state" must not turn an explanation of
# an example into a status report about an unrelated active project.
low = re.sub(r'"(?:\\.|[^"\\\n])*"|(?<!\w)\'(?:\\.|[^\'\\\n])*\'(?!\w)', ' ', q.lower())
if "`" in q or re.match(r"(?:build|make|create|write|set up|add|also|save|export|keep|serve|print|change|drop|use|"
r"actually|instead|no,)\b", low):
return None # a request to do something, however it is phrased, is not a question
names = {str(shape.get("module") or "")} | {str(e) for e in (shape.get("entries") or {})}
names |= {f for src in (shape.get("sources") or {}).values() for f in _files(src)}
refers = re.search(_REFERS, low) or any(n and n.lower() in low for n in names)
if not refers or re.search(r"\b(?:you|yourself|oracle7)\b", low) and not re.search(r"\b(?:project|it|its)\b", low):
return None
return next((kind for kind, words in _ASPECTS if re.search(r"\b(?:%s)\b" % words, low)), None)
def _describe(source):
"""a source graph in words: what is read, and how tables are joined, stacked or looked up"""
if not isinstance(source, dict):
return "nothing resolved yet"
op = source.get("op")
if op == "read":
return "`%s`" % source.get("file")
if op == "union":
return "the rows of %s stacked together" % " and ".join(_describe(x) for x in source.get("inputs") or ())
keys = " and ".join("%s = %s" % tuple(k) if k[0] != k[1] else k[0] for k in source.get("keys") or ())
if op == "lookup":
return "%s, each row looking up %s by %s" % (_describe(source.get("left")), _describe(source.get("right")), keys or "?")
return "%s joined with %s on %s (%s join%s)" % (
_describe(source.get("left")), _describe(source.get("right")), keys or "?", source.get("how") or "inner",
": every row of the first kept" if source.get("how") == "left" else ": only rows that match")
def project_answer(text, shape):
"""Word a project-state question from the kept record only."""
if not shape:
return None
q = request_reading(text)["reading"].strip().rstrip("?.! ")
kind = next((name for name, pattern in _STATE_QUESTIONS if pattern.fullmatch(q)), None)
if kind is None and (asks_about(text) or str(text).strip().endswith("?")):
kind = _aspect(q, shape)
if kind is None:
return None
if kind in ("outputs", "status", "requirements", "history"):
return _record_answer(kind, shape)
module = shape.get("module") or "the unnamed project"
state = shape.get("status") or "not recorded"
lines = ["The last recorded state of `%s` is %s." % (module, state)]
basis = ["project.status", "project.module"]
if kind == "holes":
holes = [h.get("text", "") for h in shape.get("holes_kept", ()) if h.get("text")]
last = (shape.get("last_reply") or {}).get("execution") or {}
if not holes:
holes = [str(h) for h in last.get("holes", ())]
if holes:
lines.append("To continue, I need:\n" + "\n".join("- " + h for h in holes))
basis.append("project.holes_kept/last_reply.execution.holes")
else:
pending = [r["id"] for r in last.get("requirements", ()) if r.get("status") not in ("passed", "superseded", "excluded")]
if pending:
lines.append("The last attempt left these requirements unresolved: %s." % ", ".join(pending))
elif state == "built" and last.get("state") == "changed-checked":
lines.append("The saved receipt says every requirement passed.")
else:
lines.append("The saved record names no remaining hole; that alone does not establish completion.")
basis.append("project.last_reply.execution")
else:
sources = shape.get("sources") or {}
named = [(entry, _files(source)) for entry, source in sources.items()]
named = [(entry, files) for entry, files in named if files]
if named:
lines.append("Its commands read these sources:\n" + "\n".join(
"- `%s`: %s" % (entry, ", ".join("`%s`" % f for f in files)) for entry, files in named))
combined = [(entry, s) for entry, s in sources.items() if isinstance(s, dict) and s.get("op") != "read"]
if combined:
lines.append("How they are combined:\n" + "\n".join("- `%s`: %s" % (e, _describe(s)) for e, s in combined))
else:
lines.append("No input source has been resolved in the saved project yet.")
basis.append("project.sources")
lines.append("This is the saved record; I have not rerun the project for this answer.")
return {"status": "answered", "path": "bench:project:record:" + kind, "response": "\n\n".join(lines),
"execution": {"state": "read", "project": shape.get("pid"), "basis": basis}}
def _record_answer(kind, shape):
"""outputs, status, requirements, history: from the saved receipt and attempts only"""
module = shape.get("module") or "the unnamed project"
state = shape.get("status") or "not recorded"
last = shape.get("last_reply") or {}
ex = last.get("execution") or {}
reqs = ex.get("requirements") or []
lines = ["The last recorded state of `%s` is %s." % (module, state)]
ledger = [ln.strip() for ln in (last.get("response") or "").splitlines() if re.match(r"\s+R\d+ ", ln)]
if kind == "status":
passed = sum(1 for r in reqs if r.get("status") == "passed")
open_ = [r["id"] for r in reqs if r.get("status") not in ("passed", "superseded", "excluded", "dropped")]
lines.append("Its last attempt ended %s: %d of %d recorded requirements passed%s." % (
ex.get("state") or "without a receipt", passed, len(reqs),
("; not yet met: " + ", ".join(open_)) if open_ else ""))
holes = [h.get("text", "") for h in shape.get("holes_kept") or () if h.get("text")]
if holes:
lines.append("To continue, I need:\n" + "\n".join("- " + h for h in holes))
elif kind == "requirements":
lines.append("Its requirements, as last judged:\n" + "\n".join("- " + ln for ln in ledger) if ledger else
"Its requirements: %s." % ", ".join("%s %s (%s)" % (r["id"], r["kind"], r.get("status")) for r in reqs)
if reqs else "No requirement has been recorded yet.")
elif kind == "outputs":
outs = [ln for ln in ledger if re.search(r"\b(?:writes|keeps rows|a page|prints)\b", ln)]
files = ex.get("files") or []
lines.append("What it makes:\n" + "\n".join("- " + ln for ln in outs) if outs else
"No outcome has been recorded yet.")
if files:
lines.append("Files it changed last: %s." % ", ".join("`%s`" % f for f in files))
else:
att = shape.get("attempts") or []
lines.append("What has been tried (%d attempt%s):\n" % (len(att), "" if len(att) == 1 else "s") + "\n".join(
"- %d: \"%s\" -> %s%s" % (a.get("seq"), str(a.get("text"))[:90], a.get("state"),
(", then a different step: " + a["cont"]) if a.get("cont") else "")
for a in att[-8:]) if att else "No attempt is recorded yet.")
lines.append("This is the saved record; I have not rerun the project for this answer.")
return {"status": "answered", "path": "bench:project:record:" + kind, "response": "\n\n".join(lines),
"execution": {"state": "read", "project": shape.get("pid"), "basis": ["project.last_reply", "project.attempts"]}}
def work_answer(text, shape, reading=None):
"""A question about the active general work uses that work's own record."""
if not shape:
return None
q = request_reading(text)["reading"].strip().rstrip("?.! ")
kind = next((name for name, pattern in _STATE_QUESTIONS if pattern.fullmatch(q)), None)
if kind is None and (asks_about(text) or text.strip().endswith("?")):
referring = re.sub(r"\b(?:work|task|goal)\b", "project", q, flags=re.I)
kind = _aspect(referring, {"module": "", "entries": {s["id"]: {} for s in shape.get("steps", ())}})
if kind is None:
import bench
if bench._STATUS.fullmatch(text.strip()):
kind = "status"
elif bench._TASKS.fullmatch(text.strip()):
kind = "holes"
if kind is None:
import project_discussion
return project_discussion.answer(text, shape, reading=reading)
steps = shape.get("steps") or []
done = sum(step.get("state") == "done" for step in steps)
lines = ["The active work is %s: %d of %d steps are complete." % (shape.get("state", "received"), done, len(steps)),
"The goal is: " + str(shape.get("goal") or "not recorded")]
holes = shape.get("holes") or []
if kind in ("holes", "status"):
if holes:
lines.append("What it needs next:\n" + "\n".join("- " + str(h.get("text") or h) for h in holes))
elif done < len(steps):
lines.append("Still open:\n" + "\n".join("- %s: %s" % (s["id"], s.get("request", s["kind"]))
for s in steps if s.get("state") != "done"))
elif shape.get("state") != "done":
lines.append("The saved state does not establish completion yet.")
elif kind == "requirements":
requirements = shape.get("requirements") or []
lines.append("\n".join("- %s: %s (%s)" % (r.get("id", "?"), r.get("text") or r.get("request") or r.get("kind", ""),
r.get("status", "open")) for r in requirements) or "No requirement is recorded yet.")
if shape.get("constraints"):
lines.append("Constraints:\n" + "\n".join("- " + c["text"] for c in shape["constraints"]))
elif kind == "inputs":
lines.append("The saved requests for each part:\n" + "\n".join("- %s: %s" % (s["id"], s.get("request", "")) for s in steps))
elif kind == "outputs":
files = list(dict.fromkeys(f for receipt in shape.get("receipts", ()) for f in (
receipt.get("result", {}).get("files") or receipt.get("result", {}).get("execution", {}).get("files") or [])))
lines.append("Files recorded by completed actions: %s." % ", ".join("`%s`" % f for f in files)
if files else "No changed file has been recorded in this work's receipts.")
else:
lines.append("Recorded attempts:\n" + "\n".join("- %s: %s (%d attempt%s)" % (
s["id"], s.get("state", "pending"), len(s.get("attempts") or []), "" if len(s.get("attempts") or []) == 1 else "s") for s in steps))
lines.append("This is the saved work record; I have not run a step for this answer.")
return {"status": "answered", "path": "bench:work:record:" + kind, "response": "\n\n".join(lines),
"execution": {"state": "read", "work_id": shape.get("id"), "basis": ["work.steps", "work.requirements", "work.receipts", "work.holes"]}}
def word_receipt(reply):
"""A short lead from a project receipt; keep the complete original account."""
if not str(reply.get("path", "")).startswith("bench:project") or reply.get("details") is not None:
return reply
ex = reply.get("execution") or {}
state = ex.get("state")
if state == "changed-checked":
reqs = ex.get("requirements") or []
passed = [r for r in reqs if r.get("status") == "passed"]
if reqs and len(passed) == len(reqs):
lead = "The project is built, and all %d recorded requirements passed their checks." % len(reqs)
else:
lead = "The project change completed with a checked receipt."
if ex.get("files"):
lead += " The changed file%s: %s." % ("s are" if len(ex["files"]) != 1 else " is", ", ".join("`%s`" % f for f in ex["files"]))
elif state in {"missing", "blocked"}:
holes = ex.get("holes") or []
lead = "The project is kept for the next turn, but it is not finished."
if holes:
lead += " %d unresolved requirement%s remain%s." % (len(holes), "s" if len(holes) != 1 else "", "" if len(holes) != 1 else "s")
if ex.get("started") is False:
lead += " This attempt did not start a build."
elif state == "failed":
lead = "This attempt did not pass its checks; the project is not finished."
elif state == "refused":
lead = "The project is waiting for the change permission recorded for this conversation."
else:
return reply
details = str(reply.get("response", ""))
return dict(reply, response=lead + "\n\n" + details, details=details,
wording={"basis": "execution", "state": state})
def spelling_suggestions(shape, reader, owned):
"""Use the existing Speller on unread holes only; never change the request."""
speller = getattr(reader, "sp", None)
if speller is None:
return []
owned = {str(w).lower() for w in owned}
suggestions = []
for hole in (shape or {}).get("holes_kept", ()):
if hole.get("kind") != "unread":
continue
for word in hole.get("words", ()):
if not re.fullmatch(r"[a-zA-Z]+", word) or word.lower() in owned:
continue
try:
candidate = speller.fix_word(word)
except Exception:
continue
if candidate.lower() != word.lower() and candidate.lower() in owned:
suggestion = {"word": word, "reading": candidate, "requirement": hole.get("req"), "part": "turn_reader.Speller"}
if suggestion not in suggestions:
suggestions.append(suggestion)
return suggestions