Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AUTONOMY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 15 additions & 0 deletions agents/conductors/batch/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,21 @@ starts `resumed after Q<n> 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 <slot>` 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),
Expand Down
51 changes: 50 additions & 1 deletion agents/conductors/batch/_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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; "
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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)
Expand All @@ -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 <prompt> [--slices FILE] [--apply] [--json]` — propose the
children of a needs-slicing prompt; only `--apply` writes (`_slice`)."""
Expand Down
8 changes: 8 additions & 0 deletions agents/conductors/batch/_digest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"


Expand Down
14 changes: 13 additions & 1 deletion agents/conductors/batch/_mind_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)"
Expand Down Expand Up @@ -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")
Expand Down
20 changes: 20 additions & 0 deletions agents/conductors/batch/_orchestrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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
Expand Down
38 changes: 33 additions & 5 deletions agents/conductors/batch/_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand All @@ -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"]
Expand All @@ -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 "")]
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading