diff --git a/.claude/commands/questions.md b/.claude/commands/questions.md new file mode 120000 index 00000000..a4c929e3 --- /dev/null +++ b/.claude/commands/questions.md @@ -0,0 +1 @@ +../../skills/questions/questions.md \ No newline at end of file diff --git a/.claude/skills/questions b/.claude/skills/questions new file mode 120000 index 00000000..587cc798 --- /dev/null +++ b/.claude/skills/questions @@ -0,0 +1 @@ +../../skills/questions \ No newline at end of file diff --git a/.codex/skills/questions b/.codex/skills/questions new file mode 120000 index 00000000..587cc798 --- /dev/null +++ b/.codex/skills/questions @@ -0,0 +1 @@ +../../skills/questions \ No newline at end of file diff --git a/AUTONOMY.md b/AUTONOMY.md index 2aa340f0..8aabb43b 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -991,7 +991,7 @@ refuses the merge. A PR in any other repo makes no call at all. The revert condition covers these the same way: any other call, or a repeat for the same close-out, retires the watcher to fake mode. -**Amendment — 2026-11-16 (M3.4/M3.5; PyAutoBrain#644), approved by the human.** +**Amendment — 2026-11-16 (M3.4/M3.5; PyAutoBrain#644, #645), approved by the human.** The shift cockpit's engine (DESIGN `m3_4_m3_5_design`, rulings H4b, H5a, H6a, H8a/a, H10a). The watcher's surface gains, and only: @@ -1022,6 +1022,27 @@ human named in `/kill`, a needs-you comment beyond 5 + 1 in a shift or one with an `@`, and any network call from writing or reading `events.jsonl`: any of these retires the watcher to fake mode. +The questions inbox (M3.5, PyAutoBrain#645) changes the watcher's surface by: + +4. **Questions no longer @-mention the human.** A worker that parks with a + question, or is blocked on a person past the stall grace, gets no mention + comment. Its question lands in PyAutoMind `questions.md` through the one + Mind writer (a `question-add` op, no new network act), and the human's one + notice is a line in the digest at `review-at:` (Decision H7 a: "N + questions added to your inbox", with the dashboard link). The watcher's + comment count goes down; the status comment shows the count as an edit, + which notifies nobody. +5. **Reading `questions.md` from Mind `origin/main`** is a local `git show` + after the shift's existing once-per-shift fetch, never a pull or a second + fetch. An answered question releases its task's parked hold; the next + shift resumes it at its old standing (Decision H11 a), reusing a shift + worker's claim with the answer in its prompt. A dropped question shelves + the task (H9 a). An unreadable inbox keeps every hold. + +The revert condition also covers these: an @mention for a parked question, +or any read of `questions.md` other than that local one, retires the watcher +to fake mode. + ## Human override for Heart RED (development only) Heart RED still parks every autonomous run and blocks every release. After the diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 87a84bfc..25df54d4 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -476,6 +476,30 @@ trigger is durable state (a parked task or an un-verdicted issue in a `.done` wi marker yet), so a tick that dies between parking and posting mentions on the next; a failed mention is also retried by the late sweep. +**The questions inbox replaces those two mentions (M3.5, PyAutoBrain#645).** +A parked worker or a `.done` issue not marked `verdict:` no longer +@-mentions anyone (`_mention_triggers` returns neither; the machinery above +stays for other triggers). The reap queues one `question-add` op per issue +(`land_question`): the task's prompt, the issue, `kind: question` (or +`blocked`, filed on the shift issue), the ask and options from the worker's +`{task}.question.json` sidecar (sanitised; `see the question on the issue` +without one), the shift, the time and the worker. The one Mind writer lands +it in PyAutoMind `questions.md` through Mind's own `questions_edit.add_text`. +The digest gets one line under its heading (`Inbox: N questions added to your +inbox this shift (Q17, Q18), M open in all — `), and the +status comment a `- inbox:` count. Before planning, `_questions.read_origin` +reads `questions.md` from Mind origin/main (after the one fetch) and +`parked_elsewhere(slot, inbox, resumes)` rules on each earlier park: all its +entries answered → released and resumed at its old standing; one dropped → +shelved; one open or deferred → `waiting on Q in your inbox`; none, or an +unreadable inbox → held as before. A released task a shift worker already +claimed (`- session: shift worker …`) is graded from `active/.md` on +origin (`resume_records`), kept by `on_origin(…, resumes=)` (its own claim +does not hold its repos) and spawned with `RESUME_NOTE`; its pick's `why:` +starts `resumed after Q was answered`. The human answers in a `/questions` +chat (`skills/questions`). `batch questions --backfill` prints the +`questions_edit.py add` lines that seed the inbox from today's holds. + **Watching and steering a shift from its issue (PyAutoBrain#622).** Each open tick ends with the shift's **status comment** on the brief's `issue:`: the `batch watch` snapshot as Markdown (`_watch.render_status`, no tick log), diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index 3cef57c5..4f1a461e 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -2927,7 +2927,7 @@ def organ_for(kind: str, root: Path, slot: str) -> dict: def main(argv=None) -> int: ap = argparse.ArgumentParser(prog="batch") ap.add_argument("verb", choices=["plan", "collect", "brief", "digest", "watch", - "slice", "premise", "green"], nargs="?", + "slice", "premise", "green", "questions"], nargs="?", default="plan") ap.add_argument("prompt", nargs="?", default="", help="slice: the needs-slicing prompt to decompose; " @@ -2984,6 +2984,11 @@ def main(argv=None) -> int: ap.add_argument("--home", type=Path, default=None, help="digest / watch: the watcher's state directory " "(default: $PYAUTO_ORCHESTRATOR_HOME, else .orchestrator)") + # questions (M3.5, PyAutoBrain#645) + ap.add_argument("--backfill", action="store_true", + help="questions: print `questions_edit.py add` lines for every " + "task an earlier shift left parked and still held (reads " + "the watcher's slots and Mind origin/main; writes nothing)") # watch ap.add_argument("--once", action="store_true", help="watch: print one snapshot and exit") @@ -3062,12 +3067,27 @@ def main(argv=None) -> int: return _main_watch(a) if a.verb == "green": return _main_green(mind, a) + if a.verb == "questions": + return _main_questions(mind, a) return _main_plan(mind, a, lane) except BatchUsageError as e: print(e, file=sys.stderr) return RC_USAGE +def _main_questions(mind: Path, a) -> int: + """`batch questions --backfill` (M3.5, PyAutoBrain#645, Build B step 1): + the one-off seed of the inbox from the holds the watcher keeps today.""" + if not a.backfill: + raise BatchUsageError("batch questions: only --backfill is a verb here; the inbox " + "is answered in a /questions chat") + import _orchestrator # noqa: E402 + import _questions # noqa: E402 + home = a.home or _orchestrator.orchestrator_home() + print("\n".join(_questions.backfill(home, mind))) + return 0 + + def _main_slice(mind: Path, a) -> int: """`batch slice [--slices FILE] [--apply] [--json]` — propose the children of a needs-slicing prompt; only `--apply` writes (`_slice`).""" diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index 395d436e..16faef1f 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -22,6 +22,7 @@ from pathlib import Path import _brief # noqa: E402 +import _questions # noqa: E402 — the inbox line (M3.5, #645) # The one CI judgement (PyAutoBrain#628) lives in bin/, beside its CLI. sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "bin")) @@ -539,7 +540,13 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None, named = [Path(p).stem for p in _brief.tasks_of(brief)] backlog = [t for t in picks if t not in named] - lines = [DIGEST_HEADING, "", "### Brief work"] + lines = [DIGEST_HEADING, ""] + # The one notice of the shift's parked questions (M3.5, #645, Decision + # H7 a): no @mention mid-shift, one line here; the asks live in the inbox. + inbox = [x for x in [_questions.inbox_line(counters, Path(slot).name, mind)] + + _questions.unfiled_lines(counters) if x] + lines += inbox + [""] if inbox else [] + lines += ["### Brief work"] links = MindLinks(mind, issue) # A worker still out at review-at keeps its lease (#634, N1). held = {t: l for t, l in held_leases(slot).items() if l.get("state") != "parked"} @@ -614,6 +621,10 @@ def identity_lines(counters: dict) -> list[str]: f"{auth.get('last', '?')}: {auth['error']}"] +#: A question id in a hold's reason (`waiting on Q17 in your inbox`). +_QID_RE = re.compile(r"\bQ\d+\b") + + def backlog_gate_lines(counters: dict) -> list[str]: """What the M2.3 gates kept out of the backlog dip (AUTONOMY.md "M2 rulings — 2026-11-12"), as of the watcher's last tick. Not bullets: a @@ -645,9 +656,21 @@ def names(paths): for p, w in sorted(repo_held.items())[:SUMMARY_NAMES])) parked = gates.get("parked") or {} if parked: + # The inbox's word on each, by Q-id (M3.5, #645), so "why wasn't X + # picked" answers itself; a park from before the inbox names none. + inboxed = {p: w for p, w in parked.items() if _QID_RE.search(w)} out.append(f"Parked on a question by an earlier shift: {len(parked)} draft(s) not " "startable until answered (name one in a brief to start it again): " - + names(sorted(parked))) + + ", ".join(f"`{Path(p).stem}`" + (f" ({inboxed[p]})" if p in inboxed else "") + for p in sorted(parked)[:SUMMARY_NAMES]) + + (f" +{len(parked) - SUMMARY_NAMES} more" if len(parked) > SUMMARY_NAMES + else "")) + resumed = gates.get("resumed") or {} + if resumed: + out.append(f"Released by an answer in your inbox: {len(resumed)} task(s) back at " + "their old standing — " + "; ".join( + f"`{t}` ({', '.join(v.get('ids') or [])} answered)" + for t, v in sorted(resumed.items())[:SUMMARY_NAMES])) reach = gates.get("scoped_reach") or [] if reach: out.append(f"Backlog reach (ruling 2026-11-16): {len(reach)} unqueued draft(s) not " diff --git a/agents/conductors/batch/_events.py b/agents/conductors/batch/_events.py index ef941fb6..99351126 100644 --- a/agents/conductors/batch/_events.py +++ b/agents/conductors/batch/_events.py @@ -168,6 +168,13 @@ def count(self, prefix: str) -> int: return sum(1 for k in self.keys if (k or "").startswith(prefix)) +def _inboxed(counters: dict, task: str, issue: str | None = None) -> bool: + """Whether this tick's reap filed `task`'s question (on `issue`) in the + questions inbox (M3.5, PyAutoBrain#645: `counters["inbox"]`).""" + return any(q.get("task") == task and (issue is None or q.get("issue") == issue) + for q in counters.get("inbox") or []) + + def _outcome(event: dict, counters: dict) -> dict: """A `done` reap's outcome: the event's own fields (#644 adds them), else the task's outcome in `counters` (an old `tick.log` replay).""" @@ -198,8 +205,11 @@ def _reaped(b: _Batch, result: dict, counters: dict) -> None: task=task) elif ev == "parked": since = str(e.get("why") or "").replace("blocked since ", "") + filed = _inboxed(counters, task) b.add("parked", f"parked:{task}:{run}", - f"{task} is stuck at a prompt (since {_hhmm(since)}).", task=task) + f"{task} is stuck at a prompt (since {_hhmm(since)})." + + (" Added to your inbox." if filed else ""), task=task, + inbox=filed or None) elif ev == "done": o = _outcome(e, counters) merged = list(o.get("merged") or []) @@ -216,8 +226,13 @@ def _reaped(b: _Batch, result: dict, counters: dict) -> None: f"{task} merged {ref(pr)} in-turn (notify).", task=task, pr=pr) questions = [] if "obsolete" in o else list(o.get("questions") or []) for q in questions: + # "Added to your inbox" only when the watcher filed it (#645): + # a merged task's question, or one it could not file, is not. + filed = _inboxed(counters, task, q) b.add("question", f"question:{task}:{q}", - f"{task} parked with a question on {ref(q)}.", task=task, url=q) + f"{task} parked with a question on {ref(q)}." + + (" Added to your inbox." if filed else ""), task=task, url=q, + inbox=filed or None) if "obsolete" in o or o.get("verdicts") or not (o.get("prs") or questions): if "obsolete" in o: state = "obsolete (premise check)" @@ -368,7 +383,10 @@ def _digest_event(b: _Batch, result: dict, counters: dict) -> None: if isinstance(o, dict) and o.get("questions") and "obsolete" not in o and not o.get("merged")] parked += [t for t in counters.get("parked") or [] if t not in parked] - tail = (f" {len(parked)} task{'s' if len(parked) != 1 else ''} parked on a question." + filed = len(counters.get("inbox") or []) + tail = (f" {filed} question{'s' if filed != 1 else ''} added to your inbox." + if filed else + f" {len(parked)} task{'s' if len(parked) != 1 else ''} parked on a question." if parked else "") if post.get("url"): b.add("digest", "digest", f"Shift closed. Digest: {post['url']}.{tail}", url=post["url"]) diff --git a/agents/conductors/batch/_mind_writer.py b/agents/conductors/batch/_mind_writer.py index dd51757e..662abbd2 100644 --- a/agents/conductors/batch/_mind_writer.py +++ b/agents/conductors/batch/_mind_writer.py @@ -22,6 +22,10 @@ {"op": "table-upsert", "path": "batches/pilot/pilot.md", "key": "", "row": "| … |", "header": "…"} {"op": "record-key", "path": "batches/.md", "key": "live", "value": "…"} {"op": "queue-retire", "path": "queue.md", "prompt": "x.md", "shipped_as": " → complete/…"} + {"op": "question-add", "path": "questions.md", "entry": {"task": …, "issue": …, "kind": …, + "ask": …, "options": [...], "shift": …, + "asked": …, "worker": …}} + {"op": "question-retire", "path": "questions.md", "prompt": "x.md", "day": "YYYY-MM-DD", "by": "…"} `queue-retire` moves every live `queue.md` entry whose `ref:` names the prompt file `prompt` to the `## Retired` footer with `shipped-as:`, using @@ -33,6 +37,18 @@ stayed live, and `lifecycle.py check` then failed on the dangling ref). No live entry naming the prompt is the usual case, and it is silent. +`question-add` lands one parked worker's question in the human's inbox +(M3.5, PyAutoBrain#645) through PyAutoMind's own `scripts/questions_edit.py` +`add_text`, loaded from the tree being written as `queue-retire` loads +`lifecycle.py` — so the id (the file's highest plus 1, worked out in that +tree) is right on a replay over a moved main, and an entry whose `(shift, +task, issue)` is already there is a skipped note. A question whose prompt is +in neither `draft/` nor `active/` any more is set aside, with its reason; +any other failure (a Mind main without the script) holds it pending. +`question-retire` answers the merged task's Open and Deferred questions +(`lifecycle.questions_close_text`, what `lifecycle.py close` runs), queued +beside every `queue-retire`: an unattended close-out never runs `close`. + `jsonl-upsert` keeps one JSON line per `row[key]`: the line with that key is replaced (its other fields kept), else the row is appended. `table-upsert` does the same for a Markdown table row keyed by its first cell, keeping any @@ -86,7 +102,10 @@ from pathlib import Path OPS = ("append", "write", "move", "remove", "drop-section", "table-append", - "set-header", "jsonl-upsert", "table-upsert", "record-key", "queue-retire") + "set-header", "jsonl-upsert", "table-upsert", "record-key", "queue-retire", + "question-add", "question-retire") +#: The keys a `question-add` entry carries; all strings but `options`. +QUESTION_KEYS = ("task", "issue", "kind", "ask", "options", "shift", "asked", "worker") #: What a watcher-run queue retirement says in the footer, in place of the #: `lifecycle.py close` it did not run. QUEUE_RETIRED_BY = "retired by the shift close-out (queue-retire)" @@ -101,7 +120,12 @@ #: Op kinds only the watcher writes, and an `append` to a batch record: the #: shift's own record (digest, late lines), pilot row, live line and stage-2 #: rows. Never set aside — held pending and retried (#632 review). -CRITICAL_KINDS = ("record-key", "jsonl-upsert", "table-upsert", "table-append") +CRITICAL_KINDS = ("record-key", "jsonl-upsert", "table-upsert", "table-append", + # The questions inbox (#645): a question or its retirement + # is never lost to a passing fault (a Mind main without + # questions_edit.py yet) — held and retried; only a task + # whose prompt is gone sets a question aside (`GoneError`). + "question-add", "question-retire") def is_critical(op) -> bool: @@ -118,6 +142,11 @@ class MindWriteError(RuntimeError): pass +class GoneError(MindWriteError): + """The op's subject is gone from Mind main (a question whose prompt was + completed or retired): set aside even when the op is critical.""" + + def fetch(mind_repo: Path, remote: str = "origin", branch: str = "main") -> None: """The writer's one network read: `git fetch` of Mind `main` (refs and objects only — the working tree is never touched). The watcher also calls @@ -206,6 +235,34 @@ def validate_op(op: dict, lm) -> list[str]: errs.append("queue-retire: prompt must be a bare prompt file name (x.md)") if not isinstance(shipped, str) or not shipped.strip() or "\n" in shipped: errs.append("queue-retire: shipped_as must be one non-empty line") + if kind == "question-add": + entry = op.get("entry") + if op.get("path") != "questions.md": + errs.append("question-add: path must be questions.md") + if not isinstance(entry, dict): + errs.append("question-add: entry must be an object") + else: + extra = sorted(set(entry) - set(QUESTION_KEYS)) + if extra: + errs.append(f"question-add: unknown entry keys {', '.join(extra)}") + for k in QUESTION_KEYS: + v = entry.get(k) + if k == "options": + if not isinstance(v, list) or not all(isinstance(o, str) for o in v): + errs.append("question-add: options must be a list of strings") + elif not isinstance(v, str) or not v.strip() or "\n" in v: + errs.append(f"question-add: {k} must be one non-empty line") + if kind == "question-retire": + if op.get("path") != "questions.md": + errs.append("question-retire: path must be questions.md") + if not isinstance(op.get("prompt"), str) or not re.fullmatch(r"[^/\s]+\.md", + op["prompt"]): + errs.append("question-retire: prompt must be a bare prompt file name (x.md)") + if not isinstance(op.get("day"), str) or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", + op["day"]): + errs.append("question-retire: day must be YYYY-MM-DD") + if not isinstance(op.get("by"), str) or not op["by"].strip() or "\n" in op["by"]: + errs.append("question-retire: by must be one non-empty line") if kind == "set-header": key, value = op.get("key"), op.get("value") if not isinstance(key, str) or not re.fullmatch(r"[A-Z][A-Za-z-]*", key): @@ -325,6 +382,38 @@ def apply_op(tree: Path, op: dict, lm, ctx: dict | None = None) -> str | None: f"failed: {type(exc).__name__}: {exc}") from exc if moved: target.write_text(_retired_by(new, len(moved)), encoding="utf-8") + elif kind == "question-add": + text = target.read_text(encoding="utf-8") if target.exists() else "" + qe = _mind_module(tree, "questions_edit", deps=("lifecycle",)) + try: + gone = qe.task_now(tree, op["entry"]["task"]) is None + except Exception as exc: # see queue-retire: Mind's script, not ours + raise MindWriteError(f"question-add: questions_edit.task_now failed: " + f"{type(exc).__name__}: {exc}") from exc + if gone: + raise GoneError(f"question-add: task {op['entry']['task']} is in neither draft/ " + "nor active/ on Mind main — set aside, nothing to resume") + try: + new, qid, added = qe.add_text(text, op["entry"], tree) + except MindWriteError: + raise + except Exception as exc: # Mind main's script is not ours (see queue-retire) + raise MindWriteError(f"question-add: questions_edit.add_text refused: " + f"{type(exc).__name__}: {exc}") from exc + if not added: + return f"question-add: already in questions.md as {qid} — skipped" + target.write_text(new, encoding="utf-8") + elif kind == "question-retire": + if not target.exists(): + return None # no inbox on this Mind: nothing can dangle + try: + new, ids = _mind_module(tree, "lifecycle").questions_close_text( + target.read_text(encoding="utf-8"), op["prompt"], op["day"], by=op["by"]) + except Exception as exc: # see queue-retire + raise MindWriteError(f"question-retire: lifecycle.questions_close_text failed: " + f"{type(exc).__name__}: {exc}") from exc + if ids: + target.write_text(new, encoding="utf-8") elif kind == "jsonl-upsert": target.parent.mkdir(parents=True, exist_ok=True) target.write_text(jsonl_upsert(target.read_text(encoding="utf-8") @@ -338,13 +427,22 @@ def apply_op(tree: Path, op: dict, lm, ctx: dict | None = None) -> str | None: encoding="utf-8") -def _mind_module(tree: Path, name: str): +def _mind_module(tree: Path, name: str, deps: tuple = ()): """A PyAutoMind `scripts/.py`, compiled from `tree` (the temporary worktree on origin/main) as `_ledger_merge` compiles its own: no import, - so no `__pycache__` is written anywhere.""" + so no `__pycache__` is written anywhere. + + `deps` are the sibling scripts it imports (`questions_edit` imports + `lifecycle`): each is compiled from the same tree and served under its own + name while the module runs, then removed — as is any `sys.path` entry the + module adds — so nothing from one tree outlives the op.""" path = Path(tree) / "scripts" / f"{name}.py" if not path.is_file(): raise MindWriteError(f"no scripts/{name}.py on Mind main") + saved_path = list(sys.path) + saved = {d: sys.modules.get(d) for d in deps} + for d in deps: + sys.modules[d] = _mind_module(tree, d) mod_name = f"_mind_{name}" mod = types.ModuleType(mod_name) mod.__file__ = str(path) @@ -353,6 +451,12 @@ def _mind_module(tree: Path, name: str): exec(compile(path.read_text(encoding="utf-8"), str(path), "exec"), mod.__dict__) finally: sys.modules.pop(mod_name, None) + sys.path[:] = saved_path + for d, m in saved.items(): + if m is None: + sys.modules.pop(d, None) + else: + sys.modules[d] = m return mod @@ -663,6 +767,9 @@ def commit_ledger(slot: Path, mind_repo: Path, message: str, (held if is_critical(op) else failed)[f] = ( "held" if is_critical(op) else "conflict", str(e)) continue + except GoneError as e: + failed[f] = ("set-aside", str(e)) + continue except (MindWriteError, OSError, KeyError, TypeError, ValueError) as e: (held if is_critical(op) else failed)[f] = ( "held" if is_critical(op) else "set-aside", diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 9345b973..24036029 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -23,9 +23,11 @@ Nothing here commits, merges or arms a timer: the systemd timer that calls `bin/orchestrator_watch.py` is installed by the human. Its only GitHub writes are the comments AUTONOMY.md "The watcher's network surface" lists — the -digest, one @mention per worker per state that needs the human (#611), one -correction for a late arrival (#610) and one live status comment, then only -edited (#622) — each claimed by marker first. Each open tick also reads the +digest, one correction for a late arrival (#610) and one live status +comment, then only edited (#622) — each claimed by marker first. A parked +worker's question no longer @-mentions the human (M3.5, #645): it lands in +PyAutoMind `questions.md` through the one Mind writer, and the digest counts +it. Each open tick also reads the shift issue's comments once, for the human's `/pause` `/resume` `/drop` `/stop` (#622) and `/add` `/cap` `/kill` (#644). Every tick that does work appends what it did to the slot's `events.jsonl` (`_events`, #644), which @@ -49,6 +51,7 @@ import _digest # noqa: E402 import _events # noqa: E402 import _mind_writer # noqa: E402 +import _questions # noqa: E402 STOP_FILE = "STOP" LOCK_FILE = "tick.lock" @@ -233,7 +236,7 @@ def __init__(self, seconds: float = 0.5, crash: set[str] | None = None): self.crash = set(crash or ()) def spawn(self, task: str, prompt_path: str, lease_dir: Path, - redispatch: bool = False) -> dict: + redispatch: bool = False, resume: dict | None = None) -> dict: mode = "crash" if task in self.crash else "ok" proc = subprocess.Popen( [sys.executable, "-c", _FAKE_WORKER, str(lease_dir), task, mode, @@ -269,11 +272,38 @@ def pr_state(self, url: str) -> dict: """ +#: Prepended to the prompt of a task resumed after the human answered the +#: question an earlier shift parked it on (M3.5, PyAutoBrain#645, Decision H11). +RESUME_NOTE = """\ +This task parked on a question in shift `{shift}` and the human has answered +it ({ids}): see "## Answers from the human" in your prompt{comments}. The +canonical Mind checkout is not pulled mid-shift, so read the prompt from +`git -C show origin/main:`. The answer: +{answers} +Its claim, issue, branch and worktree may exist: reuse them (look before you +create, as a re-dispatch does: `git -C show origin/main:active.md`), +continue from where the earlier worker stopped, and do not queue the claim +again. + +""" + + +def resume_note(resume: dict) -> str: + """`RESUME_NOTE` filled in from a `parked_elsewhere` release.""" + comments = [c for c in resume.get("comments") or [] if c] + return RESUME_NOTE.format( + shift=resume.get("shift", "?"), ids=", ".join(resume.get("ids") or []) or "?", + comments=(" (and " + ", ".join(comments) + ")") if comments else "", + answers="\n".join(f"> {a}" for a in resume.get("answers") or []) or "> (see the prompt)") + + def worker_prompt(task: str, prompt_path: str, brief_path: Path, lease_dir: Path, - redispatch: bool = False) -> str: + redispatch: bool = False, resume: dict | None = None) -> str: """The session template filled in for one task; a re-dispatch is told - that its predecessor's claim may already exist (#632).""" + that its predecessor's claim may already exist (#632), and a resumed + task that the human answered its question (M3.5, #645).""" head = REDISPATCH_NOTE.format(task=task, task_path=prompt_path) if redispatch else "" + head += resume_note(resume) if resume else "" return head + WORKER_TEMPLATE.read_text(encoding="utf-8").format( task=task, task_path=prompt_path, brief_path=brief_path, lease_dir=lease_dir, ledger_dir=Path(lease_dir).parent / _mind_writer.LEDGER_DIR, @@ -352,7 +382,8 @@ def worker_env(lease_dir: Path, base: dict | None = None) -> dict: def session_command(task: str, prompt_path: str, brief_path: Path, lease_dir: Path, - mode: str, redispatch: bool = False) -> list[str]: + mode: str, redispatch: bool = False, + resume: dict | None = None) -> list[str]: """The exact argv that starts one worker — named, moded, templated. No `--session-id`: `claude --bg` (2.1.316) assigns its own, so the worker is @@ -361,7 +392,7 @@ def session_command(task: str, prompt_path: str, brief_path: Path, lease_dir: Pa raise OrchestratorError(f"worker mode {mode!r} is not one of " + ", ".join(_brief.WORKER_MODES)) return ["claude", "--bg", "--name", f"shift:{task}", "--permission-mode", mode, - worker_prompt(task, prompt_path, brief_path, lease_dir, redispatch)] + worker_prompt(task, prompt_path, brief_path, lease_dir, redispatch, resume)] #: `claude --bg` prints `backgrounded · <8-hex id> · ` on its first line. @@ -449,9 +480,9 @@ def pr_state(self, url: str) -> dict | None: return self.gh(url) def spawn(self, task: str, prompt_path: str, lease_dir: Path, - redispatch: bool = False) -> dict: + redispatch: bool = False, resume: dict | None = None) -> dict: argv = session_command(task, prompt_path, self.brief_path, lease_dir, self.mode, - redispatch) + redispatch, resume) res = run_scoped(self.run, argv, task, cwd=self.cwd, capture_output=True, text=True, timeout=120, env=worker_env(lease_dir)) # An untrusted folder is refused here, fast ("Workspace not trusted") — @@ -937,6 +968,15 @@ def mark(word, rec=rec): # The digest reads these at review-at, long after the marker is gone. counters["outcomes"][task] = _digest.parse_done( done_marker.read_text(encoding="utf-8", errors="replace")) + # Each question lands in the inbox (M3.5, #645): one Mind writer + # op per issue, queued before the counters write; a replay after a + # crash is a silent repeat in `questions_edit.add_text`. + done = counters["outcomes"][task] + if done.get("questions") and "obsolete" not in done and not done.get("merged"): + for url in done["questions"]: + ask, options = _questions.sidecar(lease_dir, task, url) + land_question(slot, counters, lease, task, url, "question", ask, + options, rec.get("key") or task, now) if task not in counters["done"]: counters["done"].append(task) if task in counters["parked"]: @@ -950,6 +990,11 @@ def mark(word, rec=rec): retire = queue_retire_op(counters, task, pr, now, by="the shift worker, in-turn") if retire: _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, retire) + # Its inbox questions are moot once merged (#645 review): + # answered as `(task completed)`, as `lifecycle.py close` would. + _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, + question_retire_op(counters, task, now, + by="the shift worker, in-turn")) break _write_counters(slot, counters) proof = lease_dir / f"{task}.proof.md" @@ -983,6 +1028,11 @@ def mark(word, rec=rec): if task not in counters["parked"]: counters["parked"].append(task) mark("parked") + key = rec.get("key") or task + land_question(slot, counters, lease, task, lease.get("shift_issue") or "", + "blocked", + f"the worker stopped at a prompt nobody answered (session " + f"{key}, since {since})", [], key, now) _write_counters(slot, counters) lease.update(state="parked", parked_at=_iso(now)) events.append({"task": task, "event": "parked", @@ -1023,6 +1073,35 @@ def mark(word, rec=rec): return events +def land_question(slot: Path, counters: dict, lease: dict, task: str, issue: str, + kind: str, ask: str, options: list, worker: str, + now: _dt.datetime) -> bool: + """Queue one `question-add` op for the Mind writer (M3.5, #645) and note + it in `counters["inbox"]`. Nothing without the task's prompt or an issue + (a lease from before M3.5 carries no shift issue: held as before). The + watcher never reads the issue: the ask is the worker's sidecar, else + `see the question on the issue`. True when it was queued.""" + prompt = lease.get("prompt") or (counters["picks"].get(task) or {}).get("prompt") or "" + why = ("no prompt recorded for the task" if not prompt + else "no shift issue on its lease (spawned before M3.5)" if not issue + else f"issue `{str(issue)[:80]}` is not an https URL" + if not str(issue).startswith("https://") else "") + if why: + # Never silent (#645 review): the digest names what was not filed. + unfiled = counters.setdefault("inbox_unfiled", []) + if not any(u.get("task") == task and u.get("kind") == kind for u in unfiled): + unfiled.append({"task": task, "kind": kind, "why": why}) + return False + entry = {"task": prompt, "issue": issue, "kind": kind, + "ask": _questions.sanitise(ask, _questions.ASK_MAX), + "options": list(options or []), "shift": Path(slot).name, + "asked": now.strftime("%Y-%m-%dT%H:%MZ"), "worker": str(worker)} + if not _questions.note_added(counters, entry): + return False + _mind_writer.queue_op(Path(slot) / _mind_writer.LEDGER_DIR, _questions.add_op(entry)) + return True + + def _parse_iso(value: str) -> _dt.datetime: return _dt.datetime.fromisoformat(value.replace("Z", "+00:00")) @@ -1198,7 +1277,7 @@ def git(*args): + (active.stderr or "").strip()[:160]} sections = claim_sections(active.stdout if active.returncode == 0 else "") return {"drafts": set(filter(None, tree.stdout.split("\0"))), "active": set(sections), - "repos": claimed_repos(sections)} + "repos": claimed_repos(sections), "sections": sections} #: A claim that records human-authorized sharing of its repos (#637, item 4). @@ -1231,8 +1310,10 @@ def flush(): continue if ln.strip(): inside = False + keys = dict(re.findall(r"(?m)^- (session|prompt):[ \t]*(.*?)\s*$", "\n".join(body))) out[slug] = {"repos": repos, - "coordinated": bool(_COORDINATION_RE.search("\n".join(body)))} + "coordinated": bool(_COORDINATION_RE.search("\n".join(body))), + "session": keys.get("session", ""), "prompt": keys.get("prompt", "")} for ln in active_text.splitlines(): if ln.startswith("## "): flush() @@ -1261,8 +1342,31 @@ def claimed_repos(sections: dict[str, dict]) -> dict[str, tuple[str, str]]: return out +#: A claim's `- session:` that names a shift worker, in exactly the wording +#: `worker_template.md` pins: `shift worker ()`. Anything +#: else (a desktop session, a human who took the task over and rewrote the +#: line, the free wording of the first shifts) is not resumed unattended. +SHIFT_WORKER_SESSION_RE = re.compile(r"^shift worker ([A-Za-z0-9_.-]+) \(([^()\s]+)\)$") + + +def shift_worker_slot(session: str) -> str: + """The slot a `- session:` line names, when it is a shift worker's; else "".""" + m = SHIFT_WORKER_SESSION_RE.match((session or "").strip()) + return m.group(1) if m else "" + + +def claim_of(sections: dict[str, dict], task: str) -> tuple[str, dict] | None: + """(slug, section) of the `active.md` claim on a task: the section named + for it, else the one whose `- prompt:` is its file (a worker picks its + own slug).""" + if task in sections: + return task, sections[task] + return next(((s, sec) for s, sec in sections.items() + if Path(sec.get("prompt") or "").stem == task), None) + + def on_origin(records: list[dict], mind: Path, own: set[str], - fetch=None) -> tuple[list[dict], dict]: + fetch=None, resumes: dict | None = None) -> tuple[list[dict], dict]: """`records` without the drafts Mind origin/main no longer holds as unclaimed: a path not under its `draft/` (moved to `active/`, retired, or never pushed — the writer's claim move would fail) or a task with a @@ -1270,17 +1374,48 @@ def on_origin(records: list[dict], mind: Path, own: set[str], stays (its own re-dispatch). A task whose repo a claim in that `active.md` holds is out too, unless the claim records human-authorized coordination (PyAutoBrain#637, item 4: a named task started twice, then - parked on a repo an earlier shift's pick held). Returns (kept, {path: why}).""" + parked on a repo an earlier shift's pick held). Returns (kept, {path: why}). + + `resumes` are the tasks an answer released (M3.5, #645, Decision H11): a + resume task already claimed is kept, at its `active/` path, but only when + its claim's `- session:` is `shift worker ()` for a slot of + this home that picked it — a claim an interactive session owns, or one a + human took over, is the human's work and is left alone. Its own claim + never counts against its repos; every other claim on them does.""" claims = origin_claims(mind, fetch=fetch) if claims is None: return records, {} + resumes = resumes or {} kept, out = [], {} for r in records: task = task_id(r.get("path") or "") + claim = claim_of(claims.get("sections") or {}, task) if task in resumes \ + and "error" not in claims else None if task in own: kept.append(r) elif "error" in claims: out[r["path"]] = f"Mind {claims['error']} — fail closed" + elif claim is not None: + slug, sec = claim + mine = {_repo_key(x) for x in r.get("declared_repos") or r.get("repos") or []} + ids = ", ".join(resumes[task].get("ids") or []) + if shift_worker_slot(sec.get("session")) not in (resumes[task].get("picked_in") + or ()): + # Only a claim this watcher's own shift worker wrote, with the + # pinned wording and a slot that picked the task: a session + # line a human rewrote (or never a shift's) is the human's. + out[r["path"]] = (f"resumed after {ids}, but its claim `{slug}` in active.md " + "is not this home's shift worker's (session: " + f"{(sec.get('session') or 'none')[:60]}) — left to the human") + elif held := next(((repo, other) for other, sec2 in claims["sections"].items() + if other != slug and not sec2["coordinated"] + for repo in sec2["repos"] if _repo_key(repo) in mine), None): + # Every other claim on the repo counts, not only the first + # (`claimed_repos` keeps one per repo): its own does not. + out[r["path"]] = (f"repo {held[0]} claimed by `{held[1]}` in active.md on " + "Mind origin/main") + else: + kept.append(r) elif r["path"] not in claims["drafts"]: out[r["path"]] = "not in draft/ on Mind origin/main (claimed or retired)" elif task in claims["active"]: @@ -1295,14 +1430,31 @@ def on_origin(records: list[dict], mind: Path, own: set[str], return kept, out -def parked_elsewhere(slot: Path) -> dict[str, str]: +def parked_elsewhere(slot: Path, inbox: dict | None = None, + resumes: dict | None = None) -> dict[str, str]: """{task: why} for every task an earlier shift in this watcher's home left parked on a question — a `question:` (or other push) issue in its `.done`, or blocked on a person past the grace — and that no later shift finished (PyAutoBrain#637, item 3: a prompt still in `draft/` with no claim was picked again by the next shift). Read from the slots' own `counters.json`: - local files, no network.""" + local files, no network. + + `inbox` is `questions.md` on Mind origin/main (`_questions.read_origin`, + M3.5 #645). Per task parked in shift `d`: every inbox entry for it from + `d` answered → released, and recorded in `resumes` (`{task: {shift, ids, + comments}}`); one dropped → held, shelved (Decision H9 a); one open or + deferred → held, waiting on it; none (a park from before M3.5), or an + unreadable inbox (None) → held as before (fail closed). + + A release is used up by the first later shift that picks the task: if + that worker is still out at its review-at, crashes or is abandoned, the + task is held again, never resumed twice on one claim. Only an answer + given after that pick (a re-answer, or a new question answered) releases + it again; a brief that names it is the human's word, as before.""" out: dict[str, str] = {} + released: dict[str, dict] = {} + picked_in: dict[str, list[str]] = {} + used: dict[str, tuple[str, str]] = {} # task → (pick time, slot) of a used release home = Path(slot).parent try: others = sorted(d for d in home.iterdir() @@ -1313,27 +1465,107 @@ def parked_elsewhere(slot: Path) -> dict[str, str]: c = _safe_counters(d) if not c: continue - held = dict(out) + held, freed = dict(out), dict(released) + touched: set[str] = set() + + def park(task: str, why: str, d=d, held=held, freed=freed, touched=touched) -> None: + """Hold `task`, unless the inbox answered its questions from `d`.""" + rule, info = _questions.hold_for(task, d.name, inbox) + touched.add(task) + used.pop(task, None) + freed.pop(task, None) + if rule == "answered": + held.pop(task, None) + freed[task] = info + elif rule == "dropped": + held[task] = (f"question {', '.join(info['ids'])} dropped by the human: task " + "shelved (reopen it, name it in a brief, or /add it)") + elif rule == "waiting": + held[task] = f"waiting on {', '.join(info['ids'])} in your inbox" + else: + held[task] = why try: for task, o in c["outcomes"].items(): if not isinstance(o, dict): raise TypeError(f"outcome of {task!r} is not an object") if o.get("questions") and "obsolete" not in o and not o.get("merged"): - held[task] = (f"parked on a question in shift {d.name} (" - + ", ".join(map(str, o["questions"])) - + ") — not startable until answered") + park(task, f"parked on a question in shift {d.name} (" + + ", ".join(map(str, o["questions"])) + + ") — not startable until answered") elif o.get("prs") or o.get("verdicts") or "obsolete" in o: held.pop(task, None) # finished since: answered + freed.pop(task, None) + used.pop(task, None) + touched.add(task) for task in c["parked"]: if task not in c["outcomes"]: - held[str(task)] = (f"parked in shift {d.name} (blocked on a person) — " - "not startable until answered") + park(str(task), f"parked in shift {d.name} (blocked on a person) — " + "not startable until answered") + for task in c.get("picks") or {}: + picked_in.setdefault(task, []).append(d.name) + if task in released and task in freed and task not in touched: + # Picked on the release, and no park or finish since: + # still out, crashed or abandoned. The release is used. + info = freed.pop(task) + at = max((str(w.get("spawned") or "") for w in c.get("workers") or [] + if w.get("task") == task), default="") or d.name + used[task] = (at, d.name) + held[task] = (f"resumed in shift {d.name} after " + f"{', '.join(info.get('ids') or [])} and not finished — " + "not resumed again until a new answer (or name it in a " + "brief)") except (AttributeError, TypeError, ValueError) as e: # One malformed file holds nothing and releases nothing (#637 review). print(f"orchestrator: {d.name}/{COUNTERS_FILE} has the wrong shape ({e}) — " "read as no hold", file=sys.stderr) continue - out = held + out, released = held, freed + # A used release comes back only with an answer given after that pick. + for task, (at, where) in used.items(): + info = _questions.answered_since(task, inbox, at) + if info is not None and task in out: + out.pop(task) + released[task] = info + for task, info in released.items(): + info["picked_in"] = list(picked_in.get(task) or []) + if resumes is not None: + resumes.update(released) + return out + + +def resume_records(records: list[dict], mind: Path, resumes: dict, + ref: str = "origin/main") -> list[dict]: + """`records` with each released task that a shift already claimed graded + from its `active/.md` on Mind origin/main (M3.5, #645): `survey` + reads only `draft/`, and the canonical checkout nobody pulls mid-shift may + still show the stale draft, which `on_origin` would drop. A task still in + `draft/` on origin keeps its draft record. Each resume record carries + `resume` (its ids) for the pick's `why:`. Local git only.""" + import _batch # noqa: E402 — deferred, as in `_tick_body` + import tempfile + if not resumes: + return records + out = [r for r in records] + for task, info in resumes.items(): + try: + shown = subprocess.run(["git", "-C", str(mind), "show", f"{ref}:active/{task}.md"], + capture_output=True, text=True, timeout=60) + except (OSError, subprocess.SubprocessError): + shown = None + if shown is not None and shown.returncode == 0 and shown.stdout.strip(): + with tempfile.TemporaryDirectory(prefix="resume-") as tmp: + f = Path(tmp) / "active" / f"{task}.md" + f.parent.mkdir() + f.write_text(shown.stdout, encoding="utf-8") + g = _batch.grade(f, Path(tmp)) + text = shown.stdout + g.update(looks_shipped=False, epic=_batch._epic_of(text), + phase=_batch._phase_of(text), done=_batch._is_done(text), + themes=_batch._themes_of(text), title=_batch._title_of(text)) + out = [r for r in out if task_id(r["path"]) != task] + [g] + for r in out: + if task_id(r["path"]) == task: + r["resume"] = dict(info) return out @@ -1390,18 +1622,27 @@ def plan() -> dict: # human's word that it is; a task this shift picked stays. Read # first, so the digest gives the park as the reason. named = {Path(t).name for t in _brief.tasks_of(brief)} - parked = parked_elsewhere(slot) + # The inbox releases a hold once its questions are answered (M3.5, + # #645): read from Mind origin/main after the shift's one fetch. + resumes: dict = {} + inbox = _questions.read_origin(mind, fetch=lambda: _fetch_once(mind, counters, now)) + parked = parked_elsewhere(slot, inbox, resumes) planned["parked"] = {r["path"]: parked[task_id(r["path"])] for r in recs if task_id(r["path"]) in parked and task_id(r["path"]) not in counters["picks"] and Path(r["path"]).name not in named} recs = [r for r in recs if r["path"] not in planned["parked"]] + resumes = {t: v for t, v in resumes.items() if t not in counters["picks"]} + recs = resume_records(recs, mind, resumes) # Against Mind origin/main, not the canonical checkout nobody # pulls mid-shift (#632, F4): a draft another shift already # claimed is never picked again, nor one whose repo a claim holds. recs, claimed = on_origin(recs, mind, set(counters["picks"]), - fetch=lambda: _fetch_once(mind, counters, now)) + fetch=lambda: _fetch_once(mind, counters, now), + resumes=resumes) planned["claimed"] = claimed + planned["resume"] = {t: v for t, v in resumes.items() + if any(task_id(r["path"]) == t for r in recs)} # Unattended by construction: an absent Lane is excluded and an # empty queue.md stops the backlog dip (M2.3, AUTONOMY.md "M2 # rulings — 2026-11-12"). Recorded each tick so the digest can say so. @@ -1460,6 +1701,7 @@ def known(task: str) -> bool: "queue_stop": d["queue_stop"], "origin": planned.get("claimed") or {}, "parked": planned.get("parked") or {}, + "resumed": planned.get("resume") or {}, "scoped_reach": sorted(d.get("scoped_reach") or [])} paused = bool(counters.get("paused")) if _brief.is_shadow(brief): @@ -1526,6 +1768,9 @@ def known(task: str) -> bool: "heartbeat": _iso(now), "expires": _iso(now + _dt.timedelta(seconds=grace_s)), "pid": 0, "session_id": None, "worktree": None} + if (shift or {}).get("issue"): + # Where a worker blocked past the grace is filed in the inbox (#645). + lease["shift_issue"] = shift["issue"] lease_path = slot / "leases" / f"{task}.json" if not _create_exclusive(lease_path, lease): continue # a lease appeared since we read them: never a second worker @@ -1533,6 +1778,8 @@ def known(task: str) -> bool: # Only a re-dispatch passes the flag, so a spawner without it # (a test's) is called exactly as before. again = {"redispatch": True} if task in counters["pending_redispatch"] else {} + if member.get("resume"): + again["resume"] = member["resume"] # answered: RESUME_NOTE (#645) lease.update(spawner.spawn(task, member["path"], slot / "leases", **again)) except Exception as e: # One task's failed launch is that task's refusal, not the tick's: @@ -1756,25 +2003,19 @@ def mention_login() -> str: def _mention_triggers(counters: dict, held: dict) -> list[tuple[str, str, str]]: - """(task, state, reason) for each worker that needs the human — the push - test (AUTONOMY.md): a worker blocked on a person past the grace (parked), - or one whose `.done` names an issue not marked `verdict:` (`question:`, a - bare URL or any other marker — #632: the test fails toward the human). - Read from durable state (`counters.json`, the leases), not from this - tick's events, so a tick that died between parking a worker and posting - still mentions it on the next; the marker makes it once. A posted - `verdict:`, a crash, a refusal, a finished worker or an obsolete premise - waits for the digest.""" - out = [] - for task in counters["parked"]: - since = (held.get(task) or {}).get("stalled_since") - out.append((task, "parked", "blocked on a person" - + (f" (blocked since {since})" if since else ""))) - for task, o in counters["outcomes"].items(): - if o.get("questions") and "obsolete" not in o: - out.append((task, "awaiting-input", - "parked on its issue with a question: " + ", ".join(o["questions"]))) - return out + """(task, state, reason) for each worker that needs the human's @mention + on the shift issue. Since M3.5 (#645) none: a worker blocked on a person + past the grace (parked) and one whose `.done` names an issue not marked + `verdict:` both land in the questions inbox instead (`land_question`), + and the digest's one inbox line is their notice. The mention machinery + (markers, retries, the late sweep) stays for other triggers; a trigger is + read from durable state (`counters.json`, the leases), never from one + tick's events, so a tick that died before posting still mentions once.""" + # M3.5 (#645, Decision H7 a; memory `parked-questions-bulk-inbox`: never + # ask mid-run): a parked worker and a question no longer @-mention the + # human. Each lands in `questions.md` (`land_question`), and the digest + # says how many at review-at. The machinery stays for other triggers. + return [] def mention_body(login: str, slot_name: str, task: str, state: str, reason: str, @@ -2306,7 +2547,8 @@ def _cmd_add(slot: Path, counters: dict, arg: str, who: str, at: str, ctx: dict) kept, claimed = on_origin([rec], mind, set()) if not kept: return f"refused: {task}: {claimed.get(rel) or 'claimed on Mind origin/main'}" - was_parked = task in parked_elsewhere(slot) + # The inbox's word on earlier parks (#645): an answered park is not "was parked". + was_parked = task in parked_elsewhere(slot, _questions.read_origin(mind)) counters.setdefault("added", {})[task] = {"prompt": rel, "by": who, "at": at, "record": rec} notes = "".join([" (was excluded in the brief)" if excluded else "", " (was parked)" if was_parked else ""]) @@ -2925,6 +3167,16 @@ def queue_retire_op(counters: dict, task: str, pr: str, now: _dt.datetime, "shipped_as": f"{pr} (merged by {by}, {now.strftime('%Y-%m-%d')})"} +def question_retire_op(counters: dict, task: str, now: _dt.datetime, + by: str = "the unattended close-out") -> dict: + """The ledger op that answers a merged task's Open and Deferred inbox + questions as `(task completed)` (`lifecycle.questions_close_text`). + Queued beside `queue_retire_op`, which has already checked the prompt.""" + prompt = (counters.get("picks", {}).get(task) or {}).get("prompt") or "" + return {"op": "question-retire", "path": "questions.md", "prompt": Path(prompt).name, + "day": now.strftime("%Y-%m-%d"), "by": by} + + def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_state, tokens=transcript_usage, *, late: bool = False) -> dict: """Reap every finished close-out session (the first half of `_closeouts`): @@ -3027,6 +3279,11 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta # the safety net when it did not (#634). A second retire of # the same entry finds none live and is silent. _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, retire) + # An unattended close-out never runs `lifecycle.py close`, so + # the task's Open questions (a `blocked` one whose late `.done` + # merged) are answered here, or `check` would drift (#645). + _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, + question_retire_op(counters, co["task"], now)) events["merged"].append(pr) else: # Never retried: a close-out that ended without a verdict is the @@ -3154,7 +3411,13 @@ def stage2_row(now: _dt.datetime, task: str, pr: str, slot_name: str, gate: str, def pick_record(member: dict, brief: dict, *, proposed: bool = False) -> dict: """What `counters.json` keeps about one pick — enough for the digest and `batch watch` to show it by title, size and repo, not by file name.""" - rec = {"prompt": member["path"], "why": _brief.pick_reason(member, brief), + why = _brief.pick_reason(member, brief) + if member.get("resume"): + # An answer is not a new priority (Decision H11 a): the pick names + # the answer, then the standing it re-entered at. + why = (f"resumed after {', '.join(member['resume'].get('ids') or ['?'])} was " + f"answered · {why}") + rec = {"prompt": member["path"], "why": why, "tier": member.get("consequence") or "?", "title": member.get("title") or "", "size": member.get("difficulty") or "", "repos": list(member.get("repos") or [])} diff --git a/agents/conductors/batch/_questions.py b/agents/conductors/batch/_questions.py new file mode 100644 index 00000000..a80e63eb --- /dev/null +++ b/agents/conductors/batch/_questions.py @@ -0,0 +1,391 @@ +"""The questions inbox, Brain side (M3.5, PyAutoBrain#645) — readers only. + +PyAutoMind `questions.md` holds the questions shift workers parked on, one +`### Q. — ` entry each under `## Open`, `## Deferred`, +`## Answered` or `## Dropped` (the section is the state). Its schema and every +write are the Mind's (`scripts/questions_edit.py`): the watcher adds entries +only through its one Mind writer's `question-add` op, which runs Mind's own +`add_text` from the tree it writes, and the human answers in a `/questions` +chat. This module reads the same grammar for three consumers: + +- the watcher's parked hold (`read_origin`: the file on Mind `origin/main`, a + local `git show` after the shift's one fetch — no network of its own); +- the shift digest's one inbox line and the status comment's count; +- the Mind dashboard's read-only inbox section (`read`: the checkout's file). + +It also turns what a parked worker left (its `.question.json` sidecar) into +the entry the op carries, sanitised: one line, clipped, no `@`, no leading +`#` or `-`. A test parses one fixture with this reader and with Mind's parser, +so the two cannot drift. +""" + +from __future__ import annotations + +import json +import re +import subprocess +from pathlib import Path + +FILE = "questions.md" +SECTIONS = ("Open", "Deferred", "Answered", "Dropped") +_SECTION_RE = re.compile(r"^##\s+(Open|Deferred|Answered|Dropped)\b") +_HEAD_RE = re.compile(r"^###\s+Q(\d+)\.\s+(.+?)\s*$") +_FIELD_RE = re.compile(r"^-\s+([a-z][a-z-]*):[ \t]*(.*?)\s*$") + +#: What the sidecar may carry, and its limits (DESIGN §4.2). +ASK_MAX, OPTION_MAX, OPTIONS_MAX = 200, 120, 4 +SIDECAR_SUFFIX = ".question.json" +NO_SIDECAR_ASK = "see the question on the issue" + + +# --- the grammar --------------------------------------------------------------- + +def parse(text: str) -> list[dict]: + """The entries of a `questions.md` text, in file order: `{id, n, title, + state, fields}`. The Mind's `lifecycle.questions_parse` reads the same + grammar; a heading that is not a `Q` entry, or an entry outside the four + sections, is skipped here (the Mind's check reports it).""" + out: list[dict] = [] + state, cur, fenced = None, None, False + for line in (text or "").split("\n"): + if line.lstrip().startswith("```"): + fenced = not fenced + continue + if fenced: + continue + if line.startswith("#"): + if cur is not None: + out.append(cur) + cur = None + if line.startswith("## ") or line.startswith("# "): + m = _SECTION_RE.match(line) + state = m.group(1).lower() if m else None + elif line.startswith("### ") and state is not None: + m = _HEAD_RE.match(line) + if m: + cur = {"id": f"Q{int(m.group(1))}", "n": int(m.group(1)), + "title": m.group(2), "state": state, "fields": {}} + continue + if cur is not None: + m = _FIELD_RE.match(line) + if m and m.group(1) not in cur["fields"]: + cur["fields"][m.group(1)] = m.group(2) + if cur is not None: + out.append(cur) + return out + + +def task_of(entry: dict) -> str: + """The task id (prompt stem) an entry is about — the watcher's key.""" + return Path(entry["fields"].get("task") or "").stem + + +def read(mind) -> list[dict]: + """The entries of the checkout's `questions.md`; [] when absent.""" + try: + return parse((Path(mind) / FILE).read_text(encoding="utf-8", errors="replace")) + except (OSError, TypeError): + return [] + + +def by_task(entries: list[dict]) -> dict[str, list[dict]]: + """`{task: [{id, shift, issue, state, answer, comment}]}`.""" + out: dict[str, list[dict]] = {} + for e in entries: + f = e["fields"] + out.setdefault(task_of(e), []).append({ + "id": e["id"], "shift": f.get("shift", ""), "issue": f.get("issue", ""), + "state": e["state"], "answer": f.get("answer", ""), + "comment": f.get("answer-comment", ""), "kind": f.get("kind", ""), + "answered": (f.get("answered") or "").split(" ")[0], + "task": f.get("task", "")}) + return out + + +def read_origin(mind, ref: str = "origin/main", fetch=None, run=None) -> dict | None: + """`questions.md` on Mind `origin/main`, as `by_task`, read locally and + read-only after the shift's one fetch (`fetch`, the writer's own, run first + when given). `{}` when the ref has no such file (nothing asked yet). None + when it cannot be read — not a Mind checkout of its own, or git failed — so + the caller keeps every hold (fail closed).""" + run = run or subprocess.run + + def git(*args): + return run(["git", "-C", str(mind), *args], capture_output=True, text=True, + timeout=60) + try: + top = git("rev-parse", "--show-toplevel") + if top.returncode != 0 or Path(top.stdout.strip()).resolve() != Path(mind).resolve(): + return None + if fetch is not None: + fetch() + shown = git("show", f"{ref}:{FILE}") + if shown.returncode != 0: + listed = git("ls-tree", "--name-only", ref, "--", FILE) + if listed.returncode == 0 and not listed.stdout.strip(): + return {} + return None + except (OSError, subprocess.SubprocessError): + return None + return by_task(parse(shown.stdout)) + + +# --- the parked hold ------------------------------------------------------------- + +def hold_for(task: str, shift: str, inbox: dict | None) -> tuple[str, dict | None]: + """How the inbox rules on one task an earlier shift `shift` left parked: + ("held", None) — no entry (a park from before M3.5) or no readable inbox; + ("waiting", {ids}) — an entry is Open or Deferred; + ("dropped", {ids}) — an entry was dropped: the task is shelved (H9 a); + ("answered", {ids, comments, answers}) — every entry is answered.""" + if inbox is None: + return "held", None + mine = [e for e in inbox.get(task, []) if e.get("shift") == shift] + if not mine: + return "held", None + dropped = [e["id"] for e in mine if e["state"] == "dropped"] + if dropped: + return "dropped", {"ids": dropped} + waiting = [e["id"] for e in mine if e["state"] in ("open", "deferred")] + if waiting: + return "waiting", {"ids": waiting} + return "answered", {"ids": [e["id"] for e in mine], "shift": shift, + "comments": [e["comment"] for e in mine if e.get("comment")], + "answers": [e["answer"] for e in mine if e.get("answer")]} + + +def answered_since(task: str, inbox: dict | None, at: str) -> dict | None: + """A fresh release for a task whose earlier release a shift used up at + `at` (an ISO time): the entries answered after `at`, when none of the + task's entries is still open, deferred or dropped; else None.""" + if inbox is None: + return None + mine = inbox.get(task) or [] + if any(e["state"] != "answered" for e in mine): + return None + fresh = [e for e in mine if (e.get("answered") or "") > (at or "")] + if not fresh: + return None + return {"ids": [e["id"] for e in fresh], "shift": fresh[-1].get("shift", ""), + "comments": [e["comment"] for e in fresh if e.get("comment")], + "answers": [e["answer"] for e in fresh if e.get("answer")]} + + +# --- the sidecar and the op entry ------------------------------------------------ + +def sanitise(text, limit: int) -> str: + """One line, at most `limit` characters, no `@` (a mention would notify), + and no leading `#` or `-` (it must not read as a heading or a key).""" + out = re.sub(r"\s+", " ", str(text or "")).strip().replace("@", "") + if out[:1] in ("#", "-"): + out = "\\" + out + return out if len(out) <= limit else out[:limit - 1].rstrip() + "…" + + +def sidecar(lease_dir: Path, task: str, issue: str) -> tuple[str, list[str]]: + """(ask, options) from the worker's `{task}.question.json`, when it names + this issue (or no issue); else the no-sidecar ask and no options. The + watcher never reads the issue itself.""" + try: + raw = json.loads((Path(lease_dir) / f"{task}{SIDECAR_SUFFIX}").read_text( + encoding="utf-8", errors="replace")) + except (OSError, ValueError): + return NO_SIDECAR_ASK, [] + if not isinstance(raw, dict) or (raw.get("issue") and raw.get("issue") != issue): + return NO_SIDECAR_ASK, [] + ask = sanitise(raw.get("ask"), ASK_MAX) or NO_SIDECAR_ASK + opts = raw.get("options") if isinstance(raw.get("options"), list) else [] + return ask, [o for o in (sanitise(x, OPTION_MAX) for x in opts[:OPTIONS_MAX]) if o] + + +def add_op(entry: dict) -> dict: + """The Mind writer op that lands one question (`question-add`).""" + return {"op": "question-add", "path": FILE, "entry": entry} + + +def note_added(counters: dict, entry: dict) -> bool: + """Record one question this shift added (`counters["inbox"]`), once per + (task, issue). True when it is new.""" + seen = counters.setdefault("inbox", []) + key = (Path(entry["task"]).stem, entry["issue"]) + if any((q.get("task"), q.get("issue")) == key for q in seen): + return False + seen.append({"task": key[0], "issue": entry["issue"], "kind": entry["kind"], + "asked": entry["asked"]}) + return True + + +# --- the digest line and the dashboard link -------------------------------------- + +def dashboard_link(mind) -> str: + """The Mind dashboard's inbox anchor on Pages (`…/#inbox`), from the Mind's + own `repos.yaml` — no org is written here (the tenant firewall). "" when + it cannot be derived.""" + try: + text = (Path(mind) / "repos.yaml").read_text(encoding="utf-8", errors="replace") + except (OSError, TypeError): + return "" + m = re.search(r"^\s{2}PyAutoMind:[ \t]*\n(?:[ \t]{4,}.*\n)*?[ \t]{4,}github:" + r"[ \t]*([^\s#/]+)/([^\s#]+)", text, re.M) + return f"https://{m.group(1).lower()}.github.io/{m.group(2)}/#inbox" if m else "" + + +def unfiled_lines(counters: dict) -> list[str]: + """One digest line per question the watcher could not file (no prompt, no + shift issue, an issue that is not a URL): never a silent drop (#645).""" + return [f"Inbox: not filed — `{u.get('task')}` ({u.get('kind')}): {u.get('why')}; " + "see the task's issue or session yourself." + for u in counters.get("inbox_unfiled") or []] + + +def inbox_line(counters: dict, slot_name: str, mind=None, origin=None) -> str: + """The digest's one inbox line (Decision H7 a), "" when the shift added + none: `Inbox: 2 questions added to your inbox this shift (Q17, Q18), 5 + open in all — `. Ids and the open count come from Mind origin/main + (`origin`, else read here); a question still queued for the writer is + counted without its id.""" + added = counters.get("inbox") or [] + if not added: + return "" + if origin is None and mind is not None: + origin = read_origin(mind) + ids, open_n = [], None + if origin is not None: + mine = [e for es in origin.values() for e in es if e.get("shift") == slot_name] + ids = [e["id"] for e in sorted(mine, key=lambda e: int(e["id"][1:]))] + open_n = sum(e["state"] == "open" for es in origin.values() for e in es) + n = len(added) + line = f"Inbox: {n} question{'s' if n != 1 else ''} added to your inbox this shift" + if ids: + line += f" ({', '.join(ids)}" + (f"; {n - len(ids)} still being filed" if n > len(ids) + else "") + ")" + if open_n is not None: + line += f", {open_n} open in all" + link = dashboard_link(mind) if mind is not None else "" + return line + (f" — {link}" if link else "") + "." + + +# --- the one-off backfill (Build B, step 1) -------------------------------------- + +def _origin_path(mind, prompt: str, ref: str = "origin/main", run=None) -> str: + """Where `prompt` is on Mind origin/main now: itself, else `active/`, + else "" (completed or retired).""" + run = run or subprocess.run + for cand in (prompt, f"active/{Path(prompt).name}"): + try: + res = run(["git", "-C", str(mind), "cat-file", "-e", f"{ref}:{cand}"], + capture_output=True, text=True, timeout=30) + except (OSError, subprocess.SubprocessError): + return "" + if res.returncode == 0: + return cand + return "" + + +def _done_at(slot: Path, task: str) -> str: + """When the watcher reaped `task` as done (its tick's `at`), from tick.log.""" + try: + lines = (slot / "tick.log").read_text(encoding="utf-8", errors="replace").splitlines() + except OSError: + return "" + for line in lines: + try: + t = json.loads(line) + except ValueError: + continue + if any(isinstance(e, dict) and e.get("task") == task + and e.get("event") in ("done", "parked") for e in t.get("reaped") or []): + return (t.get("at") or "")[:16] + "Z" if t.get("at") else "" + return "" + + +def _proof_ask(slot: Path, task: str, issue: str) -> str: + """The proof packet's sentence that best states the question, for the + lead's review of the backfill only (the watcher itself never guesses): one + with a `?`, else one that asks for a choice (choose, decide, which, + whether), else one that says it parked on the issue; the no-sidecar ask + when none does. Issue links read "the issue".""" + try: + text = (slot / "proofs" / f"{task}.md").read_text(encoding="utf-8", errors="replace") + except OSError: + return NO_SIDECAR_ASK + body = " ".join(re.sub(r"^-\s+[a-z][a-z /-]*:\s*", "", ln.strip()) + for ln in text.splitlines() if ln.strip() and not ln.startswith("#")) + body = re.sub(re.escape(issue) + r"(?:#\S*)?", "the issue", body) + sentences = re.split(r"(?<=[.!?])\s+", body) + for test in (lambda x: "?" in x, + lambda x: re.search(r"\b(choose|decide|which|whether)\b", x, re.I), + lambda x: "the issue" in x and re.search(r"question|park", x, re.I)): + hit = next((x for x in sentences if test(x)), None) + if hit: + return sanitise(hit, ASK_MAX) + return NO_SIDECAR_ASK + + +def _record_issue(mind, slot_name: str) -> str: + try: + text = (Path(mind) / "batches" / f"{slot_name}.md").read_text(encoding="utf-8") + except OSError: + return "" + m = re.search(r"^- issue:[ \t]*(https://\S+)", text, re.M) + return m.group(1) if m else "" + + +def backfill(home: Path, mind, origin: dict | None = None) -> list[str]: + """`questions_edit.py add` lines for every task an earlier shift left + parked and still held today (the watcher's own `parked_elsewhere`, as if a + new shift were planning), one per question it parked on, oldest shift + first. Prints only — the lead reviews, then runs them. A task whose prompt + is no longer in `draft/` or `active/` on Mind origin/main, or whose + question is already in the inbox, is a `#` comment line instead.""" + import shlex + import _orchestrator as orch # noqa: E402 — deferred: it imports this module + home = Path(home) + held = orch.parked_elsewhere(home / ".backfill-probe") + origin = read_origin(mind) if origin is None else origin + slots = sorted(d for d in home.iterdir() if d.is_dir() + and (d / orch.COUNTERS_FILE).is_file()) if home.is_dir() else [] + rows = [] + for task in held: + # The last slot that parked it is the one whose hold stands. + for d in reversed(slots): + c = orch._safe_counters(d) or {} + o = (c.get("outcomes") or {}).get(task) + if (isinstance(o, dict) and o.get("questions")) or task in (c.get("parked") or []): + break + else: + continue + o = (c.get("outcomes") or {}).get(task) or {} + prompt = ((c.get("picks") or {}).get(task) or {}).get("prompt") or "" + worker = next((w.get("key") for w in reversed(c.get("workers") or []) + if w.get("task") == task), "") or "unknown" + if o.get("questions"): + asks = [(url, "question", _proof_ask(d, task, url)) for url in o["questions"]] + else: + asks = [(_record_issue(mind, d.name), "blocked", + f"the worker stopped at a prompt nobody answered (session {worker})")] + rows.append((d.name, task, prompt, worker, _done_at(d, task) or d.name, asks)) + out = [f"# questions backfill: {len(rows)} held task(s) in {home} — review, then run " + "each line from a temporary Mind worktree on origin/main"] + for shift, task, prompt, worker, asked, asks in sorted(rows): + now = _origin_path(mind, prompt) if prompt else "" + if not now: + out.append(f"# skipped: {task} (shift {shift}) — its prompt {prompt or '?'} is " + "no longer in draft/ or active/ on Mind origin/main; nothing to resume") + continue + for issue, kind, ask in asks: + if not issue: + out.append(f"# skipped: {task} (shift {shift}) — no issue to file it on") + continue + have = [e["id"] for e in (origin or {}).get(task, []) if e.get("shift") == shift + and e.get("issue") == issue] + if have: + out.append(f"# skipped: {task} (shift {shift}) — already in the inbox as " + + ", ".join(have)) + continue + out.append(" ".join(["python3 scripts/questions_edit.py add", + "--task", shlex.quote(now), "--issue", shlex.quote(issue), + "--kind", kind, "--ask", shlex.quote(ask), + "--shift", shlex.quote(shift), "--asked", shlex.quote(asked), + "--worker", shlex.quote(worker)])) + return out diff --git a/agents/conductors/batch/_watch.py b/agents/conductors/batch/_watch.py index 182437e3..f71f5b66 100644 --- a/agents/conductors/batch/_watch.py +++ b/agents/conductors/batch/_watch.py @@ -178,6 +178,9 @@ def snapshot(brief_path: Path, slot: Path, now: _dt.datetime, *, agents=None, "merges": f"{merges} of {_value(brief, 'merge-cap')}" f" ({values['glance-auto-merges']} unattended)", "crashes": values["workers-crashed"], + # Questions this shift added to the inbox (M3.5, #645): a count, + # never the asks, and no mention — the digest gives the link. + "inbox": len(counters.get("inbox") or []), }, "ticks": _ticks(slot, tick_lines) if started else [], } @@ -230,6 +233,8 @@ def render(snap: dict) -> str: f"- workers: {b['workers']}", f"- sessions: {b['sessions']}", f"- tokens: {b['tokens']}", f"- merges: {b['merges']}", f"- workers crashed: {b['crashes']}"] + if b.get("inbox"): + lines.append(f"- inbox: {b['inbox']} added this shift") lines += _steering_lines(snap) if snap.get("status_url"): lines += ["", f"Status comment: {snap['status_url']}"] @@ -257,6 +262,8 @@ def render_status(snap: dict) -> str: lines += ["", "**Budgets**", f"- workers: {b['workers']}", f"- sessions: {b['sessions']}", f"- tokens: {b['tokens']}", f"- merges: {b['merges']}", f"- workers crashed: {b['crashes']}"] + if b.get("inbox"): + lines.append(f"- inbox: {b['inbox']} added this shift") for line in _steering_lines(snap): lines.append(f"**{line}**" if line in ("Refusals", "Commands") else line) if snap.get("commands_unread"): diff --git a/agents/conductors/batch/worker_template.md b/agents/conductors/batch/worker_template.md index 15380c72..a4dde44f 100644 --- a/agents/conductors/batch/worker_template.md +++ b/agents/conductors/batch/worker_template.md @@ -53,6 +53,10 @@ The terms of this shift (AUTONOMY.md "Shift briefs and unattended `glance`"): change with `{shift_ledger} append|write|move|remove|drop-section ...` (ops land in {ledger_dir}/) and the orchestrator commits them. This covers your `active.md` claim, the `draft/ → active/` move and your close-out. + Your claim's session line is exactly + `- session: shift worker ()`, `` being the + brief file's name without `.md`: after the human answers a question you + parked on, a later shift resumes your claim only on that exact line. In your `active.md` row, each PR is its own `- library-pr: ` (library or organ repo) or `- workspace-pr: ` line (PyAutoMind REFERENCE.md "The PR keys"). Never a bare `pr:`: the ledger refuses it, and `/prm` @@ -65,7 +69,14 @@ The terms of this shift (AUTONOMY.md "Shift briefs and unattended `glance`"): - Then write {lease_dir}/{task}.done containing the URLs of the PRs you opened, one per line — `merged ` for a PR you merged in-turn under its tier. An issue is marked by why you ended there: `question: ` when you parked - with a question the human must answer (the watcher @-mentions them), or - `verdict: ` when you posted a verdict, your deliverable (no mention — - the digest lists it). Any other issue line @-mentions the human. Without that file the watcher counts your session as - crashed. + with a question the human must answer, or `verdict: ` when you posted + a verdict, your deliverable (the digest lists it). Nobody is @-mentioned + mid-shift: a `question:` (or any other issue line) is filed in the human's + questions inbox, which they clear in bulk after the shift; their answer is + added to your prompt and the next shift resumes the task. Without that file + the watcher counts your session as crashed. +- When you park with `question: `, first write + {lease_dir}/{task}.question.json, the line the human reads in the inbox: + `{{"issue": "", "ask": "", + "options": [""]}}`. The question + itself still lives on the issue; ask it there in full. diff --git a/agents/conductors/intake/_intake.py b/agents/conductors/intake/_intake.py index 610bee78..fdad11ee 100755 --- a/agents/conductors/intake/_intake.py +++ b/agents/conductors/intake/_intake.py @@ -87,6 +87,9 @@ # batch planner and `batch brief --new` (PyAutoMind#565). `read_queue` IS the # planner's reader, so a row's ★ `#n` is the planner's rank (PyAutoBrain#640). from _steer import queue_ranks, read_goals, read_queue, read_queue_entries # noqa: E402 +# The questions inbox (M3.5, PyAutoBrain#645): the batch conductor's reader, +# so the page and the watcher read `questions.md` one way. +import _questions # noqa: E402 # The close-out guard (strong-evidence `looks-shipped` flags): the detector and # the one reader the dashboard and the batch planner share. @@ -1761,6 +1764,9 @@ def _count(key): "queue": read_queue_entries(mind), "queue_order": read_queue(mind), "goals": read_goals(mind), + # The questions inbox (M3.5, #645), read-only: the section below + # the steering box, with a 📋 per question. + "questions": _questions.read(mind), } c["recent"] = recent_events(c) # Needs `in_flight` in place, so it is derived after the dict is built. @@ -2356,6 +2362,7 @@ def render_dashboard(c: dict) -> str: if c["batch"] is not None: L += [_status_box_md(c["batch"]), ""] L += _steer_md(c) + L += _inbox_md(c) L += ["## Start here", ""] # Epic members never appear in the pick lists or the work-type sections — @@ -2704,17 +2711,115 @@ def _steer_html(c: dict, link) -> list: return H +_INBOX_CSS = """\ +.inbox{margin:0 0 1.2rem;padding:.75rem .9rem;border:1px solid var(--edge); + border-radius:11px;background:var(--tint)} +.inbox h2{margin:.1rem 0 .4rem;font-size:1.05rem;display:flex;align-items:center;gap:.5rem} +.inbox ol{list-style:none;margin:.2rem 0;padding-left:0} +.inbox .qid{font-weight:700;margin-right:.3rem} +.inbox details{margin:.2rem 0} +""" + + +def _age(asked: str, today: str) -> str: + """`asked` (an ISO time) as an age in whole days against the census date; + "" when either cannot be read. Day-grained, so `--check` is stable.""" + try: + days = (_dt.date.fromisoformat(today[:10]) - _dt.date.fromisoformat(asked[:10])).days + except (TypeError, ValueError): + return "" + return "today" if days <= 0 else ("1 day" if days == 1 else f"{days} days") + + +def _open_questions(c: dict) -> tuple: + """(open, deferred) inbox entries, oldest first.""" + qs = sorted(c.get("questions") or [], + key=lambda e: (e["fields"].get("asked", ""), e["n"])) + return ([e for e in qs if e["state"] == "open"], + [e for e in qs if e["state"] == "deferred"]) + + +def _questions_payload(qid: str = "") -> str: + """The 📋 text for the inbox: the `/questions` skill named portably.""" + return "Use the questions skill." + (f" {qid}" if qid else "") + + +def _inbox_md(c: dict) -> list: + """The markdown page's read-only Questions list (as on the HTML twin).""" + opened, deferred = _open_questions(c) + L = [f"## Questions ({len(opened)} open, {len(deferred)} deferred)", ""] + for e in opened: + f = e["fields"] + age = _age(f.get("asked", ""), c.get("generated", "")) + L.append(f"- {e['id']} — {_md_inline_escape(f.get('ask', ''))} " + f"({f.get('issue', '')}" + (f", {age}" if age else "") + ")") + if not opened: + L.append("_(no open questions — [`questions.md`](questions.md))_") + return L + [""] + + +def _inbox_html(c: dict, link) -> list: + """The read-only questions inbox, straight after the steering box (M3.5, + PyAutoBrain#645). Server-rendered with no script of its own: each Open + question carries the 📋 every task row has, copying `Use the questions + skill. Q` to paste into a chat; the heading's 📋 copies `Use the + questions skill.`, which starts a sitting. Portable text, not a slash + command (`board/copy_contract.py`), as the task rows' start-dev line is. + Deferred entries fold to one line each. No form, input or fetch.""" + opened, deferred = _open_questions(c) + copy = ('') + H = ['"] + return H + + def _steer_first(page: str) -> str: """Lift the Goals and queue box above the section cards. The shared layout moves the orchestration panel above the navigation cards; the steering box belongs straight after it, at the top of the - first screen, not below seven count cards.""" + first screen, not below seven count cards. The questions inbox that + follows it (M3.5) travels with it.""" start = page.find('", start) + len("") + inbox = page.find('", inbox) + len("") box = page[start:end] page = page[:start] + page[end:] return page[:nav] + box + "\n" + page[nav:] @@ -2783,7 +2888,7 @@ def record_row(r): "PyAutoMind Dashboard", f"", - f"", + f"", "", "", hero(THEME_ORGAN, "Dashboard", navigation=_dashboard_navigation(c), @@ -2829,6 +2934,7 @@ def record_row(r): refreshed_at=c.get("refreshed_at"), refresh_url=home + "/actions/workflows/dashboard_refresh.yml" if home else None)) H += _steer_html(c, link) + H += _inbox_html(c, link) if c.get("drift"): H += ['

⚠️ Needs lifecycle reconciliation — draft prompts ' "whose body records a fix PR (done, never advanced):

", "
    "] diff --git a/config/policy.yaml b/config/policy.yaml index 8b3c36ef..a8845307 100644 --- a/config/policy.yaml +++ b/config/policy.yaml @@ -180,3 +180,7 @@ board: # PYAUTO_SHIFT_MENTION (which wins). Blank everywhere posts without a mention. shift_watcher: mention_login: "Jammy2211" + # How a parked worker's question reaches the human (M3.5, PyAutoBrain#645, + # Decision H7): `end` — one line in the digest at review-at, "N questions + # added to your inbox" with the dashboard link; no @mention mid-shift. + question_notice: end diff --git a/skills/COMMANDS.md b/skills/COMMANDS.md index 4d04f2b6..afdf83d3 100644 --- a/skills/COMMANDS.md +++ b/skills/COMMANDS.md @@ -113,6 +113,16 @@ call, so the Brain is not bypassed): on `origin/main`, committed with `prompt_sync_push`, then `lifecycle.py check`. The dashboard only reads the queue (★ and rank on each queued task). +- **`/questions`** — clear `PyAutoMind/questions.md`, the inbox of questions + shift workers parked on (PyAutoBrain#645; the one chat writer). A sitting + goes oldest first: answer (posted on the question's issue as the human, + then appended to the task's prompt so the next shift resumes it), later + (defer), drop (the task is shelved) or skip. A pasted `Use the questions skill. Q17` + (the dashboard's 📋) opens that question — **never start dev**. Writes through + the Mind's `scripts/questions_edit.py` in a temporary worktree detached on + `origin/main`, committed with `prompt_sync_push`, then `lifecycle.py check`, + as `/queue` writes the queue. + - **`update_issue`** — post a progress update (commits, summary, what is left) to the active task's GitHub issue, read from the PyAutoMind registry. The dev-lifecycle's progress leg; `start_dev_for_user` calls it at milestones. diff --git a/skills/batch/batch.md b/skills/batch/batch.md index 40257309..a19cdabc 100644 --- a/skills/batch/batch.md +++ b/skills/batch/batch.md @@ -105,7 +105,7 @@ One deterministic tick per timer firing; the timer is installed by the human, ne After `review-at:` its one remaining act is the digest: written into the record and posted once on the brief's `issue:`. A `shadow: yes` brief plans and digests but spawns nothing — the pilot's baseline; every shift keeps one line in `PyAutoMind/batches/pilot/pilot.jsonl`, rendered -to `pilot.md` (`?` cells the human's at check-in). A parked worker @-mentions the human on that issue, once. Once a worker's `glance` PR is green, the +to `pilot.md` (`?` cells the human's at check-in). A parked worker's question is filed in the questions inbox (Mind `questions.md`, cleared with `/questions`) and the digest says how many, with no @mention mid-shift. Once a worker's `glance` PR is green, the watcher starts one independent close-out session that merges it or refuses; each merge adds a row to the stage-2 table in `PyAutoMind/autonomy_log.md`. What a tick does, its state, caps and the install commands: `agents/conductors/batch/AGENTS.md` "The watcher". **`/batch watch`** ("how is the shift going?"): run `bin/pyauto-brain batch watch --record --once` and relay it as written; with no slot on this machine, read the status comment on its `issue:` ([`reference.md`](reference.md)). The human steers with their own comment there (`/pause`, `/resume`, `/drop `, `/stop`, `/add `, `/cap merges|workers|sessions|tokens `, `/kill `); never post one for them. `batch watch --stream --record ` prints the shift's event stream (`events.jsonl`, local reads only) until it ends — the cockpit's watch ([`reference.md`](reference.md)). diff --git a/skills/questions/SKILL.md b/skills/questions/SKILL.md new file mode 100644 index 00000000..a18e3f9c --- /dev/null +++ b/skills/questions/SKILL.md @@ -0,0 +1,15 @@ +--- +name: questions +description: Clear PyAutoMind questions.md, the inbox of questions shift workers parked on, in one sitting from chat. Use for /questions, "go through my questions", "answer Q17", or a pasted dashboard copy line "Use the questions skill. Q17". Answer, defer, drop or reopen each; never start dev. +--- + +# Questions + +Follow [`questions.md`](questions.md) exactly. A `/questions` chat walks the +inbox the shift watcher filled (one entry per parked question, PyAutoBrain#645) +and records the human's word on each: **answer**, **later** (defer), **drop** +or **skip**. Every edit is the Mind's `scripts/questions_edit.py`, never a +hand edit, written through a temporary Mind worktree and `prompt_sync_push`, +exactly as `/queue` writes `queue.md`. A pasted `Use the questions skill. Q17` line +(the dashboard's 📋 text) or `/questions Q17` means "open Q17 here"; it never +means start dev, plan or build. diff --git a/skills/questions/questions.md b/skills/questions/questions.md new file mode 100644 index 00000000..80775e92 --- /dev/null +++ b/skills/questions/questions.md @@ -0,0 +1,104 @@ +# /questions — clear the inbox of parked questions, in chat + +`PyAutoMind/questions.md` holds the questions shift workers parked on, one +`Q` entry each under Open, Deferred, Answered or Dropped. The shift watcher +adds them; no @mention is sent mid-shift, and the digest says how many were +added (PyAutoBrain#645). This chat is the one chat writer, as `/queue` is for +the queue. The dashboard's inbox section is read-only: its 📋 copies +`Use the questions skill. Q` (or `Use the questions skill.`) to paste +here. + +Shared routing context: `PyAutoBrain/skills/COMMANDS.md`. + +> No `gh` on a remote session — map each `gh` step via [`../GITHUB_ACCESS.md`](../GITHUB_ACCESS.md). + +## The rule of this chat + +After `/questions`, a pasted `Use the questions skill. Q17` line (or +`/questions Q17`), a `Q` id or "go through my questions" opens the inbox. +It is never a start-dev, `/route`, intake, plan or build request, even when +the human's answer names work to do. An answered +task resumes in the **next** shift (a shift already running has counted it), +or in a session if the human says "start it now" in words. + +## Verbs + +Run `python3 scripts/questions_edit.py …` in the Mind worktree (step 1 +of the write procedure): + +| The human says | Run | +|---|---| +| an answer in words | `answer Q --text "" --comment --by --via chat\|issue` | +| "later" / "not now" (optional date) | `defer Q [--until YYYY-MM-DD] --by ` | +| "drop" / "withdraw" (a reason) | `drop Q --why "" --by ` | +| "reopen Q" (a mistake, a revived task) | `reopen Q` | +| "skip" | nothing: go to the next entry | +| "show" / "what's open?" | `show --open` (or `show --all`, `show Q`) | + +`` is the human's GitHub login (`gh api user --jq .login`, once). +Relay a refusal in one line; never work around it by editing the file. + +## A sitting + +1. **List.** `show --open` in a fresh worktree on `origin/main` (steps 1 and 5 + below; no commit). It lists Open entries and Deferred ones that are due, + oldest first. Say "N open. Go one at a time?" +2. **Each entry.** Show its ask, options, issue link and age (`show Q`). + First make one read of the issue's comments since `asked:` by the human's + login: + `gh api "repos///issues//comments?since=" --jq '.[] | select(.user.login=="") | .body'`. + If the human already replied there, offer: "You replied on the issue: + ''. Record that as the answer?" A yes records it with + `--via issue` and that comment's URL, and posts nothing new. +3. **The human's word.** + - **Answer:** post it on the issue as the human: + `gh issue comment --body "Answer (Q, from the questions inbox): "` + (it prints the comment URL). Then run `answer` with `--comment `. + In one commit this moves the entry to Answered and appends the answer to + the task's prompt under `## Answers from the human`; the script prints + `prompt: `, which the commit must include. + - **Later:** `defer`. Nothing is posted. + - **Drop:** `drop --why`, then post + `gh issue comment --body "Question withdrawn by the human: "`. + Dropping shelves the task: no shift picks it until it is reopened, named + in a brief, or `/add`-ed. If the task is in `queue.md`, ask once whether + to take it off the queue too, and if so follow the `/queue` procedure + (`../queue/queue.md`); never edit `queue.md` here. +4. **Commit before the next question** (steps 3–5), so a sitting cut short + loses nothing. +5. **End with a summary**: answered (and whether each resumes: queued at #n, + a small single-repo dip, or "not queued and not small — `/queue` it to have + a shift pick it up"; an answer is not a new priority), deferred, dropped. + +## Procedure for a write + +1. **Temporary Mind worktree, detached on `origin/main`.** Never edit the + shared checkout: + ```bash + MIND=; T=$(mktemp -d)/mind + git -C "$MIND" fetch -q origin && git -C "$MIND" worktree add -q --detach "$T" origin/main + ``` +2. **Edit:** `cd "$T" && python3 scripts/questions_edit.py …`. +3. **Commit and push `questions.md`, plus the `prompt:` path an answer printed:** + ```bash + source scripts/prompt_sync.sh && PROMPT_REPO="$T" PROMPT_SYNC_PUSH_TO=main \ + prompt_sync_push "questions: " questions.md [] + ``` + If the push is rejected because main moved, do not rebase or `git push` + by hand: remove the worktree (step 5), re-create it on a fresh + `origin/main` (step 1), re-run the same `questions_edit.py` verb (step 2; + an issue comment already posted is reused by its URL, never posted twice), + and push again through `prompt_sync_push`. +4. **Check:** `python3 scripts/lifecycle.py check`. Report any `questions.md` + finding. Other drift is not this chat's to fix; mention it in one line. +5. **Clean up:** `git -C "$MIND" worktree remove "$T"`. + +The dashboard re-renders on its own (`dashboard_refresh.yml` watches +`questions.md`), so do not regenerate it here. + +## Without a shell (web or mobile) + +If the chat cannot run git, say so, still post the answer on the issue if the +human wants (that alone does not release the task), and give the exact +`questions_edit.py` command for the human to run later. Never hand-edit +`questions.md` through the GitHub contents API. diff --git a/skills/route/route.md b/skills/route/route.md index 2a79ffbd..73003974 100644 --- a/skills/route/route.md +++ b/skills/route/route.md @@ -22,6 +22,9 @@ If `/queue` ran earlier in this chat, a pasted prompt, prompt path, task title or dashboard 📋 line (`Use the start-dev skill. `) means "add it to `queue.md`": follow [`queue`](../queue/queue.md), never `/start_dev`. Only route a pasted task into development when the human says so in words. +The same holds in a chat that ran `/questions`: a pasted `Use the questions +skill. Q17` line or an answer that names work means "record it in `questions.md`": +follow [`questions`](../questions/questions.md), never `/start_dev`. ## Classify → dispatch diff --git a/skills/start_dev/SKILL.md b/skills/start_dev/SKILL.md index c22864ec..9351ed95 100644 --- a/skills/start_dev/SKILL.md +++ b/skills/start_dev/SKILL.md @@ -1,6 +1,6 @@ --- name: start-dev -description: Plan and register PyAutoLabs development work, then route it to a library or workspace worktree. Not for questions, reviews, status, explicit workflow opt-outs, or a task pasted into a /queue chat (that means add it to queue.md). +description: Plan and register PyAutoLabs development work, then route it to a library or workspace worktree. Not for questions, reviews, status, explicit workflow opt-outs, a task pasted into a /queue chat (that means add it to queue.md), or an answer or pasted question line in a /questions chat (that means record it in questions.md). --- # Start Dev @@ -8,7 +8,9 @@ description: Plan and register PyAutoLabs development work, then route it to a l **Not in a queue chat.** If `/queue` ran earlier in this chat, a pasted `Use the start-dev skill. ` line (the dashboard's 📋 text), prompt, path or title means "add it to `queue.md`": follow [`../queue/queue.md`](../queue/queue.md) -and stop here. +and stop here. Likewise in a `/questions` chat: an answer or a pasted +`Use the questions skill. Q` line is recorded through [`../questions/questions.md`](../questions/questions.md), +never started. Follow [`start_dev.md`](start_dev.md) in this directory exactly — the authoritative workflow body. `reference.md` holds the long-form templates and diff --git a/tests/test_m31_live_shift_findings.py b/tests/test_m31_live_shift_findings.py index cc83d69f..34c2f515 100644 --- a/tests/test_m31_live_shift_findings.py +++ b/tests/test_m31_live_shift_findings.py @@ -476,6 +476,8 @@ def test_11_an_in_turn_merge_queues_the_queue_retirement(tmp_path): events = orch._reap(slot, counters, _later(5), 0, orch.AgentsView([])) assert events == [{"task": "t1", "event": "done"}] ops = [json.loads(f.read_text()) for f in mw.pending_ops(slot)] - assert [o["op"] for o in ops] == ["queue-retire"] + # ... and its open inbox questions are answered with it (#645 review). + assert [o["op"] for o in ops] == ["queue-retire", "question-retire"] + assert ops[1]["prompt"] == "t1.md" assert ops[0]["prompt"] == "t1.md" and PR in ops[0]["shipped_as"] assert "in-turn" in ops[0]["shipped_as"] diff --git a/tests/test_orchestrator_mentions.py b/tests/test_orchestrator_mentions.py index 0e239b3d..a8b07848 100644 --- a/tests/test_orchestrator_mentions.py +++ b/tests/test_orchestrator_mentions.py @@ -1,7 +1,15 @@ -"""PyAutoBrain#611 (M1.6): a blocked shift worker reaches the human through a -GitHub @mention on the shift's digest issue (the human's channel ruling, -2026-11-12). The `gh` call sits behind a fake `run`, so nothing reaches -GitHub; the login comes from the environment or config, never the code. +"""PyAutoBrain#611 (M1.6): the @mention machinery on the shift's digest issue +(the human's channel ruling, 2026-11-12). The `gh` call sits behind a fake +`run`, so nothing reaches GitHub; the login comes from the environment or +config, never the code. + +M3.5 (PyAutoBrain#645, Decision H7 a) removed the two triggers this file was +written for: a parked worker and a question now land in the questions inbox +and no longer @-mention anyone. The machinery (markers, one post per worker +per state, retries, the late sweep, the posting identity) stays for other +needs-you triggers, so these tests drive it with a stand-in trigger (a parked +worker, as the old one); the tests marked `real_triggers` pin that the real +ones are gone. """ from __future__ import annotations @@ -19,6 +27,20 @@ from test_orchestrator_dispatch import _brief, _digest, orch # noqa: E402 NOW = d.NOW + + +def _stand_in_trigger(counters, held): + """A needs-you trigger for the machinery tests: a parked worker.""" + return [(task, "parked", "blocked on a person" + ( + f" (blocked since {(held.get(task) or {}).get('stalled_since')})" + if (held.get(task) or {}).get("stalled_since") else "")) + for task in counters["parked"]] + + +@pytest.fixture(autouse=True) +def _trigger(request, monkeypatch): + if "real_triggers" not in request.keywords: + monkeypatch.setattr(orch, "_mention_triggers", _stand_in_trigger) ISSUE = "https://github.com/example-org/example-mind/issues/4242" LOGIN = "example-human" PAST_GRACE = NOW + _dt.timedelta(minutes=1, seconds=orch.STALL_GRACE_S) @@ -32,6 +54,16 @@ def _issue_reads_answer(monkeypatch): monkeypatch.setattr(orch, "gh_issue_comments", lambda issue, since, run=None: []) +@pytest.fixture(autouse=True) +def _scratch_mind_writes_nothing(monkeypatch): + """The scratch Mind here is not a git Mind, so the questions a park now + files (`question-add`, #645) could only fail to commit — itself a + needs-you event (#644). These tests are about mentions: the ops stay + pending, unread; `test_questions_inbox.py` lands them on a real Mind.""" + monkeypatch.setattr(orch._mind_writer, "commit_ledger", + lambda *a, **k: {"committed": None, "ops": 0}) + + class FakeGh: """`gh issue comment`: records argv and the body; fails the first `fail` calls.""" @@ -126,17 +158,26 @@ def test_a_crash_makes_no_mention(tmp_path, monkeypatch): assert gh.calls == [] # the push test: the digest carries it -def test_a_worker_parked_on_its_issue_is_awaiting_input(tmp_path, monkeypatch): +def _question_ops(slot): + import _mind_writer as mw + import json + return [json.loads(f.read_text())["entry"] for f in mw.pending_ops(slot) + if json.loads(f.read_text()).get("op") == "question-add"] + + +@pytest.mark.real_triggers +def test_a_worker_parked_on_its_issue_is_filed_in_the_inbox_not_mentioned(tmp_path, + monkeypatch): + """M3.5 (#645): the question lands in questions.md; nobody is @-mentioned.""" mind, brief, home, slot = _shift(tmp_path, monkeypatch) claude, gh = d.FakeClaude(), FakeGh() _tick(brief, mind, home, NOW, claude, gh) (slot / "leases" / "t1.done").write_text("question: https://github.com/o/r/issues/77\n") _tick(brief, mind, home, NOW + _dt.timedelta(minutes=5), claude, gh, d._agents({"t1": "done"}, slot)) - assert len(gh.calls) == 1 - body = gh.calls[0][1] - assert "needs you — awaiting-input." in body - assert "parked on its issue with a question: https://github.com/o/r/issues/77" in body + assert gh.calls == [] and orch.read_counters(slot)["pushes"] == 0 + [entry] = _question_ops(slot) + assert (entry["issue"], entry["kind"]) == ("https://github.com/o/r/issues/77", "question") def test_only_an_explicit_verdict_is_not_a_push(tmp_path, monkeypatch): @@ -160,16 +201,19 @@ def test_only_an_explicit_verdict_is_not_a_push(tmp_path, monkeypatch): "QUESTION https://github.com/o/r/issues/77\n", "verdikt: https://github.com/o/r/issues/77\n", "blocked: https://github.com/o/r/issues/77\n"]) -def test_any_issue_not_marked_verdict_is_a_push(tmp_path, monkeypatch, done): - """PyAutoBrain#632 review: the push test fails toward the human — a bare - URL, a mis-cased or colon-less `question`, or an unknown marker mentions.""" +@pytest.mark.real_triggers +def test_any_issue_not_marked_verdict_is_filed_in_the_inbox(tmp_path, monkeypatch, done): + """PyAutoBrain#632 review: the test fails toward the human — a bare URL, a + mis-cased or colon-less `question`, or an unknown marker is a question. + Since M3.5 (#645) it lands in the inbox instead of a mention.""" mind, brief, home, slot = _shift(tmp_path, monkeypatch) claude, gh = d.FakeClaude(), FakeGh() _tick(brief, mind, home, NOW, claude, gh) (slot / "leases" / "t1.done").write_text(done) _tick(brief, mind, home, NOW + _dt.timedelta(minutes=5), claude, gh, d._agents({"t1": "done"}, slot)) - assert len(gh.calls) == 1 and "needs you — awaiting-input." in gh.calls[0][1] + assert gh.calls == [] + assert [e["issue"] for e in _question_ops(slot)] == ["https://github.com/o/r/issues/77"] assert orch.read_counters(slot)["outcomes"]["t1"]["issues"] == [ "https://github.com/o/r/issues/77"] diff --git a/tests/test_questions_inbox.py b/tests/test_questions_inbox.py new file mode 100644 index 00000000..624a268d --- /dev/null +++ b/tests/test_questions_inbox.py @@ -0,0 +1,793 @@ +"""The questions inbox, watcher side (M3.5, PyAutoBrain#645). + +A parked worker's question no longer @-mentions the human. It lands in +PyAutoMind `questions.md` through the one Mind writer (`question-add`, which +runs Mind's own `questions_edit.add_text` from the tree it writes), the digest +says once how many landed, an answer on Mind origin/main releases the parked +hold, and the next shift resumes the task, reusing a shift worker's claim, with +`RESUME_NOTE` and the answer in its prompt. The `claude` and `gh` binaries are +fakes; the Mind-writer legs use real git against a bare remote. +""" + +from __future__ import annotations + +import base64 +import datetime as _dt +import hashlib +import importlib.util +import json +import os +import re +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +BRAIN = Path(__file__).resolve().parents[1] +BATCH = BRAIN / "agents" / "conductors" / "batch" +MIND_SRC = BRAIN.parent / "PyAutoMind" +if not (MIND_SRC / "scripts" / "questions_edit.py").is_file(): + MIND_SRC = Path(os.environ.get("PYAUTO_MIND", "/nonexistent")) +HAVE_MIND = (MIND_SRC / "scripts" / "questions_edit.py").is_file() and shutil.which("git") +needs_mind = pytest.mark.skipif(not HAVE_MIND, reason="needs git and a PyAutoMind checkout " + "with scripts/questions_edit.py") +sys.path.insert(0, str(BRAIN / "agents" / "faculties" / "sizing")) +sys.path.insert(0, str(BATCH)) +sys.path.insert(0, str(BRAIN / "tests")) +import _brief # noqa: E402 +import _digest # noqa: E402 +import _mind_writer as mw # noqa: E402 +import _orchestrator as orch # noqa: E402 +import _questions # noqa: E402 +import _watch # noqa: E402 +import test_orchestrator_dispatch as d # noqa: E402 + +NOW = d.NOW +ISSUE = "https://github.com/example-org/example-mind/issues/4242" +Q1 = "https://github.com/example-org/widgets/issues/70" +Q2 = "https://github.com/example-org/widgets/issues/71" + + +class FakeGh: + def __init__(self): + self.calls = [] + + def __call__(self, argv, **kw): + self.calls.append(argv) + from types import SimpleNamespace + return SimpleNamespace(returncode=0, stdout=f"{ISSUE}#issuecomment-1\n", stderr="") + + +def _shift(tmp_path, names=("t1", "t2")): + mind, brief, home = d._shift(tmp_path, names=names) + brief.write_text(brief.read_text().replace( + "- review-at: 2026-11-04T11:30Z\n", f"- review-at: 2026-11-04T11:30Z\n- issue: {ISSUE}\n")) + return mind, brief, home, orch.slot_dir(brief, home) + + +def _tick(brief, mind, home, now, claude, gh, agents=None): + return orch.tick(brief, mind, home=home, now=now, grace_s=0, + spawner=orch.RealSpawner(brief, "auto", run=claude), + agents=agents or orch.AgentsView([]), tokens=lambda s: 0, + poster=lambda issue, body: orch.gh_comment(issue, body, run=gh)) + + +def _mentions(gh): + """Comment bodies that @-mention or name a worker as needing the human + (#611's mention form). Build A's needs-you event comments (`Shift … needs + you: `, no `@`) are not mentions; a scratch Mind triggers them.""" + bodies = [Path(a[a.index("--body-file") + 1]).read_text() for a in gh.calls + if "--body-file" in a] + return [b for b in bodies if "@" in b or "the worker on" in b] + + +def _ops(slot): + return [json.loads(f.read_text()) for f in mw.pending_ops(slot)] + + +# --- landing: two parked workers, two ops, no mention, one digest line ------------ + +def test_two_parked_workers_give_two_ops_no_mention_and_one_digest_line(tmp_path, + monkeypatch): + monkeypatch.setenv(orch.MENTION_ENV, "example-human") + mind, brief, home, slot = _shift(tmp_path) + claude, gh = d.FakeClaude(), FakeGh() + _tick(brief, mind, home, NOW, claude, gh) + leases = slot / "leases" + (leases / "t1.done").write_text(f"question: {Q1}\n") + (leases / "t1.question.json").write_text(json.dumps({ + "issue": Q1, "ask": "Brass or steel?\n@example-human please", + "options": ["brass", "steel", "#heading", "- dash", "five"]})) + (leases / "t2.done").write_text(f"question: {Q2}\n") # an old worker: no sidecar + r = _tick(brief, mind, home, NOW + _dt.timedelta(minutes=5), claude, gh, + d._agents({"t1": "done", "t2": "done"}, slot)) + assert sorted(e["task"] for e in r["reaped"]) == ["t1", "t2"] + ops = sorted(_ops(slot), key=lambda o: o["entry"]["task"]) + assert [o["op"] for o in ops] == ["question-add", "question-add"] + e1, e2 = (o["entry"] for o in ops) + assert e1 == {"task": "draft/feature/pyautobrain/t1.md", "issue": Q1, "kind": "question", + "ask": "Brass or steel? example-human please", + "options": ["brass", "steel", "\\#heading", "\\- dash"], + "shift": slot.name, "asked": "2026-11-04T09:05Z", "worker": "00000001"} + assert e2["ask"] == _questions.NO_SIDECAR_ASK and e2["options"] == [] + assert all(mw.validate_op(o, type("lm", (), {"is_ledger_path": staticmethod( + lambda p: p == "questions.md")})) == [] for o in ops) + # Zero @mentions: no mention comment mid-shift. + assert _mentions(gh) == [] + c = orch.read_counters(slot) + assert c["pushes"] == 0 and len(c["inbox"]) == 2 + # A re-tick queues nothing more. + _tick(brief, mind, home, NOW + _dt.timedelta(minutes=8), claude, gh) + assert len(_ops(slot)) == 2 + text = _digest.build(_brief.parse(brief.read_text())["brief"], slot, c, + health=lambda u: "HEALTHY", mind=mind) + inbox = [ln for ln in text.splitlines() if ln.startswith("Inbox:")] + assert inbox == ["Inbox: 2 questions added to your inbox this shift."] + assert text.index("Inbox:") < text.index("### Brief work") + assert not _digest.validate(text.replace("- none", "- none"))[:0] + + +def test_a_worker_blocked_past_the_grace_lands_a_blocked_entry_on_the_shift_issue(tmp_path): + mind, brief, home, slot = _shift(tmp_path, names=("t1",)) + claude, gh = d.FakeClaude(), FakeGh() + blocked = lambda: d._agents({"t1": "blocked"}, slot) # noqa: E731 + _tick(brief, mind, home, NOW, claude, gh) + assert orch.leases(slot)["t1"]["shift_issue"] == ISSUE + _tick(brief, mind, home, NOW + _dt.timedelta(minutes=1), claude, gh, blocked()) + past = NOW + _dt.timedelta(minutes=1, seconds=orch.STALL_GRACE_S) + r = _tick(brief, mind, home, past, claude, gh, blocked()) + assert r["reaped"][0]["event"] == "parked" and _mentions(gh) == [] + [op] = _ops(slot) + assert op["entry"]["kind"] == "blocked" and op["entry"]["issue"] == ISSUE + assert op["entry"]["ask"].startswith("the worker stopped at a prompt nobody answered " + "(session 00000001, since 2026-11-04T09:01") + + +def test_mention_triggers_no_longer_fire_for_questions_or_parks(): + counters = orch.read_counters(Path("/nonexistent")) + counters["parked"] = ["t1"] + counters["outcomes"] = {"t2": {"questions": [Q1], "issues": [Q1], "prs": [], "merged": []}} + assert orch._mention_triggers(counters, {}) == [] + + +def test_the_status_comment_counts_the_inbox(tmp_path): + mind, brief, home, slot = _shift(tmp_path, names=("t1",)) + claude, gh = d.FakeClaude(), FakeGh() + _tick(brief, mind, home, NOW, claude, gh) + (slot / "leases" / "t1.done").write_text(f"question: {Q1}\n") + _tick(brief, mind, home, NOW + _dt.timedelta(minutes=5), claude, gh, + d._agents({"t1": "done"}, slot)) + snap = _watch.snapshot(brief, slot, NOW + _dt.timedelta(minutes=6), + agents=orch.AgentsView([]), health=lambda u: "HEALTHY") + assert "- inbox: 1 added this shift" in _watch.render_status(snap) + assert "- inbox: 1 added this shift" in _watch.render(snap) + + +def test_sanitise(): + assert _questions.sanitise(" a\n b ", 10) == "a b" + assert _questions.sanitise("@someone ping", 50) == "someone ping" + assert _questions.sanitise("# Heading", 50) == "\\# Heading" + assert _questions.sanitise("x" * 30, 10) == "x" * 9 + "…" + + +# --- the parked hold: answered releases, the rest hold --------------------------- + +def _home_with_parks(tmp_path): + home = tmp_path / "home" + old = home / "2026-11-14-pm2" + old.mkdir(parents=True) + (old / "counters.json").write_text(json.dumps({ + "outcomes": {"alpha": {"questions": [Q1], "prs": [], "merged": []}, + "beta": {"questions": [Q2], "prs": [], "merged": []}, + "gamma": {"questions": [Q1], "prs": [], "merged": []}, + "delta": {"questions": [Q2], "prs": [], "merged": []}}, + "parked": ["eps"]})) + now = home / "2026-11-16-am" + now.mkdir() + return now + + +def _inbox(answered_at="2026-11-15T08:00Z", **states): + return {t: [{"id": f"Q{i}", "shift": "2026-11-14-pm2", "issue": Q1, "state": s, + "answered": answered_at if s == "answered" else "", + "answer": "yes" if s == "answered" else "", + "comment": f"{Q1}#issuecomment-{i}" if s == "answered" else ""}] + for i, (t, s) in enumerate(states.items(), 1)} + + +def test_an_answered_question_releases_the_hold_and_records_the_resume(tmp_path): + slot = _home_with_parks(tmp_path) + resumes = {} + held = orch.parked_elsewhere(slot, _inbox(alpha="answered", beta="dropped", + gamma="open", delta="deferred", eps="answered"), + resumes) + assert "alpha" not in held and "eps" not in held + assert resumes == {"alpha": {"ids": ["Q1"], "shift": "2026-11-14-pm2", + "comments": [f"{Q1}#issuecomment-1"], "answers": ["yes"], + "picked_in": []}, + "eps": {"ids": ["Q5"], "shift": "2026-11-14-pm2", + "comments": [f"{Q1}#issuecomment-5"], "answers": ["yes"], + "picked_in": []}} + assert held["beta"] == ("question Q2 dropped by the human: task shelved (reopen it, name " + "it in a brief, or /add it)") + assert held["gamma"] == "waiting on Q3 in your inbox" + assert held["delta"] == "waiting on Q4 in your inbox" + + +def test_an_unreadable_inbox_or_a_park_with_no_entry_keeps_every_hold(tmp_path): + slot = _home_with_parks(tmp_path) + before = orch.parked_elsewhere(slot) + assert set(before) == {"alpha", "beta", "gamma", "delta", "eps"} + resumes = {} + assert orch.parked_elsewhere(slot, None, resumes) == before and resumes == {} + assert orch.parked_elsewhere(slot, {}, resumes) == before and resumes == {} + # An answer from another shift's park does not release this one. + other = {"alpha": [{"id": "Q9", "shift": "2026-11-01-am", "state": "answered"}]} + assert orch.parked_elsewhere(slot, other, resumes) == before and resumes == {} + + +def test_a_later_park_holds_again_and_a_later_finish_releases(tmp_path): + slot = _home_with_parks(tmp_path) + later = slot.parent / "2026-11-15-am" + later.mkdir() + (later / "counters.json").write_text(json.dumps({ + "outcomes": {"alpha": {"questions": [Q2], "prs": [], "merged": []}, + "beta": {"prs": ["https://github.com/example-org/w/pull/1"]}}, + "parked": []})) + resumes = {} + held = orch.parked_elsewhere(slot, _inbox(alpha="answered", beta="dropped"), resumes) + assert "alpha" in held and "alpha" not in resumes # parked again, no entry yet + assert "beta" not in held # finished since + + +def _resumed_in(home, name, task, outcome=None, workers=None): + d = home / name + d.mkdir() + (d / "counters.json").write_text(json.dumps({ + "outcomes": {task: outcome} if outcome else {}, "parked": [], + "picks": {task: {"prompt": f"active/{task}.md"}}, + "workers": workers or [{"key": "0000000a", "task": task, + "spawned": f"{name[:10]}T09:00:00Z", "exits": ["spawned"]}]})) + + +@pytest.mark.parametrize("outcome,exits", [ + (None, ["spawned"]), # still out at its review-at + (None, ["spawned", "crashed", "late"]), # crashed, or abandoned +]) +def test_a_release_is_used_up_by_the_shift_that_resumed_it(tmp_path, outcome, exits): + """#645 review: one answer resumes a task once. A resume that did not + finish holds it again — never a second worker on the same claim.""" + slot = _home_with_parks(tmp_path) + _resumed_in(slot.parent, "2026-11-15-am", "alpha", outcome, + [{"key": "0000000a", "task": "alpha", "spawned": "2026-11-15T09:00:00Z", + "exits": exits}]) + resumes = {} + held = orch.parked_elsewhere(slot, _inbox(alpha="answered"), resumes) + assert "alpha" not in resumes + assert held["alpha"] == ("resumed in shift 2026-11-15-am after Q1 and not finished — not " + "resumed again until a new answer (or name it in a brief)") + # A re-answer given after that pick releases it once more. + resumes = {} + held = orch.parked_elsewhere(slot, _inbox(answered_at="2026-11-15T12:00Z", + alpha="answered"), resumes) + assert "alpha" not in held and resumes["alpha"]["ids"] == ["Q1"] + assert resumes["alpha"]["picked_in"] == ["2026-11-15-am"] + + +def test_a_resume_that_parks_again_waits_on_its_new_question(tmp_path): + slot = _home_with_parks(tmp_path) + _resumed_in(slot.parent, "2026-11-15-am", "alpha", + {"questions": [Q2], "prs": [], "merged": []}) + held = orch.parked_elsewhere(slot, _inbox(alpha="answered"), {}) + assert held["alpha"].startswith("parked on a question in shift 2026-11-15-am") + + +# --- the reader, the op, and Mind origin/main (real git) --------------------------- + +def git(cwd, *args, check=True): + res = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True) + if check: + assert res.returncode == 0, (args, res.stderr) + return res + + +ACTIVE = """# Active tasks + +## alpha-claim +- status: library-dev +- prompt: active/alpha.md +- session: shift worker 2026-11-14-pm2 (00000001) +- repos: + - widgets_ws + +## beta +- status: library-dev +- prompt: active/beta.md +- session: claude-code desktop (WSL), interactive + +## gears-claim +- status: library-dev +- prompt: active/gears.md +- session: claude-code desktop (WSL), interactive +- repos: + - gears_ws +""" + +PROMPT = """\ +# {name} + +Type: docs +Target: widgets_ws +Repos: +- widgets_ws +Lane: any +Difficulty: small +Autonomy: supervised +Priority: normal +Status: formalised +Consequence: glance +Witness: a unit test +Review-minutes: 3 +Unattended: ready + +Body. +""" + + +def _git_mind(tmp_path, questions: str | None = None): + """(bare remote, canonical clone) of a fictional Mind with the real scripts.""" + bare = tmp_path / "remote" / "PyAutoMind.git" + git(tmp_path, "init", "-q", "--bare", "-b", "main", str(bare)) + seed = tmp_path / "seed" + git(tmp_path, "clone", "-q", str(bare), str(seed)) + for repo in (seed,): + git(repo, "config", "user.name", "Test") + git(repo, "config", "user.email", "test@example.invalid") + (seed / "scripts").mkdir() + for name in ("ledger_merge.py", "lifecycle.py", "questions_edit.py"): + shutil.copy(MIND_SRC / "scripts" / name, seed / "scripts" / name) + (seed / "active").mkdir() + for n in ("alpha", "beta"): + (seed / "active" / f"{n}.md").write_text(PROMPT.format(name=n.title())) + (seed / "draft" / "docs" / "widgets_ws").mkdir(parents=True) + (seed / "draft" / "docs" / "widgets_ws" / "gamma.md").write_text( + PROMPT.format(name="Gamma")) + (seed / "active.md").write_text(ACTIVE) + (seed / "repos.yaml").write_text("repos:\n PyAutoMind:\n github: example-org/PyAutoMind\n") + if questions is not None: + (seed / "questions.md").write_text(questions) + git(seed, "add", "-A") + git(seed, "commit", "-q", "-m", "seed") + git(seed, "push", "-q", "origin", "HEAD:main") + canon = tmp_path / "canon" + git(tmp_path, "clone", "-q", str(bare), str(canon)) + git(canon, "config", "user.name", "Test") + git(canon, "config", "user.email", "test@example.invalid") + return bare, canon + + +def _entry(task, issue=Q1, shift="2026-11-14-pm2", ask="Brass or steel?"): + return {"task": task, "issue": issue, "kind": "question", "ask": ask, + "options": ["brass", "steel"], "shift": shift, "asked": "2026-11-14T18:12Z", + "worker": "00000001"} + + +@needs_mind +def test_the_question_add_op_lands_through_minds_own_add_text(tmp_path, monkeypatch): + monkeypatch.setattr(sys, "dont_write_bytecode", False) + bare, canon = _git_mind(tmp_path) + slot = tmp_path / "slot" + ledger = slot / mw.LEDGER_DIR + mw.queue_op(ledger, _questions.add_op(_entry("draft/docs/widgets_ws/alpha.md"))) + mw.queue_op(ledger, _questions.add_op(_entry("draft/docs/widgets_ws/gamma.md", Q2))) + mw.queue_op(ledger, _questions.add_op(_entry("draft/docs/widgets_ws/gone.md"))) + res = mw.commit_ledger(slot, canon, "shift test: questions") + assert res["committed"] and res["ops"] == 2 + assert [a["why"] for a in res["set_aside"]] == [ + "question-add: task draft/docs/widgets_ws/gone.md is in neither draft/ nor active/ " + "on Mind main — set aside, nothing to resume"] + assert res["held"] == [] + text = git(bare, "show", "main:questions.md").stdout + entries = _questions.parse(text) + assert [(e["id"], e["state"], e["fields"]["task"]) for e in entries] == [ + ("Q1", "open", "active/alpha.md"), # claimed since: resolved + ("Q2", "open", "draft/docs/widgets_ws/gamma.md")] + # The canonical tree is untouched, no Mind module or path leaks, and no + # bytecode was committed. + assert git(canon, "status", "--porcelain").stdout == "" + assert "lifecycle" not in sys.modules or "PyAutoMind" not in str( + getattr(sys.modules.get("lifecycle"), "__file__", "")) + assert not any("mind-writer-" in p for p in sys.path) + assert "__pycache__" not in git(bare, "ls-tree", "-r", "--name-only", "main").stdout + # A replay of the same op is a skipped note, never a Q3. + mw.queue_op(ledger, _questions.add_op(_entry("draft/docs/widgets_ws/alpha.md"))) + res = mw.commit_ledger(slot, canon, "shift test: replay") + assert res["committed"] is None + assert res["skipped"] == ["question-add: already in questions.md as Q1 — skipped"] + # And lifecycle check stays clean on what landed. + tree = tmp_path / "check" + git(tmp_path, "clone", "-q", str(bare), str(tree)) + out = subprocess.run([sys.executable, "scripts/lifecycle.py", "check"], cwd=tree, + capture_output=True, text=True, env=dict(os.environ, LIFECYCLE_NO_GH="1")) + assert "questions.md" not in out.stdout, out.stdout + + +def test_question_add_validation(): + lm = type("lm", (), {"is_ledger_path": staticmethod(lambda p: p in ("questions.md", + "queue.md"))}) + good = _questions.add_op(_entry("draft/x/y/z.md")) + assert mw.validate_op(good, lm) == [] + assert "path must be questions.md" in mw.validate_op(dict(good, path="queue.md"), lm)[0] + bad = dict(good, entry=dict(good["entry"], ask="two\nlines", extra="x")) + errs = mw.validate_op(bad, lm) + assert any("unknown entry keys extra" in e for e in errs) + assert any("ask must be one non-empty line" in e for e in errs) + assert any("options must be a list" in e for e in mw.validate_op( + dict(good, entry=dict(good["entry"], options="brass")), lm)) + + +@needs_mind +def test_read_origin(tmp_path): + bare, canon = _git_mind(tmp_path) + assert _questions.read_origin(canon) == {} # nothing asked yet + assert _questions.read_origin(tmp_path / "not-a-checkout") is None + other = tmp_path / "other" + git(tmp_path, "clone", "-q", str(bare), str(other)) + git(other, "config", "user.name", "Test") + git(other, "config", "user.email", "test@example.invalid") + sys.path.insert(0, str(MIND_SRC / "scripts")) + import questions_edit as qe + text, _q, _a = qe.add_text(qe.TEMPLATE, _entry("active/alpha.md")) + (other / "questions.md").write_text(text) + git(other, "add", "-A") + git(other, "commit", "-q", "-m", "q") + git(other, "push", "-q", "origin", "HEAD:main") + fetched = [] + got = _questions.read_origin(canon, fetch=lambda: fetched.append( + git(canon, "fetch", "-q", "origin", "main"))) + assert fetched and got == {"alpha": [{"id": "Q1", "shift": "2026-11-14-pm2", "issue": Q1, + "state": "open", "answer": "", "comment": "", + "kind": "question", "task": "active/alpha.md", + "answered": ""}]} + + +@needs_mind +def test_reader_parity_with_minds_parser(): + sys.path.insert(0, str(MIND_SRC / "scripts")) + import questions_edit as qe + text, _q, _a = qe.add_text(qe.TEMPLATE, _entry("active/alpha.md")) + text, _q, _a = qe.add_text(text, _entry("draft/x/y/gamma.md", Q2, ask="Second?")) + text, _q, _a = qe.add_text(text, _entry("draft/x/y/delta.md", ask="Third?")) + import lifecycle + text = lifecycle.question_move_text(text, "Q2", "answered", + {"answered": "t by h (chat)", "answer": "yes"}) + text = lifecycle.question_move_text(text, "Q3", "dropped", {"dropped": "d by h — no"}) + mine = [(e["id"], e["n"], e["title"], e["state"], e["fields"]) for e in _questions.parse(text)] + theirs = [(e["id"], e["n"], e["title"], e["state"], e["fields"]) for e in qe.parse(text)] + assert mine == theirs and [m[3] for m in mine] == ["open", "answered", "dropped"] + + +# --- resume: a claimed task, the shift-worker rule, RESUME_NOTE --------------------- + +@needs_mind +def test_a_claimed_task_resumes_only_with_a_shift_worker_session(tmp_path): + bare, canon = _git_mind(tmp_path) + resumes = {"alpha": {"ids": ["Q1"], "shift": "2026-11-14-pm2", "comments": [], + "picked_in": ["2026-11-14-pm2"]}, + "beta": {"ids": ["Q2"], "shift": "2026-11-14-pm2", "comments": [], + "picked_in": ["2026-11-14-pm2"]}} + # The canonical checkout still shows stale drafts nobody pulled. + stale = [{"path": "draft/docs/widgets_ws/alpha.md", "repos": ["widgets_ws"], + "declared_repos": ["widgets_ws"]}, + {"path": "draft/docs/widgets_ws/beta.md", "repos": ["widgets_ws"], + "declared_repos": ["widgets_ws"]}] + recs = orch.resume_records(stale, canon, resumes) + assert sorted(r["path"] for r in recs) == ["active/alpha.md", "active/beta.md"] + assert all(r["resume"]["ids"] for r in recs) + for r in recs: # fictional repos: the grader knows none, so declare them here + r["declared_repos"] = ["widgets_ws"] + kept, out = orch.on_origin(recs, canon, set(), resumes=resumes) + assert [r["path"] for r in kept] == ["active/alpha.md"] # its own repo claim ignored + # A repo another claim holds still keeps it out. + held = [dict(recs[0], declared_repos=["gears_ws"])] + kept2, out2 = orch.on_origin(held, canon, set(), resumes=resumes) + assert kept2 == [] and out2 == { + "active/alpha.md": "repo gears_ws claimed by `gears-claim` in active.md on Mind origin/main"} + assert out == {"active/beta.md": "resumed after Q2, but its claim `beta` in active.md is " + "not this home's shift worker's (session: claude-code " + "desktop (WSL), interactive) — left to the human"} + # A shift-worker line from a slot of another home (or one that never + # picked the task) is not trusted either. + other = {"alpha": dict(resumes["alpha"], picked_in=["2026-11-01-am"])} + kept3, out3 = orch.on_origin(recs[:1], canon, set(), resumes=other) + assert kept3 == [] and "not this home's shift worker's" in out3["active/alpha.md"] + # Without a release, the same claimed tasks are dropped as before. + kept, out = orch.on_origin(recs, canon, set()) + assert kept == [] and set(out) == {"active/alpha.md", "active/beta.md"} + + +def test_the_resumed_worker_prompt_carries_resume_note_and_the_pick_names_the_answer(tmp_path): + resume = {"ids": ["Q17"], "shift": "2026-11-14-pm2", + "comments": [f"{Q1}#issuecomment-9"], "answers": ["(a) brass"]} + argv = orch.session_command("alpha", "active/alpha.md", tmp_path / "shift.md", + tmp_path / "leases", "auto", resume=resume) + prompt = argv[-1] + assert prompt.startswith("This task parked on a question in shift `2026-11-14-pm2` and " + "the human has answered\nit (Q17): see \"## Answers from the " + "human\" in your prompt (and " + f"{Q1}#issuecomment-9).") + assert "do not queue the claim\nagain" in prompt + assert "The answer:\n> (a) brass\n" in prompt + assert "Use the start-dev skill. active/alpha.md --auto" in prompt + assert "RE-DISPATCH" not in prompt + rec = orch.pick_record({"path": "active/alpha.md", "resume": resume, "queued": True, + "queue_rank": 1}, {"backlog": {"value": "fill-idle"}}) + assert rec["why"] == "resumed after Q17 was answered · backlog: fill-idle · queue.md #2" + + +def test_the_worker_template_pins_the_session_line_and_the_sidecar(): + text = (BATCH / "worker_template.md").read_text() + assert "- session: shift worker" in text + assert ".question.json" in text and "the watcher @-mentions" not in text + assert orch.shift_worker_slot("shift worker 2026-11-16-am (00000001)") == "2026-11-16-am" + for loose in ("Claude Code background job (shift 2026-11-14-pm2 worker)", + "claude-code shift worker (batch 2026-11-14-pm2, --auto)", + "claude-code desktop (WSL)", "taken over: shift worker x (y) by hand"): + assert orch.shift_worker_slot(loose) == "", loose + + +# --- the dashboard section ---------------------------------------------------------- + +_spec = importlib.util.spec_from_file_location( + "_intake_questions_under_test", BRAIN / "agents" / "conductors" / "intake" / "_intake.py") +_intake = importlib.util.module_from_spec(_spec) +sys.modules["_intake_questions_under_test"] = _intake +_spec.loader.exec_module(_intake) + +QUESTIONS = """# Questions + +```markdown +### Q. — +- task: draft///.md +``` + +## Open + +### Q17. sprockets — Brass or steel? +- task: draft/feature/widgets/sprockets.md +- issue: https://github.com/example-owner/widgets/issues/70 +- kind: question +- ask: Brass or steel? +- options: (a) brass · (b) steel +- shift: 2026-11-14-pm2 +- asked: 2026-11-14T18:12Z +- worker: a1b2c3d4 + +## Deferred + +### Q18. levers — Which lever? +- task: draft/feature/widgets/levers.md +- issue: https://github.com/example-owner/widgets/issues/71 +- kind: question +- ask: Which lever? +- shift: 2026-11-14-pm2 +- asked: 2026-11-14T18:30Z +- worker: a1b2c3d4 +- until: 2026-11-20 + +## Answered + +### Q16. gears — Done? +- task: draft/feature/widgets/gears.md +- issue: https://github.com/example-owner/widgets/issues/69 +- kind: question +- ask: Done? +- shift: 2026-11-14-pm +- asked: 2026-11-14T10:00Z +- worker: a1b2c3d4 +- answered: 2026-11-15T09:00Z by example-human (chat) +- answer: yes + +## Dropped +""" + + +def _dash_mind(tmp_path, questions=QUESTIONS): + sys.path.insert(0, str(BRAIN / "tests")) + import test_intake_dashboard_queue as q + root = q._mind(tmp_path) + if questions is not None: + (root / "questions.md").write_text(questions, encoding="utf-8") + return root + + +def _csp(page): + return re.search(r"script-src '(sha256-[^']+)'", page).group(1) + + +def test_the_inbox_section_renders_read_only_with_copy_buttons(tmp_path): + with_q = _intake.render_dashboard_html(_intake.census(_dash_mind(tmp_path / "a"))) + without = _intake.render_dashboard_html(_intake.census(_dash_mind(tmp_path / "b", None))) + # The CSP hash is unchanged: no new script, the page's one handler serves it. + assert _csp(with_q) == _csp(without) + script = re.findall(r"", with_q, re.S) + assert len(script) == 1 + assert _csp(with_q) == "sha256-" + base64.b64encode( + hashlib.sha256(script[0].encode()).digest()).decode() + box = with_q[with_q.index('")] + assert "Questions (1 open, 1 deferred)" in box + assert '