"""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