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