diff --git a/AUTONOMY.md b/AUTONOMY.md index 7e53507..8c7480b 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -875,6 +875,29 @@ close-out may take the shift past its `token-budget:`, but its tokens count against that budget and the digest shows them, and no new close-out starts once the shift's spend reaches 1.5× the budget. +**Merge order and the branch update — 2026-11-19 (M3.6j, PyAutoBrain#683), +the human's rulings ("approved, all six yes").** A shift holds a library repo +for *starting* only while a worker on it is live; it holds it for *merging* +while an earlier PR of the shift on it is open. Six rulings: + +- **(a)** an unattended branch-update session may push a merge from `main` to a + shift PR's branch (`gh pr update-branch`, never a rebase or force-push), then + must end; a later close-out merges only on CI green at the new head. The + watcher itself still pushes nothing; +- **(b)** the watcher may `gh pr view` the PRs a waiting PR waits behind every + tick, carried ones included; +- **(c)** an earlier PR blocks until GitHub says MERGED or CLOSED, whatever its + state in the shift (dropped, red, refused, abandoned); +- **(d)** a park on a question keeps holding its library's start; +- **(e)** a worker may proceed past a `worktree_check_conflict` hit that names + only a listed sibling PR's slug; +- **(f)** library repos only, and only PRs this shift knows (its outcomes and a + carried PR's `behind`). + +A waiting PR is never refused for waiting and takes no merge slot; a conflict +on update, red CI on the new head or a third update refuses it for `/prm`. +Every guard of this section still applies to the merge close-out. + ### One Mind writer per shift — 2026-11-03 During a shift, **only the orchestrator commits to PyAutoMind**, from its own @@ -971,6 +994,10 @@ later tick, at most three tries in all; one that timed out may have landed and is never retried. The watcher also reads `gh pr view --json state,mergedAt,mergedBy` for the PRs its own workers named — the close-out's merge truth (#603) and, once at `review-at:`, the digest's `merges` (#610). +Since 2026-11-19 (M3.6j, PyAutoBrain#683, ruling b) it also reads that state +every tick for each earlier PR a waiting PR of the shift waits behind, carried +ones included. The branch-update session it starts pushes a merge from `main` +(ruling a); the watcher itself still makes no write to a repository. It also makes one read-only `gh api user` per shift, under the posting token, to warn when it equals the mention login (#611) — as the App, one `GET /app` with its JWT instead, naming it `[bot]` (#630). diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index e420790..20faa37 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -306,14 +306,23 @@ Until phase 3b it spawns only stub workers (`PYAUTO_ORCHESTRATOR_FAKE=1`); a rea dispatch is refused. Doctrine: `AUTONOMY.md` "The watcher's network surface — 2026-11-03"; the exemption it runs under, `PyAutoMind/policy/shift_watcher.md`. -**A library slot frees at merge (2026-11-18, PyAutoBrain#679).** The plan -admits one task per library repo, because concurrent library PRs collide at -merge. A task this shift picked holds its library while it runs, while its PR -is open or refused, and while it is parked. Once it is done and every PR it -opened has merged (or it ended with no PR and no open question), the next tick -may start the next task on that library. The finished task stays in the plan, -so it is never re-dispatched. A claim it left in `active.md`, written by this -shift's own worker, no longer holds the repo either. +**A library is held while its worker runs; merges wait in PR order (M3.6j, +2026-11-19, PyAutoBrain#683).** The plan admits one *live* task per library +repo, so two workers never share one. Work does not collide; merges do. A task +this shift picked holds its library while its worker runs, while it is parked +(on a question or a person: ruling d), while a re-dispatch or an answered +restart is pending, and while its outcome carries an open question. Once its +worker has ended, the next tick may start the next task on that library, its +PR open, refused or merged alike (`released_picks`; first PyAutoBrain#679 freed +it only at merge, and one `/prm`-bound PR stalled the shift). A `/drop`ped task +with no live worker holds nothing. The finished task stays in the plan, so it +is never re-dispatched, and a claim its own shift worker left in `active.md` +holds nothing either. The next worker's prompt starts with `SIBLING_NOTE`, +naming this shift's open PRs on that library: branch from `main`, never stack; +end `obsolete` if a sibling already does the task; a `worktree_check_conflict` +hit naming only a listed sibling's slug is not a conflict (ruling e). The plan's +reason for a held task is ` held by — will start once 's +worker ends` (named) or ` held by while its worker runs`. **The open-brief gate is a window: `dispatched:` → `review-at:`.** A brief that passes `batch brief --check` is open only from its `dispatched:` until its @@ -533,6 +542,39 @@ writer. Every refusal is final for the shift and named in the digest (`awaiting /prm — close-out refused: `). Same-model close-out: AUTONOMY "Stage-2 adversary amendment — 2026-11-04". +**Merge order and the branch update (M3.6j, PyAutoBrain#683).** Before CI is +read, a library PR waits behind every earlier PR this shift knows on the same +GitHub repo (its outcomes and a carried outcome's `behind`; library repos only, +ruling f) until GitHub says that PR is MERGED or CLOSED, whatever this shift +made of it (ruling c); an unreadable one blocks. Waiting is not a refusal: no +close-out, no merge slot, an entry in `counters["merge_waits"]` (rebuilt each +tick, one `gh pr view` per blocking PR per tick, ruling b) and a `waiting` +event when what it waits behind changes. A workspace PR waits while its own +task's library PR waits or is being closed out. Once nothing is ahead, a PR +whose branch was cut before an earlier PR merged (merged after its task's first +worker started; for a carried PR, any merged earlier PR) takes its merge slot +and gets one **branch-update session** (`closeout_update_template.md`, `claude +--bg --name shift-update:`), after the public-name gate: it runs `gh pr +update-branch` (a merge commit from `main`; never a rebase or force-push, +ruling a), writes `updated` (new head), `current` or `refused` (`conflicts with +main after merged → your /prm`) and ends. An `updated` or `current` PR +keeps its slot and is looked at again each tick: CI running, or NO-CHECKS +within `UPDATE_CHECKS_GRACE_S` (600 s), waits; red refuses (`CI on +the updated head → your /prm`) and frees the slot; green starts the merge +close-out, whose step 4b checks every earlier PR is no longer OPEN and each +merged one is in the branch. A PR needing a third update refuses (`main kept +moving`, `UPDATE_LIMIT` 2). A waiting or updated PR at `review-at:` is not +refused; the next shift carries it with what it waited behind. The digest says +`waits behind () — merge first` and lists a per-library +"Merge order" block, ▶ on the PR that needs your /prm now. The in-turn path +keeps the same order: `merge-slot take` (`bin/merge_slot.py`) refuses a +`notify` worker's in-turn merge while an earlier shift PR on the same library +is open (`in_turn_merge_blockers`, the close-out's rule), so that PR ends at +PR-open and merges through the wait above. An `updated` PR's CI is read only +once GitHub shows the head the update made; a head that moved since refuses. +The spawn loop also refuses a task whose library a live, parked or +re-dispatch-pending task holds, whatever the plan's order made of it. + **Watching a shift live (`batch watch`, PyAutoBrain#575).** `batch watch --record [--once] [--interval N]` (`_watch.py`) draws a running shift in the terminal: SHADOW or LIVE, time left until `review-at:`, STOP and diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index b21d1e4..fc3809d 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -511,10 +511,12 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, pool.sort(key=lambda r: (r["queue_rank"], priority_rank(r), r["review_minutes"], r["path"])) - # `released` (PyAutoBrain#679): the watcher's own picks whose PRs have all - # merged, or that ended with no PR and no open question. They stay members - # (known, counted, never re-dispatched) but hold no library: a merged PR - # collides with nothing, so the next task on that library may start. + # `released` (M3.6j, PyAutoBrain#683; first #679): the watcher's own + # picks whose worker has ended (PR open or not) and that wait on no + # question, re-dispatch or restart. They stay members (known, counted, + # never re-dispatched) but hold no library: merges collide, starts do + # not, and the close-out merges a library's shift PRs in PR order (the + # merge-order wait), so the next task on that library may start. released = released or set() members, spent, seen_epics, libs = [], 0, set(), {} for r in pool: @@ -529,14 +531,16 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, # invalidates the others' test and smoke evidence. Only LIBRARY repos # claim a shift: they are what the library-first gate serialises and # what downstream suites are re-run against. Workspace, docs and organ - # repos are exempt — two docs changes in one shift cost nothing. + # repos are exempt — two docs changes in one shift cost nothing. A + # library is held while its worker runs, so two workers never share + # one; its PRs then merge in PR order at the close-out (M3.6j). clash = next((x for x in r["repos"] if x in LIBRARY_REPOS and x in libs), None) if clash: holder = libs[clash] - rejected.append((r["path"], f"{clash} held by {holder} — will start after " - f"{holder}'s PR merges" + rejected.append((r["path"], f"{clash} held by {holder} — will start once " + f"{holder}'s worker ends" if Path(r["path"]).name in named_names - else f"{clash} held by {holder} until its PR merges")) + else f"{clash} held by {holder} while its worker runs")) continue cost = 0 if r["consequence"] in CHEAP_TIERS else r["review_minutes"] if spent + cost > effective_budget: diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index e8d7262..378ed17 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -261,16 +261,99 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False, state = IN_TURN_MERGED if has_slot(counters, task, url) else IN_TURN_NO_SLOT if co.get("state") == "merged" and co.get("cleanup"): state += f" — worktree: {co['cleanup']}" + elif url in (counters.get("merge_waits") or {}): + state = wait_state(url, counters) # merge order (M3.6j, #683) elif co.get("state") == "refused": state = f"awaiting /prm — close-out refused: {co.get('why', '?')}" elif co.get("state") == "running": - state = "close-out running" + state = UPDATING if co.get("kind") == "update" else "close-out running" + elif co.get("state") == "updated": + state = (f"{UPDATED} after {', '.join(map(pr_ref, co.get('after') or []))}, " + f"CI on new head {health(url)}") + elif co.get("state") == "current": + state = f"{CURRENT}, CI {health(url)}" else: state = health(url) parts.append(f"{url} — {state}") return "; ".join(parts), True +#: A PR's states in the merge order (M3.6j, PyAutoBrain#683). +UPDATING = "close-out updating the branch from main" +UPDATED = "branch updated from main" +CURRENT = "branch already up to date with main" +MERGE_ORDER_HEADING = "### Merge order" +_PR_REF_RE = re.compile(r"^https://github\.com/[^/\s]+/([^/\s]+)/pull/(\d+)") + + +def pr_ref(url: str) -> str: + """`repo#n` for a GitHub PR URL; the URL itself otherwise.""" + m = _PR_REF_RE.match(url or "") + return f"{m.group(1)}#{m.group(2)}" if m else (url or "?") + + +def _order_word(url: str, counters: dict) -> str: + """What an earlier PR in the merge order is doing, in a few words.""" + co = (counters.get("closeouts") or {}).get(url) or {} + if url in (counters.get("merge_waits") or {}): + return "itself waiting" + if co.get("state") == "refused": + return f"needs your /prm: {refusal_class(co.get('why') or '?')}" + if co.get("state") == "running": + return "close-out running" + if co.get("state") in ("updated", "current"): + return "branch updated, CI re-running" + return "open" + + +def wait_state(url: str, counters: dict) -> str: + """A PR waiting in merge order: behind which PRs, what they are doing, and + which one to merge first (M3.6j, PyAutoBrain#683).""" + behind = ((counters.get("merge_waits") or {}).get(url) or {}).get("behind") or [] + return ("waits behind " + ", ".join(f"{pr_ref(b)} ({_order_word(b, counters)})" + for b in behind) + + f" — merge {pr_ref(behind[0]) if behind else '?'} first") + + +def merge_order_lines(counters: dict) -> list[str]: + """The `### Merge order` block (M3.6j, PyAutoBrain#683): for each library + repo where a PR of this shift waits behind an earlier one, its open PRs + in PR-number order, ▶ on the one that needs your /prm now; and how many + branch updates conflicted with main. Empty when nothing waits.""" + waits = counters.get("merge_waits") or {} + if not waits: + return [] + merged = {u for o in (counters.get("outcomes") or {}).values() if isinstance(o, dict) + for u in o.get("merged") or []} + known = list(dict.fromkeys( + u for o in (counters.get("outcomes") or {}).values() if isinstance(o, dict) + for u in [*(o.get("prs") or []), *(o.get("behind") or [])])) + + def repo(u): + key = _merge_slots.pr_key(u) + return key.rsplit("/pull/", 1)[0] if key else "" + + def number(u): + key = _merge_slots.pr_key(u) + return int(key.rsplit("/", 1)[1]) if key else 0 + repos = list(dict.fromkeys(repo(w) for w, info in waits.items() + if any(repo(b) == repo(w) for b in info.get("behind") or []))) + out = ["", MERGE_ORDER_HEADING] + for r in repos: + prs = sorted((u for u in known if repo(u) == r and u not in merged), key=number) + out.append(f"- **{r.rsplit('/', 1)[-1]}**, merged in this order:") + now = next((u for u in prs if u not in waits), None) + for u in prs: + word = wait_state(u, counters) if u in waits else _order_word(u, counters) + out.append(f" - {'▶ ' if u == now else ''}{u} — {word}") + conflicts = [u for u, co in (counters.get("closeouts") or {}).items() + if str(co.get("why") or "").startswith("conflicts with main")] + if conflicts: + out.append(f"- {len(conflicts)} branch update(s) conflicted with main — your /prm: " + + ", ".join(map(pr_ref, conflicts))) + return out + + def has_slot(counters: dict, task: str, url: str) -> bool: """Whether the shift's merge-slot file (as last synced into `counters` as `slot_holders`) shows a slot for this PR held for this task.""" @@ -468,6 +551,10 @@ def label(task: str, pick: dict | None, url: str = "") -> str: ("awaiting /prm — close-out refused: CI RED", "CI failed — needs you"), ("awaiting /prm", "Needs you — not merged unattended"), ("close-out running", "Still running — close-out checking it"), + (UPDATING, "Still running — close-out updating the branch from main"), + ("waits behind", "Waiting — merges after an earlier PR (your /prm first)"), + (UPDATED, "Branch updated from main — CI re-running"), + (CURRENT, "Branch up to date — awaiting its merge close-out"), (STILL_OUT, "Still running at review time"), ("verdict posted", "Verdict posted"), ("PARKED-ON-ISSUE", "Needs you — question on the issue"), @@ -593,6 +680,7 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None, why=picks[t].get("why") or "NOT RECORDED", lease=held.get(t)) for t in backlog] or [NO_PICKS] lines += backlog_gate_lines(counters) + lines += merge_order_lines(counters) started = [t for t in named + backlog if t in counters.get("outcomes", {}) or t in counters.get("parked", []) diff --git a/agents/conductors/batch/_events.py b/agents/conductors/batch/_events.py index 9582984..9abfb34 100644 --- a/agents/conductors/batch/_events.py +++ b/agents/conductors/batch/_events.py @@ -49,7 +49,7 @@ KINDS = ("shift-open", "spawned", "redispatched", "crashed", "pr-opened", "finished", "question", "parked", "ci", "closeout-started", "merged", "merged-outside", "refused", "cap", "steer", "steer-unread", "impaired", "late", "digest", - "stopped", "shift-end", "login-expired") + "stopped", "shift-end", "login-expired", "waiting") #: The kinds after which the stream has nothing more to follow. FINAL_KINDS = ("shift-end", "stopped") @@ -342,11 +342,28 @@ def _closeouts(b: _Batch, result: dict, counters: dict, info: dict) -> None: f"{cls.removesuffix(' this shift')}: later green PRs wait for /prm.", cls=cls) continue - b.add("refused", f"refused:{pr}", f"Not merging {ref(pr)}: {cls}. Left for your /prm.", + # Merge order (M3.6j, #683): later PRs of the shift wait behind it. + later = sum(1 for w in (counters.get("merge_waits") or {}).values() + if pr in (w.get("behind") or [])) + tail = f"; {later} later PR(s) wait behind it" if later else "" + b.add("refused", f"refused:{pr}", + f"Not merging {ref(pr)}: {cls}. Left for your /prm{tail}.", task=co.get("task"), pr=pr, cls=cls) + for pr in events.get("waiting") or []: + w = (counters.get("merge_waits") or {}).get(pr) or {} + behind = w.get("behind") or [] + b.add("waiting", f"waiting:{pr}:{','.join(behind)}", + f"{ref(pr)} waits behind {', '.join(map(ref, behind)) or '?'}: " + f"merge {ref(behind[0]) if behind else '?'} first.", + task=w.get("task"), pr=pr) for pr in events.get("started") or []: co = co_all.get(pr) or {} - b.add("closeout-started", f"closeout-started:{pr}", f"Close-out started on {ref(pr)}.", + if co.get("kind") == "update": + line = (f"Branch update started on {ref(pr)} (after " + f"{', '.join(map(ref, co.get('after') or [])) or '?'} merged).") + else: + line = f"Close-out started on {ref(pr)}." + b.add("closeout-started", f"closeout-started:{pr}:{co.get('started', '')}", line, task=co.get("task"), pr=pr) diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 7c08b27..d39bc82 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -87,6 +87,10 @@ #: The worker prompt every real worker starts from (never a bare session). WORKER_TEMPLATE = Path(__file__).with_name("worker_template.md") CLOSEOUT_TEMPLATE = Path(__file__).with_name("closeout_template.md") +#: The branch-update session's prompt (M3.6j, PyAutoBrain#683): one +#: `gh pr update-branch` after an earlier PR of the shift on the same library +#: merged, then end — never a merge, never a wait. +UPDATE_TEMPLATE = Path(__file__).with_name("closeout_update_template.md") #: The model and effort every spawned worker starts on — the human's ruling of #: 2026-11-18 (PyAutoBrain#672): Opus at medium effort, whatever the effort of #: the session that composed the shift. @@ -165,6 +169,8 @@ def read_counters(slot: Path) -> dict: c.setdefault("picks", {}) # task → {prompt, why, tier}, at dispatch (3d) c.setdefault("outcomes", {}) # task → {prs, merged}, from its `.done` (3d) c.setdefault("closeouts", {}) # PR url → {task, state, why, …} (4b) + # PR url → {task, behind, since}: waiting in merge order (M3.6j, #683) + c.setdefault("merge_waits", {}) c.setdefault("glance_auto_merges", 0) # PyAutoBrain#610: tokens per session (replaced each read, never added), # the sessions whose usage could not be read this tick, one exit record @@ -244,7 +250,8 @@ def __init__(self, seconds: float = 0.5, crash: set[str] | None = None): self.crash = set(crash or ()) def spawn(self, task: str, prompt_path: str, lease_dir: Path, - redispatch: bool = False, resume: dict | None = None) -> dict: + redispatch: bool = False, resume: dict | None = None, + siblings: list[str] | None = None) -> dict: mode = "crash" if task in self.crash else "ok" proc = subprocess.Popen( [sys.executable, "-c", _FAKE_WORKER, str(lease_dir), task, mode, @@ -253,8 +260,10 @@ def spawn(self, task: str, prompt_path: str, lease_dir: Path, stderr=subprocess.DEVNULL, start_new_session=True) return {"pid": proc.pid, "session_id": f"fake-{proc.pid}", "worktree": None} - def spawn_closeout(self, task: str, pr_url: str, prompt_path: str, lease_dir: Path) -> dict: - """A dry close-out: it refuses, because a fake session merged nothing.""" + def spawn_closeout(self, task: str, pr_url: str, prompt_path: str, lease_dir: Path, + **_order) -> dict: + """A dry close-out (or branch update): it refuses, because a fake + session merged and pushed nothing.""" verdict = {"result": "refused", "pr": pr_url, "why": "fake close-out (dry shift) — nothing merged", "gate": "", "model": "fake"} @@ -296,6 +305,32 @@ def pr_state(self, url: str) -> dict: """ +#: Prepended to the prompt of a worker whose library already has open PRs +#: from this shift (M3.6j, PyAutoBrain#683): its start no longer waits for +#: them to merge, so it must not build on them, and its merge waits for them. +SIBLING_NOTE = """\ +Open sibling PRs: this shift already has these PRs OPEN on the same library +repo, and they merge BEFORE yours (the close-out merges a library's shift PRs +in PR order): +{siblings} +Branch from `main`, never from a sibling's branch: no stacked PRs. Read what +each sibling changes first (`gh pr diff --name-only`). If a sibling +already does your task, end with outcome `obsolete` and name it. If you must +touch the same lines, keep the change minimal and say so in the PR body and +your proof packet: after a sibling merges, the close-out updates your branch +from main and refuses (leaving it for the human's /prm) on a conflict. A +`worktree_check_conflict` hit that names only a listed sibling's branch slug +is not a conflict (ruling e, 2026-11-19): go on. Never merge in-turn ahead +of a sibling: `merge-slot take` refuses while one is open, so end at PR-open. + +""" + + +def sibling_note(siblings: list[str]) -> str: + """`SIBLING_NOTE` filled in with the open sibling PRs, one per line.""" + return SIBLING_NOTE.format(siblings="\n".join(f"- {u}" for u in siblings)) + + def resume_note(resume: dict) -> str: """`RESUME_NOTE` filled in from a `parked_elsewhere` release.""" comments = [c for c in resume.get("comments") or [] if c] @@ -306,12 +341,15 @@ def resume_note(resume: dict) -> str: def worker_prompt(task: str, prompt_path: str, brief_path: Path, lease_dir: Path, - redispatch: bool = False, resume: dict | None = None) -> str: + redispatch: bool = False, resume: dict | None = None, + siblings: list[str] | None = None) -> str: """The session template filled in for one task; a re-dispatch is told - that its predecessor's claim may already exist (#632), and a resumed - task that the human answered its question (M3.5, #645).""" + that its predecessor's claim may already exist (#632), a resumed task + that the human answered its question (M3.5, #645), and a task whose + library has open PRs from this shift which merge first (M3.6j, #683).""" head = REDISPATCH_NOTE.format(task=task, task_path=prompt_path) if redispatch else "" head += resume_note(resume) if resume else "" + head += sibling_note(siblings) if siblings else "" return head + WORKER_TEMPLATE.read_text(encoding="utf-8").format( task=task, task_path=prompt_path, brief_path=brief_path, lease_dir=lease_dir, ledger_dir=Path(lease_dir).parent / _mind_writer.LEDGER_DIR, @@ -330,8 +368,41 @@ def pr_repos(pr_url: str) -> str: return m.group(1) if m else "" +def after_step(after: list[str] | None = None, before: list[str] | None = None) -> str: + """The close-out's merge-order step (M3.6j, PyAutoBrain#683), or "" when + no earlier PR of the shift shares this PR's library: every earlier PR + must no longer be OPEN, and every one merged after this branch was cut + must be in it (the update session merged `main` in).""" + if not (after or before): + return "" + out = ["4b. Merge order (M3.6j, PyAutoBrain#683): this shift's earlier PRs on this\n" + " library merge before this one.\n"] + if before: + out.append(" Refuse with why ` still open → merge it first` if any of these\n" + " is still OPEN (`gh pr view --json state`):\n" + + "".join(f" - {u}\n" for u in before)) + if after: + out.append(" This branch was updated from main after these merged. For each, read\n" + " its merge commit (`gh pr view --json mergeCommit`) and this\n" + " PR's head (`gh pr view --json headRefOid`), then\n" + " `gh api repos///compare/... --jq .status`:\n" + " only `ahead` or `identical` passes; anything else refuses with why\n" + " `branch not updated after → your /prm`:\n" + + "".join(f" - {u}\n" for u in after)) + return "".join(out) + + +def update_prompt(task: str, pr_url: str, prompt_path: str, brief_path: Path, + lease_dir: Path, after: list[str]) -> str: + """The branch-update session's template filled in (M3.6j, #683).""" + return UPDATE_TEMPLATE.read_text(encoding="utf-8").format( + task=task, pr_url=pr_url, task_path=prompt_path, brief_path=brief_path, + lease_dir=lease_dir, after="\n".join(f"- {u}" for u in after)) + + def closeout_prompt(task: str, pr_url: str, prompt_path: str, brief_path: Path, - lease_dir: Path) -> str: + lease_dir: Path, after: list[str] | None = None, + before: list[str] | None = None) -> str: """The close-out session template filled in for one PR (phase 4b). Its Heart check is the scoped development-ship gate for the PR's repo (leg 4, PyAutoHeart#340): only `green` merges. Its CI check is `pyauto-brain @@ -349,19 +420,27 @@ def closeout_prompt(task: str, pr_url: str, prompt_path: str, brief_path: Path, ci_verdict_cmd=f"{BRAIN_CLI} ci-verdict {pr_url}" if repos else "(not a GitHub PR URL — refuse)", public_names_cmd=f"{BRAIN_CLI} public-names {pr_url}" if repos - else "(not a GitHub PR URL — refuse)") + else "(not a GitHub PR URL — refuse)", + after_step=after_step(after, before)) def closeout_command(task: str, pr_url: str, prompt_path: str, brief_path: Path, - lease_dir: Path, mode: str) -> list[str]: + lease_dir: Path, mode: str, *, update_after: list[str] | None = None, + after: list[str] | None = None, + before: list[str] | None = None) -> list[str]: """The argv that starts one close-out session: its own name, the close-out - model at the workers' effort, the brief's worker mode. The prompt is last.""" + model at the workers' effort, the brief's worker mode. The prompt is last. + With `update_after` it is the branch-update session instead (M3.6j).""" if mode not in _brief.WORKER_MODES: raise OrchestratorError(f"worker mode {mode!r} is not one of " + ", ".join(_brief.WORKER_MODES)) + if update_after: + return ["claude", "--bg", "--name", f"shift-update:{task}", "--model", + CLOSEOUT_MODEL, "--effort", WORKER_EFFORT, "--permission-mode", mode, + update_prompt(task, pr_url, prompt_path, brief_path, lease_dir, update_after)] return ["claude", "--bg", "--name", f"shift-close:{task}", "--model", CLOSEOUT_MODEL, "--effort", WORKER_EFFORT, "--permission-mode", mode, - closeout_prompt(task, pr_url, prompt_path, brief_path, lease_dir)] + closeout_prompt(task, pr_url, prompt_path, brief_path, lease_dir, after, before)] def worker_env(lease_dir: Path, base: dict | None = None) -> dict: @@ -391,7 +470,8 @@ def worker_env(lease_dir: Path, base: dict | None = None) -> dict: def session_command(task: str, prompt_path: str, brief_path: Path, lease_dir: Path, mode: str, redispatch: bool = False, - resume: dict | None = None) -> list[str]: + resume: dict | None = None, + siblings: list[str] | None = None) -> list[str]: """The exact argv that starts one worker — named, on `WORKER_MODEL` at `WORKER_EFFORT`, moded, templated; the prompt is the last element. @@ -402,7 +482,8 @@ def session_command(task: str, prompt_path: str, brief_path: Path, lease_dir: Pa + ", ".join(_brief.WORKER_MODES)) return ["claude", "--bg", "--name", f"shift:{task}", "--model", WORKER_MODEL, "--effort", WORKER_EFFORT, "--permission-mode", mode, - worker_prompt(task, prompt_path, brief_path, lease_dir, redispatch, resume)] + worker_prompt(task, prompt_path, brief_path, lease_dir, redispatch, resume, + siblings)] #: `claude --bg` prints `backgrounded · <8-hex id> · ` on its first line. @@ -490,9 +571,10 @@ def pr_state(self, url: str) -> dict | None: return self.gh(url) def spawn(self, task: str, prompt_path: str, lease_dir: Path, - redispatch: bool = False, resume: dict | None = None) -> dict: + redispatch: bool = False, resume: dict | None = None, + siblings: list[str] | None = None) -> dict: argv = session_command(task, prompt_path, self.brief_path, lease_dir, self.mode, - redispatch, resume) + redispatch, resume, siblings) res = run_scoped(self.run, argv, task, cwd=self.cwd, capture_output=True, text=True, timeout=120, env=worker_env(lease_dir)) # An untrusted folder is refused here, fast ("Workspace not trusted") — @@ -506,7 +588,9 @@ def spawn(self, task: str, prompt_path: str, lease_dir: Path, + res.stdout.strip()[:200]) return {"pid": 0, "agent_id": m.group(1), "session_id": None, "mode": self.mode} - def spawn_closeout(self, task: str, pr_url: str, prompt_path: str, lease_dir: Path) -> dict: + def spawn_closeout(self, task: str, pr_url: str, prompt_path: str, lease_dir: Path, + update_after: list[str] | None = None, after: list[str] | None = None, + before: list[str] | None = None) -> dict: # The public-name check runs here, deterministically, before any # session (#641): a hit or a cannot-tell is this PR's refusal, written # as the verdict a close-out would write, and nothing is spawned. @@ -517,7 +601,8 @@ def spawn_closeout(self, task: str, pr_url: str, prompt_path: str, lease_dir: Pa (Path(lease_dir) / f"{task}.closeout").write_text(json.dumps(verdict)) return {"pid": 0, "agent_id": None} argv = closeout_command(task, pr_url, prompt_path, self.brief_path, lease_dir, - self.mode) + self.mode, update_after=update_after, after=after, + before=before) # The same scoped route as a worker (#634): a close-out may be the # session that starts the daemon. res = run_scoped(self.run, argv, task, cwd=self.cwd, capture_output=True, text=True, @@ -600,11 +685,12 @@ def _liveness_known(agents) -> bool: def gh_pr_state(url: str, run=None) -> dict | None: - """One read-only `gh pr view`: {state, mergedAt, mergedBy} as GitHub has - it, or None when GitHub could not say (#603: the merge truth).""" + """One read-only `gh pr view`: {state, mergedAt, mergedBy, head} as GitHub + has it, or None when GitHub could not say (#603: the merge truth). `head` + (the head sha) tells an updated branch's CI from an older head's (M3.6j).""" run = run or subprocess.run try: - res = run(["gh", "pr", "view", url, "--json", "state,mergedAt,mergedBy"], + res = run(["gh", "pr", "view", url, "--json", "state,mergedAt,mergedBy,headRefOid"], capture_output=True, text=True, timeout=60) if res.returncode != 0: return None @@ -615,7 +701,8 @@ def gh_pr_state(url: str, run=None) -> dict | None: return None by = data.get("mergedBy") or {} return {"state": str(data["state"]).upper(), "mergedAt": data.get("mergedAt") or "", - "mergedBy": by.get("login", "") if isinstance(by, dict) else str(by)} + "mergedBy": by.get("login", "") if isinstance(by, dict) else str(by), + "head": str(data.get("headRefOid") or "")} _USAGE_FIELDS = (("input", "input_tokens"), ("output", "output_tokens"), @@ -1375,8 +1462,9 @@ def _spawned_release(counters: dict, task: str, now: _dt.datetime) -> None: def carry_in(slot: Path, counters: dict, now: _dt.datetime) -> dict: """Carry-over at a shift's first tick (M3.6c): the newest earlier slot's - late `glance`/`notify` PRs — never closed out, or refused only because - they went green too close to `review-at:` — enter this shift's outcomes, + late `glance`/`notify` PRs — never closed out (a merge-order wait among + them), updated from main but not yet closed out (M3.6j), or refused only + because they went green too close to `review-at:` — enter this shift's outcomes, so its close-out path takes them under this shift's grant (`merge-cap:`, CI green, the close-out session's own checks). A PR refused for its tier, its CI or a `/drop` stays the human's. Recorded once, as `carried_in`.""" @@ -1405,15 +1493,25 @@ def carry_in(slot: Path, counters: dict, now: _dt.datetime) -> dict: # A task parked on a question stays parked: its PR waits on # the answer, and `parked_elsewhere` keeps its hold (review). continue + # A PR still waiting in merge order, or whose branch was updated + # but not yet closed out (M3.6j), carries too. prs = [u for u in o.get("prs") or [] if "/pull/" in u and u not in (o.get("merged") or []) and ((prev.get("closeouts") or {}).get(u) is None + or ((prev.get("closeouts") or {}).get(u) or {}).get("state") + in ORDER_STATES or str(((prev.get("closeouts") or {}).get(u) or {}).get("why", "")) .startswith(cut))] if not prs: continue counters["outcomes"][task] = {"prs": prs, "merged": [], "issues": [], "carried_from": rec["from"]} + # What each waited behind comes along, so a carried PR never + # merges ahead of an earlier one that was not carried (M3.6j). + behind = [b for u in prs + for b in ((prev.get("merge_waits") or {}).get(u) or {}).get("behind") or []] + if behind: + counters["outcomes"][task]["behind"] = list(dict.fromkeys(behind)) counters["picks"][task] = dict(pick, why=f"carried over from {rec['from']} · " + str(pick.get("why") or "")) if task not in counters["done"]: @@ -1534,6 +1632,57 @@ def _repo_key(name: str) -> str: return normalise_repo(name) +def _library_key(pr_url: str) -> str: + """The library repo key a PR URL belongs to (`_repo_key` of its repo), + or "" when its repo is not a library — only library PRs merge in order + (ruling f, 2026-11-19).""" + from _sizing import LIBRARY_REPOS # noqa: E402 — the batch conductor's path + repo = pr_repos(pr_url) + key = _repo_key(repo) if repo else "" + return key if key in LIBRARY_REPOS else "" + + +def sibling_prs(counters: dict, repos) -> list[str]: + """This shift's PRs not yet merged on one of `repos`' library repos + (M3.6j, #683), in PR-number order: the PRs a new worker on that library + must not stack on, and whose merges come before its own.""" + libs = {_repo_key(r) for r in repos} + out = [] + for o in (counters.get("outcomes") or {}).values(): + if not isinstance(o, dict): + continue + merged = set(o.get("merged") or []) + out += [u for u in o.get("prs") or [] if "/pull/" in u and u not in merged + and (k := _library_key(u)) and k in libs] + return sorted(set(out), key=_pr_number) + + +def _library_holder(counters: dict, live: dict, task: str, repos) -> tuple[str, str] | None: + """(library repo, holding task) when a live, parked or re-dispatch-pending + task other than `task` already holds one of `repos`' library repos.""" + from _sizing import LIBRARY_REPOS # noqa: E402 — the batch conductor's path + mine = {_repo_key(r) for r in repos} & LIBRARY_REPOS + if not mine: + return None + holders = [*live, *(counters.get("parked") or []), + *(counters.get("pending_redispatch") or [])] + for other in dict.fromkeys(holders): + if other == task: + continue + theirs = {_repo_key(r) for r in ((counters.get("picks") or {}).get(other) or {}) + .get("repos") or []} + hit = next((r for r in sorted(mine) if r in theirs), None) + if hit: + return hit, other + return None + + +def _pr_number(url: str) -> int: + """A PR URL's number (0 when it is not a PR URL).""" + key = _merge_slots.pr_key(url) + return int(key.rsplit("/", 1)[1]) if key else 0 + + def claimed_repos(sections: dict[str, dict]) -> dict[str, tuple[str, str]]: """{repo key: (repo as written, the claiming slug)} for every claim that does not record human-authorized coordination.""" @@ -1569,24 +1718,29 @@ def claim_of(sections: dict[str, dict], task: str) -> tuple[str, dict] | None: if Path(sec.get("prompt") or "").stem == task), None) -def released_picks(counters: dict) -> set[str]: - """This shift's own picks that no longer hold their library repos - (PyAutoBrain#679): done or abandoned, and either every PR they opened has - merged, or they ended with no PR and no open question. Everything else - holds: a live lease, a park on a question or a person, a PR open or - refused (a judge PR awaiting /prm, a glance PR past `merge-cap:`), a - pending re-dispatch or an answered park waiting to restart.""" +def released_picks(counters: dict, live: set[str] | None = None) -> set[str]: + """This shift's own picks that no longer hold their library repos for a + START (M3.6j, PyAutoBrain#683; first PyAutoBrain#679): a library is held + only while a worker on it is live. A pick that finished (done or + abandoned) releases it, PR open or not: work does not collide, merges do, + and the close-out serialises merges in PR order (`_merge_blockers`). + Still holding: a live lease, a park on a question or a person (ruling d), + an outcome with an open question, a pending re-dispatch (`/kill` or a + crash: the re-dispatch reuses its PR) or an answered park waiting to + restart. A task the human `/drop`ped holds nothing once no worker of it + is live (`live`, the tick's active leases), started or not.""" hold = {*(counters.get("parked") or []), *(counters.get("pending_redispatch") or []), *(counters.get("inshift_pending") or {})} + live = set(live or ()) out = set() for task in {*(counters.get("done") or []), *(counters.get("abandoned") or [])}: if task not in (counters.get("picks") or {}) or task in hold: continue o = (counters.get("outcomes") or {}).get(task) o = o if isinstance(o, dict) else {} - prs, merged = o.get("prs") or [], set(o.get("merged") or []) - if (prs and all(u in merged for u in prs)) or (not prs and not o.get("questions")): + if not o.get("questions"): out.add(task) + out |= {t for t in (counters.get("dropped") or {}) if t not in live and t not in hold} return out @@ -1610,9 +1764,10 @@ def on_origin(records: list[dict], mind: Path, own: set[str], never counts against its repos; every other claim on them does. `released` (PyAutoBrain#679) are this shift's own picks that hold no - library any more (`released_picks`). A claim one of them left behind — - the close-out queues its `drop-section`, but a set-aside op, a failed push - or a close-out that skipped it leaves the section — holds nothing, when + library start any more (`released_picks`: finished, PR may still be + open). A claim one of them left behind — the close-out drops it only + after the merge, and a set-aside op, a failed push or a close-out that + skipped it leaves the section — holds nothing, when its `- session:` is this shift's own worker (`slot_name`). Any other claim still holds.""" claims = origin_claims(mind, fetch=fetch) @@ -1921,8 +2076,9 @@ def plan() -> dict: carried = {t for t, o in (counters.get("outcomes") or {}).items() if isinstance(o, dict) and o.get("carried_from")} recs = [r for r in recs if task_id(r["path"]) not in carried] - # A pick whose PRs have all merged frees its library (#679). - freed = released_picks(counters) - carried + # A pick whose worker has ended frees its library for a start + # (M3.6j, #683); its PR's merge waits in order at the close-out. + freed = released_picks(counters, live=set(active_leases(slot))) - carried recs, claimed = on_origin(recs, mind, set(counters["picks"]) - carried, fetch=lambda: _fetch_once(mind, counters, now), resumes=resumes, released=freed, slot_name=slot.name) @@ -2041,6 +2197,14 @@ def known(task: str) -> bool: or task in counters["abandoned"] \ or task in counters["parked"] or task in counters["dropped"]: continue + # Never two workers on one library (M3.6j review F2): a live, parked + # or re-dispatch-pending task holds its library repos whatever the + # plan's rank order made of it this tick. + holder = _library_holder(counters, live, task, member.get("repos") or []) + if holder: + refused.append({"task": task, "why": f"{holder[0]} held by {holder[1]} " + "while its worker runs"}) + continue if len(live) >= max_workers: refused.append({"task": task, "why": f"max-workers {max_workers} reached"}) continue @@ -2084,6 +2248,9 @@ def known(task: str) -> bool: again = {"redispatch": True} if task in counters["pending_redispatch"] else {} if member.get("resume"): again["resume"] = member["resume"] # answered: RESUME_NOTE (#645) + siblings = sibling_prs(counters, member.get("repos") or []) + if siblings: + again["siblings"] = siblings # open on its library (M3.6j) lease.update(spawner.spawn(task, member["path"], slot / "leases", **again)) except Exception as e: # One task's failed launch is that task's refusal, not the tick's: @@ -3609,6 +3776,23 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta # GitHub decides every merge count. Without a GitHub seam (a test # spawner) the verdict file is all there is. merged = gh_state == "MERGED" if gh else said_merged + result = (verdict or {}).get("result") + if result in ORDER_STATES and not merged: + # A branch-update session's word (M3.6j, #683): the branch now has + # main in it (`updated`) or already had (`current`). Neither is a + # merge nor a refusal: the slot stays held, and a later tick + # starts the merge close-out on CI green at the new head. + co.update(state=result, updated=_iso(now)) + if result == "updated": + co.update(head=str(verdict.get("head") or "")[:64], + updates=int(co.get("updates") or 0) + 1) + co.pop("why", None) + events.setdefault("updated", []).append(pr) + if co.get("agent_id") in counters["usage"]: + counters["usage"][co["agent_id"]]["final"] = True + _write_counters(slot, counters) + verdict_file.unlink(missing_ok=True) + continue if said_merged and gh and gh_state == "OPEN": co["why"] = "close-out said merged; GitHub still OPEN — re-checked each tick" _write_counters(slot, counters) @@ -3697,113 +3881,307 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta return events +#: How long an `updated` PR (its branch just merged `main` in) may read +#: NO-CHECKS before that is its CI verdict: room for CI to register on the new +#: head (M3.6j, PyAutoBrain#683). +UPDATE_CHECKS_GRACE_S = 600 +#: Branch updates one PR may have in a shift; the next one it would need +#: refuses it, `main kept moving → your /prm` (M3.6j). +UPDATE_LIMIT = 2 +#: Close-out states the watcher looks at again on later ticks (M3.6j): the +#: branch was brought up to date with `main` (or already was), its slot is +#: held, and its merge close-out has not started yet. +ORDER_STATES = ("updated", "current") + + +def _iso_or_none(text: str) -> _dt.datetime | None: + try: + return _dt.datetime.fromisoformat(str(text).replace("Z", "+00:00")) + except ValueError: + return None + + +def _known_prs(counters: dict) -> dict[str, str]: + """{canonical PR key: URL} for every PR this shift knows (ruling f): its + outcomes' PRs, carried ones included, and a carried outcome's `behind`.""" + out: dict[str, str] = {} + for o in (counters.get("outcomes") or {}).values(): + if not isinstance(o, dict): + continue + for u in [*(o.get("prs") or []), *(o.get("behind") or [])]: + k = _merge_slots.pr_key(u) + if k: + out.setdefault(k, u) + return out + + +def _earlier_prs(counters: dict, pr: str) -> list[str]: + """This shift's known PRs that merge before `pr`, in PR order: the same + GitHub repo, a lower number, and only on a library repo (ruling f).""" + key = _merge_slots.pr_key(pr) + if not key or not _library_key(pr): + return [] + repo, n = key.rsplit("/pull/", 1) + return sorted((u for k, u in _known_prs(counters).items() + if k.rsplit("/pull/", 1)[0] == repo and _pr_number(k) < int(n)), + key=_pr_number) + + +def _recorded_merged(counters: dict) -> set[str]: + """Canonical keys of the PRs this shift recorded merged.""" + urls = [u for o in (counters.get("outcomes") or {}).values() if isinstance(o, dict) + for u in o.get("merged") or []] + urls += [pr for pr, co in (counters.get("closeouts") or {}).items() + if co.get("state") == "merged"] + return {k for k in map(_merge_slots.pr_key, urls) if k} + + +def _merge_blockers(counters: dict, pr: str, pr_state, cache: dict) -> list[str]: + """The earlier PRs (`_earlier_prs`) `pr` must wait behind (M3.6j, + PyAutoBrain#683): every one not recorded merged and not MERGED or CLOSED + on GitHub, whatever this shift made of it — refused, dropped, red + (ruling c). One GitHub read per PR per tick (`cache`, ruling b); a PR + GitHub cannot say about blocks.""" + merged = _recorded_merged(counters) + out = [] + for u in _earlier_prs(counters, pr): + if _merge_slots.pr_key(u) in merged: + continue + gh = _gh_once(pr_state, cache, u) + if (gh or {}).get("state") in ("MERGED", "CLOSED"): + continue + out.append(u) + return out + + +def in_turn_merge_blockers(slot: Path, pr: str, pr_state=None) -> list[str]: + """The earlier PRs of this shift a worker's in-turn merge of `pr` would + jump (M3.6j review F1): the same rule as the close-out's wait + (`_merge_blockers`), read from the slot's `counters.json`. `merge-slot + take` refuses while any is open, so the PR ends at PR-open and the + watcher's close-out merges it in order. A missing counters file (no shift + state yet) blocks nothing; an unreadable one raises `OSError`/`ValueError`.""" + path = Path(slot) / COUNTERS_FILE + if not path.exists(): + return [] + counters = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(counters, dict): + raise ValueError(f"{path} is not a JSON object") + counters.setdefault("outcomes", {}) + counters.setdefault("closeouts", {}) + return _merge_blockers(counters, pr, pr_state or gh_pr_state, {}) + + +def _gh_once(pr_state, cache: dict, url: str) -> dict | None: + """`pr_state(url)`, read at most once a tick; None when it cannot say.""" + if url not in cache: + try: + cache[url] = pr_state(url) if pr_state else None + except Exception: # an unreadable PR blocks, as an unknown one does + cache[url] = None + return cache[url] + + +def _merged_after_start(counters: dict, task: str, pr: str, pr_state, cache: dict, + carried: bool) -> list[str]: + """The earlier PRs that merged after `task`'s first worker started (M3.6j): + its branch was cut from a `main` without them, so it is updated before it + merges. A carried PR's every merged earlier PR counts; so does one whose + merge time cannot be read.""" + first = None if carried else min( + (t for t in (_iso_or_none(w.get("spawned") or "") for w in counters.get("workers") or [] + if w.get("task") == task) if t), default=None) + merged = _recorded_merged(counters) + out = [] + for u in _earlier_prs(counters, pr): + co = (counters.get("closeouts") or {}).get(u) or {} + at = (co.get("github") or {}).get("mergedAt") if co.get("state") == "merged" else "" + if not at: + gh = _gh_once(pr_state, cache, u) + if (gh or {}).get("state") != "MERGED" and _merge_slots.pr_key(u) not in merged: + continue # closed unmerged: nothing of it is on main + at = (gh or {}).get("mergedAt") or "" + when = _iso_or_none(at) if at else None + if first is None or when is None or when > first: + out.append(u) + return out + + def _start_closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.datetime, health, events: dict, review_at: _dt.datetime | None, pr_state=None) -> dict: - """Start one close-out per newly green PR, under the watcher's guards.""" + """Start one close-out per newly green PR, under the watcher's guards. + + Merge order (M3.6j, PyAutoBrain#683): a library PR whose earlier PR of + this shift on the same library is still open waits — no close-out, no + merge slot, no refusal — in `counters["merge_waits"]`, rebuilt each tick; + a workspace PR waits while its own task's library PR waits or is being + closed out. Once nothing is ahead of it, a PR whose branch was cut before + an earlier PR merged gets a branch-update session first (`gh pr + update-branch`, ruling a) under its merge slot, and its merge close-out + starts on a later tick, only on CI green at the new head.""" lease_dir = slot / "leases" health = health or _digest.pr_health budget = _brief._nonneg_int(brief.get("token-budget", {}).get("value", "")) - for task, out in counters["outcomes"].items(): - for pr in out["prs"]: - if "/pull/" not in pr or pr in out["merged"] or pr in counters["closeouts"]: - continue - tier = counters["picks"].get(task, {}).get("tier", "?") - if task in counters["dropped"]: - counters["closeouts"][pr] = {"task": task, "state": "refused", - "why": "dropped by /drop — the human's /prm"} - events["refused"].append(pr) - continue - if tier not in ("glance", "notify"): - # Ruling R3 (2026-11-17, #661): a `notify` PR a worker left - # open is closed out on the same terms as a `glance` one. - counters["closeouts"][pr] = {"task": task, "state": "refused", - "why": f"tier {tier} — never merged unattended " - "→ your /prm"} - events["refused"].append(pr) - continue - if out.get("carried_from"): - # A carried PR (M3.6c) may have been merged or closed by the - # human since its shift: only an OPEN one is closed out, so a - # human's merge is never counted as an unattended one. - gh = pr_state(pr) if pr_state else None - if not gh: - continue # GitHub unreadable: asked again next tick, never assumed - state = gh.get("state") - if state != "OPEN": - counters["closeouts"][pr] = { - "task": task, "state": "refused", - "why": f"carried over from {out['carried_from']}, but GitHub reads it " - f"{state or '?'} — not closed out"} - events["refused"].append(pr) - continue - verdict = health(pr) - if verdict == "RUNNING": - continue # CI has not landed yet; look again next tick - if verdict != "HEALTHY": - counters["closeouts"][pr] = {"task": task, "state": "refused", - "why": f"CI {verdict} — never merged unattended"} - events["refused"].append(pr) - continue - if review_at is not None \ - and (review_at - now).total_seconds() < CLOSEOUT_CUTOFF_S: - # A close-out runs ~10-20 min; one still out at review-at - # merged outside the digest (#632, F1). Final, like the others. - counters["closeouts"][pr] = { - "task": task, "state": "refused", - "why": f"green within {CLOSEOUT_CUTOFF_S // 60} min of review-at — " - "no close-out starts this late"} - events["refused"].append(pr) - continue - if budget is not None and counters["usage_unavailable"]: - # As the spawn gate: a spend that cannot be read could be - # anything, so nothing starts this tick; asked again next tick. - events.setdefault("held", []).append( - {"pr": pr, "why": "token usage unavailable (" - + ", ".join(counters["usage_unavailable"]) + ")"}) + cache: dict = {} # GitHub's word on a PR, read once this tick (ruling b) + before_waits = counters.get("merge_waits") or {} + waits: dict = {} + counters["merge_waits"] = waits + + def refuse(pr: str, task: str, why: str, held: bool = False) -> None: + prev = counters["closeouts"].get(pr) or {} + counters["closeouts"][pr] = {**{k: prev[k] for k in ("after", "updates") if k in prev}, + "task": task, "state": "refused", "why": why} + events["refused"].append(pr) + if held: # an updated PR's slot, taken before its update session + try: + _merge_slots.release(slot, pr, _merge_slots.WATCHER, why) + except (_merge_slots.MergeSlotError, OSError): + pass + + # Library PRs first, so a workspace PR sees its task's library PR's wait. + pairs = sorted(((task, pr) for task, out in counters["outcomes"].items() + for pr in out["prs"]), key=lambda tp: not _library_key(tp[1])) + for task, pr in pairs: + out = counters["outcomes"][task] + if "/pull/" not in pr or pr in out["merged"]: + continue + co = counters["closeouts"].get(pr) + again = co is not None + if again and co.get("state") not in ORDER_STATES: + continue + tier = counters["picks"].get(task, {}).get("tier", "?") + if task in counters["dropped"]: + refuse(pr, task, "dropped by /drop — the human's /prm", held=again) + continue + if tier not in ("glance", "notify"): + # Ruling R3 (2026-11-17, #661): a `notify` PR a worker left + # open is closed out on the same terms as a `glance` one. + refuse(pr, task, f"tier {tier} — never merged unattended → your /prm", held=again) + continue + if out.get("carried_from"): + # A carried PR (M3.6c) may have been merged or closed by the + # human since its shift: only an OPEN one is closed out, so a + # human's merge is never counted as an unattended one. + gh = _gh_once(pr_state, cache, pr) + if not gh: + continue # GitHub unreadable: asked again next tick, never assumed + state = gh.get("state") + if state != "OPEN": + refuse(pr, task, f"carried over from {out['carried_from']}, but GitHub reads " + f"it {state or '?'} — not closed out", held=again) continue - spent = _committed_tokens(counters) - # `is not None`: a `/cap tokens 0` (#644) means zero, not "no budget". - if budget is not None and spent >= CLOSEOUT_BUDGET_FACTOR * budget: - # The human's ruling 2026-11-14 (#632, F5): a close-out may pass - # the budget, but none starts once spend reaches 1.5x it — - # spend as the spawn gate counts it, reservations included. - counters["closeouts"][pr] = { - "task": task, "state": "refused", - "why": f"token spend {spent} (committed) reached " - f"{CLOSEOUT_BUDGET_FACTOR}× token-budget {budget}"} - events["refused"].append(pr) + # Merge order (M3.6j): an earlier library PR of this shift still open + # holds this one back. Waiting is not a refusal and takes no slot. + behind = _merge_blockers(counters, pr, pr_state, cache) + if not behind and not _library_key(pr): + behind = [u for u in out["prs"] if u != pr and _library_key(u) + and u not in out["merged"] + and (u in waits or (counters["closeouts"].get(u) or {}).get("state") + in ("running", *ORDER_STATES))] + if behind: + prev = before_waits.get(pr) or {} + waits[pr] = {"task": task, "behind": behind, + "since": prev.get("since") or _iso(now)} + if prev.get("behind") != behind: + events.setdefault("waiting", []).append(pr) + continue + if again and co.get("state") == "updated" and co.get("head"): + # CI is judged on the head the update made (review F5): until + # GitHub shows that head, a check read may be an older head's. + head = (_gh_once(pr_state, cache, pr) or {}).get("head") or "" + if not head: + continue # GitHub cannot say yet: asked again next tick + if head != co["head"]: + refuse(pr, task, f"head moved after the branch update ({co['head'][:12]} → " + f"{head[:12]}) → your /prm", held=True) continue - # One merge-slot count for the shift (R3, #661): a worker's in-turn - # merge and a close-out take from it alike. Taken last, just - # before the spawn, so no other refusal holds a slot. - try: - taken, why = _merge_slots.take(slot, pr, _merge_slots.WATCHER, task) - except (_merge_slots.MergeSlotError, OSError) as e: - taken, why = False, f"merge slot cannot tell ({str(e)[:200]}) — left for your /prm" - if not taken: - # Final for this shift, like every refusal: the PR waits for a - # human `/prm`, and the digest says why. - counters["closeouts"][pr] = {"task": task, "state": "refused", "why": why} - events["refused"].append(pr) + verdict = health(pr) + if verdict == "RUNNING": + continue # CI has not landed yet; look again next tick + if again and verdict == "NO-CHECKS" and co.get("state") == "updated": + since = _iso_or_none(co.get("updated") or "") + if since is None or (now - since).total_seconds() < UPDATE_CHECKS_GRACE_S: + continue # CI has not registered on the new head yet + if verdict != "HEALTHY": + refuse(pr, task, f"CI {verdict} on the updated head → your /prm" if again + else f"CI {verdict} — never merged unattended", held=again) + continue + if review_at is not None \ + and (review_at - now).total_seconds() < CLOSEOUT_CUTOFF_S: + if again: + # An updated PR at review-at is not refused: it keeps its + # state, the digest reports it, and the next shift carries it. continue - prompt = counters["picks"].get(task, {}).get("prompt", "") - co = {"task": task, "state": "running", "started": _iso(now), "tier": tier} + # A close-out runs ~10-20 min; one still out at review-at + # merged outside the digest (#632, F1). Final, like the others. + refuse(pr, task, f"green within {CLOSEOUT_CUTOFF_S // 60} min of review-at — " + "no close-out starts this late") + continue + if budget is not None and counters["usage_unavailable"]: + # As the spawn gate: a spend that cannot be read could be + # anything, so nothing starts this tick; asked again next tick. + events.setdefault("held", []).append( + {"pr": pr, "why": "token usage unavailable (" + + ", ".join(counters["usage_unavailable"]) + ")"}) + continue + spent = _committed_tokens(counters) + # `is not None`: a `/cap tokens 0` (#644) means zero, not "no budget". + if budget is not None and spent >= CLOSEOUT_BUDGET_FACTOR * budget: + # The human's ruling 2026-11-14 (#632, F5): a close-out may pass + # the budget, but none starts once spend reaches 1.5x it — + # spend as the spawn gate counts it, reservations included. + refuse(pr, task, f"token spend {spent} (committed) reached " + f"{CLOSEOUT_BUDGET_FACTOR}× token-budget {budget}", held=again) + continue + # Branch update (M3.6j): an earlier PR merged after this branch was + # cut, and this PR's branch does not have it yet. + after = list((co or {}).get("after") or []) + need = [u for u in _merged_after_start(counters, task, pr, pr_state, cache, + bool(out.get("carried_from"))) + if u not in after] + updates = int((co or {}).get("updates") or 0) + if need and updates >= UPDATE_LIMIT: + refuse(pr, task, f"main kept moving ({updates} branch updates this shift) " + "→ your /prm", held=again) + continue + # One merge-slot count for the shift (R3, #661): a worker's in-turn + # merge and a close-out take from it alike. Taken last, just + # before the spawn, so no other refusal holds a slot. Idempotent: + # an updated PR already holds its slot. + try: + taken, why = _merge_slots.take(slot, pr, _merge_slots.WATCHER, task) + except (_merge_slots.MergeSlotError, OSError) as e: + taken, why = False, f"merge slot cannot tell ({str(e)[:200]}) — left for your /prm" + if not taken: + # Final for this shift, like every refusal: the PR waits for a + # human `/prm`, and the digest says why. + refuse(pr, task, why) + continue + prompt = counters["picks"].get(task, {}).get("prompt", "") + new = {"task": task, "state": "running", "started": _iso(now), "tier": tier} + if need: + kw = {"update_after": need} + new.update(kind="update", after=after + need, updates=updates) + else: + # Only a PR with earlier PRs of the shift on its library is + # told about them, so every other close-out starts as before. + before = _earlier_prs(counters, pr) + kw = {k: v for k, v in (("after", after), ("before", before)) if v} + new.update({k: v for k, v in (("after", after), ("updates", updates)) if v}) + try: + new.update(spawner.spawn_closeout(task, pr, prompt, lease_dir, **kw)) + except Exception as e: + refuse(pr, task, f"the close-out could not start: {str(e)[:300]}") try: - co.update(spawner.spawn_closeout(task, pr, prompt, lease_dir)) - except Exception as e: - counters["closeouts"][pr] = {"task": task, "state": "refused", - "why": f"the close-out could not start: {str(e)[:300]}"} - events["refused"].append(pr) - try: - _merge_slots.release(slot, pr, _merge_slots.WATCHER, "the close-out could not start") - except (_merge_slots.MergeSlotError, OSError): - pass - _write_counters(slot, counters) - continue - counters["closeouts"][pr] = co - _write_counters(slot, counters) # a started close-out is never started twice - events["started"].append(pr) + _merge_slots.release(slot, pr, _merge_slots.WATCHER, "the close-out could not start") + except (_merge_slots.MergeSlotError, OSError): + pass + _write_counters(slot, counters) + continue + counters["closeouts"][pr] = new + _write_counters(slot, counters) # a started close-out is never started twice + events["started"].append(pr) return events diff --git a/agents/conductors/batch/closeout_template.md b/agents/conductors/batch/closeout_template.md index 3acfc7a..6e42a4d 100644 --- a/agents/conductors/batch/closeout_template.md +++ b/agents/conductors/batch/closeout_template.md @@ -49,7 +49,7 @@ outcome — the human merges by `/prm` at check-in. reason line (`CI PENDING: …` / `CI RED: …`): no waiting, no re-run. A `GREEN` that names a skipped **test** leg refuses too (a tiered merge stops on a skipped test leg, `skills/prm/reference.md` "Tiered merge"). -5. Immediately before you merge — after every check above, and again right +{after_step}5. Immediately before you merge — after every check above, and again right before the merge command itself — look for {lease_dir}/{task}.dropped. If it exists, the human dropped this task with `/drop` mid-shift: do not merge; refuse with why `dropped by /drop`. diff --git a/agents/conductors/batch/closeout_update_template.md b/agents/conductors/batch/closeout_update_template.md new file mode 100644 index 0000000..7d0cad2 --- /dev/null +++ b/agents/conductors/batch/closeout_update_template.md @@ -0,0 +1,43 @@ +You are the branch-update session for one pull request in a shift the human +launched by writing a shift brief: +{brief_path} + +The PR: {pr_url} +Its task: {task_path} + +A shift merges a library's PRs in PR order (M3.6j, PyAutoBrain#683). These +earlier PRs of this shift, on the same library, merged after this PR's branch +was cut from `main`: +{after} + +Your one job is to bring this PR's branch up to date with `main`, so that its +CI runs on code that includes them. You merge nothing, review nothing and +write nothing else. AUTONOMY.md ruling (a) of 2026-11-19 allows exactly one +push here: GitHub's own merge of `main` into the PR branch. + +1. If {lease_dir}/{task}.dropped exists, the human dropped this task with + `/drop`: stop, and refuse with why `dropped by /drop`. +2. Note the head: `gh pr view {pr_url} --json state,headRefOid`. If the PR + is not OPEN, refuse with why `PR is — not updated`. +3. Run `gh pr update-branch {pr_url}`. It makes a merge commit from `main` + on the PR branch. Never `--rebase`, never a force-push, never a local + merge, commit or push of your own. +4. If it reports a conflict, or fails: refuse with why + `conflicts with main after merged → your /prm` + (or the failure's first line). Never resolve a conflict yourself. +5. Read the head again (`gh pr view {pr_url} --json headRefOid`). Unchanged: + the result is `current`. Changed: the result is `updated`, with the new + head sha. +6. End at your deliverable. Never wait for CI and never arm anything that + outlives your turn: the watcher reads CI on the new head and starts the + merge close-out itself. + +Last, write {lease_dir}/{task}.closeout as one JSON object: + + {{"result": "updated" | "current" | "refused", "pr": "{pr_url}", + "head": "", + "why": "", + "model": ""}} + +Without that file the watcher records the update as ended without a verdict, +and the PR waits for the human's /prm. diff --git a/agents/conductors/batch/worker_template.md b/agents/conductors/batch/worker_template.md index e78c97f..8494578 100644 --- a/agents/conductors/batch/worker_template.md +++ b/agents/conductors/batch/worker_template.md @@ -54,6 +54,8 @@ The terms of this shift (AUTONOMY.md "Shift briefs and unattended `glance`"): before a bare `gh pr merge` (ruling R3, AUTONOMY.md "`notify` merges under `--auto` and inside a shift — 2026-11-17"). If it refuses, do not merge: list the PR in your `.done` without `merged`, and it is left for `/prm`. + A refusal naming an earlier open sibling PR of this shift means end at + PR-open: the close-out merges yours after it, in order (M3.6j). If the take succeeded but `gh pr merge` then fails, free the slot with `{brain_cli} merge-slot release --task {task} --why "merge failed"` and list the PR diff --git a/bin/merge_slot.py b/bin/merge_slot.py index 4d92335..c5eaac6 100644 --- a/bin/merge_slot.py +++ b/bin/merge_slot.py @@ -25,8 +25,9 @@ EXIT. 0 = the slot is taken (or already held for this PR and task), or this is not a shift, so nothing is counted; 1 = refused (no slot left, the shift is -paused, no cap published, or the PR's slot is another task's) — do not merge, -leave the PR for `/prm`; 2 = cannot tell (not a PR URL, no task named, or the +paused, no cap published, the PR's slot is another task's, or an earlier PR of +the shift on the same library is still open: M3.6j merge order) — do not merge, +leave the PR for `/prm` or the close-out; 2 = cannot tell (not a PR URL, no task named, or the slot directory or its file cannot be read) — do not merge either. `release` (task required, as for `take`) exits 0 when it freed this task's slot, 1 when there was none to free (the holder is named). `status` prints the @@ -44,6 +45,19 @@ sys.path.insert(0, str(BATCH)) import _merge_slots # noqa: E402 +#: The take's message when an earlier PR of the shift must merge first (M3.6j). +ORDER_REFUSAL = ("{blockers} of this shift on the same library is still open and merges " + "first — do not merge; end at PR-open (list the PR without `merged`): the " + "close-out updates it from main and merges it in order") + + +def _order_blockers(slot: Path, pr: str) -> list[str]: + """The earlier shift PRs this in-turn merge would jump (M3.6j review F1).""" + brain = Path(__file__).resolve().parents[1] + sys.path.insert(0, str(brain / "agents" / "faculties" / "sizing")) + import _orchestrator # noqa: E402 — deferred: only a take reads the order + return _orchestrator.in_turn_merge_blockers(slot, pr) + #: Every worker and close-out session takes as one holder class; the watcher #: takes as `_merge_slots.WATCHER`, so no session can free a close-out's slot. WORKER = "worker" @@ -88,6 +102,16 @@ def main(argv=None) -> int: return 2 try: if args.action == "take": + # Merge order (M3.6j): an earlier PR of this shift on the same + # library merges first, whatever path this PR would merge by. + try: + blockers = _order_blockers(slot, args.pr) + except (OSError, ValueError) as e: + print(f"cannot tell the merge order: {e} — do not merge; leave the PR for /prm") + return 2 + if blockers: + print("refused: " + ORDER_REFUSAL.format(blockers=", ".join(blockers))) + return 1 ok, why = _merge_slots.take(slot, args.pr, WORKER, task) print(("taken: " if ok else "refused: ") + why) return 0 if ok else 1 diff --git a/skills/batch/batch.md b/skills/batch/batch.md index bceb0db..feed9ad 100644 --- a/skills/batch/batch.md +++ b/skills/batch/batch.md @@ -40,8 +40,8 @@ Report, per task they named: `autonomy human-required — would park at ship` (it cannot run unattended; it would come back as a question — `supervised` no longer parks, AUTONOMY.md "Decide-and-flag"), `Status: says the work is already done`, `epic - phase N is not next`, ` held by until its PR merges` (then the - next starts; PyAutoBrain#679), `would exceed the budget`. + phase N is not next`, ` held by while its worker runs` (its + PRs then merge in PR order, M3.6j), `would exceed the budget`. If everything they named is rejected, **say so plainly and offer the planner's own proposal instead** — never hand back a batch they did not ask for as though diff --git a/tests/test_batch_named_tasks.py b/tests/test_batch_named_tasks.py index 5959c35..bb11e94 100644 --- a/tests/test_batch_named_tasks.py +++ b/tests/test_batch_named_tasks.py @@ -423,24 +423,26 @@ def test_review4_the_batch_conductor_is_refused_whatever_the_task_declares(tmp_p # --- PyAutoBrain#679: a shift's library slot frees once its task's PR has merged ------ +# --- M3.6j (#683): ... once its task's worker has ended; merges wait in PR order ------ PR1 = "https://github.com/example-org/autogalaxy/pull/7" GALAXY = ("ag_bug_one", "ag_bug_two") -def _galaxy_shift(tmp_path: Path) -> tuple[Path, Path, Path]: - """A brief naming two glance tasks on one library, first tick already run.""" +def _galaxy_shift(tmp_path: Path, names=GALAXY, *, first=True) -> tuple[Path, Path, Path]: + """A brief naming glance tasks on one library, first tick already run.""" mind, brief, home = _shift(tmp_path) rels = [] - for name in GALAXY: + for name in names: rel = _write(mind, name, target="autogalaxy") f = mind / rel f.write_text(f.read_text().replace("Consequence: notify", "Consequence: glance")) rels.append(rel) brief.write_text(brief.read_text().replace( " - draft/feature/x/none.md", "\n".join(f" - {r}" for r in rels))) - r = d._tick(brief, mind, home, NOW, d.FakeClaude()) - assert [s["task"] for s in r["spawned"]] == ["ag_bug_one"], r + if first: + r = d._tick(brief, mind, home, NOW, d.FakeClaude()) + assert [s["task"] for s in r["spawned"]] == ["ag_bug_one"], r return mind, brief, home @@ -464,8 +466,8 @@ def test_679_1_the_second_task_on_a_library_waits_while_the_first_is_live(tmp_pa assert r["spawned"] == [], r named = orch.read_counters(orch.slot_dir(brief, home))["backlog_gates"]["named"] assert named == {"draft/feature/x/ag_bug_two.md": - "autogalaxy held by ag_bug_one — will start after ag_bug_one's PR " - "merges"}, named + "autogalaxy held by ag_bug_one — will start once ag_bug_one's worker " + "ends"}, named def test_679_2_the_second_task_starts_once_every_pr_of_the_first_has_merged(tmp_path): @@ -475,16 +477,10 @@ def test_679_2_the_second_task_starts_once_every_pr_of_the_first_has_merged(tmp_ assert [s["task"] for s in r["spawned"]] == ["ag_bug_two"], r -@pytest.mark.parametrize("outcome, extra", [ - ({"prs": [PR1], "merged": [], "issues": []}, {}), # PR open - ({"prs": [PR1], "merged": [], "issues": []}, # refused - {"closeouts": {PR1: {"task": "ag_bug_one", "state": "refused", "why": "red"}}}), - ({"prs": [], "merged": [], "issues": [ISSUE], "questions": [ISSUE]}, {}), # question - ({"prs": [PR1, PR1 + "0"], "merged": [PR1], "issues": []}, {}), # one of two -]) -def test_679_3_an_open_or_refused_pr_or_a_question_still_holds(tmp_path, outcome, extra): +def test_679_3_a_question_still_holds(tmp_path): mind, brief, home = _galaxy_shift(tmp_path) - _end(brief, home, "ag_bug_one", outcome, **extra) + _end(brief, home, "ag_bug_one", + {"prs": [], "merged": [], "issues": [ISSUE], "questions": [ISSUE]}) r = d._tick(brief, mind, home, NOW, d.FakeClaude()) assert r["spawned"] == [], r @@ -539,3 +535,134 @@ def claim(session): claim("desktop session, human") assert orch.on_origin(records, mind, own={"ag_bug_one"}, released={"ag_bug_one"}, slot_name="2026-11-18-pm") == ([], held) + + +# --- M3.6j (PyAutoBrain#683): starts wait for a live worker only ----------------------- + +@pytest.mark.parametrize("outcome, extra", [ + ({"prs": [PR1], "merged": [], "issues": []}, {}), # PR open + ({"prs": [PR1], "merged": [], "issues": []}, # decision-taken + {"closeouts": {PR1: {"task": "ag_bug_one", "state": "refused", + "why": "decision-taken label → human /prm"}}}), + ({"prs": [PR1], "merged": [], "issues": []}, # public name + {"closeouts": {PR1: {"task": "ag_bug_one", "state": "refused", + "why": "public name added/renamed: Thing → human /prm"}}}), + ({"prs": [PR1], "merged": [], "issues": []}, # judge + {"closeouts": {PR1: {"task": "ag_bug_one", "state": "refused", + "why": "tier judge — never merged unattended → your /prm"}}}), + ({"prs": [PR1, PR1 + "0"], "merged": [PR1], "issues": []}, {}), # one of two +]) +def test_683_1_the_second_task_starts_once_the_first_worker_ended_pr_open( + tmp_path, outcome, extra): + mind, brief, home = _galaxy_shift(tmp_path) + _end(brief, home, "ag_bug_one", outcome, **extra) + r = d._tick(brief, mind, home, NOW, d.FakeClaude()) + assert [s["task"] for s in r["spawned"]] == ["ag_bug_two"], r + + +@pytest.mark.parametrize("how, outcome, extra", [ + ("done", {"prs": [], "merged": [], "issues": [ISSUE], "questions": [ISSUE]}, {}), + ("parked", None, {}), # ruling d + ("done", {"prs": [PR1], "merged": [], "issues": []}, # /kill: re-dispatch + {"pending_redispatch": ["ag_bug_one"]}), + ("done", {"prs": [PR1], "merged": [], "issues": []}, # answered, to restart + {"inshift_pending": {"ag_bug_one": {"ids": ["Q1"]}}}), +]) +def test_683_2_a_question_park_redispatch_or_restart_still_holds(tmp_path, how, outcome, + extra): + mind, brief, home = _galaxy_shift(tmp_path) + _end(brief, home, "ag_bug_one", outcome, how=how, **extra) + r = d._tick(brief, mind, home, NOW, d.FakeClaude()) + assert "ag_bug_two" not in [s["task"] for s in r["spawned"]], r + + +def test_683_3_never_two_workers_on_one_library_the_reason_names_the_live_one(tmp_path): + names = ("ag_bug_one", "ag_bug_two", "ag_bug_three") + mind, brief, home = _galaxy_shift(tmp_path, names) + _end(brief, home, "ag_bug_one", {"prs": [PR1], "merged": [], "issues": []}) + r = d._tick(brief, mind, home, NOW, d.FakeClaude()) + assert [s["task"] for s in r["spawned"]] == ["ag_bug_two"], r + r = d._tick(brief, mind, home, NOW, d.FakeClaude()) + assert r["spawned"] == [], r + named = orch.read_counters(orch.slot_dir(brief, home))["backlog_gates"]["named"] + assert named == {"draft/feature/x/ag_bug_three.md": + "autogalaxy held by ag_bug_two — will start once ag_bug_two's worker " + "ends"}, named + + +def test_683_4_a_dropped_task_that_never_started_frees_its_library(tmp_path): + mind, brief, home = _galaxy_shift(tmp_path, first=False) + slot = orch.slot_dir(brief, home) + slot.mkdir(parents=True, exist_ok=True) + c = orch.read_counters(slot) + c["dropped"]["ag_bug_one"] = {"by": "example-human", "at": "2026-11-04T08:40:00Z"} + orch._write_counters(slot, c) + r = d._tick(brief, mind, home, NOW, d.FakeClaude()) + assert [s["task"] for s in r["spawned"]] == ["ag_bug_two"], r + + +def test_683_5_released_picks_counts_a_finished_pick_with_its_pr_open(): + c = {"done": ["a", "q"], "abandoned": [], "parked": [], "pending_redispatch": [], + "inshift_pending": {}, "picks": {"a": {}, "q": {}, "live": {}, "gone": {}}, + "outcomes": {"a": {"prs": [PR1], "merged": [], "issues": []}, + "q": {"prs": [], "merged": [], "questions": [ISSUE]}}, + "dropped": {"live": {}, "gone": {}}} + assert orch.released_picks(c, live={"live"}) == {"a", "gone"} + + +def test_683_6_a_worker_on_a_library_with_an_open_sibling_pr_is_told_not_to_stack(tmp_path): + mind, brief, home = _galaxy_shift(tmp_path) + _end(brief, home, "ag_bug_one", {"prs": [PR1], "merged": [], "issues": []}) + claude = d.FakeClaude() + r = d._tick(brief, mind, home, NOW, claude) + assert [s["task"] for s in r["spawned"]] == ["ag_bug_two"], r + prompt = claude.calls[-1][0][-1] + assert prompt.startswith("Open sibling PRs:"), prompt[:200] + assert f"- {PR1}\n" in prompt and "never from a sibling's branch" in prompt + assert "obsolete" in prompt and "worktree_check_conflict" in prompt + # No sibling, no note: the first worker's prompt starts as before. + assert not orch.worker_prompt("t", "p.md", brief, tmp_path).startswith("Open sibling") + + +def test_683_7_a_finished_picks_leftover_claim_does_not_hold_with_its_pr_open(tmp_path): + """test_679_5 with the first task's PR still open: `released_picks` now + counts it, so its own shift worker's leftover claim holds nothing.""" + if shutil.which("git") is None: + pytest.skip("needs git") + bare, mind = tmp_path / "mind.git", tmp_path / "mind" + _git(tmp_path, "init", "-q", "--bare", "-b", "main", str(bare)) + _git(tmp_path, "clone", "-q", str(bare), str(mind)) + first = _write(mind, "ag_bug_one", target="autogalaxy") + second = _write(mind, "ag_bug_two", target="autogalaxy") + (mind / "active.md").write_text( + f"# Active\n\n## ag-bug-one\n- prompt: {first}\n" + "- session: shift worker 2026-11-18-pm (abc123)\n" + "- repos:\n - autogalaxy: feature/ag-bug-one\n") + _git(mind, "add", "-A") + _git(mind, "-c", "user.name=T", "-c", "user.email=t@example.invalid", "commit", + "-q", "-m", "claim") + _git(mind, "push", "-q", "origin", "HEAD:main") + _git(mind, "fetch", "-q", "origin") + records = [_batch.grade(mind / second, mind)] + c = {"done": ["ag_bug_one"], "picks": {"ag_bug_one": {}}, + "outcomes": {"ag_bug_one": {"prs": [PR1], "merged": [], "issues": []}}} + kept, out = orch.on_origin(records, mind, own={"ag_bug_one"}, + released=orch.released_picks(c), slot_name="2026-11-18-pm") + assert (kept, out) == (records, {}) + + +def test_683_f2_a_live_task_holds_its_library_even_when_it_leaves_the_plan(tmp_path): + """Review F2: the plan gives a library to the first member that asks, in + its own order; a live task that is no longer a member this tick (here its + draft left the survey, as when the canonical checkout is pulled and the + claimed draft has moved to `active/`; a queue.md reorder does the same + for backlog picks) held nothing there. The spawn loop never starts a + second worker on that library, and its refusal names the live one.""" + mind, brief, home = _galaxy_shift(tmp_path) + (mind / "draft/feature/x/ag_bug_one.md").unlink() + slot = orch.slot_dir(brief, home) + working = d._agents({"ag_bug_one": "working"}, slot) # its usage reads + r = d._tick(brief, mind, home, NOW, d.FakeClaude(), agents=working) + assert r["spawned"] == [], r + assert {"task": "ag_bug_two", + "why": "autogalaxy held by ag_bug_one while its worker runs"} in r["refused"], r diff --git a/tests/test_batch_plan.py b/tests/test_batch_plan.py index 3d4afa7..b2a7247 100644 --- a/tests/test_batch_plan.py +++ b/tests/test_batch_plan.py @@ -60,11 +60,12 @@ def test_notify_tier_work_costs_the_human_nothing(): def test_one_member_per_library_repo_per_shift(): """They do not collide at dispatch — separate worktrees — they collide at - merge, when the first /prm moves main and invalidates the rest.""" + merge, when the first /prm moves main and invalidates the rest. A library + is held only while its worker runs (M3.6j, #683); merges wait in order.""" d = _batch.plan([rec("a.md", repos=["autoarray"]), rec("b.md", repos=["autoarray"])], budget=100) assert paths(d) == ["a.md"] - assert "autoarray held by a until its PR merges" in why(d, "b.md") + assert "autoarray held by a while its worker runs" in why(d, "b.md") def test_a_released_member_holds_no_library(): diff --git a/tests/test_orchestrator_closeout.py b/tests/test_orchestrator_closeout.py index 63df66c..5619f3f 100644 --- a/tests/test_orchestrator_closeout.py +++ b/tests/test_orchestrator_closeout.py @@ -360,10 +360,11 @@ def run(argv, **kw): seen.append(argv) return SimpleNamespace(returncode=0, stdout=json.dumps( {"state": "MERGED", "mergedAt": "2026-11-04T09:00:00Z", - "mergedBy": {"login": "someone"}})) + "mergedBy": {"login": "someone"}, "headRefOid": "abc123"})) assert orch.gh_pr_state(PR1, run=run) == { - "state": "MERGED", "mergedAt": "2026-11-04T09:00:00Z", "mergedBy": "someone"} - assert seen == [["gh", "pr", "view", PR1, "--json", "state,mergedAt,mergedBy"]] + "state": "MERGED", "mergedAt": "2026-11-04T09:00:00Z", "mergedBy": "someone", + "head": "abc123"} + assert seen == [["gh", "pr", "view", PR1, "--json", "state,mergedAt,mergedBy,headRefOid"]] assert orch.gh_pr_state(PR1, run=lambda a, **k: SimpleNamespace( returncode=1, stdout="")) is None assert orch.gh_pr_state(PR1, run=lambda a, **k: SimpleNamespace( @@ -547,3 +548,301 @@ def test_the_digest_names_closeout_tokens_and_an_overrun(): "co": {"kind": "closeout", "total": 400}}} v = _digest.counter_values({"token-budget": {"value": "1200"}}, c) assert v["tokens"] == "1400 of 1200 (close-outs 400; over budget by 200)" + + +# --- M3.6j (PyAutoBrain#683): a library's shift PRs merge in PR order --------------------- +# Two tasks of one shift on one library: `named` opened #7, `picked` #8. #8's +# close-out waits (no session, no slot, no refusal) while #7 is open; once #7 +# merges, #8's branch is updated from main and merges only on CI green there. + +GA7 = "https://github.com/example-org/autogalaxy/pull/7" +GA8 = "https://github.com/example-org/autogalaxy/pull/8" +GW9 = "https://github.com/example-org/example-docs/pull/9" +FIT8 = "https://github.com/example-org/autofit/pull/8" +SPAWNED = "2026-11-04T09:00:00Z" # both workers start at the first tick + + +class OrderSpawner(t.FilesSpawner): + """Workers that finished at once with library PRs open; every close-out + or update session recorded with what it was told, verdicts by the test.""" + + def __init__(self, picked=GA8): + super().__init__(done={"named": GA7 + "\n", "picked": picked + "\n"}, proofs={}) + self.closeouts = [] + + def spawn_closeout(self, task, pr_url, prompt_path, lease_dir, **kw): + self.closeouts.append((task, pr_url, kw)) + return {"pid": 0, "agent_id": f"co{len(self.closeouts):06d}"} + + +def _gh_states(states, heads=None): + """`gh pr view`: OPEN unless named; a name may map to None (unreadable). + Every head reads `abc123` (the updated head) unless `heads` says else.""" + def read(url): + if url in states and states[url] is None: + return None + st = states.get(url, "OPEN") + st, at = st if isinstance(st, tuple) else (st, "") + return {"state": st, "mergedAt": at, "mergedBy": "a-maintainer" if at else "", + "head": (heads or {}).get(url, "abc123")} + return read + + +def _order_shift(tmp_path, picked=GA8, cap=2): + mind = t._mind(tmp_path / "mind") + brief = tmp_path / "shift.md" + brief.write_text(t.BRIEF.format(issue=t.ISSUE, packet="") + .replace("merge-cap: 1", f"merge-cap: {cap}")) + home = tmp_path / "home" + sp = OrderSpawner(picked) + orch.tick(brief, mind, home=home, now=t.NOW, spawner=sp, agents=Agents(), + health=_health({})) + return mind, brief, home, sp + + +def _otick(brief, mind, home, sp, minutes, states=None, health=None, agents=None, + heads=None): + return orch.tick(brief, mind, home=home, now=t.NOW + _dt.timedelta(minutes=minutes), + spawner=sp, agents=agents or Agents(), health=health or _health({}), + pr_state=_gh_states(states or {}, heads)) + + +def _slots(brief, home): + return orch._merge_slots.holders(orch.slot_dir(brief, home)) + + +def _waiting(tmp_path): + """#7's close-out refused (decision-taken), #7 still OPEN, #8 green.""" + mind, brief, home, sp = _order_shift(tmp_path) + _otick(brief, mind, home, sp, 1) + assert [(task, pr) for task, pr, _ in sp.closeouts] == [("named", GA7)] + _verdict(home, brief, "named", result="refused", pr=GA7, + why="decision-taken label → human /prm") + r = _otick(brief, mind, home, sp, 2) + return mind, brief, home, sp, r + + +def test_683_a_later_pr_waits_behind_an_earlier_refused_one_no_slot_no_refusal(tmp_path): + mind, brief, home, sp, r = _waiting(tmp_path) + assert r["closeouts"]["refused"] == [GA7] + c = orch.read_counters(orch.slot_dir(brief, home)) + assert GA8 not in c["closeouts"] # no close-out, not refused + assert c["merge_waits"][GA8]["behind"] == [GA7] + assert c["merge_waits"][GA8]["task"] == "picked" + assert orch._merge_slots.pr_key(GA8) not in _slots(brief, home) + assert [pr for _, pr, _ in sp.closeouts] == [GA7] + r = _otick(brief, mind, home, sp, 3) # still waiting, still quiet + assert r["closeouts"]["started"] == [] and r["closeouts"]["refused"] == [] + assert "waiting" not in r["closeouts"] # an event only when it changes + + +@pytest.mark.parametrize("picked, states, kw", [ + (FIT8, {}, {}), # another repo + (GA8, {GA7: "CLOSED"}, {"before": [GA7]}), # closed unmerged + (GA8, {GA7: ("MERGED", "2026-11-04T08:00:00Z")}, {"before": [GA7]}), # before #8 began +]) +def test_683_no_wait_on_another_repo_or_behind_a_merged_or_closed_pr(tmp_path, picked, + states, kw): + mind, brief, home, sp = _order_shift(tmp_path, picked) + _otick(brief, mind, home, sp, 1, states) + assert ("picked", picked, kw) in sp.closeouts, sp.closeouts + assert picked not in orch.read_counters(orch.slot_dir(brief, home))["merge_waits"] + + +def test_683_an_earlier_pr_github_cannot_read_blocks(tmp_path): + mind, brief, home, sp = _order_shift(tmp_path) + _otick(brief, mind, home, sp, 1, {GA7: None}) + assert [pr for _, pr, _ in sp.closeouts] == [GA7] + assert orch.read_counters(orch.slot_dir(brief, home))["merge_waits"][GA8]["behind"] == [GA7] + + +def _merged_then_update(tmp_path): + """#7 merges after #8's worker began: #8 gets one branch-update session.""" + mind, brief, home, sp, _ = _waiting(tmp_path) + states = {GA7: ("MERGED", "2026-11-04T09:30:00Z")} + r = _otick(brief, mind, home, sp, 31, states) + return mind, brief, home, sp, r, states + + +def test_683_once_the_earlier_pr_merged_after_it_began_the_branch_is_updated(tmp_path): + mind, brief, home, sp, r, _ = _merged_then_update(tmp_path) + assert sp.closeouts[-1] == ("picked", GA8, {"update_after": [GA7]}) + c = orch.read_counters(orch.slot_dir(brief, home)) + assert c["closeouts"][GA8]["kind"] == "update" and c["merge_waits"] == {} + assert orch._merge_slots.pr_key(GA8) in _slots(brief, home) # taken before the update + argv = orch.closeout_command("picked", GA8, "p.md", brief, home, "auto", + update_after=[GA7]) + assert argv[argv.index("--name") + 1] == "shift-update:picked" + assert f"gh pr update-branch {GA8}" in argv[-1] and GA7 in argv[-1] + assert "Never `--rebase`, never a force-push" in argv[-1] + + +def _updated(tmp_path): + mind, brief, home, sp, r, states = _merged_then_update(tmp_path) + _verdict(home, brief, "picked", result="updated", pr=GA8, head="abc123") + r = _otick(brief, mind, home, sp, 32, states, health=_health({GA8: "RUNNING"})) + return mind, brief, home, sp, r, states + + +def test_683_an_updated_branch_holds_its_slot_and_waits_for_ci_on_the_new_head(tmp_path): + mind, brief, home, sp, r, states = _updated(tmp_path) + c = orch.read_counters(orch.slot_dir(brief, home)) + co = c["closeouts"][GA8] + assert (co["state"], co["head"], co["updates"], co["after"]) == ("updated", "abc123", 1, [GA7]) + assert r["closeouts"]["merged"] == [] and r["closeouts"]["refused"] == [] + assert orch._merge_slots.pr_key(GA8) in _slots(brief, home) + n = len(sp.closeouts) + _otick(brief, mind, home, sp, 33, states, health=_health({GA8: "RUNNING"})) + _otick(brief, mind, home, sp, 34, states, health=_health({GA8: "NO-CHECKS"})) # in grace + assert len(sp.closeouts) == n + assert orch.read_counters(orch.slot_dir(brief, home))["closeouts"][GA8]["state"] == "updated" + r = _otick(brief, mind, home, sp, 35, states) # green + assert r["closeouts"]["started"] == [GA8] + assert sp.closeouts[-1] == ("picked", GA8, {"after": [GA7], "before": [GA7]}) + prompt = orch.closeout_prompt("picked", GA8, "p.md", brief, home, after=[GA7], + before=[GA7]) + assert "4b. Merge order" in prompt and "branch not updated after " in prompt + assert f" - {GA7}\n" in prompt and "still open → merge it first" in prompt + assert "4b. Merge order" not in orch.closeout_prompt("picked", GA8, "p.md", brief, home) + + +def test_683_red_ci_on_the_updated_head_is_refused_and_frees_the_slot(tmp_path): + mind, brief, home, sp, r, states = _updated(tmp_path) + r = _otick(brief, mind, home, sp, 33, states, health=_health({GA8: "FAILED"})) + assert r["closeouts"]["refused"] == [GA8] + co = orch.read_counters(orch.slot_dir(brief, home))["closeouts"][GA8] + assert co["why"] == "CI FAILED on the updated head → your /prm" + assert orch._merge_slots.pr_key(GA8) not in _slots(brief, home) + + +def test_683_a_conflicting_update_is_refused_and_never_retried(tmp_path): + mind, brief, home, sp, r, states = _merged_then_update(tmp_path) + _verdict(home, brief, "picked", result="refused", pr=GA8, + why=f"conflicts with main after {GA7} merged → your /prm") + r = _otick(brief, mind, home, sp, 32, states) + assert r["closeouts"]["refused"] == [GA8] + assert orch._merge_slots.pr_key(GA8) not in _slots(brief, home) + n = len(sp.closeouts) + _otick(brief, mind, home, sp, 33, states) + _otick(brief, mind, home, sp, 34, states) + assert len(sp.closeouts) == n + slot = orch.slot_dir(brief, home) + c = orch.read_counters(slot) + d = _digest.build(_brief.parse(brief.read_text())["brief"], slot, c, health=t._health) + assert "conflicts with main after" in d + + +def test_683_a_third_update_is_refused_main_kept_moving(tmp_path): + mind, brief, home, sp, r, states = _updated(tmp_path) + slot = orch.slot_dir(brief, home) + c = orch.read_counters(slot) + c["closeouts"][GA8].update(updates=orch.UPDATE_LIMIT, after=[]) # two updates used + orch._write_counters(slot, c) + n = len(sp.closeouts) + r = _otick(brief, mind, home, sp, 33, states) + assert r["closeouts"]["refused"] == [GA8] and len(sp.closeouts) == n + co = orch.read_counters(slot)["closeouts"][GA8] + assert co["why"].startswith("main kept moving") and co["why"].endswith("→ your /prm") + assert orch._merge_slots.pr_key(GA8) not in _slots(brief, home) + + +def test_683_a_workspace_pr_waits_behind_its_own_tasks_waiting_library_pr(tmp_path): + mind, brief, home, sp = _order_shift(tmp_path, picked=GA8 + "\n" + GW9) + _otick(brief, mind, home, sp, 1) + c = orch.read_counters(orch.slot_dir(brief, home)) + assert c["merge_waits"][GA8]["behind"] == [GA7] + assert c["merge_waits"][GW9]["behind"] == [GA8] + assert GW9 not in c["closeouts"] and [pr for _, pr, _ in sp.closeouts] == [GA7] + + +def test_683_a_wait_at_review_at_is_not_refused_and_the_digest_says_so(tmp_path): + mind, brief, home, sp = _order_shift(tmp_path) + r = _otick(brief, mind, home, sp, 140) # 11:20, review-at 11:30 + slot = orch.slot_dir(brief, home) + c = orch.read_counters(slot) + assert GA8 not in c["closeouts"] and GA8 in c["merge_waits"] + assert GA8 not in r["closeouts"]["refused"] + d = _digest.build(_brief.parse(brief.read_text())["brief"], slot, c, health=t._health) + assert f"{GA8} — waits behind autogalaxy#7" in d or "waits behind autogalaxy#7" in d + assert "merge autogalaxy#7 first" in d + + +def test_683_carry_in_carries_an_updated_or_waiting_pr_with_what_it_waited_behind(tmp_path): + home = tmp_path / "home" + prev = home / "2026-11-03-pm" + prev.mkdir(parents=True) + pick = {"prompt": "draft/feature/x/{}.md", "why": "named task", "tier": "glance"} + (prev / orch.COUNTERS_FILE).write_text(json.dumps({ + "picks": {k: dict(pick, prompt=pick["prompt"].format(k)) for k in "abc"}, + "outcomes": {"a": {"prs": [GA7], "merged": [], "issues": []}, + "b": {"prs": [GA8], "merged": [], "issues": []}, + "c": {"prs": [FIT8], "merged": [], "issues": []}}, + "closeouts": {GA7: {"task": "a", "state": "refused", + "why": "decision-taken label → human /prm"}, + FIT8: {"task": "c", "state": "updated", "after": [], "updates": 1}}, + "merge_waits": {GA8: {"task": "b", "behind": [GA7], "since": SPAWNED}}, + "parked": [], "done": ["a", "b", "c"]})) + slot = home / "2026-11-04-am" + slot.mkdir() + c = {"outcomes": {}, "picks": {}, "done": []} + rec = orch.carry_in(slot, c, t.NOW) + assert sorted(rec["prs"]) == sorted([GA8, FIT8]) # never the refused #7 + assert c["outcomes"]["b"]["behind"] == [GA7] + assert "behind" not in c["outcomes"]["c"] + # In the new shift the carried #8 still waits behind the uncarried #7. + c.update(closeouts={}, dropped={}, merge_waits={}) + assert orch._merge_blockers(c, GA8, _gh_states({}), {}) == [GA7] + + +# --- M3.6j review fixes ---------------------------------------------------------------- + +def test_683_f5_ci_is_judged_only_on_the_head_the_update_made(tmp_path): + """An `updated` PR's CI is read only once GitHub shows the update's head; + a head GitHub cannot give waits, and a head that moved since refuses.""" + mind, brief, home, sp, r, states = _updated(tmp_path) + slot = orch.slot_dir(brief, home) + n = len(sp.closeouts) + # GitHub cannot say the head yet: no close-out, even on a green read. + _otick(brief, mind, home, sp, 33, states, heads={GA8: ""}) + assert len(sp.closeouts) == n + assert orch.read_counters(slot)["closeouts"][GA8]["state"] == "updated" + # The head moved after the update: refused for /prm, the slot freed. + r = _otick(brief, mind, home, sp, 34, states, heads={GA8: "fff999"}) + assert r["closeouts"]["refused"] == [GA8] and len(sp.closeouts) == n + co = orch.read_counters(slot)["closeouts"][GA8] + assert co["why"] == "head moved after the branch update (abc123 → fff999) → your /prm" + assert orch._merge_slots.pr_key(GA8) not in _slots(brief, home) + + +def test_683_f1_an_in_turn_merge_take_refuses_while_an_earlier_sibling_is_open( + tmp_path, monkeypatch, capsys): + """`merge-slot take` (the slot a `notify` worker's in-turn merge must take) + refuses while an earlier shift PR on the same library is open, so the + in-turn path cannot jump the merge order; once it merged, it is taken.""" + sys.path.insert(0, str(BRAIN / "bin")) + import merge_slot + slot = tmp_path / "slot" + (slot / "ledger").mkdir(parents=True) + (slot / orch.COUNTERS_FILE).write_text(json.dumps({ + "outcomes": {"named": {"prs": [GA7], "merged": [], "issues": []}}})) + orch._merge_slots.publish(slot, 2, False) + monkeypatch.setenv("PYAUTO_SHIFT_WORKER", "1") + monkeypatch.setenv("PYAUTO_SHIFT_LEDGER_DIR", str(slot / "ledger")) + gh = {GA7: "OPEN"} + monkeypatch.setattr(orch, "gh_pr_state", lambda u: {"state": gh.get(u, "OPEN"), + "mergedAt": "", "mergedBy": ""}) + assert merge_slot.main(["take", GA8, "--task", "picked"]) == 1 + out = capsys.readouterr().out + assert out.startswith(f"refused: {GA7} of this shift on the same library is still open") + assert "end at PR-open" in out + assert orch._merge_slots.used(slot) == 0 + # Another library, or the sibling merged: the take goes through. + assert merge_slot.main(["take", FIT8, "--task", "other"]) == 0 + gh[GA7] = "MERGED" + assert merge_slot.main(["take", GA8, "--task", "picked"]) == 0 + # GitHub cannot say: the sibling blocks (ruling c). + monkeypatch.setattr(orch, "gh_pr_state", lambda u: None) + assert merge_slot.main(["take", GA8.replace("/8", "/10"), "--task", "x"]) == 1 + # An unreadable counters file cannot tell the order: do not merge. + (slot / orch.COUNTERS_FILE).write_text("{not json") + assert merge_slot.main(["take", GA8.replace("/8", "/11"), "--task", "y"]) == 2 diff --git a/tests/test_orchestrator_digest.py b/tests/test_orchestrator_digest.py index 91c7e54..933a577 100644 --- a/tests/test_orchestrator_digest.py +++ b/tests/test_orchestrator_digest.py @@ -478,3 +478,37 @@ def test_batch_digest_verb_prints_and_writes_nothing(tmp_path): assert res.stdout.startswith("## Digest") and "- merges: 1" in res.stdout assert sorted(p.name for p in slot.rglob("*")) == before assert not (slot / orch.DIGEST_MARKER).exists() + + +# --- M3.6j (PyAutoBrain#683): the digest's merge order ------------------------------- + +def test_683_the_digest_lists_each_librarys_merge_order_and_marks_the_next_prm(tmp_path): + """A library's shift PRs merge in PR order: the digest names, per library, + the PRs in order, ▶ on the one that needs the human's /prm now, and says + of each later PR what it waits behind — and still validates.""" + mind, brief, home = _shift(tmp_path) + slot = orch.slot_dir(brief, home) + c = orch.read_counters(slot) + g7, g8, g9 = (f"https://github.com/example-org/autogalaxy/pull/{n}" for n in (7, 8, 9)) + c["outcomes"] = {"named": {"prs": [g7], "merged": [], "issues": []}, + "picked": {"prs": [g9, g8], "merged": [], "issues": []}} + c["closeouts"] = {g7: {"task": "named", "state": "refused", + "why": "decision-taken label → human /prm"}} + c["merge_waits"] = {g8: {"task": "picked", "behind": [g7]}, + g9: {"task": "picked", "behind": [g7, g8]}} + d = _digest.build(_brief.parse(brief.read_text())["brief"], slot, c, health=_health, + issue=ISSUE) + block = d.split("### Merge order")[1].split("### Proof packets")[0] + lines = [ln.strip() for ln in block.strip().splitlines()] + assert lines[0] == "- **autogalaxy**, merged in this order:" + assert lines[1] == (f"- ▶ {g7} — needs your /prm: decision-taken label → human /prm") + assert lines[2] == (f"- {g8} — waits behind autogalaxy#7 (needs your /prm: " + "decision-taken label → human /prm) — merge autogalaxy#7 first") + assert lines[3].startswith(f"- {g9} — waits behind autogalaxy#7") \ + and "autogalaxy#8 (itself waiting)" in lines[3] + assert "Waiting — merges after an earlier PR (your /prm first)" in d + assert _digest.validate(d) == [] + # Nothing waits: no block. + c["merge_waits"] = {} + assert "### Merge order" not in _digest.build( + _brief.parse(brief.read_text())["brief"], slot, c, health=_health, issue=ISSUE) diff --git a/tests/test_orchestrator_events.py b/tests/test_orchestrator_events.py index 0e33520..7402123 100644 --- a/tests/test_orchestrator_events.py +++ b/tests/test_orchestrator_events.py @@ -162,7 +162,10 @@ def _every_kind_results(): "why": "CI FAILED — never merged unattended"}, "https://github.com/o/r/pull/4": {"task": "t7", "state": "refused", "why": "merge-cap 2 reached this shift"}}, - dropped={"t5": {"by": "h", "at": "x"}}, commands_unread="2026-11-04T09:00:00Z") + dropped={"t5": {"by": "h", "at": "x"}}, commands_unread="2026-11-04T09:00:00Z", + # M3.6j (#683): a later PR waits behind the refused r#3 in merge order. + merge_waits={"https://github.com/o/r/pull/5": { + "task": "t1", "behind": ["https://github.com/o/r/pull/3"]}}) return [ (0, {"action": "ticked", "spawned": [{"task": "t1"}, {"task": "t2"}, {"task": "t3"}], "refused": [{"task": "t7", "why": "max-workers 2 reached"}, @@ -183,7 +186,8 @@ def _every_kind_results(): "closeouts": {"started": [], "merged": [PR], "refused": [PR2, "https://github.com/o/r/pull/4"], "merged_outside": [PR2]}}, c), (9, {"action": "ticked", "login": {"state": "expired", "since": "2026-11-04T09:09:00Z", - "detail": "loggedIn: false"}}, c), + "detail": "loggedIn: false"}, + "closeouts": {"waiting": ["https://github.com/o/r/pull/5"]}}, c), (12, {"action": "stopped", "reason": "STOP written by /stop"}, c), (180, {"action": "digest", "post": {"posted": True, "url": "https://github.com/o/m/issues/1#issuecomment-5"}}, c), (183, {"action": "late", "late": ["- late: t8 — https://github.com/o/r/pull/7 (after review-at, 2026-11-04T12:33:00Z)"]}, c), @@ -211,6 +215,10 @@ def test_every_kind_is_written(tmp_path): assert by["cap"]["line"] == "max-workers 2 reached: 1 task wait." assert any(e["line"] == "merge-cap 2 reached: later green PRs wait for /prm." for e in events) assert by["refused"]["line"] == "t9 not started: spawn failed." + assert ("Not merging r#3: CI FAILED — never merged unattended. Left for your /prm; " + "1 later PR(s) wait behind it.") in [e["line"] for e in events] + assert by["waiting"]["line"] == "r#5 waits behind r#3: merge r#3 first." + assert not by["waiting"]["needs_you"] assert by["steer-unread"]["needs_you"] and by["impaired"]["needs_you"] assert by["steer"]["needs_you"] # an `ignored:` ack assert by["late"]["line"] == "Late arrival: t8 — https://github.com/o/r/pull/7 after review-at."