From e6b36488f0b92c55040a924935bd1d719efdd849 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 19 Nov 2026 22:16:15 +0000 Subject: [PATCH] feat: queued epics drive shifts; briefs allow RAL by default (#696) - brief --new writes lanes: any local-dev ral plus a default ral-allowance (packets 2, partition ral, cpu-hours 64) - a queue.md entry naming an epic ledger queues the epic's members at the ledger's rank (queue_standing); the 2026-11-16 scoped-reach rule no longer blocks them; every other gate unchanged - one line per queued epic (taken / why idle) in plan text+json, brief --check and the shift digest - phase order now also reads members the brief scope or claims withheld Co-Authored-By: Claude Opus 5.5 --- AUTONOMY.md | 4 +- agents/conductors/batch/AGENTS.md | 20 +- agents/conductors/batch/_batch.py | 256 +++++++++++++++++++++-- agents/conductors/batch/_brief.py | 3 +- agents/conductors/batch/_digest.py | 7 + agents/conductors/batch/_orchestrator.py | 15 +- agents/conductors/batch/_ready.py | 6 +- skills/batch/batch.md | 2 +- skills/queue/queue.md | 4 + tests/test_batch_brief_goals.py | 60 ++++++ tests/test_batch_plan.py | 128 ++++++++++++ tests/test_digest_counters.py | 14 ++ 12 files changed, 485 insertions(+), 34 deletions(-) diff --git a/AUTONOMY.md b/AUTONOMY.md index 363e9522..29259768 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -971,7 +971,9 @@ not open. **Human ruling 2026-11-16 (backlog reach, PyAutoBrain#637):** a `backlog: scoped` dip takes `queue.md` first, then only `Difficulty: small` single-repo -backlog tasks; anything bigger must be queued by the human. +backlog tasks; anything bigger must be queued by the human. Narrowed +2026-11-19 (human, PyAutoBrain#696): queuing an epic ledger queues its +members, at the ledger's rank; phase order and every other gate still apply. **Human rulings R5 and R2 — 2026-11-17 (M3.6b, PyAutoBrain#667).** R5 (option a): the one-slice-per-epic limit and phase order bind only tasks with diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 688c6cf0..53a9487f 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -108,6 +108,19 @@ priority. `retired`, `epic-slice` and `theme-sweep` entries are skipped rather than resolved: resolving one is a decision (which phase? which chip?), and the reader does not decide. +**A queued epic ledger queues its members** (PyAutoBrain#696). A `kind: +prompt` entry whose prompt is an epic ledger (`Epic:`, no `Phase:`, `Status: +campaign map`), or which `epics.md` lists as an epic's `- ledger:`, makes every +member of that epic count as queued at the ledger's rank (`queue_standing`, the +one test of "is this queued?"). So the backlog-reach ruling no longer keeps a +medium or multi-repo phase out. Every other gate still applies: phase order, +`human-required`, `Unattended:`, `Blocked-by:`, Witness, lane, repo holds and +budget. A queued phase or side task queues only itself. `batch plan` (text and +`--json` `queued_epics`), `brief --check` and the digest give one line per +queued epic: what it takes, or why nothing (its next phase and each member's +gate, or "no draft prompt" — file it from the epic's Continue prompt in an +attended chat). + `plan` also reports what the **previous slot carried**: the members its `outcomes:` block marks `carried` are read first, because they are already costing the human review-minutes in the slot being planned and a batch composed @@ -199,8 +212,9 @@ whole grant (`AUTONOMY.md`, "Shift briefs and unattended `glance`"). `batch brief --new --review-at ` composes that writing: a skeleton brief whose `goals:` are `PyAutoMind/goals.md`'s, in order, with `backlog: scoped` to their `epics:`/`tags:` (else `scoped` by `tiers: notify, -glance`, M3.6b) and -`merge-cap: 0`. It prints to stdout (`--out FILE` writes it) and never writes a +glance`, M3.6b), plus the epics of `queue.md`'s queued ledgers, `merge-cap: 0`, +and `lanes: any local-dev ral` with a `ral-allowance:` of 2 packets, partition +`ral`, 64 cpu-hours (PyAutoBrain#696; edit either per shift). It prints to stdout (`--out FILE` writes it) and never writes a record into `batches/` — saving it there is the human's dispatch. `goals.md` is written by the human alone (by hand or in chat), so every goal is copied as their word; `--new` also prints on stderr how the goals changed @@ -297,7 +311,7 @@ organ rule to it); a task an earlier shift in the same home left parked on a question is not startable until a later shift finishes it or a brief names it again; a dip never takes a Brain, Mind or Hands target; a `backlog: scoped` dip beyond `queue.md` takes only small single-repo tasks -(ruling 2026-11-16); a re-dispatch goes first and may pass `max-sessions:` by +(ruling 2026-11-16; a queued epic ledger queues its members, #696); a re-dispatch goes first and may pass `max-sessions:` by one; and a worker's token reservation is the larger of the even share and the mean spend of finished workers in this and the last three shifts. State lives under `$PYAUTO_ORCHESTRATOR_HOME` (default `.orchestrator` under the worktree diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index fc3809db..c434537c 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -246,6 +246,7 @@ def survey(mind: Path) -> list[dict]: g["phase"] = _phase_of(text) g["phase_declared"] = _phase_declared(text) g["done"] = _is_done(text) + g["ledger"] = is_ledger_text(text) g["themes"] = _themes_of(text) g["title"] = _title_of(text) out.append(g) @@ -263,6 +264,7 @@ def grade_text(text: str, rel: str, mind: Path) -> dict: g["phase"] = _phase_of(text) g["phase_declared"] = _phase_declared(text) g["done"] = _is_done(text) + g["ledger"] = is_ledger_text(text) g["themes"] = _themes_of(text) g["title"] = _title_of(text) return g @@ -299,6 +301,76 @@ def queue_rank(r: dict, queue: list[str]) -> int: return len(queue) +def is_ledger_text(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(_epic_of(text)) and not _phase_declared(text) \ + and _header_of(text, "status").lower().startswith("campaign map") + + +def read_epic_ledgers(mind: Path) -> dict[str, str]: + """{ledger path: epic slug} from Mind `epics.md` (`## ` sections, + each with a `- ledger:` line). The fallback that maps a queued ledger to + its epic when the ledger's own `Epic:` header is missing or sits below + the lines `_header_of` reads.""" + try: + text = (Path(mind) / "epics.md").read_text(encoding="utf-8", errors="replace") + except OSError: + return {} + out: dict[str, str] = {} + slug = "" + for line in text.splitlines(): + h = re.match(r"^##\s+(\S+)", line) + if h: + slug = h.group(1) + elif slug and line.startswith("- ledger:"): + ledger = line.split(":", 1)[1].strip().strip("`") + if ledger and not ledger.startswith("http"): + out.setdefault(ledger, slug) + slug = "" + return out + + +def queued_epics(queue: list[str], records: list[dict], + epic_ledgers: dict[str, str] | None = None) -> dict[str, int]: + """{epic slug: queue index} for every queue entry that names an epic + ledger (PyAutoBrain#696). An entry is an epic when the prompt it names is + a ledger (`ledger` in its survey record: `Epic:`, no `Phase:`, `Status: + campaign map`), or when `epics.md` lists it as an epic's `- ledger:`. + A queued phase or side task queues only itself. The first entry wins.""" + by_path = {r.get("path") or "": r for r in records} + by_name: dict[str, dict] = {} + for r in records: + by_name.setdefault(Path(r.get("path") or "").name, r) + ledgers = epic_ledgers or {} + ledger_names = {Path(p).name: s for p, s in ledgers.items()} + out: dict[str, int] = {} + for i, q in enumerate(queue): + r = by_path.get(q) or by_name.get(Path(q).name) + slug = r["epic"] if r and r.get("ledger") and r.get("epic") else "" + slug = slug or ledgers.get(q) or ledger_names.get(Path(q).name, "") + if slug: + out.setdefault(slug, i) + return out + + +def queue_standing(r: dict, queue: list[str], + epic_ranks: dict[str, int] | None = None) -> tuple[int, str]: + """(rank, epic it is queued through or "") — the ONE answer to "is this + record queued?" (PyAutoBrain#696). Queued directly (`queue_rank`), or as + a member of a queued epic ledger, at the ledger's rank, whichever is + higher in the file. `rank == len(queue)` is unqueued. Only the queue + standing changes: every gate of `pool_gate` (phase order, autonomy, + Unattended, Blocked-by) still applies to the member.""" + direct = queue_rank(r, queue) + epic = r.get("epic") or "" + via = (epic_ranks or {}).get(epic) if epic and not r.get("ledger") else None + if via is not None and via < direct: + return via, epic + return direct, "" + + def next_phases(records: list[dict]) -> dict[str, float]: """Each epic's lowest un-shipped phase — the only one that is startable.""" next_phase: dict[str, float] = {} @@ -385,6 +457,69 @@ def scoped_reach_why(r: dict) -> str: "bigger work (ruling 2026-11-16)") +#: The idle line for a queued epic with no draft prompt at its next phase. +NO_NEXT_PHASE_DRAFT = ("no draft prompt for {phase} — run the epic's Continue prompt " + "in an attended chat to file it") +#: How many next-phase members an idle line names before `+n more`. +EPIC_LINE_MEMBERS = 4 + + +def queued_epic_summary(records: list[dict], epic_ranks: dict[str, int], + members: list[dict], rejected: list[tuple[str, str]], + queue: list[str]) -> list[dict]: + """One entry per queued epic, in queue order (PyAutoBrain#696): what it + contributes to this plan, or why nothing — its next phase, and each + next-phase member with the planner's reason for leaving it out; or no + draft prompt at all for its next phase. Each entry carries its `line`.""" + why_of: dict[str, str] = {} + for p, w in rejected: + why_of.setdefault(p, w) + out = [] + for slug, rank in sorted(epic_ranks.items(), key=lambda kv: kv[1]): + tag = f"{slug} (q{rank + 1})" + taken = [m["path"] for m in members if m.get("epic") == slug] + open_ = [r for r in records if r.get("epic") == slug and not r.get("ledger") + and not r.get("done")] + phased = [r for r in open_ if has_phase(r)] + nxt = min((r["phase"] for r in phased), default=None) + e = {"epic": slug, "rank": rank + 1, "ledger": queue[rank] if rank < len(queue) else "", + "taken": taken, "next_phase": None, "members": []} + if nxt is not None: + e["next_phase"] = f"{nxt:g}" if nxt != float("inf") else "(unnumbered)" + e["members"] = [{"path": r["path"], + "why": why_of.get(r["path"], "not planned this tick")} + for r in sorted(phased, key=lambda r: r["path"]) + if r["phase"] == nxt] + if taken: + e["line"] = f"{tag}: takes " + ", ".join(Path(p).stem for p in taken) + elif nxt is None: + e["line"] = f"{tag}: nothing — " + NO_NEXT_PHASE_DRAFT.format( + phase="its next phase") + else: + shown = e["members"][:EPIC_LINE_MEMBERS] + more = len(e["members"]) - len(shown) + e["line"] = (f"{tag}: nothing — next phase {e['next_phase']}: " + + "; ".join(f"{Path(m['path']).stem} ({_gate_word(m['why'])})" + for m in shown) + + (f"; +{more} more" if more > 0 else "")) + out.append(e) + return out + + +def _gate_word(why: str) -> str: + """A rejection reason cut to its gate words for a one-line epic summary: + the clause before ` — `, prompt paths as their stems, asides dropped. The + full reason stays in the entry's `members`.""" + w = why.split(" — ")[0] + w = re.sub(r"(?:draft|active)/\S*?([\w-]+)\.md", r"\1", w) + return re.sub(r"\s*\([^()]*\)", "", w).strip() + + +def queued_epic_lines(d: dict) -> list[str]: + """The one-line-per-queued-epic text of a plan (`plan()["queued_epics"]`).""" + return [e["line"] for e in d.get("queued_epics") or []] + + def planner_pool(records: list[dict]) -> list[dict]: """The records every session's planner would consider, before its lane filters them — what a Lane backfill must cover.""" @@ -397,7 +532,9 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, cap: int = DEFAULT_BACKPRESSURE_CAP, queue: list[str] | None = None, awaiting_source: str = "given", carried: list[str] | None = None, carried_from: str = "", brief: dict | None = None, - attended: bool = False, released: set[str] | None = None) -> dict: + attended: bool = False, released: set[str] | None = None, + epic_ledgers: dict[str, str] | None = None, + withheld: list[tuple[dict, str]] | None = None) -> dict: """Compose the next batch — a BatchDecision. Every constraint states itself in `rejected`, because a planner that @@ -424,6 +561,14 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, With `attended=True` (`batch plan --attended`, a human at the keyboard picking for this session) an absent Lane reads as `any` and an empty queue falls back to the backlog order, as before. + + A queue entry naming an epic ledger queues the epic's members at the + ledger's rank (`queue_standing`, PyAutoBrain#696); `epic_ledgers` is + `read_epic_ledgers(mind)`, the `epics.md` fallback for a ledger whose + `Epic:` header the survey did not read. `queued_epics` in the result says, + per queued epic, what it contributes or why nothing; `withheld` is the + (record, why) pairs the caller kept out before planning (claimed on Mind + origin/main, parked), read only for that summary. """ rejected: list[tuple[str, str]] = [] queue_given = queue is not None @@ -457,11 +602,19 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, else: effective_budget, pressure = budget, "clear" + # A queued epic ledger queues its members at its rank (#696). Read from + # every record, before the brief's scope drops any, so a ledger outside + # the brief's scope still lends its rank. + epic_ranks = queued_epics(queue, all_records, epic_ledgers) + # An epic's members are worked IN ORDER, so only its lowest un-shipped # phase is startable. Without this the planner can propose phase 6 while # phase 3 is still open — the one-slice-per-epic rule below caps how many - # run, not which. - next_phase = next_phases(records) + # run, not which. Read over every record, the ones the brief's scope or + # the caller kept out included (#696): a phase held by a claim, parked, or + # outside the brief is still open, so the phase after it is not next. + held_out = [w for w, _ in withheld or []] + next_phase = next_phases(all_records + held_out) shift_dip = brief is not None and not attended scoped_dip = shift_dip and brief.get("backlog", {}).get("value") == "scoped" @@ -491,7 +644,8 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, rejected.append((r["path"], "no Witness — a shift dips only witnessed " "drafts (declare one to make it pickable)")) witness_absent.append(r["path"]) - elif scoped_dip and backlog and queue_rank(r, queue) >= len(queue) \ + elif scoped_dip and backlog \ + and queue_standing(r, queue, epic_ranks)[0] >= len(queue) \ and scoped_reach_why(r): rejected.append((r["path"], scoped_reach_why(r))) reach.append(r["path"]) @@ -506,8 +660,10 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, # the cheapest review win and broke ties by filename, which picked work the # human did not want. Cheapest first still decides within a priority. for r in pool: - r["queue_rank"] = queue_rank(r, queue) + r["queue_rank"], via = queue_standing(r, queue, epic_ranks) r["queued"] = r["queue_rank"] < len(queue) + if via: + r["queued_via"] = via pool.sort(key=lambda r: (r["queue_rank"], priority_rank(r), r["review_minutes"], r["path"])) @@ -586,6 +742,12 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, "scoped_reach": reach, # Backlog drafts with no `Witness:`, kept out of a shift's dip (M3.6b). "witness_absent": witness_absent, + # Per queued epic ledger, what it gives this plan or why nothing (#696). + "queued_epics": queued_epic_summary( + all_records + [w for w in held_out + if w.get("path") not in {r.get("path") for r in all_records}], + epic_ranks, members, rejected + [(w.get("path"), why) for w, why in withheld or []], + queue), } @@ -646,6 +808,13 @@ def emit(d: dict) -> None: print(f"Carried in: {', '.join(d['carried'])} " f"(from {d.get('carried_from') or 'the previous slot'}) — still " f"in flight, and yours to review before anything new") + lines = queued_epic_lines(d) + if lines: + # One line per queued epic ledger (#696): what it gives this batch, or + # why nothing — read before the long tally of rejections below. + print("Queued epics:") + for line in lines: + print(f" {line}") print() if d["members"]: queued = len(d.get("queue") or []) @@ -3389,9 +3558,14 @@ def _main_watch(a) -> int: SLOT_RE = re.compile(r"^\d{4}-\d{2}-\d{2}-(am|pm)$") #: Defaults `brief --new` writes for the keys the human usually leaves alone. #: `merge-cap: 0` is the safe one: nothing merges unattended until raised. +#: RAL is in `lanes:` by default (PyAutoBrain#696): a shift that left it out +#: rejected every `Lane: ral` phase the human had queued. NEW_BRIEF_DEFAULTS = {"review-minutes": str(DEFAULT_REVIEW_BUDGET), - "lanes": "any", "merge-cap": "0", + "lanes": "any local-dev ral", "merge-cap": "0", "token-budget": "5000000"} +#: The `ral-allowance:` `brief --new` writes beside `ral` in `lanes:` — the +#: block `brief --check` requires then. Edit it per shift. +NEW_BRIEF_RAL_ALLOWANCE = {"packets": "2", "partition": "ral", "cpu-hours": "64"} def _last_brief_goals(mind: Path) -> tuple[str, list[str]] | None: @@ -3462,6 +3636,11 @@ def new_brief(mind: Path, slot: str, review_at: str, now=None, for g in goals: epics += [e for e in g["epics"] if e not in epics] tags += [t for t in g["tags"] if t not in tags] + # A queued epic ledger queues its phases (#696), so its epic is in scope: + # without it a `scoped` brief would keep out the work the queue asks for. + goal_scoped = bool(epics or tags) + queued = [e for e in queued_epics(read_queue(mind), survey(mind), + read_epic_ledgers(mind)) if e not in epics] shift = {"am": "morning", "pm": "afternoon"}.get(slot.rsplit("-", 1)[-1], slot) L = [f"# Batch {slot.rsplit('-', 1)[0]} {slot.rsplit('-', 1)[-1]}", f"- dispatched: {now.strftime('%Y-%m-%dT%H:%MZ')}", @@ -3480,11 +3659,15 @@ def new_brief(mind: Path, slot: str, review_at: str, now=None, "fixable Heart reasons the lane picked (see ## Heart)") L.append(" - tasks: # the heart-green lane's picks") L += [f" - {t}" for t in picks] - if epics or tags: + every = epics + queued + epics_line = (f" - epics: {', '.join(every)}" + + (" # queue.md's queued epics" if queued and not epics + else " # goals' epics, then queue.md's" if queued else "")) + if goal_scoped: L += [" - backlog: scoped # the goals' epics and tags", " - scoped:"] - if epics: - L.append(f" - epics: {', '.join(epics)}") + if every: + L.append(epics_line) if tags: L.append(f" - tags: {', '.join(tags)}") else: @@ -3496,11 +3679,16 @@ def new_brief(mind: Path, slot: str, review_at: str, now=None, "queue.md small single-repo only (ruling 2026-11-16)", " - scoped:", f" - tiers: {', '.join(NEW_BRIEF_SCOPED_TIERS)}"] + if queued: + L.append(epics_line) L += [f" - review-minutes: {NEW_BRIEF_DEFAULTS['review-minutes']}", f" - lanes: {NEW_BRIEF_DEFAULTS['lanes']}", f" - merge-cap: {NEW_BRIEF_DEFAULTS['merge-cap']}" " # unattended glance merges: raise deliberately", f" - token-budget: {NEW_BRIEF_DEFAULTS['token-budget']}"] + if "ral" in NEW_BRIEF_DEFAULTS["lanes"].split(): + L += [" - ral-allowance: # what the shift may spend on RAL; edit per shift"] + L += [f" - {k}: {v}" for k, v in NEW_BRIEF_RAL_ALLOWANCE.items()] text = "\n".join(L) + "\n" return text + "\n" + _green.section(heart) if heart else text @@ -3510,27 +3698,42 @@ def new_brief(mind: Path, slot: str, review_at: str, now=None, "as a resume after an answered question (or it has started)") -def named_skips(brief: dict, mind: Path) -> tuple[dict[str, str], str]: - """({named task: why it will not start}, a note when the claims on Mind - origin/main could not be read) — the watcher's own gates, run at - `brief --check` (M3.6b, ruling R5): the claim gate against Mind's local - `origin/main` (never a fetch), then `plan` under this brief, unattended, - on the watcher's lane. A task the planner keeps is not listed; one that - resolves to no prompt is `_brief.check`'s warning already.""" +def check_plan(brief: dict, mind: Path) -> tuple[dict, dict[str, str], str]: + """(plan, {path: why held}, note) — the watcher's plan under `brief`, as + `brief --check` runs it (M3.6b): the claim gate against Mind's local + `origin/main` (never a fetch), then `plan` unattended on the watcher's + lane. `note` says when the claims could not be read.""" import _orchestrator as orch # noqa: E402 — deferred: it imports this module - named = _brief.tasks_of(brief) - if not named: - return {}, "" recs = survey(mind) note = "" claims = orch.origin_claims(mind) held: dict[str, str] = {} + withheld: list[tuple[dict, str]] = [] if claims is not None and "error" in claims: note = (f"brief.tasks: claims on Mind origin/main not read ({claims['error']}) — " "the watcher fails closed on that; repo claims not checked here") elif claims is not None: - recs, held = orch.on_origin(recs, mind, own=set()) - d = plan(recs, session_lane="local-dev", brief=brief, queue=read_queue(mind)) + kept, held = orch.on_origin(recs, mind, own=set()) + withheld = [(r, held[r["path"]]) for r in recs if r["path"] in held] + recs = kept + d = plan(recs, session_lane="local-dev", brief=brief, queue=read_queue(mind), + epic_ledgers=read_epic_ledgers(mind), withheld=withheld) + return d, held, note + + +def named_skips(brief: dict, mind: Path, + planned: tuple[dict, dict[str, str], str] | None = None + ) -> tuple[dict[str, str], str]: + """({named task: why it will not start}, a note when the claims on Mind + origin/main could not be read) — the watcher's own gates, run at + `brief --check` (M3.6b, ruling R5): the claim gate against Mind's local + `origin/main` (never a fetch), then `plan` under this brief, unattended, + on the watcher's lane. A task the planner keeps is not listed; one that + resolves to no prompt is `_brief.check`'s warning already.""" + named = _brief.tasks_of(brief) + if not named: + return {}, "" + d, held, note = planned or check_plan(brief, mind) rejected = {Path(p).name: w for p, w in d["rejected"]} rejected.update({Path(p).name: w for p, w in held.items()}) members = {Path(m["path"]).name for m in d["members"]} @@ -3727,11 +3930,18 @@ def _main_brief(mind: Path, a) -> int: # reason, and the organ rule for each one, before the shift opens. res["notes"] = [] if rec is not None and rec["brief"] is not None: - why_not, claim_note = named_skips(rec["brief"], mind) + planned = check_plan(rec["brief"], mind) + why_not, claim_note = named_skips(rec["brief"], mind, planned) res["warnings"] += [f"brief.tasks: {Path(t).stem} will not start — {w}" for t, w in why_not.items()] if claim_note: res["warnings"].append(claim_note) + # #696: each queued epic ledger, and why it gives this shift nothing. + res["queued_epics"] = planned[0]["queued_epics"] + res["warnings"] += [f"queued epic {e['line']}" for e in res["queued_epics"] + if not e["taken"]] + res["notes"] += [f"queued epic {e['line']}" for e in res["queued_epics"] + if e["taken"]] for t in _brief.tasks_of(rec["brief"]): f = _brief._resolve(mind, t) if f is not None: @@ -3868,7 +4078,7 @@ def _main_plan(mind: Path, a, lane: str) -> int: d = plan(survey(mind), budget=a.budget, session_lane=lane, awaiting_review=awaiting, cap=a.cap, queue=read_queue(mind), awaiting_source=source, carried=carried, carried_from=carried_from, - brief=brief, attended=a.attended) + brief=brief, attended=a.attended, epic_ledgers=read_epic_ledgers(mind)) if a.as_json: print(json.dumps(d, indent=2)) return RC_OK diff --git a/agents/conductors/batch/_brief.py b/agents/conductors/batch/_brief.py index 4a8ccbd2..fd29fd7e 100644 --- a/agents/conductors/batch/_brief.py +++ b/agents/conductors/batch/_brief.py @@ -688,7 +688,8 @@ def rank_note(record: dict) -> str: (M2.3, 2026-11-12), then the path — so a tie is alphabetical, and says so.""" parts = [] if record.get("queued"): - parts.append(f"queue.md #{record['queue_rank'] + 1}") + parts.append(f"queue.md #{record['queue_rank'] + 1}" + + (f" via epic {record['queued_via']}" if record.get("queued_via") else "")) elif "queue_rank" in record: parts.append("not in queue.md") parts.append(f"priority {record.get('priority') or 'normal'}") diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index fa83a28e..5f219230 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -976,6 +976,13 @@ def names(paths): if reach: out.append(f"Backlog reach (ruling 2026-11-16): {len(reach)} unqueued draft(s) not " "dipped — beyond queue.md only small single-repo tasks: " + names(reach)) + # One line per queued epic ledger (#696): what it gave the shift, or why + # nothing. `· ` rather than an indent: an indented line would read as the + # continuation of the pick above it. + epics = gates.get("queued_epics") or [] + if epics: + out.append("Queued epics:") + out += [f"· {line}" for line in epics] absent = gates.get("lane_absent") or [] if absent: out.append(f"Lane absent: {len(absent)} draft(s) excluded — no valid `Lane:`, " diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 5d06208f..0e36da3c 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -2174,6 +2174,7 @@ def plan() -> dict: recs = recs + [a["record"] for a in (counters.get("added") or {}).values() if isinstance(a.get("record"), dict) and a["record"].get("path") not in have] + surveyed = list(recs) # Parked on a question by an earlier shift (#637, item 3): not # startable until answered. A brief that names it again is the # human's word that it is; a task this shift picked stays. Read @@ -2220,8 +2221,16 @@ def plan() -> dict: # 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. + # Kept out above, with why: read only by the queued-epic lines (#696). + kept = {r["path"] for r in recs} + why_out = {**planned["parked"], **(claimed or {})} + withheld = [(r, why_out.get(r["path"], "kept out before planning " + "(carried or resumed elsewhere)")) + for r in surveyed if r["path"] not in kept] planned["d"] = _batch.plan(recs, session_lane="local-dev", brief=brief, - queue=_batch.read_queue(mind), released=freed) + queue=_batch.read_queue(mind), released=freed, + epic_ledgers=_batch.read_epic_ledgers(mind), + withheld=withheld) return planned["d"] def known(task: str) -> bool: @@ -2291,7 +2300,9 @@ def known(task: str) -> bool: # digest's "Not started" reason), and the backlog # drafts kept out for want of a `Witness:`. "named": _named_reasons(brief, d, planned), - "witness_absent": sorted(d.get("witness_absent") or [])} + "witness_absent": sorted(d.get("witness_absent") or []), + # #696: one line per queued epic ledger. + "queued_epics": _batch.queued_epic_lines(d)} paused = bool(counters.get("paused")) if _brief.is_shadow(brief): proposed = [] if paused else _propose( diff --git a/agents/conductors/batch/_ready.py b/agents/conductors/batch/_ready.py index 6aada53a..e5d1e5e3 100644 --- a/agents/conductors/batch/_ready.py +++ b/agents/conductors/batch/_ready.py @@ -110,9 +110,9 @@ def epic_members(mind: Path, epic: str) -> list[dict]: 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") + `Phase:`, any other status) is an ordinary prompt. The planner's own + test (`_batch.is_ledger_text`), so both read a ledger alike.""" + return _batch.is_ledger_text(text) def origin_epic_members(mind: Path, epic: str, ref: str = "origin/main") -> list[dict] | None: diff --git a/skills/batch/batch.md b/skills/batch/batch.md index 4729112f..37e16829 100644 --- a/skills/batch/batch.md +++ b/skills/batch/batch.md @@ -32,7 +32,7 @@ Resolve it to prompt paths; plan exactly that set as a brief's named tasks, or its named tasks go first, then the backlog dip its policy allows (`none` | `fill-idle` | `scoped:` plus `exclude:`). Backlog the brief does not cover is never dipped, and every dipped pick carries a one-line reason in the digest. -`brief --check` says why any named task will not start (AUTONOMY.md, R5 and R2). +`brief --check` says why any named task will not start (AUTONOMY.md, R5 and R2); a queued epic ledger queues its members (#696), and plan, check and digest say per epic why it is idle. Report, per task they named: - **taken** — with its tier and review-minutes; diff --git a/skills/queue/queue.md b/skills/queue/queue.md index c546c7d4..c2139767 100644 --- a/skills/queue/queue.md +++ b/skills/queue/queue.md @@ -35,6 +35,10 @@ in one line and ask for the path. Never work around it by editing the file. `remove` moves the entry to `## Retired` with `shelved-as:` and keeps its note. The prompt itself stays in `draft/`. +Adding an epic's ledger queues the whole epic (PyAutoBrain#696): a shift then +takes its next phase at the ledger's rank, under every other gate. Adding one +phase prompt queues only that phase. + `show` writes nothing: run it in a fresh worktree (steps 1, 2 and 5 below) and skip the commit, so it reads `origin/main`, not a stale checkout. diff --git a/tests/test_batch_brief_goals.py b/tests/test_batch_brief_goals.py index 3077efe1..6dc4860a 100644 --- a/tests/test_batch_brief_goals.py +++ b/tests/test_batch_brief_goals.py @@ -188,3 +188,63 @@ def test_goals_are_copied_as_written_with_or_without_git(tmp_path): assert [c["text"] for c in _brief.parse(text)["brief"]["goals"]["children"]] == [ "1. Land the flywheel rework", "2. Clear review-ready PRs"] assert "# - " not in text + + +# --- RAL by default, and queued epics in scope (PyAutoBrain#696) ------------ + +LEDGER_TEXT = """# Widgets epic + +Type: feature +Target: widgets +Difficulty: too-large +Autonomy: human-required +Status: campaign map — phases route one at a time +Epic: widgets +Lane: local-dev +""" +QUEUE_TEXT = """# Queue + +## 1. Widgets epic +- kind: prompt +- ref: draft/feature/x/widgets_epic.md +""" + + +def test_an_unedited_new_brief_allows_ral_and_passes_check(tmp_path, capsys): + """The Witness, part (a): `brief --new` writes `ral` into `lanes:` with a + `ral-allowance:` block, and `brief --check` passes it as written.""" + mind = _mind(tmp_path, "# Goals\n\n## 1. Ship it\n") + out = tmp_path / "brief.md" + assert _batch.main(["brief", "--new", "2026-11-14-am", "--review-at", + "2099-01-01T12:00Z", "--mind", str(mind), "--out", str(out), + "--issue", "https://github.com/example-org/PyAutoMind/issues/1"]) == 0 + text = out.read_text() + brief = _brief.parse(text)["brief"] + assert "ral" in _brief.lanes_of(brief) + allow = _brief._keyed(brief["ral-allowance"]["children"]) + assert {k: v["value"] for k, v in allow.items()} == { + "packets": "2", "partition": "ral", "cpu-hours": "64"} + assert _brief.check(out, mind)["ok"] + capsys.readouterr() + assert _batch.main(["brief", "--check", str(out), "--mind", str(mind), + "--no-premise"]) == 0 + + +def test_new_puts_queued_epics_in_scope_and_check_says_why_one_is_idle(tmp_path, capsys): + """A queued epic ledger queues its phases, so `brief --new` scopes the + brief to its epic beside the default tiers, and `brief --check` warns, + one line per queued epic, why nothing of it starts.""" + mind = _mind(tmp_path, "# Goals\n\n## 1. Ship it\n") + (mind / "draft" / "feature" / "x" / "widgets_epic.md").write_text(LEDGER_TEXT) + (mind / "queue.md").write_text(QUEUE_TEXT) + text = _batch.new_brief(mind, "2026-11-14-am", "2099-01-01T12:00Z", + issue="https://github.com/example-org/PyAutoMind/issues/1") + scoped = _brief.scoped_of(_brief.parse(text)["brief"]) + assert scoped == {"tiers": ["notify", "glance"], "epics": ["widgets"]} + out = tmp_path / "brief.md" + out.write_text(text) + assert _batch.main(["brief", "--check", str(out), "--mind", str(mind), + "--no-premise"]) == 0 + printed = capsys.readouterr().out + assert ("! queued epic widgets (q1): nothing — no draft prompt for its next " + "phase") in printed diff --git a/tests/test_batch_plan.py b/tests/test_batch_plan.py index b2a72476..b121727f 100644 --- a/tests/test_batch_plan.py +++ b/tests/test_batch_plan.py @@ -329,3 +329,131 @@ def test_carried_members_are_reported_to_the_next_plan(): carried_from="2026-09-03-pm") assert d["carried"] == ["subhalo-wave"] assert d["carried_from"] == "2026-09-03-pm" + + +# ------------------------------------- a queued epic queues its phases (#696) -- +EPIC_BRIEF = """# Batch 2026-11-20 am +- dispatched: 2026-11-20T08:00Z +- review-at: 2026-11-20T12:00Z +- brief: + - goals: + - 1. drive the queued epics + - backlog: scoped + - scoped: + - epics: lib + - tiers: notify, glance + - review-minutes: 200 + - lanes: any local-dev ral + - merge-cap: 0 + - token-budget: 5000000 +""" +LEDGER = "draft/feature/lib/lib_epic.md" + + +def _brief_of(text=EPIC_BRIEF): + return _batch._brief.parse(text)["brief"] + + +def ledger(path=LEDGER, epic="lib"): + r = rec(path, epic=epic, autonomy="human-required") + r.update(ledger=bool(epic), phase_declared=False, witness="the map") + return r + + +def member(path, phase, *, epic="lib", repos=("autofit", "autolens"), **kw): + r = rec(path, epic=epic, phase=phase, repos=repos, **kw) + r.update(phase_declared=True, witness="a fixture passes") + return r + + +def test_a_queued_epic_ledger_queues_its_medium_multi_repo_phase(): + """Ruling 2026-11-16 narrowed (#696): the human queuing an epic ledger is + the human queuing its phases. The medium 2-repo next phase is taken at the + ledger's rank, with no scoped-reach rejection.""" + other = rec("draft/x/queued_first.md", repos=["autoarray"]) + other["witness"] = "w" + d = _batch.plan([ledger(), member("draft/feature/lib/p5c.md", 5), other], + budget=200, session_lane="local-dev", brief=_brief_of(), + queue=["draft/x/queued_first.md", LEDGER]) + assert "draft/feature/lib/p5c.md" in paths(d) + m = next(m for m in d["members"] if m["path"] == "draft/feature/lib/p5c.md") + assert m["queue_rank"] == 1 and m["queued"] and m["queued_via"] == "lib" + assert d["scoped_reach"] == [] + assert "via epic lib" in _batch._brief.rank_note(m) + assert [e["line"] for e in d["queued_epics"]] == ["lib (q2): takes p5c"] + + +def test_an_unqueued_epic_member_is_still_held_to_the_reach_ruling(): + d = _batch.plan([ledger(), member("draft/feature/lib/p5c.md", 5)], + budget=200, session_lane="local-dev", brief=_brief_of(), queue=["x.md"]) + assert "ruling 2026-11-16" in why(d, "draft/feature/lib/p5c.md") + + +def test_a_queued_epic_still_offers_only_its_next_phase(): + d = _batch.plan([ledger(), member("draft/feature/lib/p5.md", 5), + member("draft/feature/lib/p6.md", 6)], + budget=200, session_lane="local-dev", brief=_brief_of(), queue=[LEDGER]) + assert paths(d) == ["draft/feature/lib/p5.md"] + assert why(d, "draft/feature/lib/p6.md") == "epic lib phase 6 is not next" + # The ledger itself is never a member: it is human-required. + assert "human-required" in why(d, LEDGER) + + +def test_epics_md_maps_a_ledger_whose_epic_header_was_not_read(tmp_path): + (tmp_path / "epics.md").write_text( + "# Epics\n\n## lib\n- title: L\n- ledger: draft/feature/lib/lib_epic.md\n" + "## web\n- ledger: https://example.invalid/x.md\n", encoding="utf-8") + ledgers = _batch.read_epic_ledgers(tmp_path) + assert ledgers == {LEDGER: "lib"} + plain = ledger(epic="") + assert _batch.queued_epics([LEDGER], [plain], ledgers) == {"lib": 0} + assert _batch.queued_epics([LEDGER], [plain]) == {} + # A queued phase prompt queues only itself, not its epic. + assert _batch.queued_epics(["draft/feature/lib/p5.md"], + [member("draft/feature/lib/p5.md", 5)]) == {} + + +def test_a_queued_epic_with_no_draft_phase_says_to_file_one(): + d = _batch.plan([ledger()], budget=200, session_lane="local-dev", + brief=_brief_of(), queue=[LEDGER]) + (line,) = _batch.queued_epic_lines(d) + assert line.startswith("lib (q1): nothing — no draft prompt for its next phase") + assert "Continue prompt in an attended chat" in line + + +def test_a_queued_epic_whose_next_phase_is_human_required_names_the_gate(): + d = _batch.plan([ledger(), + member("draft/feature/lib/p2a.md", 2, autonomy="human-required"), + member("draft/feature/lib/p2b.md", 2, autonomy="human-required"), + member("draft/feature/lib/p3.md", 3)], + budget=200, session_lane="local-dev", brief=_brief_of(), queue=[LEDGER]) + assert paths(d) == [] + (e,) = d["queued_epics"] + assert e["next_phase"] == "2" and not e["taken"] + assert e["line"] == ("lib (q1): nothing — next phase 2: " + "p2a (autonomy human-required); p2b (autonomy human-required)") + assert e["members"][0]["why"] == "autonomy human-required — would park at ship" + + +def test_a_held_lower_phase_still_blocks_the_next_one(): + """A phase the caller kept out before planning (claimed on Mind + origin/main, parked) is still open: the phase after it is not next.""" + p4 = member("draft/feature/lib/p4.md", 4) + d = _batch.plan([ledger(), member("draft/feature/lib/p5.md", 5)], budget=200, + session_lane="local-dev", brief=_brief_of(), queue=[LEDGER], + withheld=[(p4, "repo autofit claimed by `x` in active.md")]) + assert paths(d) == [] + assert why(d, "draft/feature/lib/p5.md") == "epic lib phase 5 is not next" + (line,) = _batch.queued_epic_lines(d) + assert line == "lib (q1): nothing — next phase 4: p4 (repo autofit claimed by `x` in active.md)" + + +def test_the_plan_text_and_json_carry_the_queued_epics(capsys): + d = _batch.plan([ledger()], budget=200, session_lane="local-dev", + brief=_brief_of(), queue=[LEDGER]) + _batch.emit(d) + out = capsys.readouterr().out + assert "Queued epics:\n lib (q1): nothing" in out + assert out.index("Queued epics:") < out.index("Not selected:") + import json + assert json.loads(json.dumps(d))["queued_epics"][0]["epic"] == "lib" diff --git a/tests/test_digest_counters.py b/tests/test_digest_counters.py index acf26ed7..80cdf3e9 100644 --- a/tests/test_digest_counters.py +++ b/tests/test_digest_counters.py @@ -255,3 +255,17 @@ def test_refusals_are_one_entry_per_task_and_reason_class(tmp_path): _digest.note_refusals(old, [{"task": "a", "why": "token-budget 400000 spent (3)"}], "2026-11-16T13:05:00Z") assert len(old["refusals"]) == 2 and "3× from" in _digest.refusal_lines(old)[0] + + +def test_the_digest_says_per_queued_epic_what_it_gave_or_why_not(): + """PyAutoBrain#696: one line per queued epic ledger under the backlog + picks, never read as the continuation of the pick above it.""" + lines = _digest.backlog_gate_lines({"backlog_gates": {"queued_epics": [ + "lib (q1): takes p5c", + "cti (q2): nothing — next phase 2: p2a (autonomy human-required — would park at ship)"]}}) + assert lines[1:] == ["Queued epics:", "· lib (q1): takes p5c", + "· cti (q2): nothing — next phase 2: p2a (autonomy " + "human-required — would park at ship)"] + section = ["- `a-pick` — why: scoped epic lib · queue.md #1 via epic lib"] + lines + (item,) = _digest._items(section) + assert "Queued epics" not in item