diff --git a/AUTONOMY.md b/AUTONOMY.md index 09e9ec0d..7e535079 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -1094,6 +1094,8 @@ The questions inbox (M3.5, PyAutoBrain#645) changes the watcher's surface by: worker's claim with the answer in its prompt. A dropped question shelves the task (H9 a). An unreadable inbox keeps every hold. +6. **The readiness pass (M3.3, PyAutoBrain#671)** runs offline at shift end (no fetch, no gh; Mind read from its local `origin/main`) and files each gate on the queue's next units as a `ruling` through the one Mind writer (`question-add`), never a direct push to Mind main. + 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. diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index d3063303..58f10a9e 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -595,6 +595,21 @@ 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. +**The readiness pass (M3.3, PyAutoBrain#671, `_ready.py`).** `batch ready` +resolves each `queue.md` entry to its next unit(s) (an epic ledger to its open +members at the lowest phase, in `draft/` and `active/`), checks the gates +(`looks-shipped` and `obsolete` first, then `claimed`, `unattended`, +`human-required`, `blocked-by`, `no-lane`; an epic with no open member is +`no-next-phase`) and files each as an inbox entry of kind `ruling` (a `gate:`, +no `issue:`), skipping a task and gate already ruled on Mind origin/main in +any state (once answered or dropped it stays quiet; `/questions` reopen asks +again — the human's ruling, 2026-11-18) and filing none while Mind main has +no `ruling` kind. Dry run by default; +`--queue ` queues `question-add` ops, `--apply` writes a session-branch +checkout (never main). `finish_shift` runs it offline before the digest, whose +last line is "The next shift needs N rulings from you." Rulings never hold or +release a parked task, and the inbox line leaves them out. + **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 86637e15..c1a794eb 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -2968,7 +2968,8 @@ 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", "questions"], nargs="?", + "slice", "premise", "green", "questions", "ready"], + nargs="?", default="plan") ap.add_argument("prompt", nargs="?", default="", help="slice: the needs-slicing prompt to decompose; " @@ -3035,6 +3036,12 @@ def main(argv=None) -> int: 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)") + # ready (M3.3, PyAutoBrain#671) + ap.add_argument("--queue", type=Path, default=None, metavar="SLOT_DIR", dest="queue_slot", + help="ready: queue each new ruling as a question-add op in this " + "shift slot's Mind-writer ledger (default: a dry run that " + "writes nothing); --apply instead writes them into --mind's " + "questions.md on a session branch (never main, no commit)") # watch ap.add_argument("--once", action="store_true", help="watch: print one snapshot and exit") @@ -3115,6 +3122,8 @@ def main(argv=None) -> int: return _main_green(mind, a) if a.verb == "questions": return _main_questions(mind, a) + if a.verb == "ready": + return _main_ready(mind, a) return _main_plan(mind, a, lane) except BatchUsageError as e: print(e, file=sys.stderr) @@ -3134,6 +3143,46 @@ def _main_questions(mind: Path, a) -> int: return 0 +def _main_ready(mind: Path, a) -> int: + """`batch ready [--queue SLOT_DIR | --apply] [--fetch] [--root DIR]` — the + readiness pass (M3.3, PyAutoBrain#671, `_ready`): every queue.md entry's + next unit(s), their gates, and the rulings it would file. A dry run by + default; the premise check is offline unless `--fetch`.""" + import _ready + if a.queue_slot is not None and a.apply: + raise BatchUsageError("batch ready: --queue and --apply are exclusive") + if not (mind / "queue.md").is_file() and not (mind / "draft").is_dir(): + print(f"batch: no PyAutoMind backlog at {mind}", file=sys.stderr) + return RC_NO_MIND + slot = a.queue_slot.resolve() if a.queue_slot is not None else None + if slot is not None and _ready.slot_refusal(slot): + print(_ready.slot_refusal(slot), file=sys.stderr) + return RC_USAGE + res = _ready.run(mind, root=a.root, fetch=a.fetch, + shift=slot.name if slot is not None else "") + if a.apply: + try: + written = _ready.apply(res, mind) + except _ready.ApplyRefused as e: + print(e, file=sys.stderr) + return RC_USAGE + print(_ready.report(res, written=written)) + return RC_OK + if slot is not None: + try: + queued = _ready.queue(res, slot) + except _ready.QueueRefused as e: + print(e, file=sys.stderr) + return RC_USAGE + print(_ready.report(res, queued=queued, slot=slot)) + return RC_OK + if a.as_json: + print(json.dumps({k: v for k, v in res.items()}, indent=2, default=str)) + else: + print(_ready.report(res)) + return RC_OK + + 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 b7cdbc71..e8d72621 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -613,6 +613,14 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None, lines += ["", REFUSALS_HEADING] + (refusal_lines(counters) or [NO_PICKS]) lines += report_lines(slot) lines += identity_lines(counters) + # The readiness pass's count is the digest's last line (M3.3, #671). + try: + import _ready # noqa: E402 — deferred: it imports the batch conductor + lines += _ready.digest_lines(counters) + except Exception as e: # noqa: BLE001 — never break the digest + if "rulings" in counters: + lines += ["", f"Readiness pass failed: the digest could not read it " + f"({type(e).__name__}: {e})"[:240]] return "\n".join(lines) + "\n" diff --git a/agents/conductors/batch/_mind_writer.py b/agents/conductors/batch/_mind_writer.py index f57ff0bb..1a4c0d17 100644 --- a/agents/conductors/batch/_mind_writer.py +++ b/agents/conductors/batch/_mind_writer.py @@ -26,6 +26,7 @@ {"op": "question-add", "path": "questions.md", "entry": {"task": …, "issue": …, "kind": …, "ask": …, "options": [...], "shift": …, "asked": …, "worker": …}} + (kind `ruling`, from the readiness pass: `gate` required, `issue` optional) {"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 @@ -129,7 +130,11 @@ #: The `needs` of a set-aside op: already true on main, or the human's call. NEEDS_MECHANICAL, NEEDS_HUMAN = "mechanical", "human" #: The keys a `question-add` entry carries; all strings but `options`. -QUESTION_KEYS = ("task", "issue", "kind", "ask", "options", "shift", "asked", "worker") +QUESTION_KEYS = ("task", "issue", "kind", "ask", "options", "shift", "asked", "worker", + "gate") +#: A `ruling` (the readiness pass's, M3.3, PyAutoBrain#671) needs `gate` and +#: may have no `issue`; every other kind needs `issue` and has no `gate`. +QUESTION_RULING = "ruling" #: 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)" @@ -304,8 +309,15 @@ def validate_op(op: dict, lm) -> list[str]: extra = sorted(set(entry) - set(QUESTION_KEYS)) if extra: errs.append(f"question-add: unknown entry keys {', '.join(extra)}") + ruling = entry.get("kind") == QUESTION_RULING for k in QUESTION_KEYS: v = entry.get(k) + if (k == "issue" and ruling and v is None) or (k == "gate" and not ruling + and v is None): + continue + if k == "gate" and not ruling: + errs.append("question-add: gate is for kind ruling only") + continue 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") diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 45ba19c7..ffd7f3c5 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -3328,6 +3328,9 @@ def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, # is named in the digest itself, which still reaches the record. _auth().failed() _note_auth(counters, now) + # The readiness pass (M3.3, PyAutoBrain#671): every gate on the next + # shift's queue becomes a ruling, queued for this shift's one Mind writer. + readiness_pass(slot, counters, mind, now) # Everything the Mind writer reported so far is in this digest; what it # reports from here on reaches the human through the late sweep (#632). counters["ledger_reported"] = len(_mind_writer.report(slot)) @@ -3371,6 +3374,23 @@ def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, return result +def readiness_pass(slot: Path, counters: dict, mind: Path, now: _dt.datetime) -> None: + """Run `batch ready` at shift end (M3.3, PyAutoBrain#671): offline (the + premise check never fetches, no gh), against the watcher's Mind, each new + ruling queued as a `question-add` op in this shift's own ledger and noted + in `counters["rulings"]`. A shadow shift runs it too: its digest is + written through the same writer. A failure never breaks the close: its + reason is recorded and the digest says so.""" + try: + import _ready # noqa: E402 — inside the try: an import failure is a failed pass + res = _ready.run(mind, fetch=False, shift=Path(slot).name, now=now) + _ready.queue(res, slot, counters) + except Exception as e: # noqa: BLE001 — the digest must still be written + r = counters.setdefault("rulings", {}) + r.setdefault("new", []) + r["error"] = f"{type(e).__name__}: {e}"[:200] + + def _close_status(brief_path: Path, slot: Path, issue: str, now: _dt.datetime, agents, github=None, *, mind=None) -> dict | None: """One last edit of the status comment at `review-at:`, saying the shift diff --git a/agents/conductors/batch/_questions.py b/agents/conductors/batch/_questions.py index a80e63eb..fba6a87d 100644 --- a/agents/conductors/batch/_questions.py +++ b/agents/conductors/batch/_questions.py @@ -97,6 +97,7 @@ def by_task(entries: list[dict]) -> dict[str, list[dict]]: "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", ""), + "gate": f.get("gate", ""), "answered": (f.get("answered") or "").split(" ")[0], "task": f.get("task", "")}) return out @@ -132,6 +133,21 @@ def git(*args): # --- the parked hold ------------------------------------------------------------- +#: The inbox kind the readiness pass files (M3.3, PyAutoBrain#671): a gate on a +#: queued task for the human to rule on. It is answered like a question but +#: never holds or releases a parked task, and the inbox line leaves it out. +RULING = "ruling" + + +def is_ruling(e: dict) -> bool: + return (e.get("kind") or "") == RULING + + +def questions_only(entries) -> list[dict]: + """The entries that are questions (or blocked), not rulings.""" + return [e for e in entries or [] if not is_ruling(e)] + + 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; @@ -140,7 +156,7 @@ def hold_for(task: str, shift: str, inbox: dict | None) -> tuple[str, dict | Non ("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] + mine = [e for e in questions_only(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"] @@ -160,7 +176,7 @@ def answered_since(task: str, inbox: dict | None, at: str) -> dict | None: task's entries is still open, deferred or dropped; else None.""" if inbox is None: return None - mine = inbox.get(task) or [] + mine = questions_only(inbox.get(task)) if any(e["state"] != "answered" for e in mine): return None fresh = [e for e in mine if (e.get("answered") or "") > (at or "")] @@ -205,7 +221,15 @@ def add_op(entry: dict) -> dict: 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.""" + (task, issue). A ruling goes in `counters["rulings"]["new"]` instead, once + per (task, gate): the two are never counted together. True when it is new.""" + if is_ruling(entry): + new = counters.setdefault("rulings", {}).setdefault("new", []) + key = (Path(entry["task"]).stem, entry.get("gate", "")) + if any((r.get("task"), r.get("gate")) == key for r in new): + return False + new.append({"task": key[0], "path": entry["task"], "gate": key[1]}) + return True seen = counters.setdefault("inbox", []) key = (Path(entry["task"]).stem, entry["issue"]) if any((q.get("task"), q.get("issue")) == key for q in seen): @@ -251,9 +275,13 @@ def inbox_line(counters: dict, slot_name: str, mind=None, origin=None) -> str: 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] + # Rulings (the readiness pass's) are not questions: the digest's last + # line counts them. + mine = [e for es in origin.values() for e in questions_only(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) + open_n = sum(e["state"] == "open" for es in origin.values() + for e in questions_only(es)) n = len(added) line = f"Inbox: {n} question{'s' if n != 1 else ''} added to your inbox this shift" if ids: diff --git a/agents/conductors/batch/_ready.py b/agents/conductors/batch/_ready.py new file mode 100644 index 00000000..6aada53a --- /dev/null +++ b/agents/conductors/batch/_ready.py @@ -0,0 +1,568 @@ +"""The readiness pass, `batch ready` (M3.3 slice 1, PyAutoBrain#671). + +It walks Mind `queue.md`, resolves each entry to its next startable unit(s), +checks each unit's gates, and turns every gate into an inbox entry of kind +`ruling` for the human. The next launch is then `brief --new`, read, go, +instead of a kick-off chat that finds each epic's next unit and asks the +rulings one at a time. + +Resolution (human decisions D3, 2026-11-18): + +- an epic ledger (a prompt with `Epic:` and no `Phase:`) resolves to every + open member of that epic at the lowest leading phase number (`5c` is 5), + scanning `draft/` and `active/`. A member in `active/` is in flight, not + gated. An epic with no open `Phase:` member is one ruling on the ledger, + gate `no-next-phase`. The ledgers' free-form phase tables are not read; +- any other prompt resolves to itself, in flight when it is in `active/`. + +Gates on each draft unit (Q5): `looks-shipped`, then `obsolete` (the premise +check, offline unless `--fetch`), and either one stops the rest. Then each of +`claimed`, `unattended`, `human-required`, `blocked-by` and `no-lane` that +applies is its own ruling. A `judge` unit gets a note (D4: a tier is not a +gate). + +What it writes: nothing on a dry run. `queue` puts one `question-add` op per +new ruling in a slot's ledger, for the shift's one Mind writer, and records +`counters["rulings"]`; `apply` writes them into a session-branch Mind checkout +through Mind's own `questions_edit.add_text` (never on `main`, never a commit +or a push). A ruling still Open or Deferred on Mind `origin/main` for the same +task and gate is not filed again. Everything on the Mind side is read from the +local `origin/main` ref: no fetch. +""" + +from __future__ import annotations + +import datetime as _dt +import os +import re +import subprocess +from pathlib import Path + +import _batch +import _mind_writer +import _questions +from _steer import read_queue_entries + +WORKER = "readiness pass" +GATES = ("no-next-phase", "looks-shipped", "obsolete", "claimed", "unattended", + "human-required", "blocked-by", "no-lane") +NOT_FILED_KIND = "Mind has no `ruling` inbox kind yet (PyAutoBrain#671)" +_KINDS_RE = re.compile(r"^QUESTION_KINDS\s*=\s*\(([^)]*)\)", re.M) + + +# --- reading the Mind ------------------------------------------------------------ + +def _git(mind, *args): + return subprocess.run(["git", "-C", str(mind), *args], capture_output=True, text=True, + timeout=60) + + +def mind_has_ruling(mind, ref: str = "origin/main") -> str: + """"" when Mind `ref`'s `scripts/lifecycle.py` lists `ruling` in its + `QUESTION_KINDS` (a local `git show`, no fetch); else why rulings are not + filed.""" + try: + shown = _git(mind, "show", f"{ref}:scripts/lifecycle.py") + except (OSError, subprocess.SubprocessError) as e: + return f"Mind {ref} unreadable ({e})"[:200] + if shown.returncode != 0: + return f"Mind {ref}:scripts/lifecycle.py unreadable — {NOT_FILED_KIND}" + m = _KINDS_RE.search(shown.stdout) + return "" if m and re.search(r"['\"]ruling['\"]", m.group(1)) else NOT_FILED_KIND + + +def _read(path: Path) -> str: + try: + return path.read_text(encoding="utf-8", errors="replace") + except OSError: + return "" + + +def resolve_ref(mind: Path, ref: str) -> str: + """Where a queue ref's prompt is now, Mind-relative: itself, else the same + file name in `draft/` or `active/`; "" when it is in neither.""" + if not ref: + return "" + if (mind / ref).is_file() and ref.startswith(("draft/", "active/")): + return ref + name = Path(ref).name + hit = next(iter(sorted(mind.glob(f"draft/**/{name}"))), None) or ( + mind / "active" / name if (mind / "active" / name).is_file() else None) + return hit.relative_to(mind).as_posix() if hit else "" + + +def epic_members(mind: Path, epic: str) -> list[dict]: + """Every open (not done) member of `epic` with a `Phase:`, in `draft/` and + `active/`: `{path, phase}`.""" + out = [] + files = [*sorted(mind.glob("draft/**/*.md")), *sorted(mind.glob("active/*.md"))] + for f in files: + if f.name == "README.md": + continue + text = _read(f) + if _batch._epic_of(text) != epic or not _batch._phase_declared(text) \ + or _batch._is_done(text): + continue + out.append({"path": f.relative_to(mind).as_posix(), "phase": _batch._phase_of(text)}) + return out + + +def is_ledger(text: str) -> bool: + """An epic ledger: `Status: campaign map` with `Epic:` and no `Phase:` + (as intake's `_shipped` reads a map). A side task of an epic (`Epic:`, no + `Phase:`, any other status) is an ordinary prompt.""" + return bool(_batch._epic_of(text)) and not _batch._phase_declared(text) \ + and _batch._header_of(text, "status").lower().startswith("campaign map") + + +def origin_epic_members(mind: Path, epic: str, ref: str = "origin/main") -> list[dict] | None: + """The open `Phase:` members of `epic` in `draft/` and `active/` on Mind + `ref`, read locally (`git grep`, `git show`; no fetch): `{path, phase}`. + None when the ref cannot be read (not a git checkout of its own).""" + try: + top = _git(mind, "rev-parse", "--show-toplevel") + if top.returncode != 0 or Path(top.stdout.strip()).resolve() != Path(mind).resolve(): + return None + hits = _git(mind, "grep", "-l", "-i", "-E", rf"^Epic:[[:space:]]*{re.escape(epic)}", + ref, "--", "draft/", "active/") + except (OSError, subprocess.SubprocessError): + return None + if hits.returncode not in (0, 1): + return None + out = [] + for line in hits.stdout.splitlines(): + path = line.split(":", 1)[1] if line.startswith(f"{ref}:") else line + if not path.endswith(".md") or Path(path).name == "README.md": + continue + shown = _git(mind, "show", f"{ref}:{path}") + if shown.returncode != 0: + continue + text = shown.stdout + if _batch._epic_of(text) != epic or not _batch._phase_declared(text) \ + or _batch._is_done(text): + continue + out.append({"path": path, "phase": _batch._phase_of(text)}) + return out + + +BEHIND = "Mind working tree behind origin/main — rerun after a pull" + + +def behind_origin(local: list[dict], origin: list[dict] | None) -> bool: + """Whether origin/main has an open member the working tree lacks, or the + two disagree on the lowest phase (None: origin not read, not behind).""" + if origin is None: + return False + names = {Path(m["path"]).name for m in local} + if any(Path(m["path"]).name not in names for m in origin): + return True + low = lambda ms: min((m["phase"] for m in ms), default=None) # noqa: E731 + return low(local) != low(origin) + + +def _phase_label(p: float) -> str: + return f"{p:g}" if p != float("inf") else "(unnumbered)" + + +# --- the rulings ------------------------------------------------------------------- + +def _options(*opts) -> list[str]: + return [_questions.sanitise(o, _questions.OPTION_MAX) for o in opts if o][:3] + + +def ruling(task: str, gate: str, ask: str, options: list[str], shift: str, + asked: str) -> dict: + """One `question-add` entry of kind ruling (no `issue`).""" + return {"task": task, "kind": _questions.RULING, "gate": gate, + "ask": _questions.sanitise(ask, _questions.ASK_MAX), "options": options, + "shift": shift, "asked": asked, "worker": WORKER} + + +def _gate_rulings(r: dict, stem: str, held, premise: dict | None) -> list[tuple]: + """(gate, ask, options) for one draft unit, in the plan's order.""" + if r.get("looks_shipped"): + return [("looks-shipped", + f"`{stem}` looks shipped ({_batch._shipped.FLAGS_FILE}): confirm and close " + "it, or dismiss the flag?", + _options("close it as shipped", + f"dismiss the flag ({_batch._shipped.DISMISS_FILE})", + "drop it from the queue"))] + if premise and premise.get("status") == "obsolete": + why = "; ".join(premise.get("reasons") or [])[:120] or "see `batch premise`" + return [("obsolete", f"`{stem}`'s premise looks obsolete on main: {why}", + _options("retire the prompt", "rewrite its premise", "keep it as it is"))] + out = [] + if held: + repo, slug = held + out.append(("claimed", + f"`{stem}` cannot start: repo {repo} is claimed by `{slug}` in active.md " + "with no coordination line naming it.", + _options(f"wait for {slug} to ship", "record a coordination line", + "drop it from the queue"))) + if r.get("unattended") != "ready": + out.append(("unattended", + f"`{stem}` is Unattended: {r.get('unattended') or '?'}, so no shift " + "starts it.", + _options("make it ready (slice or size it)", + "keep it for an attended session", "drop it from the queue"))) + if r.get("autonomy") == "human-required": + out.append(("human-required", + f"`{stem}` is Autonomy: human-required, so a shift worker would park " + "at ship.", + _options("lower it to supervised", "keep it for an attended session", + "drop it from the queue"))) + if r.get("blocked"): + waits = "; ".join(r.get("blocked_by") or []) or "its Blocked-by" + out.append(("blocked-by", f"`{stem}` waits for {waits} (its Blocked-by).", + _options(f"wait for {waits}", "remove the Blocked-by", + "drop it from the queue"))) + if not r.get("lane"): + out.append(("no-lane", + f"`{stem}` has no valid Lane:, so every unattended pick fails closed.", + _options("declare Lane: any", "declare a laptop lane", + "drop it from the queue"))) + return out + + +def _premise_root() -> Path: + return Path(os.environ.get("PYAUTO_ROOT") or _batch.pyauto_root()).resolve() + + +def run(mind, *, root=None, fetch: bool = False, shift: str = "", now=None, + check_premise=None) -> dict: + """The pass, read-only. Returns `{entries, found, rulings, skipped, open, + not_filed, notes, shift}`: `found` is every gate as a ruling entry, + `rulings` those to file (no ruling on the same task and gate in any state + on Mind origin/main — once ruled, quiet — and none at all when Mind main + has no `ruling` kind), `skipped` the `(entry, id)` already ruled, `open` + the Open and Deferred rulings on Mind origin/main.""" + import _orchestrator as orch # noqa: E402 — deferred: it imports this module + mind = Path(mind) + now = now or _dt.datetime.now(_dt.timezone.utc) + asked = now.astimezone(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%MZ") + shift = shift or f"ready-{now.strftime('%Y-%m-%d')}" + notes: list[str] = [] + if check_premise is None: + import _premise + try: + proot = Path(root).resolve() if root is not None else _premise_root() + except Exception as e: # noqa: BLE001 — degrade: no premise check + proot = None + notes.append(f"premise check skipped: no workspace root ({e})") + views: dict = {} + + def check_premise(path: Path): + if proot is None: + return None + return _premise.safe_check(path, proot, fetch=fetch, offline=not fetch, + views=views) + queued = read_queue_entries(mind) + # The survey grades every draft: only when the queue names one. + records = {r["path"]: r for r in _batch.survey(mind)} if queued else {} + claims = orch.origin_claims(mind) + if claims is None: + notes.append("claims not read: the Mind is not a git checkout of its own") + elif "error" in claims: + notes.append(f"claims not read: {claims['error']}") + sections = (claims or {}).get("sections") or {} if claims and "error" not in claims \ + else None + entries, found = [], [] + for q in queued: + e = {"pos": q["pos"], "label": q["label"], "ref": q["ref"], "kind": q["kind"], + "path": "", "units": [], "notes": []} + entries.append(e) + if q["kind"] != "prompt": + e["notes"].append(f"kind {q['kind'] or '?'}: not a prompt, not resolved") + continue + path = resolve_ref(mind, q["ref"]) + e["path"] = path + if not path: + e["notes"].append("unresolved: its prompt is in neither draft/ nor active/") + continue + text = _read(mind / path) + epic = _batch._epic_of(text) + if is_ledger(text): + members = epic_members(mind, epic) + if behind_origin(members, origin_epic_members(mind, epic)): + e["notes"].append(f"epic {epic}: {BEHIND}; no ruling filed") + continue + if not members: + e["notes"].append(f"epic {epic}: no open Phase: member in draft/ or active/") + found.append(ruling( + path, "no-next-phase", + f"Epic {epic} is queued but no next-phase prompt is filed (no open " + "Phase: member in draft/ or active/).", + _options("file the next phase's prompt", "close the epic", + "drop it from the queue"), shift, asked)) + continue + low = min(m["phase"] for m in members) + unit_paths = sorted(m["path"] for m in members if m["phase"] == low) + e["notes"].append(f"epic {epic}: next phase {_phase_label(low)}") + else: + unit_paths = [path] + if epic and _batch._phase_declared(text) and not _batch._is_done(text): + # A Phase member queued directly that is not its epic's next + # phase: a note, not a gate (PyAutoBrain#671 review, M3). + low = min((m["phase"] for m in epic_members(mind, epic)), + default=float("inf")) + mine = _batch._phase_of(text) + if mine > low: + e["notes"].append(f"epic {epic} phase {_phase_label(mine)} is not next " + f"— phase {_phase_label(low)} is") + continue + for up in unit_paths: + u = {"path": up, "state": "draft", "gates": [], "notes": []} + e["units"].append(u) + stem = Path(up).stem + if up.startswith("active/"): + u["state"] = "in flight" + continue + r = records.get(up) + if r is None: + u["notes"].append("not graded (not in the draft/ survey)") + continue + if r.get("done"): + u["notes"].append("Status: says the work is done — retire it from the queue") + continue + if sections is not None and up not in claims["drafts"]: + # The working tree is behind: origin/main has moved it. + claim = orch.claim_of(sections, stem) + u["state"] = "in flight" if claim else "moved" + u["notes"].append( + f"not in draft/ on Mind origin/main — claimed by `{claim[0]}`" if claim + else "not in draft/ on Mind origin/main (moved or retired) — rerun " + "after a pull") + continue + if sections is not None and stem in claims["active"]: + u["state"] = "in flight" + u["notes"].append("claimed in active.md on Mind origin/main") + continue + held = orch._held_for(sections, stem, r.get("declared_repos") or r.get("repos") + or []) if sections is not None else None + premise = None + if not r.get("looks_shipped"): + premise = check_premise(mind / up) + for gate, ask, opts in _gate_rulings(r, stem, held, premise): + u["gates"].append(gate) + if not any((f["task"], f["gate"]) == (up, gate) for f in found): + found.append(ruling(up, gate, ask, opts, shift, asked)) + if r.get("consequence") == "judge": + u["notes"].append("judge tier: a human judges the result at review " + "(a note, not a gate)") + origin = _questions.read_origin(mind) + if origin is None: + notes.append("questions.md on Mind origin/main not read: open rulings not checked") + open_ = sorted(({"task": t, "gate": x.get("gate", ""), "id": x["id"]} + for t, xs in (origin or {}).items() for x in xs + if _questions.is_ruling(x) and x["state"] in ("open", "deferred")), + key=lambda x: int(x["id"][1:]) if x["id"][1:].isdigit() else 0) + # Once ruled, quiet (the human's L1 ruling, 2026-11-18): a ruling in any + # state — Open, Deferred, Answered or Dropped — keeps its task and gate + # from being filed again; `/questions` reopen asks again. An open one is + # named first. + ruled: dict = {} + for t, xs in (origin or {}).items(): + for x in xs: + if _questions.is_ruling(x): + key = (t, x.get("gate", "")) + if key not in ruled or x["state"] in ("open", "deferred"): + ruled[key] = x["id"] if x["state"] in ("open", "deferred") \ + else f"{x['id']}, {x['state']}" + rulings, skipped = [], [] + for f in found: + have = ruled.get((Path(f["task"]).stem, f["gate"])) + if have: + skipped.append((f, have)) + else: + rulings.append(f) + not_filed = mind_has_ruling(mind) + return {"mind": str(mind), "shift": shift, "entries": entries, "found": found, + "rulings": [] if not_filed else rulings, "would_file": rulings, + "skipped": skipped, "open": open_, "not_filed": not_filed, "notes": notes} + + +# --- writing ------------------------------------------------------------------------- + +def ops(res: dict) -> list[dict]: + return [_questions.add_op(r) for r in res["rulings"]] + + +def record(res: dict, counters: dict) -> list[dict]: + """Note the pass in `counters["rulings"]` (new rulings once per task and + gate, the Open ones on origin, why none were filed); the entries new to + this slot.""" + c = counters.setdefault("rulings", {}) + c.pop("error", None) + fresh = [r for r in res["rulings"] if _questions.note_added(counters, r)] + c["open"] = [{"task": o["task"], "gate": o["gate"], "id": o["id"]} for o in res["open"]] + if res["not_filed"]: + c["not_filed"] = f"{res['not_filed']} — {len(res['would_file'])} found" + else: + c.pop("not_filed", None) + return fresh + + +class QueueRefused(Exception): + pass + + +def slot_refusal(slot) -> str: + """Why `--queue` may not write into `slot`, or "": it must be an existing + watcher slot (its `counters.json` or Mind-writer ledger) whose digest is + not yet posted. Nothing is created.""" + import _orchestrator as orch # noqa: E402 + slot = Path(slot) + if not slot.is_dir(): + return f"--queue: no slot directory {slot}" + if not ((slot / orch.COUNTERS_FILE).is_file() or (slot / _mind_writer.LEDGER_DIR).is_dir()): + return (f"--queue: {slot} is not a watcher slot (no {orch.COUNTERS_FILE} or " + f"{_mind_writer.LEDGER_DIR}/)") + if (slot / orch.DIGEST_MARKER).exists(): + return f"--queue: {slot.name}'s digest is already posted — the shift is closed" + return "" + + +def queue(res: dict, slot, counters: dict | None = None, now=None) -> list[dict]: + """Queue one `question-add` op per new ruling into `slot`'s ledger and + record them. With `counters` (finish_shift's, inside its tick), they are + updated in place and not written. Else (`--queue`) the slot must pass + `slot_refusal`, and the slot's tick lock is taken, non-blocking, around + the read and write of its `counters.json` (QueueRefused while a tick + holds it).""" + import _orchestrator as orch # noqa: E402 + slot = Path(slot) + if counters is not None: + fresh = record(res, counters) + for r in fresh: + _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, _questions.add_op(r)) + return fresh + why = slot_refusal(slot) + if why: + raise QueueRefused(why) + now = now or _dt.datetime.now(_dt.timezone.utc) + if not orch._take_lock(slot, now): + raise QueueRefused(f"--queue: {slot.name}'s tick lock is held — a tick is running; " + "try again in a minute") + try: + if (slot / orch.DIGEST_MARKER).exists(): + raise QueueRefused(f"--queue: {slot.name}'s digest is already posted") + counters = orch.read_counters(slot) + fresh = record(res, counters) + for r in fresh: + _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, _questions.add_op(r)) + orch._write_counters(slot, counters) + finally: + orch._drop_lock(slot) + return fresh + + +class ApplyRefused(Exception): + pass + + +def apply(res: dict, mind) -> list[str]: + """Write the rulings into the `mind` checkout's `questions.md` with Mind's + own `questions_edit.add_text`, loaded from that checkout. Refused on branch + `main` (the shift never writes Mind main); never commits or pushes.""" + mind = Path(mind) + branch = _git(mind, "rev-parse", "--abbrev-ref", "HEAD") + if branch.returncode != 0: + raise ApplyRefused(f"--apply: {mind} is not a git checkout") + if branch.stdout.strip() == "main": + raise ApplyRefused(f"--apply: {mind} is on branch main — write the rulings from a " + "session branch (or queue them with --queue); never Mind main") + if res["not_filed"]: + raise ApplyRefused(f"--apply: rulings not filed: {res['not_filed']}") + try: + qe = _mind_writer._mind_module(mind, "questions_edit", deps=("lifecycle",)) + except _mind_writer.MindWriteError as e: + raise ApplyRefused(f"--apply: {e}") from e + target = mind / _questions.FILE + text = _read(target) + out = [] + for r in res["rulings"]: + text, qid, added = qe.add_text(text, r, mind) + out.append(f"{qid} {'added' if added else 'already there'}: " + f"{Path(r['task']).stem} ({r['gate']})") + if res["rulings"]: + target.write_text(text, encoding="utf-8") + return out + + +# --- reading it back ----------------------------------------------------------------- + +def needed(counters: dict) -> int: + """New rulings plus those still Open or Deferred on Mind origin/main, once + per task and gate.""" + c = counters.get("rulings") or {} + keys = {(r.get("task"), r.get("gate")) for r in c.get("new") or []} + open_ = c.get("open") or [] + keys |= {(o.get("task"), o.get("gate")) for o in open_} if isinstance(open_, list) \ + else set() + return len(keys) + (open_ if isinstance(open_, int) else 0) + + +def digest_lines(counters: dict) -> list[str]: + """The digest's closing lines: why the pass failed or filed nothing, then + "The next shift needs N rulings from you." — nothing for a shift whose + watcher predates the pass (no `counters["rulings"]`).""" + if "rulings" not in counters: + return [] + c = counters["rulings"] or {} + out = [""] + if c.get("error"): + out.append(f"Readiness pass failed: {c['error']}") + if c.get("not_filed"): + out.append(f"Rulings not filed: {c['not_filed']}") + n = needed(counters) + out.append(f"The next shift needs {n} ruling{'s' if n != 1 else ''} from you.") + return out + + +def report(res: dict, *, written: list[str] | None = None, queued: list | None = None, + slot=None) -> str: + """The dry run's (and every mode's) plain report.""" + lines = [f"batch ready — {res['mind']} (shift `{res['shift']}`)"] + lines += [f"note: {n}" for n in res["notes"]] + by_task: dict = {} + for f in res["found"]: + by_task.setdefault(f["task"], []).append(f) + skipped = {(s["task"], s["gate"]): q for s, q in res["skipped"]} + shown: set = set() + for e in res["entries"]: + lines.append(f"{e['pos']}. {e['label']} — {e['path'] or e['ref'] or '(no ref)'}") + lines += [f" {n}" for n in e["notes"]] + if e["path"] and not e["units"]: + for f in by_task.get(e["path"], []): + lines.append(_ruling_line(f, skipped, " ", shown)) + for u in e["units"]: + lines.append(f" unit {u['path']} ({u['state']})" + + ("" if u["gates"] or u["state"] != "draft" else " — ready")) + lines += [f" note: {n}" for n in u["notes"]] + for f in by_task.get(u["path"], []): + lines.append(_ruling_line(f, skipped, " ", shown)) + n_new, n_skip = len(res["would_file"]), len(res["skipped"]) + if res["not_filed"]: + lines.append(f"Rulings not filed: {res['not_filed']} — {n_new} found.") + elif queued is not None: + lines.append(f"Queued {len(queued)} ruling(s) in {slot}; {n_skip} skipped as already " + "ruled.") + elif written is not None: + lines += [f" {w}" for w in written] + lines.append(f"Applied {len(written)} ruling(s) (not committed); {n_skip} skipped as " + "already ruled.") + else: + lines.append(f"Dry run: would file {n_new} ruling(s); {n_skip} skipped as already " + "ruled; nothing written.") + lines.append(f"Open or deferred rulings on Mind origin/main: {len(res['open'])}.") + return "\n".join(lines) + + +def _ruling_line(f: dict, skipped: dict, pad: str, shown: set) -> str: + key = (f["task"], f["gate"]) + if key in shown: + return f"{pad}ruling {f['gate']} (listed above)" + shown.add(key) + q = skipped.get(key) + head = f"{pad}ruling {f['gate']}" + (f" (already in your inbox as {q})" if q else "") + return f"{head} — {f['ask']} [{' | '.join(f['options'])}]" diff --git a/agents/conductors/intake/_intake.py b/agents/conductors/intake/_intake.py index 4912b6d8..3b7c7d52 100755 --- a/agents/conductors/intake/_intake.py +++ b/agents/conductors/intake/_intake.py @@ -2715,14 +2715,33 @@ def _age(asked: str, today: str) -> str: return "today" if days <= 0 else ("1 day" if days == 1 else f"{days} days") +def _is_ruling(e: dict) -> bool: + return e["fields"].get("kind") == "ruling" + + def _open_questions(c: dict) -> tuple: - """(open, deferred) inbox entries, oldest first.""" - qs = sorted(c.get("questions") or [], + """(open, deferred) inbox questions, oldest first. Rulings (the readiness + pass's, PyAutoBrain#671) are counted apart, as the digest's inbox line + counts them (`_open_rulings`).""" + qs = sorted((e for e in c.get("questions") or [] if not _is_ruling(e)), 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 _open_rulings(c: dict) -> list: + """Open and deferred rulings, oldest first.""" + return sorted((e for e in c.get("questions") or [] if _is_ruling(e) + and e["state"] in ("open", "deferred")), + key=lambda e: (e["fields"].get("asked", ""), e["n"])) + + +def _subject(f: dict) -> str: + """`ruling ` for a ruling, else the entry's issue URL.""" + return f"ruling {f.get('gate') or '?'}" if f.get("kind") == "ruling" \ + else f.get("issue", "") + + 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 "") @@ -2757,14 +2776,17 @@ def _autopilot_md(c: dict) -> list: L += ["", "**Queue** ([`queue.md`](queue.md)) — read-only; change it in a `/queue` chat", ""] L += [f"{n}. [{_md_inline_escape(label)}]({ref})" for n, label, ref in _queued_rows(c)] or [ f"_{QUEUE_EMPTY}_"] - L += ["", f"**Questions** ({len(opened)} open, {len(deferred)} deferred — " + n_rul = len(_open_rulings(c)) + L += ["", f"**Questions** ({len(opened)} open, {len(deferred)} deferred" + + (f", {n_rul} ruling{'' if n_rul == 1 else 's'}" if n_rul else "") + " — " "[`questions.md`](questions.md))", ""] - for e in opened: + rulings = _open_rulings(c) + for e in opened + rulings: 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: + f"({_subject(f)}" + (f", {age}" if age else "") + ")") + if not opened and not rulings: L.append(f"_{QUESTIONS_EMPTY}_") L += ["", _shift_md(c.get("batch"), c.get("last_batch")), ""] return L @@ -2789,7 +2811,8 @@ def _question_row(c: dict, e: dict, link) -> str: + f" — {_summary_label(f.get('ask', ''))}") if f.get("options"): text += f' — {_summary_label(f["options"])}' - text += _issue_link(f.get("issue", "")) + text += (f' — {_summary_label(_subject(f))}' + if _is_ruling(e) else _issue_link(f.get("issue", ""))) meta = f"from shift {_summary_label(f.get('shift', '?'))}" + (f" · {age}" if age else "") if e["state"] == "deferred": meta += f" · deferred until {_summary_label(f.get('until') or 'the next sitting')}" @@ -2830,9 +2853,11 @@ def _autopilot_html(c: dict, link, h2) -> list: H += [_html_task(link(ref, _summary_label(label)), _prompt_payload(ref), _queue_star(ref, {Path(ref).name: n})) for n, label, ref in queue] or [f'

{_md_inline(QUEUE_EMPTY)}

'] + rulings = _open_rulings(c) + n_rul = (f", {len(rulings)} ruling{'' if len(rulings) == 1 else 's'}" if rulings else "") H.append(f'

Questions ({len(opened)} open, ' - f"{len(deferred)} deferred — read-only; answer by pasting a 📋 into a chat)" - "

") + f"{len(deferred)} deferred{n_rul} — read-only; answer by pasting a 📋 into a " + "chat)") if opened: H.append(_html_task("Answer the open questions in one sitting", _questions_payload())) @@ -2843,6 +2868,7 @@ def _autopilot_html(c: dict, link, h2) -> list: H += ["
", f"{len(deferred)} deferred"] H += [_question_row(c, e, link) for e in deferred] H += ["
"] + H += [_question_row(c, e, link) for e in rulings] H.append(_shift_html(c.get("batch"), c.get("last_batch"))) return H diff --git a/skills/batch/batch.md b/skills/batch/batch.md index 72e20c63..18dd297b 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'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 +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. `batch ready` (the readiness pass) runs at shift end and on request: it files each gate on the queue's next units as a `ruling` in the inbox, and the digest ends "The next shift needs N rulings from you" (dry run by default; `--queue `, `--apply` on a session branch). 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/questions.md b/skills/questions/questions.md index 7ec94c8f..836a4150 100644 --- a/skills/questions/questions.md +++ b/skills/questions/questions.md @@ -20,6 +20,7 @@ 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. +A `ruling` (kind `ruling`, a `gate:`, filed by the readiness pass `batch ready`) is answered like a question but never resumes a parked task. If `/queue` or `/cockpit` also ran in this chat, ask which one a paste is for. ## Verbs diff --git a/tests/test_batch_ready.py b/tests/test_batch_ready.py new file mode 100644 index 00000000..7da1629c --- /dev/null +++ b/tests/test_batch_ready.py @@ -0,0 +1,613 @@ +"""The readiness pass, `batch ready` (M3.3 slice 1, PyAutoBrain#671). + +It walks Mind `queue.md`, resolves each entry to its next startable unit(s), +checks the gates, and files each gate as a questions-inbox entry of kind +`ruling` through the shift's one Mind writer (`question-add`). It runs at the +end of every shift, and the digest ends "The next shift needs N rulings from +you." The fixture Mind is a git repo whose `origin/main` is a local ref: the +pass reads it locally and never fetches. +""" + +from __future__ import annotations + +import datetime as _dt +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" +sys.path.insert(0, str(BRAIN / "agents" / "faculties" / "sizing")) +sys.path.insert(0, str(BATCH)) +sys.path.insert(0, str(BRAIN / "tests")) +import _batch # noqa: E402 +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 test_orchestrator_dispatch as d # noqa: E402 + +needs_git = pytest.mark.skipif(not shutil.which("git"), reason="needs git") + +NOW = d.NOW +FOLDER = "draft/feature/pyautogut" +EPIC = f"{FOLDER}/example_epic.md" +TASK = f"{FOLDER}/example_task.md" +LAST = "The next shift needs 2 rulings from you." + +PROMPT = """\ +# {name} + +Type: feature +Target: PyAutoGut +Repos: +- PyAutoGut +{extra}Lane: any +Difficulty: small +Autonomy: supervised +Priority: normal +Status: formalised +Consequence: glance +Witness: a unit test +Review-minutes: 3 +Unattended: ready + +Body. +""" + +LEDGER = """\ +# Example epic + +Epic: example-epic +Type: feature +Target: PyAutoGut +Status: campaign map + +| Phase | What | +|---|---| +| 1 | done | +| 2 | next, no prompt yet | +""" + +QUEUE = """\ +# Queue + +``` +## .