oracle7 / workbench /converse /writing_request.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 4)
04e89f2 verified
Raw History Blame Contribute Delete
11.3 kB
"""A durable writing obligation, prepared from held records and committed after delivery.
This part arranges source sentences; it does not certify new deductions or supply
missing knowledge. Numeric constraints are judged on the delivered prose alone.
"""
import hashlib
import json
import os
import re
import threading
import uuid
from pathlib import Path
LOCK = threading.RLock()
WORD = re.compile(r"\b[\w]+(?:[’'-][\w]+)*\b", re.UNICODE)
CITE = re.compile(r"\s*\[(?:\d+|wd:Q\d+ P\d+ Q\d+)\]")
FOLLOW = re.compile(r"^\s*(?:it|its|they|their|them|he|his|she|her|this|these|that|those|such|however|therefore|also)\b", re.I)
def _path(sid):
root = Path(os.environ.get("ORACLE7_STATE") or Path.home() / ".oracle7") / "writing"
return root / (hashlib.sha256(str(sid).encode()).hexdigest() + ".json")
def load(sid):
try:
return json.loads(_path(sid).read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
def save(sid, state):
path = _path(sid)
path.parent.mkdir(parents=True, exist_ok=True)
temp = path.with_name(uuid.uuid4().hex + ".tmp")
try:
temp.write_text(json.dumps(state, ensure_ascii=False), encoding="utf-8")
os.replace(temp, path)
finally:
if temp.exists():
temp.unlink()
def plain(body):
return CITE.sub("", body).strip()
def counts(body, items=None):
text = plain(body)
return {"word": len(WORD.findall(text)),
"sentence": len([s for s in re.split(r'(?<=[.!?])\s+(?=[A-Z0-9"“])', text) if s.strip()]) if text else 0,
"paragraph": len([p for p in text.split("\n\n") if p.strip()])}
def constraints(sizes):
result = {}
for size in sizes:
unit = size.get("unit")
if unit not in ("sentence", "word", "paragraph"):
continue
lo, hi = int(size.get("min", size["n"])), int(size.get("max", size["n"]))
if unit in result:
lo, hi = max(lo, result[unit][0]), min(hi, result[unit][1])
result[unit] = [lo, hi]
return result
def satisfied(actual, bounds):
return bool(bounds) and all(lo <= actual.get(unit, 0) <= hi for unit, (lo, hi) in bounds.items())
def _render(selected, paragraphs):
paragraphs = min(max(1, paragraphs), len(selected)) if selected else 0
groups = [[] for _ in range(paragraphs)]
refs, evidence = [], []
for index, item in enumerate(selected):
record = dict(item)
if item.get("claim"):
citation = "[%d]" % (len(refs) + 1)
refs.append("%d. %s - %s (%s)" % (len(refs) + 1, item["title"], item["source"], item["claim"]))
else:
citation = "[wd:Q%d P%d Q%d]" % tuple(item["triple"])
# Keep contiguous source order. Each requested paragraph is nonempty.
group = min(paragraphs - 1, index * paragraphs // len(selected))
groups[group].append(item["sentence"] + " " + citation)
record["citation"] = citation
evidence.append(record)
return "\n\n".join(" ".join(group) for group in groups), refs, evidence
def prepare(sid, subject, title, text, sizes, records, *, mode="new", dupe=None, question=None,
required_record=None, missing_answer=False):
"""Receive and prepare one draft. No record is marked delivered here."""
with LOCK:
old = load(sid)
previous = old.get("request") or {}
bounds = constraints(sizes) or previous.get("bounds") or {"sentence": [5, 5]}
retained = mode in ("more", "revise", "resume") and previous.get("subject") == subject
request = {"id": previous.get("id") if retained else uuid.uuid4().hex,
"subject": subject, "title": title, "original": previous.get("original", text) if retained else text,
"text": text, "bounds": bounds, "sizes": sizes or previous.get("sizes", []), "mode": mode}
if question:
request["question"] = question
excluded = set(old.get("delivered_ids", [])) if mode == "more" else set()
prior_text = old.get("delivered_text", []) if mode == "more" else []
compare = dupe or (lambda a, b: a.casefold().strip() == b.casefold().strip())
selected, seen, words, sentence_count = [], [], 0, 0
sentence_bounds = bounds.get("sentence")
word_bounds = bounds.get("word")
paragraphs = bounds.get("paragraph", [1, 1])[0]
desired_sentences = sentence_bounds[0] if sentence_bounds else max(1, paragraphs * 3)
invalid = any(lo < 1 or hi < lo for lo, hi in bounds.values())
for record in records:
if invalid:
break
item = dict(record)
sentence = " ".join(str(item.get("sentence", "")).split())
identifier = item.get("claim") or "wd:" + ":".join(map(str, item.get("triple", [])))
if not sentence or identifier in excluded or any(compare(sentence, t) for t in seen + prior_text):
continue
# An extracted anaphor keeps its source predecessor, rather than
# becoming a free-standing assertion after selection skipped it.
if FOLLOW.match(sentence) and item.get("previous") and item["previous"] not in {r["id"] for r in selected} | excluded:
continue
amount = len(WORD.findall(sentence))
sentence_amount = counts(sentence)["sentence"]
if word_bounds and words + amount > word_bounds[1]:
continue
if sentence_bounds and sentence_count + sentence_amount > sentence_bounds[1]:
continue
item.update(sentence=sentence, id=identifier)
selected.append(item)
seen.append(sentence)
words += amount
sentence_count += sentence_amount
enough_sentences = sentence_count >= desired_sentences
enough_words = not word_bounds or words >= word_bounds[0]
if enough_sentences and enough_words:
break
body, refs, evidence = _render(selected, paragraphs)
actual = counts(body, evidence)
answer_present = not missing_answer and (not required_record or required_record in {r.get("claim") for r in selected})
complete = not invalid and answer_present and satisfied(actual, bounds)
need = [{"unit": unit, "asked": [lo, hi], "written": actual[unit]}
for unit, (lo, hi) in bounds.items() if not lo <= actual[unit] <= hi]
prefix = ""
if not complete:
details = "; ".join("%s %d, requested %s" % (n["unit"], n["written"],
str(n["asked"][0]) if n["asked"][0] == n["asked"][1] else "%d–%d" % tuple(n["asked"])) for n in need)
prefix = "The supported draft is short of the requested shape (%s). Provide another source about %s, then continue this writing request." % (details, title)
if invalid:
prefix = "The requested sizes conflict or are not positive. Correct the writing amount to continue this request."
elif not answer_present:
prefix = "I still need a supported answer to '%s' to complete this writing request. Provide a source answering that question, then continue." % question
response = ((prefix + "\n\n") if prefix else "") + body
if refs:
response += "\n\n### Sources\n\n" + "\n".join(refs)
draft = {"id": uuid.uuid4().hex, "request": request, "body": body, "prefix": prefix,
"evidence": evidence, "counts": actual, "complete": complete, "need": need,
"answer_present": answer_present, "required_record": required_record,
"version": int(old.get("version", 0)) + 1}
history = list(old.get("history", [])) + [{"text": text, "bounds": bounds, "mode": mode, "version": draft["version"]}]
state = dict(old, request=request, pending=draft, version=draft["version"], history=history)
save(sid, state)
reply = {"status": "answered" if complete else "hole", "response": response,
"path": "converse:parts:discussion:pool" + ("" if complete else ":short"),
"subjects": [subject], "records": [r["claim"] for r in evidence if r.get("claim")],
"claims": [r["triple"] for r in evidence if r.get("triple")],
"writing": draft, "basis": {"parts": "held source sentences + Parts.say", "written": actual,
"asked": bounds, "mode": "source-grounded account"}}
if not complete:
reply["execution"] = {"state": "not_run", "cause": "writing-evidence-or-size",
"takes": ["a source about %s, or corrected writing bounds; then continue this writing request" % title],
"writing_request": request["id"], "missing": need}
return reply
def commit(sid, reply):
"""Check actual delivered text and commit only this still-current draft."""
draft = reply.get("writing")
if not isinstance(draft, dict) or not draft.get("id"):
return reply
with LOCK:
state = load(sid)
if state.get("committed_id") == draft["id"]:
return reply
if (state.get("pending") or {}).get("id") != draft["id"]:
return dict(reply, status="hole", writing_error="writing draft superseded before delivery")
# The persisted prepared record, rather than a caller's altered
# metadata, owns the expected body and its size/source obligations.
draft = state["pending"]
body = str(reply.get("response", "")).partition("### Sources")[0].strip()
body = re.sub(r"\s*\[hole:[^\]]+\]", "", body)
prefix = draft.get("prefix", "")
if prefix and body.startswith(prefix):
body = body[len(prefix):].strip()
# Seal diagnostics are process commentary, never prose length credit.
body = body.partition("\n\n(Not counted as answered:")[0].strip()
expected = draft.get("body", "")
checked = body == expected and not (reply.get("seal") or {}).get("error") and not reply.get("writing_source_error")
actual = counts(body) if not checked else counts(body, draft["evidence"])
complete = checked and draft.get("answer_present", True) and satisfied(actual, draft["request"]["bounds"])
out = dict(reply, writing=dict(draft, delivered_counts=actual, delivered_checked=checked, complete=complete))
if not checked:
out["status"] = "hole"
out["writing_error"] = "delivered prose differs from the supported draft, or its final check failed"
return out
if not complete:
out["status"] = "hole"
state.update(committed_id=draft["id"], last=out["writing"], pending=None)
reset = draft["request"].get("mode") in ("new", "revise", "resume")
state["delivered_ids"] = list(dict.fromkeys(([] if reset else state.get("delivered_ids", [])) + [e["id"] for e in draft["evidence"]]))
state["delivered_text"] = list(dict.fromkeys(([] if reset else state.get("delivered_text", [])) + [e["sentence"] for e in draft["evidence"]]))
save(sid, state)
return out