From f549245b9e6eff0cbaa580fe4a4ef6a209022fa2 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Mon, 16 Nov 2026 13:46:07 +0000 Subject: [PATCH] feat(questions): the questions inbox store, questions_edit.py and its checks (PyAutoBrain#645) M3.5 Build B, Mind half. Parked shift questions get one ledger file, questions.md (Open / Deferred / Answered / Dropped; the section is the state), and one script for every write: - scripts/questions_edit.py: show / add / answer / defer / drop / reopen, built like queue_edit.py (Refused, exit 0/1/2, a write that adds a lifecycle finding is undone). add_text() is the pure function the shift watcher's question-add op runs from the tree it writes: ids are the file's highest plus 1, and (shift, task, issue) is unique, so a replay is a silent repeat. answer appends the answer to the task's prompt (draft/ or active/) under "## Answers from the human" and prints the path to commit. - lifecycle.py: questions_parse/questions_findings in `check` (ids unique, required keys, Open/Deferred task resolves); `close` moves the task's open questions to Answered with answer: (task completed). - ledger_merge.py: questions.md is a ledger file. - spawn.py: questions.md is EMPTY instance state; dashboard_refresh.yml watches it; REFERENCE.md gains a questions inbox section. questions.md itself is not added here: add creates it from the template, and the lead lands the seed after merge. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/dashboard_refresh.yml | 6 + REFERENCE.md | 35 ++ scripts/ledger_merge.py | 4 + scripts/lifecycle.py | 227 ++++++++++++ scripts/questions_edit.py | 454 ++++++++++++++++++++++++ scripts/spawn.py | 4 + tests/test_questions_edit.py | 387 ++++++++++++++++++++ 7 files changed, 1117 insertions(+) create mode 100644 scripts/questions_edit.py create mode 100644 tests/test_questions_edit.py diff --git a/.github/workflows/dashboard_refresh.yml b/.github/workflows/dashboard_refresh.yml index 1e9ffd595..3123f7ccd 100644 --- a/.github/workflows/dashboard_refresh.yml +++ b/.github/workflows/dashboard_refresh.yml @@ -51,6 +51,9 @@ on: # edit) makes it stale. - "queue.md" - "goals.md" + # The inbox section (M3.5, PyAutoBrain#645): an answer, a defer or the + # watcher's question-add makes the page stale. + - "questions.md" pull_request: paths: - "draft/**" @@ -73,6 +76,9 @@ on: # edit) makes it stale. - "queue.md" - "goals.md" + # The inbox section (M3.5, PyAutoBrain#645): an answer, a defer or the + # watcher's question-add makes the page stale. + - "questions.md" workflow_dispatch: # contents: write is needed by the self-heal push on main; PR runs never push. diff --git a/REFERENCE.md b/REFERENCE.md index 4123ddf37..51adeb2eb 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -489,6 +489,41 @@ history unattended will not record it. written at dispatch and appended at collection. Schema and the three fields that are easy to get wrong are in [`batches/AGENTS.md`](batches/AGENTS.md). +### The questions inbox (`questions.md`) + +A shift worker that parks on a question asks it on its issue and stops. The +question also lands here, so the human answers the shift's questions in bulk +after the run instead of being @-mentioned mid-shift (M3.5, PyAutoBrain#645). + +- **[`questions.md`](questions.md)** โ€” one `### Q. โ€” ` + entry per question, under `## Open`, `## Deferred`, `## Answered` or + `## Dropped`; the section is the state. Keys: `task:` (the prompt), + `issue:` (where the question lives), `kind:` (`question`, or `blocked` for a + worker stopped at a prompt nobody answered), `ask:`, `options:`, `shift:`, + `asked:`, `worker:`. Ids are global and increasing; `(shift, task, issue)` + is unique. +- **Two writers, one script.** The shift watcher adds entries through its one + Mind writer (the `question-add` op calls `scripts/questions_edit.py` + `add_text` from the tree it writes). A chat that ran `/questions` (PyAutoBrain + `skills/questions`) answers, defers, drops or reopens them with + `questions_edit.py`, in a temporary worktree detached on `origin/main`, + committed with `prompt_sync_push`. Nothing hand-edits the file. +- **An answer resumes the task.** `answer` moves the entry to Answered and, in + the same commit, appends the answer to the task's prompt under + `## Answers from the human`. The watcher holds a task an earlier shift left + parked until every question it parked on is answered; then the next shift + re-enters it at its old standing (its `queue.md` rank, else a small dip) and, + for a task already claimed by a shift worker, resumes the claim, issue, + branch and worktree with the answer in its prompt. Defer keeps the hold; + drop shelves the task (held until reopened, named in a brief, or `/add`-ed). +- **Validated.** `lifecycle.py check` fails on a malformed entry, a repeated + id, or an Open or Deferred entry whose task is in neither `draft/` nor + `active/`. `lifecycle.py close` moves the closed task's Open and Deferred + entries to Answered with `answer: (task completed)`. +- **Read-only on the dashboard.** The inbox section lists the Open entries + with a ๐Ÿ“‹ that copies `Use the questions skill. Q` to paste into a + chat that runs `/questions`. + ### The review-cost model `Difficulty:` measures blast radius โ€” how far a change reaches. It cannot answer diff --git a/scripts/ledger_merge.py b/scripts/ledger_merge.py index 2dcb4326b..48e76e58b 100755 --- a/scripts/ledger_merge.py +++ b/scripts/ledger_merge.py @@ -97,6 +97,10 @@ # them (PyAutoBrain `intake looks-shipped`) โ€” ledger, like queue.md. "looks_shipped.json", "looks_shipped_dismissed.md", + # Parked questions waiting for the human (M3.5, PyAutoBrain#645): the + # shift watcher adds entries through its one Mind writer (`question-add`) + # and a `/questions` chat answers them โ€” ledger, like queue.md. + "questions.md", ) # Names that are ledger by location but executable by collection. The ledger diff --git a/scripts/lifecycle.py b/scripts/lifecycle.py index b20a4702c..48a7d8ee5 100644 --- a/scripts/lifecycle.py +++ b/scripts/lifecycle.py @@ -69,6 +69,8 @@ * every live queue.md ref resolves, and no prompt is queued twice * goals.md parses: numbered 1..n, at most 10 goals of at most 200 characters, known fields only (an unknown epic only warns) + * questions.md parses: ids unique, required keys present, and + every Open or Deferred entry's task: a draft/ or active/ prompt Wire into /health and CI. `--paths` scopes the EXIT CODE to the findings about those paths (a branch can only be held to its own diff โ€” see REFERENCE.md "Scoping a drift check to one branch"); @@ -3049,6 +3051,214 @@ def goals_findings(root: Path) -> "tuple[list[Finding], list[Finding]]": return problems, warnings +# --------------------------------------------------------------------------- # +# questions.md โ€” parked questions waiting for the human (M3.5, +# PyAutoBrain#645). The shift watcher adds entries through its one Mind +# writer; a `/questions` chat answers, defers or drops them through +# `scripts/questions_edit.py`. The section an entry sits under is its state. +# --------------------------------------------------------------------------- # +#: The four states, in file order. `## ` may carry a trailing comment. +QUESTION_SECTIONS = ("Open", "Deferred", "Answered", "Dropped") +QUESTION_SECTION_RE = re.compile(r"^##\s+(Open|Deferred|Answered|Dropped)\b") +#: An entry's heading, `### Q. โ€” `. +QUESTION_HEAD_RE = re.compile(r"^###\s+Q(\d+)\.\s+(.+?)\s*$") +QUESTION_FIELD_RE = re.compile(r"^-\s+([a-z][a-z-]*):[ \t]*(.*?)\s*$") +QUESTION_REQUIRED = ("task", "issue", "kind", "ask", "shift", "asked", "worker") +QUESTION_KINDS = ("question", "blocked") +#: The keys each later state adds (and `reopen` strips). +QUESTION_STATE_KEYS = ("until", "deferred", "answered", "answer", "answer-comment", + "dropped") +QUESTION_STATE_REQUIRED = {"answered": ("answered", "answer"), "dropped": ("dropped",)} + + +def questions_parse(text: str) -> "tuple[list[dict], list[str]]": + """(entries, errors) for the text of `questions.md`, in file order. + + Each entry: `{id: "Q17", n: 17, title, state: open|deferred|answered| + dropped, fields: {key: value}, start, end}` โ€” `[start, end)` is its line + span, heading included, up to the next heading of any level. A fenced + block is the schema's own example; any heading ends the entry above it. + PyAutoBrain's `_questions.read` reads the same grammar (a parity test + holds the two together).""" + lines = text.split("\n") + out: "list[dict]" = [] + errors: "list[str]" = [] + state, cur, fenced = None, None, False + for i, line in enumerate(lines + ["#"]): + if line.lstrip().startswith("```"): + fenced = not fenced + continue + if fenced: + continue + if line.startswith("#"): + if cur is not None: + cur["end"] = i + out.append(cur) + cur = None + if i == len(lines): + break + if line.startswith("## ") or line.startswith("# "): + m = QUESTION_SECTION_RE.match(line) + state = m.group(1).lower() if m else None + continue + if line.startswith("### "): + m = QUESTION_HEAD_RE.match(line) + if not m: + if state is not None: + errors.append(f"heading `{line.strip()[:80]}` under ## " + f"{state.title()} is not `### Q. โ€” `") + continue + if state is None: + errors.append(f"Q{m.group(1)} sits outside the four sections " + f"({', '.join(QUESTION_SECTIONS)})") + continue + cur = {"id": f"Q{int(m.group(1))}", "n": int(m.group(1)), + "title": m.group(2), "state": state, "fields": {}, "start": i} + continue + if cur is not None: + m = QUESTION_FIELD_RE.match(line) + if m and m.group(1) not in cur["fields"]: + cur["fields"][m.group(1)] = m.group(2) + return out, errors + + +def questions_entries(root: Path) -> "list[dict]": + """The entries of `questions.md`; an absent file is an empty list.""" + try: + text = (root / "questions.md").read_text(encoding="utf-8", errors="replace") + except OSError: + return [] + return questions_parse(text)[0] + + +def questions_findings(root: Path) -> "list[Finding]": + """Every entry well-formed, its id unique, and every Open or Deferred + entry's `task:` a live prompt in `draft/` or `active/` (as a queue ref + resolves: the path itself, or `active/` once issued). An absent + file is clean.""" + try: + text = (root / "questions.md").read_text(encoding="utf-8", errors="replace") + except OSError: + return [] + entries, errors = questions_parse(text) + at = ("questions.md",) + out = [Finding(f"questions.md: {e}", at) for e in errors] + seen: "dict[str, int]" = {} + triples: "dict[tuple, str]" = {} + for e in entries: + qid, f = e["id"], e["fields"] + seen[qid] = seen.get(qid, 0) + 1 + if seen[qid] == 2: + out.append(Finding(f"questions.md: {qid} is used twice โ€” ids are unique", at)) + missing = [k for k in QUESTION_REQUIRED + QUESTION_STATE_REQUIRED.get(e["state"], ()) + if not f.get(k)] + if missing: + out.append(Finding(f"questions.md: {qid} has no {', '.join(k + ':' for k in missing)}", + at)) + if f.get("kind") and f["kind"] not in QUESTION_KINDS: + out.append(Finding(f"questions.md: {qid} has kind `{f['kind']}` โ€” one of " + f"{' | '.join(QUESTION_KINDS)}", at)) + triple = (f.get("shift"), f.get("task"), f.get("issue")) + if all(triple): + if triple in triples: + out.append(Finding(f"questions.md: {qid} repeats {triples[triple]} (same " + "shift, task and issue) โ€” keep one", at)) + triples.setdefault(triple, qid) + task = f.get("task") or "" + if e["state"] in ("open", "deferred") and task \ + and not _queue_ref_resolves(root, task): + name = Path(task).name + out.append(Finding( + f"questions.md: {qid} ({e['state']}) task `{task}` resolves to no draft/ or " + "active/ prompt โ€” answer or drop it, or fix the path", + tuple(dict.fromkeys(("questions.md", task, f"active/{name}"))))) + return out + + +def _question_block(lines: "list[str]", e: dict) -> "list[str]": + block = lines[e["start"]:e["end"]] + while block and not block[-1].strip(): + block.pop() + return block + + +def question_set_fields(block: "list[str]", fields: "dict[str, str]", + drop: "tuple[str, ...]" = ()) -> "list[str]": + """An entry's lines with each `fields` key set (its line replaced, else + appended) and each `drop` key's line removed.""" + out = [] + done = set() + for ln in block: + m = QUESTION_FIELD_RE.match(ln) + key = m.group(1) if m else None + if key in drop and key not in fields: + continue + if key in fields: + if key in done: + continue + out.append(f"- {key}: {fields[key]}") + done.add(key) + continue + out.append(ln) + out += [f"- {k}: {v}" for k, v in fields.items() if k not in done] + return out + + +def question_insert(lines: "list[str]", state: str, block: "list[str]") -> "list[str]": + """`lines` with `block` added at the end of the `## ` section.""" + fenced, head = False, None + for i, ln in enumerate(lines): + if ln.lstrip().startswith("```"): + fenced = not fenced + continue + if not fenced and (m := QUESTION_SECTION_RE.match(ln)) and m.group(1).lower() == state: + head = i + break + if head is None: + raise ValueError(f"questions.md has no `## {state.title()}` section") + end = next((j for j in range(head + 1, len(lines)) + if lines[j].startswith("## ") or lines[j].startswith("# ")), len(lines)) + last = end - 1 + while last > head and not lines[last].strip(): + last -= 1 + tail = lines[end:] + return lines[:last + 1] + [""] + list(block) + ([""] if tail else []) + tail + + +def _questions_tidy(lines: "list[str]") -> str: + return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).rstrip("\n") + "\n" + + +def question_move_text(text: str, qid: str, state: str, fields: "dict[str, str]", + drop: "tuple[str, ...]" = ()) -> str: + """`questions.md` with entry `qid` moved to the end of `## `, its + `fields` set and its `drop` keys removed. KeyError for an unknown id.""" + entries, _errs = questions_parse(text) + e = next((x for x in entries if x["id"] == qid), None) + if e is None: + raise KeyError(qid) + lines = text.split("\n") + block = question_set_fields(_question_block(lines, e), fields, drop) + rest = lines[:e["start"]] + lines[e["end"]:] + return _questions_tidy(question_insert(rest, state, block)) + + +def questions_close_text(text: str, prompt_name: str, day: str, *, + by: str = "`lifecycle.py close`") -> "tuple[str, list[str]]": + """(`questions.md` with every Open or Deferred entry whose `task:` names + `prompt_name` moved to Answered as `answer: (task completed)`, the ids + moved). Unchanged text and [] when none โ€” `lifecycle.py close` runs it as + it retires queue entries.""" + entries, _errs = questions_parse(text) + ids = [e["id"] for e in entries if e["state"] in ("open", "deferred") + and Path(e["fields"].get("task", "")).name == prompt_name] + for qid in ids: + text = question_move_text(text, qid, "answered", { + "answered": f"{day} by {by} (close)", "answer": "(task completed)"}, + drop=("until", "deferred")) + return text, ids + + def check_findings(root: Path) -> "tuple[list[Finding], list[Finding]]": """(problems, warnings) for the whole tree, each attributed to its paths. @@ -3124,6 +3334,9 @@ def check_findings(root: Path) -> "tuple[list[Finding], list[Finding]]": g_problems, g_warnings = goals_findings(root) problems.extend(g_problems) warnings.extend(g_warnings) + # Parked questions waiting for the human (M3.5, PyAutoBrain#645): a + # malformed entry or an Open one whose task is gone is drift. + problems.extend(questions_findings(root)) warnings.extend(batch_member_notes_findings(root)) warnings.extend(batch_record_warning_findings(root)) return problems, warnings @@ -3937,6 +4150,15 @@ def cmd_close(args) -> int: f"{dest.relative_to(root).as_posix()} ({args.date})") for label in queue_moved: print(f" queue: queue.md โ€” retire `{label}` to the footer (shipped-as:)") + # questions.md (M3.5): the task's Open or Deferred questions are moot once + # its work reaches complete/, and left Open their task: would dangle. + questions_md = root / "questions.md" + questions_new, questions_moved = (None, []) + if questions_md.is_file(): + questions_new, questions_moved = questions_close_text( + questions_md.read_text(encoding="utf-8"), prompt.name, args.date) + for qid in questions_moved: + print(f" question: questions.md โ€” {qid} to Answered (answer: (task completed))") # Every path this close-out writes, in the order above โ€” the explicit list # `prompt_sync_push` needs (it commits only the paths it is given). @@ -3948,6 +4170,7 @@ def cmd_close(args) -> int: *registries, *([_rel(root, log)] if row is not None else []), *(["queue.md"] if queue_moved else []), + *(["questions.md"] if questions_moved else []), ] if not args.apply: @@ -3979,6 +4202,10 @@ def cmd_close(args) -> int: queue_md.write_text(queue_new, encoding="utf-8") print(f"queue.md: retired {', '.join(queue_moved)}") + if questions_moved: + questions_md.write_text(questions_new, encoding="utf-8") + print(f"questions.md: answered {', '.join(questions_moved)} (task completed)") + if row is not None: # The row close printed in its dry run, verbatim โ€” `mergedBy` evidence # included โ€” through the same append `shadow-row` uses. diff --git a/scripts/questions_edit.py b/scripts/questions_edit.py new file mode 100644 index 000000000..51597067b --- /dev/null +++ b/scripts/questions_edit.py @@ -0,0 +1,454 @@ +#!/usr/bin/env python3 +"""Edit `questions.md`, the human's inbox of parked questions (M3.5). + +A shift worker that parks on a question leaves it on its issue; the shift +watcher adds one entry here through its one Mind writer (the `question-add` +op, which calls `add_text` from the tree it writes, PyAutoBrain#645). The +human clears the inbox in bulk, in a chat that ran `/questions` (PyAutoBrain +`skills/questions`). That skill never hand-edits the markdown: it runs this +script in a temporary Mind worktree detached on `origin/main`, then commits +with `prompt_sync_push` and runs `lifecycle.py check`. + + python3 scripts/questions_edit.py show [--open | --all] [Q] + python3 scripts/questions_edit.py add --task PATH --issue URL --kind question|blocked + --ask TEXT [--option TEXT]... --shift S + --asked T --worker K + python3 scripts/questions_edit.py answer Q --text TEXT [--comment URL] + [--by LOGIN] [--via chat|issue] + python3 scripts/questions_edit.py defer Q [--until YYYY-MM-DD] [--by LOGIN] + python3 scripts/questions_edit.py drop Q --why TEXT [--by LOGIN] + python3 scripts/questions_edit.py reopen Q + +The section an entry sits under is its state: Open, Deferred, Answered, +Dropped. Ids are global and increasing (the file's highest plus 1, worked out +in the tree being written), and `(shift, task, issue)` is unique: an add +whose triple exists is a silent repeat. `answer` also appends the answer to +the task's prompt under `## Answers from the human` (wherever the prompt is +now, `draft/` or `active/`) โ€” the next worker reads it there โ€” and prints +`prompt: ` so the caller commits that path too. A write that would add a +`lifecycle.py check` questions finding is undone and refused. + +Exit 0: done (or no change). 1: refused, nothing written. 2: usage. +""" + +from __future__ import annotations + +import argparse +import datetime as _dt +import re +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import lifecycle # noqa: E402 + +ROOT = Path(__file__).resolve().parent.parent +FILE = "questions.md" +ID_RE = re.compile(r"^#?Q?(\d+)\.?$", re.I) +ISSUE_RE = re.compile(r"^https://github\.com/[^/\s]+/([^/\s]+)/(?:issues|pull)/(\d+)") +ANSWERS_HEADING = "## Answers from the human" +ASK_MAX, OPTION_MAX, OPTIONS_MAX, SHORT_MAX = 200, 120, 4, 70 + +TEMPLATE = """# Questions + +Parked questions from shift workers, waiting for the human (M3.5, +PyAutoBrain#645). The shift watcher adds entries through its one Mind writer; +a `/questions` chat (PyAutoBrain `skills/questions`) answers, defers or drops +them with `scripts/questions_edit.py`. Never edit by hand: the section an +entry sits under is its state, and `lifecycle.py check` validates the file. +An answer releases the parked task: the next shift resumes it with the answer +in its prompt. + +```markdown +### Q. โ€” +- task: draft///.md +- issue: https://github.com///issues/ +- kind: question +- ask: +- options: (a) ยท (b) +- shift: +- asked: +- worker: +``` + +## Open + +## Deferred + +## Answered + +## Dropped +""" + + +class Refused(Exception): + """The edit is not made; the message says why.""" + + +# --------------------------------------------------------------------------- # +# reading +# --------------------------------------------------------------------------- # +def parse(text: str) -> "list[dict]": + """The entries, in file order (`lifecycle.questions_parse`).""" + return lifecycle.questions_parse(text)[0] + + +def _read(root: Path) -> str: + try: + return (root / FILE).read_text(encoding="utf-8") + except OSError: + return "" + + +def _one_line(text) -> str: + return re.sub(r"\s+", " ", str(text or "")).strip() + + +def _clip(text: str, limit: int) -> str: + text = _one_line(text) + return text if len(text) <= limit else text[:limit - 1].rstrip() + "โ€ฆ" + + +def _qid(who: str) -> str: + m = ID_RE.match((who or "").strip()) + if not m: + raise Refused(f"`{who}` is not a question id (Q)") + return f"Q{int(m.group(1))}" + + +def _find(text: str, who: str) -> dict: + qid = _qid(who) + e = next((x for x in parse(text) if x["id"] == qid), None) + if e is None: + raise Refused(f"{qid} is not in questions.md") + return e + + +def issue_short(url: str) -> str: + """`autolens_workspace#670` for an issue URL; the URL itself otherwise.""" + m = ISSUE_RE.match(url or "") + return f"{m.group(1)}#{m.group(2)}" if m else (url or "?") + + +def task_now(root: Path, task: str) -> "str | None": + """Where the task's prompt is now: the path itself, else `active/` + (a draft claimed since), else None.""" + if not task.startswith(("draft/", "active/")) or ".." in Path(task).parts: + return None + if (root / task).is_file(): + return task + act = f"active/{Path(task).name}" + return act if (root / act).is_file() else None + + +def _today() -> str: + return _dt.date.today().isoformat() + + +def _now() -> str: + return _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%MZ") + + +# --------------------------------------------------------------------------- # +# the watcher's add (a pure text function: the Mind writer calls it) +# --------------------------------------------------------------------------- # +def _labelled(options) -> str: + out = [] + for i, o in enumerate([o for o in (options or []) if _one_line(o)][:OPTIONS_MAX]): + o = _clip(o, OPTION_MAX) + out.append(o if re.match(r"^\([a-z]\)\s", o) else f"({'abcd'[i]}) {o}") + return " ยท ".join(out) + + +def entry_errors(entry: dict) -> "list[str]": + """What is wrong with an add's entry; empty when it may be added.""" + if not isinstance(entry, dict): + return ["the entry is not an object"] + errs = [f"{k} is missing" for k in lifecycle.QUESTION_REQUIRED + if not isinstance(entry.get(k), str) or not _one_line(entry.get(k))] + if entry.get("kind") and entry.get("kind") not in lifecycle.QUESTION_KINDS: + errs.append(f"kind must be one of {' | '.join(lifecycle.QUESTION_KINDS)}") + task = entry.get("task") + if isinstance(task, str) and task and (not task.startswith(("draft/", "active/")) + or ".." in Path(task).parts): + errs.append("task must be a draft/ or active/ prompt path") + opts = entry.get("options", []) + if not isinstance(opts, list) or not all(isinstance(o, str) for o in opts): + errs.append("options must be a list of strings") + return errs + + +def add_text(text: str, entry: dict, root: "Path | None" = None) -> "tuple[str, str, bool]": + """(`questions.md` with `entry` added at the end of `## Open`, its id, + whether it was added). An entry whose `(shift, task, issue)` is already + in the file is a silent repeat: (text unchanged, that id, False). + + `entry`: {task, issue, kind, ask, options: [..], shift, asked, worker}. + With `root` (the tree being written), `task` is resolved to where the + prompt is now and refused when it is in neither `draft/` nor `active/`.""" + errs = entry_errors(entry) + if errs: + raise Refused("question add: " + "; ".join(errs)) + task = _one_line(entry["task"]) + if root is not None: + now = task_now(Path(root), task) + if now is None: + raise Refused(f"question add: task {task} resolves to no draft/ or active/ prompt") + task = now + text = text if text.strip() else TEMPLATE + entries = parse(text) + issue, shift = _one_line(entry["issue"]), _one_line(entry["shift"]) + for e in entries: + f = e["fields"] + if (f.get("shift"), Path(f.get("task", "")).name, f.get("issue")) == \ + (shift, Path(task).name, issue): + return text, e["id"], False + n = max([e["n"] for e in entries] or [0]) + 1 + ask = _clip(entry["ask"], ASK_MAX) + block = [f"### Q{n}. {Path(task).stem} โ€” {_clip(ask, SHORT_MAX)}", + f"- task: {task}", f"- issue: {issue}", f"- kind: {entry['kind']}", + f"- ask: {ask}"] + options = _labelled(entry.get("options")) + if options: + block.append(f"- options: {options}") + block += [f"- shift: {shift}", f"- asked: {_one_line(entry['asked'])}", + f"- worker: {_one_line(entry['worker'])}"] + try: + lines = lifecycle.question_insert(text.split("\n"), "open", block) + except ValueError as e: + raise Refused(str(e)) + return lifecycle._questions_tidy(lines), f"Q{n}", True + + +# --------------------------------------------------------------------------- # +# writing +# --------------------------------------------------------------------------- # +def _write(root: Path, writes: "list[tuple[str, str, str]]") -> None: + """Write each `(path, old, new)`, undoing them all if they add a + `lifecycle.py check` questions finding.""" + writes = [w for w in writes if w[1] != w[2]] + if not writes: + return + before = {f.msg for f in lifecycle.questions_findings(root)} + for rel, _old, new in writes: + (root / rel).write_text(new, encoding="utf-8") + added = [f.msg for f in lifecycle.questions_findings(root) if f.msg not in before] + if added: + for rel, old, _new in writes: + p = root / rel + if old is None: + p.unlink(missing_ok=True) + else: + p.write_text(old, encoding="utf-8") + raise Refused("the edit would add lifecycle drift: " + added[0]) + + +def add(root: Path, entry: dict) -> str: + old = _read(root) + new, qid, added = add_text(old, entry, root) + if not added: + return f"{qid} already holds this question (same shift, task and issue) โ€” no change" + _write(root, [(FILE, old if (root / FILE).exists() else None, new)]) + return f"added {qid}" + + +def append_answer(prompt_text: str, line: str) -> str: + """The prompt with `line` at the end of its `## Answers from the human` + section (made at the end of the file when it has none).""" + lines = prompt_text.rstrip("\n").split("\n") + head = next((i for i, ln in enumerate(lines) if ln.strip() == ANSWERS_HEADING), None) + if head is None: + return "\n".join(lines + ["", ANSWERS_HEADING, line]) + "\n" + end = next((j for j in range(head + 1, len(lines)) if lines[j].startswith("#")), len(lines)) + last = end - 1 + while last > head and not lines[last].strip(): + last -= 1 + lines[last + 1:last + 1] = [line] + return "\n".join(lines) + "\n" + + +def answer(root: Path, who: str, text: str, comment: str = "", by: str = "", + via: str = "chat", day: str = "", at: str = "") -> "tuple[str, str | None]": + """Answer an Open or Deferred entry: (the ack, the prompt path appended to + or None when the prompt is gone).""" + old = _read(root) + e = _find(old, who) + if e["state"] not in ("open", "deferred"): + raise Refused(f"{e['id']} is {e['state']} โ€” reopen it first") + said = _one_line(text) + if not said: + raise Refused("no answer text given") + if via not in ("chat", "issue"): + raise Refused("--via is chat or issue") + comment = _one_line(comment) + if comment and not comment.startswith("https://"): + raise Refused("--comment must be the answer comment's URL") + by = _one_line(by) or "the human" + fields = {"answered": f"{at or _now()} by {by} ({via})", "answer": said} + if comment: + fields["answer-comment"] = comment + new = lifecycle.question_move_text(old, e["id"], "answered", fields, + drop=("until", "deferred")) + f = e["fields"] + writes = [(FILE, old, new)] + prompt = task_now(root, f.get("task", "")) + if prompt is not None: + line = (f"- {e['id']} ({day or _today()}, shift {f.get('shift', '?')} question on " + f"{issue_short(f.get('issue', ''))}): {said}" + (f" {comment}" if comment else "")) + ptext = (root / prompt).read_text(encoding="utf-8") + writes.append((prompt, ptext, append_answer(ptext, line))) + _write(root, writes) + if prompt is None: + return (f"answered {e['id']} (the prompt {f.get('task')} is gone โ€” the answer is " + "recorded on the entry; no task is resumed)", None) + return f"answered {e['id']}; the answer is in {prompt}", prompt + + +def defer(root: Path, who: str, until: str = "", by: str = "", day: str = "") -> str: + old = _read(root) + e = _find(old, who) + if e["state"] not in ("open", "deferred"): + raise Refused(f"{e['id']} is {e['state']} โ€” reopen it first") + until = (until or "").strip() + if until and not re.fullmatch(r"\d{4}-\d{2}-\d{2}", until): + raise Refused("--until is a date, YYYY-MM-DD") + fields = {"deferred": f"{day or _today()} by {_one_line(by) or 'the human'}"} + if until: + fields["until"] = until + new = lifecycle.question_move_text(old, e["id"], "deferred", fields, + drop=() if until else ("until",)) + _write(root, [(FILE, old, new)]) + return f"deferred {e['id']}" + (f" until {until}" if until else " to the next sitting") + + +def drop(root: Path, who: str, why: str, by: str = "", day: str = "") -> str: + old = _read(root) + e = _find(old, who) + if e["state"] not in ("open", "deferred"): + raise Refused(f"{e['id']} is {e['state']} โ€” reopen it first") + why = _one_line(why) + if not why: + raise Refused("drop needs --why") + fields = {"dropped": f"{day or _today()} by {_one_line(by) or 'the human'} โ€” {why} " + "(task shelved)"} + new = lifecycle.question_move_text(old, e["id"], "dropped", fields, + drop=("until", "deferred")) + _write(root, [(FILE, old, new)]) + return f"dropped {e['id']} โ€” its task stays held (shelved) until reopened, named in a " \ + "brief, or /add-ed" + + +def reopen(root: Path, who: str, day: str = "") -> str: + old = _read(root) + e = _find(old, who) + if e["state"] == "open": + return f"no change: {e['id']} is already open" + new = lifecycle.question_move_text(old, e["id"], "open", + {"reopened": day or _today()}, + drop=lifecycle.QUESTION_STATE_KEYS) + _write(root, [(FILE, old, new)]) + return f"reopened {e['id']} (was {e['state']})" + + +def due(e: dict, today: str) -> bool: + """Open, or Deferred with no `until:` or one that has passed.""" + if e["state"] == "open": + return True + return e["state"] == "deferred" and (e["fields"].get("until") or "") <= today + + +def show(root: Path, which: str = "", who: str = "", today: str = "") -> "list[str]": + """The inbox, oldest first. `open`: Open plus Deferred entries that are + due (a sitting's list); `all`: every entry; default: Open and Deferred.""" + entries = parse(_read(root)) + today = today or _today() + if who: + e = next((x for x in entries if x["id"] == _qid(who)), None) + if e is None: + raise Refused(f"{_qid(who)} is not in questions.md") + return [f"{e['id']} [{e['state']}] {e['title']}"] + [ + f" {k}: {v}" for k, v in e["fields"].items()] + if which == "open": + picked = [e for e in entries if due(e, today)] + elif which == "all": + picked = entries + else: + picked = [e for e in entries if e["state"] in ("open", "deferred")] + picked.sort(key=lambda e: (e["fields"].get("asked", ""), e["n"])) + out = [] + for e in picked: + f = e["fields"] + out.append(f"{e['id']} [{e['state']}] {e['title']} โ€” {issue_short(f.get('issue', ''))}" + + (f" (until {f['until']})" if f.get("until") else "")) + counts = {s.lower(): sum(e["state"] == s.lower() for e in entries) + for s in lifecycle.QUESTION_SECTIONS} + return (out or ["(no questions)"]) + [ + ", ".join(f"{n} {s}" for s, n in counts.items())] + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(prog="questions_edit.py", description=__doc__.split("\n\n")[0]) + ap.add_argument("--root", default=str(ROOT), help="the Mind checkout (default: this one)") + sub = ap.add_subparsers(dest="verb", required=True) + s = sub.add_parser("show") + g = s.add_mutually_exclusive_group() + g.add_argument("--open", dest="which", action="store_const", const="open") + g.add_argument("--all", dest="which", action="store_const", const="all") + s.add_argument("qid", nargs="?", default="") + s.add_argument("--today", default="", help=argparse.SUPPRESS) + a = sub.add_parser("add") + for k in ("task", "issue", "kind", "ask", "shift", "asked", "worker"): + a.add_argument(f"--{k}", required=True) + a.add_argument("--option", action="append", default=[]) + r = sub.add_parser("answer") + r.add_argument("qid") + r.add_argument("--text", required=True) + r.add_argument("--comment", default="") + r.add_argument("--by", default="") + r.add_argument("--via", default="chat") + r.add_argument("--date", default="", help=argparse.SUPPRESS) + r.add_argument("--at", default="", help=argparse.SUPPRESS) + d = sub.add_parser("defer") + d.add_argument("qid") + d.add_argument("--until", default="") + d.add_argument("--by", default="") + d.add_argument("--date", default="", help=argparse.SUPPRESS) + p = sub.add_parser("drop") + p.add_argument("qid") + p.add_argument("--why", required=True) + p.add_argument("--by", default="") + p.add_argument("--date", default="", help=argparse.SUPPRESS) + o = sub.add_parser("reopen") + o.add_argument("qid") + o.add_argument("--date", default="", help=argparse.SUPPRESS) + args = ap.parse_args(argv) + root = Path(args.root) + try: + if args.verb == "show": + print("\n".join(show(root, args.which or "", args.qid, args.today))) + return 0 + if args.verb == "add": + entry = {k: getattr(args, k) for k in + ("task", "issue", "kind", "ask", "shift", "asked", "worker")} + entry["options"] = list(args.option) + print(f"questions.md: {add(root, entry)}") + elif args.verb == "answer": + msg, prompt = answer(root, args.qid, args.text, args.comment, args.by, args.via, + args.date, args.at) + print(f"questions.md: {msg}") + if prompt: + print(f"prompt: {prompt}") + elif args.verb == "defer": + print(f"questions.md: {defer(root, args.qid, args.until, args.by, args.date)}") + elif args.verb == "drop": + print(f"questions.md: {drop(root, args.qid, args.why, args.by, args.date)}") + elif args.verb == "reopen": + print(f"questions.md: {reopen(root, args.qid, args.date)}") + except Refused as e: + print(f"questions_edit: refused โ€” {e}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/spawn.py b/scripts/spawn.py index e2f0dfcea..8251d6e18 100644 --- a/scripts/spawn.py +++ b/scripts/spawn.py @@ -110,6 +110,9 @@ ("queue.md", "EMPTY"), # The human's goals: instance intent, like the queue (PyAutoMind#565). ("goals.md", "EMPTY"), + # The human's inbox of parked questions (M3.5, PyAutoBrain#645): instance + # state, like the queue โ€” the format lives in questions_edit.py. + ("questions.md", "EMPTY"), ("autonomy_log.md", "SPECIAL:autonomy_log"), # Prompt-file lifecycle (issue #71): draft/ (not-started) -> active/ # (in-flight) -> complete/YYYY/MM (shipped). A fresh template ships an empty @@ -360,6 +363,7 @@ "ideas.md": "# Ideas", "queue.md": "# Queue", "goals.md": "# Goals", + "questions.md": "# Questions", "reading-queue.md": "# Reading queue", "arxiv-inbox.md": "# arXiv inbox", "arxiv-interests.md": "# arXiv interests", diff --git a/tests/test_questions_edit.py b/tests/test_questions_edit.py new file mode 100644 index 000000000..c4db3db43 --- /dev/null +++ b/tests/test_questions_edit.py @@ -0,0 +1,387 @@ +"""Contract tests for `scripts/questions_edit.py`, the questions inbox (M3.5). + +Parked shift questions land in `questions.md` (the watcher's `question-add` +op calls `add_text` from the tree it writes) and the human clears them in bulk +from a `/questions` chat (PyAutoBrain#645). The witness: add, answer, defer, +drop and reopen round-trip; an add replayed on a moved main takes the next free +id; an answer is appended to the task's prompt wherever it is now (`draft/` or +`active/`); a refused write changes nothing and leaves `lifecycle.py check` +clean; `lifecycle.py close` answers a closed task's open questions. Fictional +fixtures only (`tests/**` ships in the public template). +""" + +import os +import shutil +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + +MIND = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(MIND / "scripts")) + +import lifecycle # noqa: E402 +import questions_edit as qe # noqa: E402 + +ISSUE = "https://github.com/example-owner/flywheel/issues/70" +ISSUE2 = "https://github.com/example-owner/flywheel/issues/71" +PROMPTS = { + "draft/feature/flywheel/sprocket_calibration.md": "# Sprocket calibration\n\nBody.\n", + "draft/feature/flywheel/gearbox_rattle.md": "# Gearbox rattle\n", + "active/axle_balance.md": "# Axle balance\n\nIssued.\n", +} + + +def _entry(task="draft/feature/flywheel/sprocket_calibration.md", issue=ISSUE, + shift="2026-11-14-pm2", **kw): + e = {"task": task, "issue": issue, "kind": "question", + "ask": "Should the sprocket default to brass or steel?", + "options": ["brass, as the manual", "steel, as the pipeline"], + "shift": shift, "asked": "2026-11-14T18:12Z", "worker": "a1b2c3d4"} + e.update(kw) + return e + + +@pytest.fixture +def mind(tmp_path): + root = tmp_path / "mind" + (root / "scripts").mkdir(parents=True) + for name in ("lifecycle.py", "questions_edit.py"): + shutil.copy(MIND / "scripts" / name, root / "scripts" / name) + for rel, body in PROMPTS.items(): + p = root / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(body) + (root / "active.md").write_text( + "# Active\n\n## axle-balance\n- status: issued\n- prompt: active/axle_balance.md\n") + (root / "questions.md").write_text(qe.TEMPLATE) + return root + + +def _run(root, *args): + env = dict(os.environ, LIFECYCLE_NO_GH="1") + return subprocess.run([sys.executable, str(root / "scripts" / "questions_edit.py"), *args], + cwd=root, env=env, capture_output=True, text=True) + + +def _check(root): + """`python3 scripts/lifecycle.py check` on the fixture Mind, as the skill runs it.""" + env = dict(os.environ, LIFECYCLE_NO_GH="1") + res = subprocess.run([sys.executable, str(root / "scripts" / "lifecycle.py"), "check"], + cwd=root, env=env, capture_output=True, text=True) + assert "questions.md" not in res.stdout, res.stdout + return res + + +def _states(root): + return {e["id"]: e["state"] for e in qe.parse((root / "questions.md").read_text())} + + +def _cli_add(root, **kw): + e = _entry(**kw) + args = ["add"] + for k in ("task", "issue", "kind", "ask", "shift", "asked", "worker"): + args += [f"--{k}", e[k]] + for o in e["options"]: + args += ["--option", o] + return _run(root, *args) + + +def test_the_template_is_clean_and_empty(mind): + assert qe.parse(qe.TEMPLATE) == [] + assert lifecycle.questions_findings(mind) == [] + assert qe.show(mind)[0] == "(no questions)" + _check(mind) + + +def test_add_round_trip(mind): + res = _cli_add(mind) + assert res.returncode == 0, res.stderr + assert "questions.md: added Q1" in res.stdout + text = (mind / "questions.md").read_text() + assert ("## Open\n\n### Q1. sprocket_calibration โ€” Should the sprocket default to brass " + "or steel?\n- task: draft/feature/flywheel/sprocket_calibration.md\n" + f"- issue: {ISSUE}\n- kind: question\n" + "- ask: Should the sprocket default to brass or steel?\n" + "- options: (a) brass, as the manual ยท (b) steel, as the pipeline\n" + "- shift: 2026-11-14-pm2\n- asked: 2026-11-14T18:12Z\n- worker: a1b2c3d4\n\n" + "## Deferred") in text + [e] = qe.parse(text) + assert (e["id"], e["state"], e["fields"]["kind"]) == ("Q1", "open", "question") + # The same (shift, task, issue) again is a silent repeat. + res = _cli_add(mind) + assert res.returncode == 0 and "Q1 already holds this question" in res.stdout + assert (mind / "questions.md").read_text() == text + _check(mind) + + +def test_add_text_is_pure_and_its_id_follows_the_tree_it_is_replayed_on(mind): + """The watcher's op replays on a moved main: the id is worked out inside + the text being written, so a concurrent Q1 makes this one Q2.""" + base = qe.TEMPLATE + mine, qid, added = qe.add_text(base, _entry()) + assert (qid, added) == ("Q1", True) + moved_main, other, _ = qe.add_text(base, _entry(task="draft/feature/flywheel/gearbox_rattle.md", + issue=ISSUE2)) + assert other == "Q1" + replay, qid, added = qe.add_text(moved_main, _entry()) + assert (qid, added) == ("Q2", True) + assert [e["id"] for e in qe.parse(replay)] == ["Q1", "Q2"] + # A second replay of the same op is a repeat, not a Q3. + again, qid, added = qe.add_text(replay, _entry()) + assert (again, qid, added) == (replay, "Q2", False) + + +def test_add_with_root_resolves_a_claimed_draft_to_active(mind): + text, qid, _ = qe.add_text(qe.TEMPLATE, _entry(task="draft/feature/flywheel/axle_balance.md"), + mind) + assert qe.parse(text)[0]["fields"]["task"] == "active/axle_balance.md" + with pytest.raises(qe.Refused, match="resolves to no draft/ or active/ prompt"): + qe.add_text(qe.TEMPLATE, _entry(task="draft/feature/flywheel/gone.md"), mind) + with pytest.raises(qe.Refused, match="kind must be one of"): + qe.add_text(qe.TEMPLATE, _entry(kind="musing")) + with pytest.raises(qe.Refused, match="ask is missing"): + qe.add_text(qe.TEMPLATE, _entry(ask=" ")) + + +def test_answer_moves_the_entry_and_appends_to_a_draft_prompt(mind): + _cli_add(mind) + res = _run(mind, "answer", "Q1", "--text", "(a), and note steel in the docstring", + "--comment", f"{ISSUE}#issuecomment-9", "--by", "example-human", + "--date", "2026-11-16", "--at", "2026-11-16T09:00Z") + assert res.returncode == 0, res.stderr + assert "prompt: draft/feature/flywheel/sprocket_calibration.md" in res.stdout + assert _states(mind) == {"Q1": "answered"} + [e] = qe.parse((mind / "questions.md").read_text()) + assert e["fields"]["answered"] == "2026-11-16T09:00Z by example-human (chat)" + assert e["fields"]["answer"] == "(a), and note steel in the docstring" + assert e["fields"]["answer-comment"] == f"{ISSUE}#issuecomment-9" + prompt = (mind / "draft/feature/flywheel/sprocket_calibration.md").read_text() + assert prompt == ("# Sprocket calibration\n\nBody.\n\n## Answers from the human\n" + "- Q1 (2026-11-16, shift 2026-11-14-pm2 question on flywheel#70): (a), " + f"and note steel in the docstring {ISSUE}#issuecomment-9\n") + _check(mind) + + +def test_answer_follows_a_claimed_prompt_into_active(mind): + """The entry still names the draft/ path; the prompt has been issued since.""" + qe.add(mind, _entry(task="draft/feature/flywheel/axle_balance.md")) + qe.add(mind, _entry(task="draft/feature/flywheel/axle_balance.md", issue=ISSUE2, + ask="And the bearing?")) + msg, prompt = qe.answer(mind, "Q1", "steel", day="2026-11-16") + assert prompt == "active/axle_balance.md" + qe.answer(mind, "q2", "sealed", day="2026-11-16") + text = (mind / "active/axle_balance.md").read_text() + # One section, both answers, in order. + assert text.count("## Answers from the human") == 1 + assert text.endswith("## Answers from the human\n" + "- Q1 (2026-11-16, shift 2026-11-14-pm2 question on flywheel#70): steel\n" + "- Q2 (2026-11-16, shift 2026-11-14-pm2 question on flywheel#71): " + "sealed\n") + _check(mind) + + +def test_answer_with_the_prompt_gone_records_it_on_the_entry_only(mind): + qe.add(mind, _entry(task="draft/feature/flywheel/gearbox_rattle.md")) + (mind / "draft/feature/flywheel/gearbox_rattle.md").unlink() # completed since + # The Open entry now dangles: check reports it, and an answer clears it. + assert any("Q1 (open) task" in f.msg for f in lifecycle.questions_findings(mind)) + msg, prompt = qe.answer(mind, "Q1", "rattle fixed upstream") + assert prompt is None and "no task is resumed" in msg + assert _states(mind) == {"Q1": "answered"} + assert lifecycle.questions_findings(mind) == [] + + +def test_defer_show_open_and_reopen(mind): + qe.add(mind, _entry()) + qe.add(mind, _entry(task="draft/feature/flywheel/gearbox_rattle.md", issue=ISSUE2, + asked="2026-11-14T19:00Z")) + res = _run(mind, "defer", "Q1", "--until", "2026-11-20", "--date", "2026-11-16") + assert res.returncode == 0 and "deferred Q1 until 2026-11-20" in res.stdout + assert _states(mind) == {"Q1": "deferred", "Q2": "open"} + # A sitting's list skips a deferral that is not due yet, then shows it. + assert [ln.split()[0] for ln in qe.show(mind, "open", today="2026-11-16")[:-1]] == ["Q2"] + assert [ln.split()[0] for ln in qe.show(mind, "open", today="2026-11-20")[:-1]] == ["Q1", "Q2"] + assert qe.show(mind)[-1] == "1 open, 1 deferred, 0 answered, 0 dropped" + # Deferred with no date: due at the next sitting. + qe.defer(mind, "Q2") + assert "until" not in qe.parse((mind / "questions.md").read_text())[1]["fields"] + assert [ln.split()[0] for ln in qe.show(mind, "open", today="2026-11-16")[:-1]] == ["Q2"] + assert qe.reopen(mind, "Q1", day="2026-11-17") == "reopened Q1 (was deferred)" + e = next(x for x in qe.parse((mind / "questions.md").read_text()) if x["id"] == "Q1") + assert e["state"] == "open" and "until" not in e["fields"] and "deferred" not in e["fields"] + assert e["fields"]["reopened"] == "2026-11-17" + _check(mind) + + +def test_drop_then_reopen(mind): + qe.add(mind, _entry()) + res = _run(mind, "drop", "Q1", "--why", "not worth it", "--by", "example-human", + "--date", "2026-11-16") + assert res.returncode == 0 and "shelved" in res.stdout + [e] = qe.parse((mind / "questions.md").read_text()) + assert e["state"] == "dropped" + assert e["fields"]["dropped"] == "2026-11-16 by example-human โ€” not worth it (task shelved)" + # The prompt is untouched: dropping a question is not answering it. + assert "Answers" not in (mind / "draft/feature/flywheel/sprocket_calibration.md").read_text() + qe.reopen(mind, "Q1") + [e] = qe.parse((mind / "questions.md").read_text()) + assert e["state"] == "open" and "dropped" not in e["fields"] + _check(mind) + + +def test_answered_entries_reopen_and_lose_their_answer_keys(mind): + qe.add(mind, _entry()) + qe.answer(mind, "Q1", "brass") + qe.reopen(mind, "Q1") + [e] = qe.parse((mind / "questions.md").read_text()) + assert e["state"] == "open" + assert not {"answered", "answer", "answer-comment"} & set(e["fields"]) + + +@pytest.mark.parametrize("args,why", [ + (("answer", "Q9", "--text", "x"), "Q9 is not in questions.md"), + (("answer", "Q1", "--text", " "), "no answer text given"), + (("answer", "Q1", "--text", "x", "--comment", "not-a-url"), "--comment must be"), + (("answer", "Q1", "--text", "x", "--via", "carrier-pigeon"), "--via is chat or issue"), + (("answer", "seventeen", "--text", "x"), "is not a question id"), + (("defer", "Q1", "--until", "next week"), "--until is a date"), + (("drop", "Q1", "--why", " "), "drop needs --why"), +]) +def test_refused_writes_change_nothing_and_check_stays_clean(mind, args, why): + qe.add(mind, _entry()) + before = (mind / "questions.md").read_text() + prompt = (mind / "draft/feature/flywheel/sprocket_calibration.md").read_text() + res = _run(mind, *args) + assert res.returncode == 1 and why in res.stderr, res.stderr + assert (mind / "questions.md").read_text() == before + assert (mind / "draft/feature/flywheel/sprocket_calibration.md").read_text() == prompt + _check(mind) + + +def test_a_settled_entry_is_refused_until_reopened(mind): + qe.add(mind, _entry()) + qe.answer(mind, "Q1", "brass") + before = (mind / "questions.md").read_text() + for verb in (lambda: qe.answer(mind, "Q1", "steel"), lambda: qe.defer(mind, "Q1"), + lambda: qe.drop(mind, "Q1", "x")): + with pytest.raises(qe.Refused, match="Q1 is answered โ€” reopen it first"): + verb() + assert (mind / "questions.md").read_text() == before + + +def test_a_write_that_adds_lifecycle_drift_is_undone_with_its_prompt(mind, monkeypatch): + qe.add(mind, _entry()) + before = (mind / "questions.md").read_text() + prompt_path = mind / "draft/feature/flywheel/sprocket_calibration.md" + prompt = prompt_path.read_text() + real, calls = lifecycle.questions_findings, {"n": 0} + + def flaky(root): + calls["n"] += 1 + found = real(root) + if calls["n"] == 2: + found = found + [lifecycle.Finding("questions.md: injected", ("questions.md",))] + return found + + monkeypatch.setattr(lifecycle, "questions_findings", flaky) + with pytest.raises(qe.Refused, match="would add lifecycle drift"): + qe.answer(mind, "Q1", "brass") + assert (mind / "questions.md").read_text() == before + assert prompt_path.read_text() == prompt + + +def test_add_creates_the_file_from_the_template_when_absent(mind): + (mind / "questions.md").unlink() + assert qe.add(mind, _entry()) == "added Q1" + text = (mind / "questions.md").read_text() + assert text.startswith("# Questions\n") and "## Dropped" in text + _check(mind) + + +# --- lifecycle.py check ---------------------------------------------------------- + +def _findings(mind, text): + (mind / "questions.md").write_text(text) + return [f.msg for f in lifecycle.questions_findings(mind)] + + +def test_check_reports_malformed_and_dangling_entries(mind): + good, _q, _a = qe.add_text(qe.TEMPLATE, _entry()) + assert _findings(mind, good) == [] + dup = good.replace("## Deferred", good[good.index("### Q1"):good.index("## Deferred")] + .replace(ISSUE, ISSUE2) + "## Deferred") + assert any("Q1 is used twice" in m for m in _findings(mind, dup)) + assert any("Q1 has no worker:" in m + for m in _findings(mind, good.replace("- worker: a1b2c3d4\n", ""))) + assert any("has kind `musing`" in m + for m in _findings(mind, good.replace("kind: question", "kind: musing"))) + assert any("is not `### Q. โ€” `" in m + for m in _findings(mind, good.replace("### Q1.", "### Question 1:"))) + gone = good.replace("sprocket_calibration.md", "no_such_prompt.md") + assert any("Q1 (open) task `draft/feature/flywheel/no_such_prompt.md` resolves to no" + in m for m in _findings(mind, gone)) + # Answered and dropped entries may name a prompt that is gone; they need + # their own keys. + answered = lifecycle.question_move_text(gone, "Q1", "answered", {"answered": "t by h (chat)", + "answer": "x"}) + assert _findings(mind, answered) == [] + assert any("Q1 has no answer:" in m for m in _findings( + mind, answered.replace("- answer: x\n", ""))) + + +def test_lifecycle_check_runs_the_questions_leg(mind): + (mind / "questions.md").write_text(qe.TEMPLATE.replace("## Open", "## Open\n\n### Q1. x")) + env = dict(os.environ, LIFECYCLE_NO_GH="1") + res = subprocess.run([sys.executable, "scripts/lifecycle.py", "check"], cwd=mind, env=env, + capture_output=True, text=True) + assert res.returncode == 1 and "questions.md: Q1 has no task:" in res.stdout + + +# --- lifecycle.py close ---------------------------------------------------------- + +def test_questions_close_text_answers_the_closed_tasks_entries(): + text, _q, _a = qe.add_text(qe.TEMPLATE, _entry()) + text, _q, _a = qe.add_text(text, _entry(issue=ISSUE2, ask="Bearings?")) + text, _q, _a = qe.add_text(text, _entry(task="draft/feature/flywheel/gearbox_rattle.md")) + text = lifecycle.question_move_text(text, "Q2", "deferred", {"until": "2026-12-01"}) + out, ids = lifecycle.questions_close_text(text, "sprocket_calibration.md", "2026-11-16") + assert ids == ["Q1", "Q2"] + states = {e["id"]: (e["state"], e["fields"].get("answer"), e["fields"].get("until")) + for e in qe.parse(out)} + assert states == {"Q1": ("answered", "(task completed)", None), + "Q2": ("answered", "(task completed)", None), + "Q3": ("open", None, None)} + assert lifecycle.questions_close_text(out, "sprocket_calibration.md", "x") == (out, []) + + +def test_close_moves_the_tasks_open_questions_to_answered(tmp_path, monkeypatch): + root = tmp_path + (root / "active").mkdir() + (root / "complete").mkdir() + (root / "active" / "sprocket_calibration.md").write_text("# Sprocket calibration\n") + (root / "active.md").write_text("# Active\n\n## sprocket-calibration\n- status: x\n" + "- prompt: active/sprocket_calibration.md\n") + (root / "body.md").write_text("## sprocket-calibration\n- completed: 2026-09-17\n") + text, _q, _a = qe.add_text(qe.TEMPLATE, _entry()) + (root / "questions.md").write_text(text) + for name, value in (("ROOT", root), ("ACTIVE_DIR", root / "active"), + ("ACTIVE_MD", root / "active.md"), ("DRAFT_DIR", root / "draft"), + ("COMPLETE_DIR", root / "complete"), + ("ARCHIVE_DIR", root / "complete" / "archive"), + ("INDEX_MD", root / "complete" / "index.md"), + ("AUTONOMY_LOG", root / "autonomy_log.md")): + monkeypatch.setattr(lifecycle, name, value) + args = SimpleNamespace(slug="sprocket-calibration", date="2026-09-17", + from_file=str(root / "body.md"), prompt=None, pr=[], tier=None, + gate=None, action=None, stage="1", no_shadow_row=False, log=None, + apply=False) + assert lifecycle.cmd_close(args) == 0 + assert (root / "questions.md").read_text() == text # the dry run writes nothing + args.apply = True + assert lifecycle.cmd_close(args) == 0 + [e] = qe.parse((root / "questions.md").read_text()) + assert e["state"] == "answered" and e["fields"]["answer"] == "(task completed)" + assert lifecycle.questions_findings(root) == []