diff --git a/AUTONOMY.md b/AUTONOMY.md index 3d3750b..dd12007 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -338,14 +338,13 @@ never an assumption: import path, or a public name the diff touches); none match → the cheapest script of the changed repo's own workspace, as an import check. The PR body says which smoke ran. - - *Before any unattended merge* — the **full affected** smoke on the PR - head: `pyauto-heart smoke --affected-by --jobs 3` (every - workspace whose install chain has the repo, three at a time, - thread-capped). The close-out runs it for a `glance` PR or a `notify` PR - (every `notify` PR in a shift, since its worker now ends at PR-open — - "Shift `notify` workers end at PR-open — 2026-11-19" below; - `agents/conductors/batch/closeout_template.md`). Any failure refuses the - merge → `/prm`. + - *Before any unattended merge* — no full smoke since ruling S2 ("Shift + speed — 2026-11-19" below; M3.7b, PyAutoBrain#688). The pre-merge smoke + is the worker's targeted smoke, and PR CI must be green. The full sweep + runs in the cloud after the merge: the Workspace Smoke workflow, nightly + (M3.7d) and at shift end (M3.7e). Until S2 the close-out ran + `pyauto-heart smoke --affected-by --jobs 3` on the PR + head; S2's revert condition brings that back. - *PRs bound for the human's `/prm`* (`decision-taken`, `judge`, a public-name hit, a refusal) — no automatic full sweep: the worker's targeted smoke plus PR CI; the human runs `/smoke_test` if they want it. @@ -504,13 +503,43 @@ human (`/prm`) already reads the PR a second time. unattended merge ("Stage-2 adversary amendment — 2026-11-04") and the human at `/prm` for everything else. +- **S2, leg 2 before an unattended merge** (M3.7b, PyAutoBrain#688). The + pre-merge smoke is the worker's targeted smoke. The close-out runs no full + affected smoke. The full sweep runs in the cloud after the merge (nightly, + M3.7d; at shift end, M3.7e). *Revert condition:* one red sweep traced to + an unattended merge restores the close-out's full affected smoke. +- **S5, close-out timing** (M3.7b). A close-out may start at PR-open, while + CI still runs. It runs the `Witness:`, reads the diff adversarially and + checks the label, public names and Heart first. Then it waits in-turn for + CI and merges only on a green `ci-verdict`. The wait has a limit: 30 + minutes from the start, and never later than 5 minutes before + `review-at:` (`CLOSEOUT_MERGE_MARGIN_S`, room for the `/prm` run after + green, so no close-out merges after `review-at:`). The merge is pinned to + the witnessed head (`gh pr merge --match-head-commit`). A CI that has not + finished by then refuses to `/prm`. Every other guard of "Unattended + `glance` merges — 2026-11-03" applies unchanged. The merge slot is taken + immediately before the merge, by the close-out session itself + (`pyauto-brain merge-slot take`, the human's decision A). The watcher only + checks that one is free before it starts the session. A close-out that + sees red CI after it started has spent its tokens; the digest counts them + as before. +- **S6, M3.6j ruling (a) amended** (M3.7b). The branch update and the CI + rerun on the new head are needed only when the PR's changed files overlap + those of a PR of this shift merged ahead of it on that library, or when + GitHub reports the branch as conflicting. A file list that cannot be read + counts as an overlap. Otherwise the PR merges on its own green CI. Merge + order (rulings b, c, f) is unchanged. Two disjoint PRs that are each green + can still break `main` together; `main` CI and the shift-end sweep find + that after the merge. *Revert condition:* one red `main` CI traced to two + disjoint shift PRs merged this way restores the unconditional update. + A worker caps any pytest it runs at `-n 4`. It starts the review beside the tests and the targeted smoke (leg 2), and opens the PR as soon as they pass (`agents/conductors/batch/worker_template.md`). Outside a shift (an `--auto` chat) nothing changes. -Later rulings from the same review (S2, S4 to S7) are added to this section. +Later rulings from the same review (S4, S7) are added to this section. ## Merge authority follows Consequence — 2026-10-02 @@ -615,8 +644,8 @@ and the close-out merges after the affected smoke.** This replaces R3's in-turn path inside a shift (its first two bullets): a shift worker never runs `merge-slot take` or `gh pr merge`, whatever its tier. The watcher closes out a green `notify` PR exactly as a `glance` one (R3's third bullet, unchanged), -and that close-out runs the witness and the full affected smoke -(`pyauto-heart smoke --affected-by --jobs 3`) before it merges. R3's +and that close-out runs the witness before it merges (it ran the full +affected smoke too, until ruling S2 of "Shift speed — 2026-11-19"). R3's fourth bullet stands: these are `notify` merges, not stage-2 rows. Outside a shift (an `--auto` chat, no close-out), R3's in-turn merge is unchanged. `merge-slot take` keeps refusing an out-of-order in-turn merge as a backstop, @@ -706,7 +735,7 @@ section is that dated doctrine edit. the author** — Opus 5.5 for both, on cost: the alternatives were a more expensive model (Fable) or a weaker one (Sonnet). What makes it the leg is **independence, not the model**: a **fresh close-out session** the watcher -starts after CI lands, which did not write the PR, shares none of the worker's +starts after CI lands (at PR-open since ruling S5, 2026-11-19), which did not write the PR, shares none of the worker's context, **runs the `Witness:` itself** and reviews the diff adversarially before it merges or refuses (`agents/conductors/batch/closeout_template.md`). It applies to the first 10 rows of the stage-2 sub-window exactly as the ruling @@ -920,8 +949,9 @@ to per-task `--auto` until the cause is found. ### Unattended `glance` merges — 2026-11-03 This extends the 2026-10-02 table. For a declared `glance` task under an open -brief, **the in-turn wait may be replaced by a watcher-started close-out after -CI lands**, only when every one of these holds: +brief, **the in-turn wait may be replaced by a watcher-started close-out**, +only when every one of these holds. Since ruling S5 ("Shift speed — +2026-11-19") the close-out starts at PR-open and merges only on green CI: 1. an **independent session** ran the `Witness:` — not the author; a different model where one is available, as leg 5 already requires of the adversary; @@ -955,7 +985,9 @@ 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; + watcher itself still pushes nothing. Since ruling S6 (2026-11-19, M3.7b) + this applies only when the PR's changed files overlap a PR merged ahead of + it, or GitHub reports a conflict; - **(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 @@ -1199,6 +1231,15 @@ The revert condition also covers these: an @mention for a parked question, or any read of `questions.md` other than that local one, retires the watcher to fake mode. +**Amendment — 2026-11-19 (M3.7b, PyAutoBrain#688), approved by the human +(decision B).** For ruling S6 ("Shift speed — 2026-11-19") the watcher may +read, read-only, the changed-file list (`gh pr view --json files`) of a +waiting library PR and of the earlier PRs of the shift merged ahead of it on +that library. It reads each PR's list at most once per shift and keeps it. +`mergeable` is a field of the `gh pr view` it already makes, not a new call. +A repeat read for the same PR in one shift falls under the existing revert +condition. + **Login probe — 2026-11-17.** The watcher runs `claude auth status --json` (local, no model call) on a shift's first tick and when a worker shows as blocked. `loggedIn: false`, or a `loginExpiresAt` already passed, is a `login-expired` event, never "blocked on a person", and no worker starts until it passes. ## Human override for Heart RED (development only) diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 0fa1367..faf8198 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -528,17 +528,28 @@ running close-outs — `.closeout` (`merged` | `refused`, `why`, `gate`, each PR a worker named, judges the guards it can see with its own reads: the recorded tier is `glance` or `notify` (ruling R3, 2026-11-17; since 2026-11-19 every `notify` PR comes here, its worker having ended at PR-open — ruling "ii", -PyAutoHeart#352), `gh pr checks` is green — at least one completed -check, all green (pending waits a tick; red, none or unknown is refused), the -shift is not shadow, `review-at:` is more than 20 minutes away, spend is -under 1.5× `token-budget:` (#632; AUTONOMY.md "Close-out budget — 2026-11-14"), -and — last — a merge slot is free under `merge-cap:` (`_merge_slots.py`; a -worker's in-turn merge takes from the same count). Then it starts **one** close-out session -(`closeout_template.md`; `claude --bg --name shift-close: --model opus --effort medium`). -That session is the independent leg: it runs the `Witness:` itself, reviews the -diff adversarially, checks the `decision-taken` label and Heart, runs the full -affected smoke on the PR head (`pyauto-heart smoke --affected-by --jobs 3`, -PyAutoHeart#352), and only then runs the `/prm` close-out — or refuses. A merge marks the PR merged; a `glance` one also bumps `glance_auto_merges` +PyAutoHeart#352), `gh pr checks` is running or green (ruling S5, M3.7b: +the close-out starts at PR-open; red or unknown is refused; none at all waits +`UPDATE_CHECKS_GRACE_S`, 600 s, from when the watcher first saw the PR in +`counters["pr_seen"]`, then is refused), the shift is not shadow, +`review-at:` is more than 20 minutes away, spend is under 1.5× +`token-budget:` (#632; AUTONOMY.md "Close-out budget — 2026-11-14"), and — +last — a merge slot is free under `merge-cap:` (`_merge_slots.room`, counting +the merge close-outs already running without one). The watcher takes no slot +for a merge close-out (decision A): the session takes it itself with +`pyauto-brain merge-slot take` immediately before the merge, and the reaper +frees it when the close-out refuses, whoever holds it for that task. Then the +watcher starts **one** close-out session +(`closeout_template.md`; `claude --bg --name shift-close: --model opus --effort medium`), +with a CI deadline: `CLOSEOUT_CI_WAIT_S` (30 minutes) from now, never later +than `review-at:` minus `CLOSEOUT_MERGE_MARGIN_S` (5 minutes). That session is the independent leg: it runs the `Witness:` +itself on the PR head and records that head, reviews the diff adversarially, +checks the `decision-taken` label and Heart, then waits in-turn for CI +(`pyauto-brain ci-verdict --until `, repeated while PENDING), +checks the head did not move, takes its slot (its output must say `taken: `) +and runs the `/prm` close-out, its merge pinned with `--match-head-commit` — +or refuses. It runs no full affected smoke (ruling S2); the cloud sweep runs +after the merge. A merge marks the PR merged; a `glance` one also bumps `glance_auto_merges` and queues a `table-append` op that lands one row in `autonomy_log.md` "Unattended `glance` sub-window (stage 2)" through the one Mind writer. Every refusal is final for the shift and named in the digest @@ -555,17 +566,26 @@ 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 +worker started; for a carried PR, any merged earlier PR) gets a branch update +only when the two PRs' changed files overlap, a file list cannot be read, or +GitHub reports this PR `CONFLICTING` (ruling S6, M3.7b). The watcher reads +each PR's files once a shift (`gh pr view --json files`, kept in +`counters["pr_files"]`; an unreadable list is kept as unreadable, counts as +an overlap and is not read again) and `mergeable` from its usual `gh pr view`. A +disjoint earlier PR is not updated for: the close-out's step 4b names it +`merged ahead, disjoint files, not updated (S6)` and does not compare it. A +PR that needs the update has the watcher take 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 +keeps its slot and is looked at again each tick: NO-CHECKS within +`UPDATE_CHECKS_GRACE_S` (600 s) waits; red refuses (`CI on the +updated head → your /prm`) and frees the slot; running or green on the head +the update made starts the merge close-out (S5), which waits in-turn for CI +and whose step 4b checks every earlier PR is no longer OPEN and each merged +one it was updated for 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 diff --git a/agents/conductors/batch/_merge_slots.py b/agents/conductors/batch/_merge_slots.py index 0c29871..7990c3d 100644 --- a/agents/conductors/batch/_merge_slots.py +++ b/agents/conductors/batch/_merge_slots.py @@ -4,8 +4,10 @@ in-turn `notify` merge and the watcher's close-outs alike. Shift 2026-11-16-pm read "2 merged of merge-cap 1" because the workers never asked. A worker runs `pyauto-brain merge-slot take ` (`bin/merge_slot.py`) as its own bare call -before its bare `gh pr merge`; the watcher takes a slot just before it spawns a -close-out. Both write the same file. +before its bare `gh pr merge`; so does a merge close-out session, immediately +before its merge (M3.7b, PyAutoBrain#688, decision A). The watcher takes a slot +only before it spawns a branch-update session; before a merge close-out it only +reads whether one is free (`room`). All write the same file. The file is `merge_slots.json` in the shift's slot directory, read and written under an exclusive `fcntl.flock` on `merge_slots.lock` beside it, and written @@ -36,6 +38,9 @@ LOCK_FILE = "merge_slots.lock" #: Who the watcher is, as a slot holder. WATCHER = "watcher" +#: Who every worker and close-out session is, as a slot holder (one class: +#: `bin/merge_slot.py` takes as this). +SESSION = "worker" #: A GitHub PR URL, with anything after the number (`/files`, `/`, `#…`, `?…`). @@ -120,6 +125,27 @@ def publish(slot: Path, cap: int, paused: bool) -> None: data["published"] = _now() +def _judge(data: dict, key: str, task: str, pending: int = 0) -> tuple[bool | None, str]: + """(True, why) when `key` already holds a slot for `task`; (None, "") when + a slot is free for it; (False, why) when it is refused. `pending` counts + slots promised but not yet taken (`room`).""" + held = data["slots"].get(key) + cap, used = data.get("cap"), len(data["slots"]) + if held and task and held.get("task") == task: + return True, (f"{key} already holds a merge slot for task {task} " + f"(taken by {held.get('by', '?')})") + if held: + return False, (f"{key} holds a merge slot for task {held.get('task') or '?'}, " + f"not {task or '(no task)'} — left for your /prm") + if cap is None: + return False, "no merge-cap published by the watcher — left for your /prm" + if data.get("paused"): + return False, "the shift is paused — left for your /prm" + if used + pending >= int(cap): + return False, f"merge-cap {cap} reached this shift — left for your /prm" + return None, "" + + def take(slot: Path, pr: str, by: str, task: str = "") -> tuple[bool, str]: """(taken, why). Idempotent per PR and task; every refusal is recorded.""" key = pr_key(pr) @@ -127,27 +153,31 @@ def take(slot: Path, pr: str, by: str, task: str = "") -> tuple[bool, str]: return False, (f"{pr!r} is not a https://github.com///pull/ URL " "— left for your /prm") with _locked(slot) as data: - held = data["slots"].get(key) - cap, used = data.get("cap"), len(data["slots"]) - if held and task and held.get("task") == task: - return True, (f"{key} already holds a merge slot for task {task} " - f"(taken by {held.get('by', '?')})") - if held: - why = (f"{key} holds a merge slot for task {held.get('task') or '?'}, " - f"not {task or '(no task)'} — left for your /prm") - elif cap is None: - why = "no merge-cap published by the watcher — left for your /prm" - elif data.get("paused"): - why = "the shift is paused — left for your /prm" - elif used >= int(cap): - why = f"merge-cap {cap} reached this shift — left for your /prm" - else: + ok, why = _judge(data, key, task) + if ok: + return True, why + if ok is None: + used, cap = len(data["slots"]), data.get("cap") data["slots"][key] = {"by": by, "task": task, "at": _now()} return True, f"merge slot {used + 1} of merge-cap {cap} taken for {key}" data["refusals"].append({"pr": key, "by": by, "task": task, "why": why, "at": _now()}) return False, why +def room(slot: Path, pr: str, task: str, pending: int = 0) -> tuple[bool, str]: + """(free, why) — whether `take(pr, task)` would succeed now, read only: + nothing is taken and no refusal recorded (M3.7b, decision A: the watcher + reads this before a merge close-out; the session takes its slot itself, + immediately before the merge). `pending` is the slots already promised to + close-outs still running without one, so the cap is never oversold.""" + key = pr_key(pr) + if key is None: + return False, (f"{pr!r} is not a https://github.com///pull/ URL " + "— left for your /prm") + ok, why = _judge(state(slot), key, task, pending) + return ok is not False, why + + def release(slot: Path, pr: str, by: str, why: str = "", *, task: str | None = None) -> bool: """Free `pr`'s slot, only when `by` took it — and, when `task` is given (every worker or close-out session holds as one class), only for that diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index ed9fe85..6a16ac8 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -171,6 +171,10 @@ def read_counters(slot: Path) -> dict: 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", {}) + # M3.7b (#688): when the watcher first saw each PR (the NO-CHECKS grace), + # and each PR's changed files, read once per shift (the S6 overlap rule). + c.setdefault("pr_seen", {}) + c.setdefault("pr_files", {}) 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 @@ -274,6 +278,10 @@ def pr_state(self, url: str) -> dict: """A dry shift merges nothing, so GitHub is never asked.""" return {"state": "OPEN", "mergedAt": "", "mergedBy": ""} + def pr_files(self, url: str) -> None: + """Never asked in a dry shift: nothing merges ahead of anything.""" + return None + #: Prepended to a re-dispatched worker's prompt (PyAutoBrain#632, B1): the #: crashed worker may already have claimed the task through the ledger. @@ -368,12 +376,15 @@ 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: +def after_step(after: list[str] | None = None, before: list[str] | None = None, + disjoint: 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): + must be in it (the update session merged `main` in) — except those whose + changed files are disjoint from this PR's (S6, M3.7b), which are named + and not checked.""" + if not (after or before or disjoint): return "" out = ["4b. Merge order (M3.6j, PyAutoBrain#683): this shift's earlier PRs on this\n" " library merge before this one.\n"] @@ -389,6 +400,13 @@ def after_step(after: list[str] | None = None, before: list[str] | None = None) " 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)) + if disjoint: + out.append(" These merged ahead after this branch was cut, but their changed files\n" + " are disjoint from this PR's and GitHub reported no conflict, so the\n" + " branch was not updated for them. Do not compare them; PR CI on this\n" + " head is the verdict (AUTONOMY.md \"Shift speed\", ruling S6):\n" + + "".join(f" - {u} — merged ahead, disjoint files, not updated (S6)\n" + for u in disjoint)) return "".join(out) @@ -400,31 +418,29 @@ def update_prompt(task: str, pr_url: str, prompt_path: str, brief_path: Path, lease_dir=lease_dir, after="\n".join(f"- {u}" for u in after)) -#: Workspaces a close-out smokes at once (PyAutoHeart#352): laptop-safe, and -#: Heart caps each one's thread pools so the three share the cores. -CLOSEOUT_SMOKE_JOBS = 3 - - -def smoke_command(repos: str) -> str: - """The close-out's full affected smoke (AUTONOMY.md leg 2, split - 2026-11-19, PyAutoHeart#352): every smoke workspace whose install chain - has the PR's repo, CLOSEOUT_SMOKE_JOBS at a time, against the task root - the close-out brought to the PR's head. Empty when the repo is unknown.""" - if not repos: - return "" - return (f"bash -c 'source \"{COMMON_SH}\"; \"$(resolve_heart)\" smoke " - f"--root \"$PWD\" --affected-by {repos} --jobs {CLOSEOUT_SMOKE_JOBS}'") +#: How long a close-out started at PR-open waits in-turn for CI before it +#: refuses (`CI not finished by → /prm`; ruling S5, M3.7b). The +#: deadline is never later than `review-at:`. +CLOSEOUT_CI_WAIT_S = 1800 +#: The CI deadline ends this long before `review-at:`, leaving room for the +#: `/prm` run after GREEN, so no close-out merges after `review-at:` (#632 F1). +CLOSEOUT_MERGE_MARGIN_S = 300 def closeout_prompt(task: str, pr_url: str, prompt_path: str, brief_path: Path, lease_dir: Path, after: list[str] | None = None, - before: list[str] | None = None) -> str: + before: list[str] | None = None, disjoint: list[str] | None = None, + ci_until: str = "") -> 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 - ci-verdict` on the PR (PyAutoBrain#628): only `GREEN` merges. Its - public-name check is `pyauto-brain public-names` (PyAutoBrain#641): an - added or renamed public library name, or a diff it cannot read, refuses.""" + ci-verdict --until ` on the PR (PyAutoBrain#628; the in-turn + wait of ruling S5, M3.7b): only `GREEN` merges. Its public-name check is + `pyauto-brain public-names` (PyAutoBrain#641): an added or renamed public + library name, or a diff it cannot read, refuses. It runs no full affected + smoke (ruling S2). `ci_until` is the watcher's deadline; without one it is + CLOSEOUT_CI_WAIT_S from now.""" + ci_until = ci_until or _iso(_now() + _dt.timedelta(seconds=CLOSEOUT_CI_WAIT_S)) repos = pr_repos(pr_url) heart_cmd = (f"bash -c 'source \"{COMMON_SH}\"; consult_vitals_verdict --repos {repos}'" if repos else "") @@ -433,18 +449,18 @@ def closeout_prompt(task: str, pr_url: str, prompt_path: str, brief_path: Path, lease_dir=lease_dir, ledger_dir=Path(lease_dir).parent / _mind_writer.LEDGER_DIR, shift_ledger=SHIFT_LEDGER, pr_repos=repos or "(none — not a GitHub PR URL)", heart_cmd=heart_cmd or "(cannot be scoped — refuse)", - ci_verdict_cmd=f"{BRAIN_CLI} ci-verdict {pr_url}" if repos - else "(not a GitHub PR URL — refuse)", + ci_verdict_cmd=f"{BRAIN_CLI} ci-verdict {pr_url} --until {ci_until}" if repos + else "(not a GitHub PR URL — refuse)", ci_until=ci_until, public_names_cmd=f"{BRAIN_CLI} public-names {pr_url}" if repos else "(not a GitHub PR URL — refuse)", - smoke_cmd=smoke_command(repos) or "(not a GitHub PR URL — refuse)", - after_step=after_step(after, before)) + after_step=after_step(after, before, disjoint)) def closeout_command(task: str, pr_url: str, prompt_path: str, brief_path: Path, lease_dir: Path, mode: str, *, update_after: list[str] | None = None, after: list[str] | None = None, - before: list[str] | None = None) -> list[str]: + before: list[str] | None = None, disjoint: list[str] | None = None, + ci_until: str = "") -> 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. With `update_after` it is the branch-update session instead (M3.6j).""" @@ -457,7 +473,8 @@ def closeout_command(task: str, pr_url: str, prompt_path: str, brief_path: Path, 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, after, before)] + closeout_prompt(task, pr_url, prompt_path, brief_path, lease_dir, after, before, + disjoint, ci_until)] def worker_env(lease_dir: Path, base: dict | None = None) -> dict: @@ -577,16 +594,21 @@ class RealSpawner: real = True def __init__(self, brief_path: Path, mode: str, cwd: Path | None = None, run=None, - gh=None, public_names=None): + gh=None, public_names=None, files=None): self.brief_path, self.mode, self.cwd = Path(brief_path), mode, cwd self.run = run or subprocess.run self.gh = gh or gh_pr_state + self.files = files or gh_pr_files self.public_names = public_names or public_names_gate def pr_state(self, url: str) -> dict | None: """GitHub's word on a PR — the merge truth for a close-out (#603).""" return self.gh(url) + def pr_files(self, url: str) -> list[str] | None: + """A PR's changed files — the branch-update decision (S6, M3.7b).""" + return self.files(url) + def spawn(self, task: str, prompt_path: str, lease_dir: Path, redispatch: bool = False, resume: dict | None = None, siblings: list[str] | None = None) -> dict: @@ -607,7 +629,8 @@ def spawn(self, task: str, prompt_path: str, lease_dir: Path, 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: + before: list[str] | None = None, disjoint: list[str] | None = None, + ci_until: str = "") -> 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. @@ -619,7 +642,7 @@ def spawn_closeout(self, task: str, pr_url: str, prompt_path: str, lease_dir: Pa return {"pid": 0, "agent_id": None} argv = closeout_command(task, pr_url, prompt_path, self.brief_path, lease_dir, self.mode, update_after=update_after, after=after, - before=before) + before=before, disjoint=disjoint, ci_until=ci_until) # 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, @@ -702,12 +725,15 @@ def _liveness_known(agents) -> bool: def gh_pr_state(url: str, run=None) -> dict | None: - """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).""" + """One read-only `gh pr view`: {state, mergedAt, mergedBy, head, + mergeable} 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); `mergeable` (`MERGEABLE`, `CONFLICTING` or + `UNKNOWN`) sends a conflicting PR to its branch update (S6, M3.7b).""" run = run or subprocess.run try: - res = run(["gh", "pr", "view", url, "--json", "state,mergedAt,mergedBy,headRefOid"], + res = run(["gh", "pr", "view", url, "--json", + "state,mergedAt,mergedBy,headRefOid,mergeable"], capture_output=True, text=True, timeout=60) if res.returncode != 0: return None @@ -719,7 +745,36 @@ def gh_pr_state(url: str, run=None) -> dict | 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), - "head": str(data.get("headRefOid") or "")} + "head": str(data.get("headRefOid") or ""), + "mergeable": str(data.get("mergeable") or "").upper()} + + +#: `gh pr view --json files` lists at most this many files; a list this long +#: may be cut short, so it is read as unknown (and the branch is updated). +PR_FILES_LIMIT = 100 + + +def gh_pr_files(url: str, run=None) -> list[str] | None: + """One read-only `gh pr view --json files`: the PR's changed paths, or + None when GitHub could not say or the list may be truncated (S6, M3.7b: + the branch-update decision; AUTONOMY.md "The watcher's network surface", + amendment 2026-11-19). The watcher reads it at most once per PR per shift.""" + run = run or subprocess.run + try: + res = run(["gh", "pr", "view", url, "--json", "files"], + capture_output=True, text=True, timeout=60) + if res.returncode != 0: + return None + data = json.loads(res.stdout) + except (OSError, ValueError, subprocess.SubprocessError): + return None + files = data.get("files") if isinstance(data, dict) else None + if not isinstance(files, list) or len(files) >= PR_FILES_LIMIT: + return None + paths = [f.get("path") for f in files if isinstance(f, dict)] + if not all(isinstance(p, str) and p for p in paths): + return None + return paths _USAGE_FIELDS = (("input", "input_tokens"), ("output", "output_tokens"), @@ -1291,9 +1346,14 @@ def _tick(brief_path: Path, mind: Path, *, home: Path | None = None, grace_s: float = LEASE_GRACE_S, records: list[dict] | None = None, agents: AgentsView | None = None, tokens=transcript_usage, poster=None, health=None, pr_state=None, - token_reserve: int | None = None, whoami=None, github=None) -> dict: + token_reserve: int | None = None, whoami=None, github=None, + pr_files=None) -> dict: """One watcher tick. Returns what it did; also appended to `tick.log`. + `pr_state` and `pr_files` are the `gh pr view` seams (a PR's state, and + its changed files for the branch-update decision, S6); unset, the + spawner's. + `github` is the `run` seam for the live status comment and the steering read (PyAutoBrain#622) — a test's fake `gh`; unset, the real one. @@ -1366,7 +1426,7 @@ def _tick(brief_path: Path, mind: Path, *, home: Path | None = None, spawner or default_spawner(brief_path, brief), grace_s, records, agents, tokens, health, pr_state, poster=poster, shift=shift, token_reserve=token_reserve, - whoami=whoami, github=github) + whoami=whoami, github=github, pr_files=pr_files) _record_events(slot, now, result, brief_path, poster) finally: _drop_lock(slot) @@ -2000,7 +2060,7 @@ def active_leases(slot: Path) -> dict[str, dict]: def _tick_locked(slot, brief, mind, now, spawner, grace_s, records, agents, tokens, health=None, pr_state=None, *, poster=None, shift=None, - token_reserve=None, whoami=None, github=None) -> dict: + token_reserve=None, whoami=None, github=None, pr_files=None) -> dict: """The tick under its lock, then the live status (PyAutoBrain#622): one `claude agents` view and one set of `gh pr checks` reads serve both.""" shift = shift or {} @@ -2008,7 +2068,8 @@ def _tick_locked(slot, brief, mind, now, spawner, grace_s, records, agents, health = _TickHealth(health) out = _tick_body(slot, brief, mind, now, spawner, grace_s, records, agents, tokens, health, pr_state, poster=poster, shift=shift, - token_reserve=token_reserve, whoami=whoami, github=github) + token_reserve=token_reserve, whoami=whoami, github=github, + pr_files=pr_files) status = _live_status(slot, mind, shift, now, agents, health.cached, github, stopped=out.get("action") == "stopped") if status: @@ -2041,7 +2102,7 @@ def _named_reasons(brief: dict, d: dict, planned: dict) -> dict[str, str]: def _tick_body(slot, brief, mind, now, spawner, grace_s, records, agents, tokens, health=None, pr_state=None, *, poster=None, shift=None, - token_reserve=None, whoami=None, github=None) -> dict: + token_reserve=None, whoami=None, github=None, pr_files=None) -> dict: counters = read_counters(slot) counters["usage_unavailable"] = [] # this tick's reads decide reaped = _reap(slot, counters, now, grace_s, agents, tokens) @@ -2143,7 +2204,7 @@ def known(task: str) -> bool: carry_in(slot, counters, now) # the shift's first tick (M3.6c) _write_counters(slot, counters) closeouts = _closeouts(slot, brief, counters, spawner, now, agents, health, pr_state, - tokens=tokens, + tokens=tokens, pr_files=pr_files, review_at=_brief._iso((shift or {}).get("review_at") or "")) if _mind_writer.pending_ops(slot): # a stage-2 row queued by a merged close-out try: @@ -3674,15 +3735,18 @@ def closeouts_running(slot: Path) -> bool: def _closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.datetime, agents: AgentsView | None, health, pr_state=None, - tokens=transcript_usage, review_at: _dt.datetime | None = None) -> dict: - """Reap finished close-out sessions, then start one per newly green PR. + tokens=transcript_usage, review_at: _dt.datetime | None = None, + pr_files=None) -> dict: + """Reap finished close-out sessions, then start one per newly open PR. The watcher's guards are the ones it can judge from its own reads (AUTONOMY - "Unattended `glance` merges"): the recorded tier, green CI by `gh pr checks` - (at least one completed check, all green — a PR with none is refused, - PyAutoHeart#343), the brief's `merge-cap:`, and never in a shadow shift. The label, Heart and - the witness are the close-out session's to check — it is the independent - session, and it refuses rather than merges when one fails. + "Unattended `glance` merges"): the recorded tier, CI by `gh pr checks` not + red — running or green starts the close-out at PR-open (ruling S5, + M3.7b), which waits in-turn for a green `ci-verdict`; none at all is + refused after a grace (PyAutoHeart#343) — a free slot under the brief's + `merge-cap:`, and never in a shadow shift. The label, Heart, the witness, + the CI wait and the merge slot's take are the close-out session's — it is + the independent session, and it refuses rather than merges when one fails. GitHub is the merge truth (#603): before a finished close-out is counted merged or refused — which frees its `merge-cap:` slot — the PR's state is @@ -3700,6 +3764,7 @@ def _closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.dateti `token-budget:`. """ pr_state = pr_state or getattr(spawner, "pr_state", None) + pr_files = pr_files or getattr(spawner, "pr_files", None) events = reap_closeouts(slot, counters, now, agents, pr_state, tokens) events.setdefault("started", []) # The cap every in-shift merge takes a slot against, worker or close-out @@ -3714,9 +3779,9 @@ def _closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.dateti except (_merge_slots.MergeSlotError, OSError) as e: events["slots_error"] = str(e)[:300] # a take reads what is there, or cannot tell if _brief.is_shadow(brief) or counters.get("paused"): - return events # paused (#622): a green PR waits; it is not refused + return events # paused (#622): an open PR waits; it is not refused return _start_closeouts(slot, brief, counters, spawner, now, health, events, - review_at, pr_state=pr_state) + review_at, pr_state=pr_state, pr_files=pr_files) def queue_retire_op(counters: dict, task: str, pr: str, now: _dt.datetime, @@ -3798,7 +3863,7 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta # 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. + # starts the merge close-out once CI on the new head is not red (S5). co.update(state=result, updated=_iso(now)) if result == "updated": co.update(head=str(verdict.get("head") or "")[:64], @@ -3883,12 +3948,18 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta co.update(state="refused", why=why) events["refused"].append(pr) if co["state"] == "refused": - # A refused close-out frees the merge slot the watcher took for it - # (R3, #661); a merge made outside the close-out is not the shift's. - try: - _merge_slots.release(slot, pr, _merge_slots.WATCHER, co.get("why") or "refused") - except (_merge_slots.MergeSlotError, OSError): - pass # the slot stays held: fails toward fewer merges + # A refused close-out frees its PR's merge slot (R3, #661) whoever + # holds it for this task: the watcher (taken before a branch + # update) or the close-out session itself (its own `merge-slot + # take` just before the merge, M3.7b decision A). A merge made + # outside the close-out is not the shift's. A merged one keeps it. + for by, of_task in ((_merge_slots.WATCHER, None), + (_merge_slots.SESSION, co["task"])): + try: + _merge_slots.release(slot, pr, by, co.get("why") or "refused", + task=of_task) + except (_merge_slots.MergeSlotError, OSError): + pass # the slot stays held: fails toward fewer merges if late: co["late"] = _iso(now) if co.get("agent_id") in counters["usage"]: @@ -4024,10 +4095,61 @@ def _merged_after_start(counters: dict, task: str, pr: str, pr_state, cache: dic return out +def _pr_files_once(counters: dict, pr_files, url: str) -> list[str] | None: + """A PR's changed files, read at most once per PR per shift and kept in + `counters["pr_files"]` (S6, M3.7b; AUTONOMY.md "The watcher's network + surface", amendment 2026-11-19). A read that fails, raises or may be + truncated is kept as None — unreadable, an overlap — and never read + again. None, uncached, when there is no reader (a test spawner): that + fails toward the branch update, as before S6.""" + cache = counters.setdefault("pr_files", {}) + if url in cache: + return cache[url] + if pr_files is None: + return None + try: + files = pr_files(url) + except Exception: # unreadable: update, never assume disjoint + files = None + cache[url] = list(files) if isinstance(files, list) else None + return cache[url] + + +def _overlap(counters: dict, pr: str, merged_ahead: list[str], pr_state, pr_files, + cache: dict) -> tuple[list[str], list[str]]: + """(need, disjoint): which PRs merged ahead of `pr` its branch must be + updated for (ruling S6, M3.7b). Every one when GitHub reports `pr` + CONFLICTING or `pr`'s own files cannot be read; otherwise each one whose + changed files intersect `pr`'s, or cannot be read. The rest are disjoint.""" + if not merged_ahead: + return [], [] + if (_gh_once(pr_state, cache, pr) or {}).get("mergeable") == "CONFLICTING": + return list(merged_ahead), [] + mine = _pr_files_once(counters, pr_files, pr) + if mine is None: + return list(merged_ahead), [] + need, disjoint = [], [] + for u in merged_ahead: + theirs = _pr_files_once(counters, pr_files, u) + (need if theirs is None or set(theirs) & set(mine) else disjoint).append(u) + return need, disjoint + + 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. + pr_state=None, pr_files=None) -> dict: + """Start one close-out per newly open PR, under the watcher's guards. + + Ruling S5 (M3.7b, PyAutoBrain#688): a PR whose CI reads RUNNING or + HEALTHY starts its close-out at once; the session runs the witness and + reads the diff while CI runs, then waits in-turn (`ci-verdict --until`, + at most CLOSEOUT_CI_WAIT_S and never past `review-at:`) and merges only on + GREEN. FAILED or UNKNOWN refuses with no session; NO-CHECKS waits + UPDATE_CHECKS_GRACE_S from when the watcher first saw the PR, then refuses. + Decision A: the watcher takes no merge slot for a merge close-out; it + refuses one when the cap has no room (`_merge_slots.room`, counting the + close-outs already running without a slot). The session takes its slot + itself, immediately before the merge. 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 @@ -4035,8 +4157,10 @@ def _start_closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt. 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.""" + update-branch`, ruling a) under a merge slot the watcher takes — only when + their changed files overlap, a file list cannot be read, or GitHub reports + this PR CONFLICTING (ruling S6). Its merge close-out starts on a later + tick, once GitHub shows the update's head and CI there is not red.""" lease_dir = slot / "leases" health = health or _digest.pr_health budget = _brief._nonneg_int(brief.get("token-budget", {}).get("value", "")) @@ -4044,6 +4168,7 @@ def _start_closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt. before_waits = counters.get("merge_waits") or {} waits: dict = {} counters["merge_waits"] = waits + seen = counters.setdefault("pr_seen", {}) # when the watcher first saw each PR def refuse(pr: str, task: str, why: str, held: bool = False) -> None: prev = counters["closeouts"].get(pr) or {} @@ -4067,6 +4192,7 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: again = co is not None if again and co.get("state") not in ORDER_STATES: continue + seen.setdefault(pr, _iso(now)) tier = counters["picks"].get(task, {}).get("tier", "?") if task in counters["dropped"]: refuse(pr, task, "dropped by /drop — the human's /prm", held=again) @@ -4089,7 +4215,9 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: f"it {state or '?'} — not closed out", held=again) continue # 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. + # holds this one back. Waiting is not a refusal and takes no slot. An + # earlier PR whose close-out is running (waiting in-turn on its CI, + # S5) is still open, so this one gets no session until it merges. 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) @@ -4114,13 +4242,14 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: f"{head[:12]}) → your /prm", held=True) continue 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 verdict == "NO-CHECKS": + # CI may not have registered yet — on a new PR or on the head a + # branch update made: wait out the grace, then it is the verdict. + since = _iso_or_none((co.get("updated") if again and co.get("state") == "updated" + else seen.get(pr)) 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": + continue + if verdict not in ("RUNNING", "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 @@ -4130,9 +4259,9 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: # An updated PR at review-at is not refused: it keeps its # state, the digest reports it, and the next shift carries it. continue - # A close-out runs ~10-20 min; one still out at review-at + # A close-out runs ~10-30 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 — " + refuse(pr, task, f"open 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"]: @@ -4152,28 +4281,41 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: 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. + # cut, and this PR's branch does not have it yet — needed only when + # their changed files overlap or GitHub reports a conflict (S6). 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] + ahead = [u for u in _merged_after_start(counters, task, pr, pr_state, cache, + bool(out.get("carried_from"))) + if u not in after] + need, disjoint = _overlap(counters, pr, ahead, pr_state, pr_files, cache) 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 need: + # One merge-slot count for the shift (R3, #661). The watcher + # takes it before a branch-update session, last, so no other + # refusal holds a slot. Idempotent: an updated PR 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" + else: + # Decision A (M3.7b): the merge close-out takes its own slot just + # before the merge. The watcher only reads that one would be free, + # counting the close-outs already running without one. + pending = sum(1 for u, c in counters["closeouts"].items() + if c.get("state") == "running" and c.get("kind") != "update" + and _merge_slots.pr_key(u) not in counters.get("slot_holders", {})) + try: + taken, why = _merge_slots.room(slot, pr, task, pending) + 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) + refuse(pr, task, why, held=again) continue prompt = counters["picks"].get(task, {}).get("prompt", "") new = {"task": task, "state": "running", "started": _iso(now), "tier": tier} @@ -4184,8 +4326,15 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: # 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}) + until = now + _dt.timedelta(seconds=CLOSEOUT_CI_WAIT_S) + if review_at is not None: + until = min(until, review_at + - _dt.timedelta(seconds=CLOSEOUT_MERGE_MARGIN_S)) + kw = {k: v for k, v in (("after", after), ("before", before), + ("disjoint", disjoint)) if v} + kw["ci_until"] = _iso(until) + new.update({k: v for k, v in (("after", after), ("updates", updates), + ("disjoint", disjoint)) if v}) try: new.update(spawner.spawn_closeout(task, pr, prompt, lease_dir, **kw)) except Exception as e: diff --git a/agents/conductors/batch/closeout_template.md b/agents/conductors/batch/closeout_template.md index e9876b8..486f8a8 100644 --- a/agents/conductors/batch/closeout_template.md +++ b/agents/conductors/batch/closeout_template.md @@ -11,10 +11,22 @@ it out on the same terms): you did not write this PR, and you trust nothing its Merge only if every check below passes; otherwise refuse. A refusal is a good outcome — the human merges by `/prm` at check-in. +You may have started while the PR's CI is still running (AUTONOMY.md "Shift +speed — 2026-11-19", ruling S5). Do steps 1 to 4 first, then wait for CI in +step 5. There is no full affected smoke here (ruling S2): the worker ran the +targeted smoke, and the full sweep runs in the cloud after the merge. + 1. Read the task's `Witness:` header and **run it yourself** against the PR's - head. Record what decided it. A `notify` task that declares no `Witness:` - is refused, with why `notify with no Witness: → human /prm` (ruling R3: - the close-out session runs the witness). + head. Use the task root the worker shipped from (the folder holding + `.pyauto-root` and its `{pr_repos}` worktree on the PR's branch, the one + you clean up in step 9): bring that worktree to the PR's head with `git + fetch origin ` and `git merge --ff-only FETCH_HEAD`, and record + `gh pr view {pr_url} --json headRefOid`; `git rev-parse HEAD` must equal + it. No task root, a dirty tree, or a head that will not match: refuse with + why `cannot run the witness on the PR head → /prm`. Record what decided the + witness. A `notify` task that declares no `Witness:` is refused, with why + `notify with no Witness: → human /prm` (ruling R3: the close-out session + runs the witness). 2. Review the diff adversarially: look for a changed default, a user-visible error message, a removed or weakened test, a renamed public thing, or a wrong docs claim. Any one of them → refuse. Added or renamed public @@ -27,52 +39,63 @@ outcome — the human merges by `/prm` at check-in. Exit 0 passes (a repo the ruling does not cover prints CLEAN). Exit 1 (a public name added or renamed) or 2 (it cannot tell) refuses, with its first output line as the `why`: `public name added/renamed: → human /prm`. -3. Refuse if the PR carries the `decision-taken` label, if its tier is not - `glance` or `notify`, or unless Heart's **scoped development-ship verdict** for the - PR's repo ({pr_repos}) is `green` (AUTONOMY.md leg 4, PyAutoHeart#340): +3. Refuse if the PR carries the `decision-taken` label, or if its tier is not + `glance` or `notify`. +4. Refuse unless Heart's **scoped development-ship verdict** for the PR's + repo ({pr_repos}) is `green` (AUTONOMY.md leg 4, PyAutoHeart#340): {heart_cmd} It prints `green`, `red`, `stale` or `unknown`. Only `green` passes: `stale` never does, and `unknown` (a reply that is not Heart's dev-ship gate, or no Heart here) parks — refuse with the word it printed. A repo Heart does not - gate reads `green` with a "gate-deferred" note: its PR checks (step 4) + gate reads `green` with a "gate-deferred" note: its PR checks (step 5) decide (PyAutoHeart#343). -4. Judge the PR's CI with the one CI-verdict script (PyAutoBrain#628), for - every repo — never by reading `gh pr checks` yourself: +{after_step}5. Wait for CI in your turn, then judge it with the one CI-verdict script + (PyAutoBrain#628), for every repo — never by reading `gh pr checks` + yourself. The deadline is {ci_until}: {ci_verdict_cmd} It reads every check-run, workflow run and job on the REST head sha, and mergeability, and prints `GREEN`, `PENDING` or `RED` with reasons (exit 0, - 2, 1). Only `GREEN` passes. `PENDING` or `RED` refuses with its first - 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"). -{after_step}5. Run the full affected smoke on the PR's head (AUTONOMY.md leg 2, split - 2026-11-19, PyAutoHeart#352). The worker ran only a targeted smoke; this - is the sweep, and it runs only here, before an unattended merge. Use the - task root the worker shipped from (the folder holding `.pyauto-root` and - its `{pr_repos}` worktree on the PR's branch, the one you clean up in - step 8): bring that worktree to the PR's head with `git fetch origin - ` and `git merge --ff-only FETCH_HEAD`, and check `git rev-parse - HEAD` equals `gh pr view {pr_url} --json headRefOid`. No task root, a - dirty tree, or a head that will not match: refuse with why - `cannot smoke the PR head locally → /prm`. Then, from the task root with - its `activate.sh` sourced: - - {smoke_cmd} - - It runs every workspace whose install chain has the repo, three at a - time, and prints a per-workspace summary. Exit 0 passes ("nothing to run" - for a repo no workspace installs passes too). Any other exit refuses with - why `smoke FAILED: → /prm`: no re-run, no fix. -6. Immediately before you merge — after every check above, and again right + 2, 1). While CI is pending it re-judges every 30 s for up to 9 minutes, + then exits 2. Run it with a Bash timeout of 600000 ms (the default 120 s + would kill it), and again, as a bare call, while it exits 2 and the + deadline has not passed. `PENDING` at the deadline refuses with why + `CI not finished by {ci_until} → /prm`. `RED` refuses with its first + reason line (`CI RED: …`): no re-run. Only `GREEN` passes. 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"). +6. Read `gh pr view {pr_url} --json headRefOid` again. If it is not the head + you recorded in step 1, refuse with why + `head moved after the witness → /prm`. +7. 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`. -7. If everything passed, use the prm skill on {pr_url}: the full close-out, - judged exactly as a human-typed `/prm`. Never commit to PyAutoMind yourself +8. Take the merge slot yourself, as a bare call, immediately before the merge + (AUTONOMY.md "Shift speed", decision A of M3.7b): + + pyauto-brain merge-slot take {pr_url} --task {task} + + Go on only when it exits 0 **and** its first line starts with `taken: ` + — `taken: merge slot of merge-cap taken for ` or + `taken: already holds a merge slot for task {task} (taken by …)`. + Anything else refuses with why + `merge slot not taken: → /prm`: a `refused: …` line + (`merge-cap … reached`, the shift is paused, or an earlier PR on this + library is still open), a `cannot tell: …` line, and also exit 0 with + `not in a shift …` (your shift environment is missing, so the merge would + not be counted). Then use the prm skill on {pr_url}: the full close-out, + judged exactly as a human-typed `/prm`. Its own merge slot take + (reference.md "Tiered merge") succeeds again for this PR and task. Pin + its merge call to the head you witnessed: + `gh pr merge {pr_url} --merge --match-head-commit `, + still one bare call, so a push after step 6 cannot merge an unwitnessed + head (GitHub refuses the merge; refuse with why + `head moved after the witness → /prm`). + Never commit to PyAutoMind yourself — a hook refuses it; queue each Mind change with `{shift_ledger} --task {task} append|write|edit|move|remove|drop-section ...` (ops land in {ledger_dir}/) and the orchestrator commits them. `write` @@ -89,23 +112,21 @@ outcome — the human merges by `/prm` at check-in. Do **not** append the Shadow-window row: the watcher writes the stage-2 row from your verdict for a `glance` PR, and none for a `notify` one. - The `/prm` merge slot take (reference.md "Tiered merge") is - `pyauto-brain merge-slot take {pr_url} --task {task}`; it succeeds for - this PR and task: the watcher took its slot before starting you. -8. After a merge, remove the task's worktree and local branch as `/prm` does +9. After a merge, remove the task's worktree and local branch as `/prm` does (`skills/prm/closeout.md` steps 5–6): `worktree_remove ` once your `drop-section active.md ` is queued — the stale-claim guard counts a claim release queued in {ledger_dir}/ — then `git -C branch -d feature/` for a local branch left in a canonical checkout. Never `PYAUTO_WT_FORCE=1`, never `rm -rf`: a dirty tree or any other refusal stays, and you say why in the verdict's `cleanup` field. -9. End at your deliverable. Never arm anything that outlives your turn. +10. End at your deliverable. Never arm anything that outlives your turn: the + CI wait of step 5 is in your turn, never a schedule. Last, write {lease_dir}/{task}.closeout as one JSON object: {{"result": "merged" | "refused", "pr": "{pr_url}", "why": "", - "gate": "tests …/witness …/review …/heart …/smoke …", + "gate": "witness …/review …/heart …/ci …", "model": "", "cleanup": ""}} diff --git a/agents/conductors/batch/worker_template.md b/agents/conductors/batch/worker_template.md index b9f5010..52beb5a 100644 --- a/agents/conductors/batch/worker_template.md +++ b/agents/conductors/batch/worker_template.md @@ -74,12 +74,13 @@ The terms of this shift (AUTONOMY.md "Shift briefs and unattended `glance`"): It runs the curated scripts that reference your change, or one cheap import-check script when none do. Say in the PR body which smoke ran (the - scripts it picked, or the import check) and that the full affected smoke - runs in the close-out before an unattended merge. A failure is yours to fix like a test. + scripts it picked, or the import check). It is the only smoke before an + unattended merge; the full sweep runs in the cloud after the merge + (AUTONOMY.md "Shift speed", ruling S2). A failure is yours to fix like a test. - If the task is `Consequence: glance` or `notify`, end at PR-open: do not - wait for CI and do not merge. Once CI lands, the watcher starts an - independent close-out session that runs the witness and the full affected - smoke and merges, or refuses (AUTONOMY.md "Unattended `glance` merges"; + wait for CI and do not merge. The watcher then starts an + independent close-out session that runs the witness, waits for CI and + merges on green, or refuses (AUTONOMY.md "Unattended `glance` merges"; `notify` workers stopped merging in-turn on 2026-11-19, the human's ruling "ii", PyAutoHeart#352). Never run `merge-slot take` or `gh pr merge` yourself. diff --git a/bin/ci_verdict.py b/bin/ci_verdict.py index f6f28ee..066813e 100644 --- a/bin/ci_verdict.py +++ b/bin/ci_verdict.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """bin/ci_verdict.py — one CI verdict for one pull request (PyAutoBrain#628). - pyauto-brain ci-verdict # [--json] + pyauto-brain ci-verdict # [--json] [--until ] WHY. The CI judgement for a merge lived in three places that disagreed: `/prm` prose, the shift watcher's `pr_health` (`batch/_digest.py`) and the close-out @@ -37,6 +37,16 @@ hands its rows to `judge` with mergeability not read (`from_pr_checks`). Exit status: 0 GREEN, 1 RED, 2 PENDING, 64 usage. `--json` prints one object. + +`--until ` is the close-out's in-turn CI wait (ruling S5, M3.7b, +PyAutoBrain#688): while the verdict is PENDING and the deadline has not +passed, sleep 30 s and judge again. One call runs for at most about 540 s of +wall time from its start, gh reads included (it reads again only while +the next sleep plus its longest read so far still fits), so a single Bash +call run with a 600000 ms timeout never meets it; the caller repeats it +while it exits 2 and the deadline has not passed. Output and exit codes are +unchanged. A timestamp that does not parse is a usage error (64); one with no +zone is read as UTC. `gh` is behind the `run` seam (a `subprocess.run`-shaped callable) so the tests are offline. """ @@ -44,6 +54,7 @@ from __future__ import annotations import argparse +import datetime as _dt import json import re import subprocess @@ -53,6 +64,9 @@ GREEN, PENDING, RED = "GREEN", "PENDING", "RED" EXIT = {GREEN: 0, RED: 1, PENDING: 2} EXIT_USAGE = 64 +#: `--until`: seconds between judgements, and the most one call polls for. +UNTIL_POLL_S = 30 +UNTIL_MAX_S = 540 #: Completed conclusions that are green. SUCCESS = frozenset({"success"}) @@ -334,15 +348,47 @@ def error(self, message): raise SystemExit(EXIT_USAGE) -def main(argv=None, run=None, sleep=time.sleep) -> int: +def parse_until(text: str) -> _dt.datetime: + """An ISO 8601 deadline (`Z` allowed; no zone means UTC).""" + try: + t = _dt.datetime.fromisoformat(str(text).strip().replace("Z", "+00:00")) + except ValueError as e: + raise UsageError(f"--until is not an ISO 8601 time: {text!r}") from e + return t if t.tzinfo else t.replace(tzinfo=_dt.timezone.utc) + + +def _utcnow() -> _dt.datetime: + return _dt.datetime.now(_dt.timezone.utc) + + +def main(argv=None, run=None, sleep=time.sleep, now=_utcnow) -> int: p = _Parser(prog="pyauto-brain ci-verdict", description="Judge one PR's CI: GREEN, PENDING or RED, with reasons. " "Exit 0 GREEN, 1 RED, 2 PENDING.") p.add_argument("pr", help="owner/repo#N, owner/repo/pull/N or the PR URL") p.add_argument("--json", action="store_true", help="print one JSON object") + p.add_argument("--until", metavar="ISO8601", + help="while PENDING and before this time, re-judge every 30 s " + f"(at most {UNTIL_MAX_S} s per call)") a = p.parse_args(argv) try: + until = parse_until(a.until) if a.until else None + start = now() v = verdict_for(a.pr, run=run, sleep=sleep) + read_s = (now() - start).total_seconds() # the longest gh read so far + + def spent() -> float: # wall time of this call, gh reads included + return (now() - start).total_seconds() + # Sleep and read again only while both fit inside UNTIL_MAX_S of wall + # time; the deadline is re-checked after each sleep. + while until is not None and v["verdict"] == PENDING and now() < until \ + and spent() + UNTIL_POLL_S + read_s <= UNTIL_MAX_S: + sleep(UNTIL_POLL_S) + if now() >= until: + break + t0 = now() + v = verdict_for(a.pr, run=run, sleep=sleep) + read_s = max(read_s, (now() - t0).total_seconds()) except UsageError as e: print(f"ci-verdict: {e}", file=sys.stderr) return EXIT_USAGE diff --git a/bin/merge_slot.py b/bin/merge_slot.py index c5eaac6..3d4eba2 100644 --- a/bin/merge_slot.py +++ b/bin/merge_slot.py @@ -10,7 +10,9 @@ repo's PR of the same number and exits 2. `--task` (or `PYAUTO_SHIFT_TASK`) is required for a take in a shift: a held slot answers yes again only to the same task — the worker that took it, or the close-out session of the task the -watcher took it for. +watcher took it for (before a branch update). A merge close-out session takes +its own slot here as a bare call immediately before its merge (M3.7b, +PyAutoBrain#688, decision A). WHY. AUTONOMY.md "`notify` merges under `--auto` and inside a shift — 2026-11-17" (ruling R3): inside a shift every merge counts against the brief's @@ -59,8 +61,10 @@ def _order_blockers(slot: Path, pr: str) -> list[str]: 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" +#: takes as `_merge_slots.WATCHER` (before a branch-update session), so no +#: session can free a slot the watcher holds. A merge close-out takes its own +#: slot here, immediately before its merge (M3.7b, decision A). +WORKER = _merge_slots.SESSION def _slot() -> Path | None: diff --git a/bin/pyauto-brain b/bin/pyauto-brain index 188e32c..8a70aa4 100755 --- a/bin/pyauto-brain +++ b/bin/pyauto-brain @@ -41,7 +41,7 @@ # a PyAutoMind prompt (the heuristic intake + feature both consult) # pyauto-brain board [args] (surface) render the operational board — the morning # page brain_board.yml publishes (md/html/json/badge) -# pyauto-brain ci-verdict # [--json] +# pyauto-brain ci-verdict # [--json] [--until ] # (tool) read-only: one PR's CI verdict — GREEN/PENDING/RED # with reasons (bin/ci_verdict.py; /prm, the close-out, pr_health) # pyauto-brain public-names # | --repo --range a..b [--json] @@ -177,7 +177,7 @@ EOF echo # A tool, not an agent: listed as prose for the same reason as the surfaces. echo "Tools (read-only helpers the merge paths share):" - echo " ci-verdict # [--json] — one PR's CI: GREEN, PENDING or RED, with reasons" + echo " ci-verdict # [--json] [--until ] — one PR's CI: GREEN, PENDING or RED, with reasons (--until: wait while PENDING)" echo " public-names # [--json] — a public library name added or renamed: a human /prm" echo " merge-slot take|release|status --task — inside a shift, a merge slot before a bare gh pr merge" echo " merge-mode [--auto] [--in-shift] — the effective level and merge mode, one line" diff --git a/skills/prm/reference.md b/skills/prm/reference.md index 6a19df8..8cc2389 100644 --- a/skills/prm/reference.md +++ b/skills/prm/reference.md @@ -162,8 +162,8 @@ differences: (no slot left under `merge-cap:`, the shift is paused, or the slot is another task's) or 2 (it cannot tell) → do not merge: report its line and stop, leaving the PR for `/prm`. Never wrap the merge in it. A close-out - session's take for its own PR and task succeeds: the watcher took that - slot. + session takes its own slot as a bare call just before it starts this skill + (M3.7b, decision A), so the take for the same PR and task succeeds again. If the take succeeded and the merge call then fails, run `pyauto-brain merge-slot release --task --why "merge failed"` so the slot returns to the shift, then stop as above. diff --git a/tests/test_closeout_at_pr_open.py b/tests/test_closeout_at_pr_open.py new file mode 100644 index 0000000..4cda284 --- /dev/null +++ b/tests/test_closeout_at_pr_open.py @@ -0,0 +1,441 @@ +"""M3.7b (PyAutoBrain#688): the close-out starts at PR-open and merges on green CI. + +The human's rulings of 2026-11-19 (AUTONOMY.md "Shift speed — 2026-11-19"): + +- S5: a close-out may start while CI still runs; it runs the witness and reads + the diff first, then waits in-turn for CI (`ci-verdict --until`) and merges + only on GREEN. It takes its merge slot itself, just before the merge + (decision A). +- S2: the close-out runs no full affected smoke. +- S6: a later library PR is updated from `main` only when its changed files + overlap a PR of the shift merged ahead of it, or GitHub reports a conflict. +""" + +from __future__ import annotations + +import datetime as _dt +import json +import subprocess +import sys +from pathlib import Path + +import pytest + +BRAIN = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN / "tests")) +sys.path.insert(0, str(BRAIN / "bin")) +import test_orchestrator_closeout as tc # noqa: E402 — the phase-4b and M3.6j fixtures +from test_orchestrator_closeout import (FIT8, GA7, GA8, PR1, PR2, Agents, # noqa: E402 + _verdict) +from test_orchestrator_digest import orch # noqa: E402 +import ci_verdict # noqa: E402 + +NOW = tc.t.NOW + + +class KwSpawner(tc.Spawner): + """The phase-4b spawner, keeping what each close-out was told.""" + + def __init__(self): + super().__init__() + self.kws = [] + + def spawn_closeout(self, task, pr_url, prompt_path, lease_dir, **kw): + self.kws.append(kw) + return super().spawn_closeout(task, pr_url, prompt_path, lease_dir) + + +def _shift(tmp_path, cap=2): + mind = tc.t._mind(tmp_path / "mind") + brief = tmp_path / "shift.md" + brief.write_text(tc.t.BRIEF.format(issue=tc.t.ISSUE, packet="") + .replace("merge-cap: 1", f"merge-cap: {cap}")) + home = tmp_path / "home" + sp = KwSpawner() + orch.tick(brief, mind, home=home, now=NOW, spawner=sp, agents=Agents(), + health=tc._health({})) + return mind, brief, home, sp + + +def _holders(brief, home): + return orch._merge_slots.holders(orch.slot_dir(brief, home)) + + +# --- S5: started at PR-open, CI still running ----------------------------------------- + +def test_s5_a_glance_and_a_notify_pr_with_ci_running_start_their_closeouts(tmp_path): + mind, brief, home, sp = _shift(tmp_path) + slot = orch.slot_dir(brief, home) + c = orch.read_counters(slot) + c["picks"]["picked"]["tier"] = "notify" + orch._write_counters(slot, c) + running = tc._health({PR1: "RUNNING", PR2: "RUNNING"}) + r = tc._tick(brief, mind, home, sp, 1, health=running) + assert sorted(r["closeouts"]["started"]) == [PR1, PR2] + assert sorted(sp.closeouts) == [("named", PR1), ("picked", PR2)] + # The in-turn CI wait's deadline: 30 min from the start (review-at is later). + until = orch._iso(NOW + _dt.timedelta(minutes=31)) + assert all(kw.get("ci_until") == until for kw in sp.kws), sp.kws + # Decision A: the watcher takes no merge slot for a merge close-out. + assert _holders(brief, home) == {} + tc._tick(brief, mind, home, sp, 2, health=running) + assert len(sp.closeouts) == 2 # never twice + + +def test_s5_the_ci_deadline_leaves_the_merge_margin_before_review_at(tmp_path): + """Review round 1, finding 1: a close-out started 21 min before review-at + must not wait until review-at and merge after it (#632 F1): the deadline + is review-at minus CLOSEOUT_MERGE_MARGIN_S (the /prm run after GREEN).""" + mind, brief, home, sp = _shift(tmp_path) + tc._tick(brief, mind, home, sp, 129, health=tc._health({PR1: "RUNNING"})) # 11:09 + assert orch.CLOSEOUT_MERGE_MARGIN_S == 300 + assert sp.kws and all(kw["ci_until"] == "2026-11-04T11:25:00Z" for kw in sp.kws) + + +def test_s5_red_or_unknown_ci_still_refuses_with_no_session(tmp_path): + mind, brief, home, sp = _shift(tmp_path) + tc._tick(brief, mind, home, sp, 1, health=tc._health({PR1: "FAILED", PR2: "UNKNOWN"})) + assert sp.closeouts == [] + c = orch.read_counters(orch.slot_dir(brief, home)) + assert c["closeouts"][PR1]["why"] == "CI FAILED — never merged unattended" + assert c["closeouts"][PR2]["why"] == "CI UNKNOWN — never merged unattended" + + +def test_s5_no_checks_waits_out_the_grace_then_refuses(tmp_path): + mind, brief, home, sp = _shift(tmp_path) + none = tc._health({PR1: "NO-CHECKS", PR2: "NO-CHECKS"}) + tc._tick(brief, mind, home, sp, 1, health=none) + tc._tick(brief, mind, home, sp, 9, health=none) + c = orch.read_counters(orch.slot_dir(brief, home)) + assert sp.closeouts == [] and PR1 not in c["closeouts"] # waiting, not refused + tc._tick(brief, mind, home, sp, 12, health=none) # 11 min after first seen + c = orch.read_counters(orch.slot_dir(brief, home)) + assert sp.closeouts == [] + assert c["closeouts"][PR1]["why"] == "CI NO-CHECKS — never merged unattended" + + +# --- S2 + S5: the rendered close-out prompt ------------------------------------------- + +def _prompt(**kw): + return orch.closeout_prompt("t1", PR1, "draft/x/t1.md", Path("b.md"), Path("leases"), + ci_until="2026-11-04T09:31:00Z", **kw) + + +def test_s2_s5_the_prompt_runs_no_smoke_and_waits_for_ci_after_the_witness(tmp_path): + text = _prompt() + assert "--affected-by" not in text and "smoke --affected-by" not in text + wait = text.index(f"ci-verdict {PR1} --until 2026-11-04T09:31:00Z") + assert text.index("Witness:") < wait + assert text.index("Review the diff adversarially") < wait + assert text.index("headRefOid") < wait # recorded at the witness + assert "2026-11-04T09:31:00Z" in text + assert "CI not finished by 2026-11-04T09:31:00Z → /prm" in text + assert "head moved after the witness → /prm" in text + # Decision A: the session takes its own merge slot, just before the merge. + take = text.index(f"merge-slot take {PR1} --task t1") + assert wait < take < text.index("use the prm skill") + assert "took its slot before starting you" not in text + assert "/smoke" not in text.split("Last, write", 1)[1] # the verdict's gate + + +def test_r1_the_merge_slot_take_must_say_taken(): + """Review round 1, finding 3: `merge-slot take` exits 0 with "not in a + shift" when the shift env is missing; only a `taken: ` line goes on.""" + text = _prompt() + step = text.split("\n8. ", 1)[1].split("\n9. ", 1)[0] + assert "`taken: `" in step and "not in a shift" in step + assert "merge slot not taken: → /prm" in step + + +def test_r1_the_ci_wait_runs_under_a_long_bash_timeout_and_the_merge_is_pinned(): + """Review round 1, findings 4 and 5.""" + text = _prompt() + wait = text.split("\n5. ", 1)[1].split("\n6. ", 1)[0] + assert "600000" in wait + step = text.split("\n8. ", 1)[1].split("\n9. ", 1)[0] + assert "gh pr merge" in step and "--match-head-commit " in step + + +def test_s6_disjoint_merged_ahead_prs_are_named_not_compared(): + text = _prompt(after=[GA7], before=[GA7, "https://github.com/example-org/autogalaxy/pull/5"], + disjoint=["https://github.com/example-org/autogalaxy/pull/5"]) + step = text.split("4b. Merge order", 1)[1].split("\n5. ", 1)[0] + assert "merged ahead, disjoint files, not updated (S6)" in step + compare = step.split("ahead` or `identical`", 1)[1].split("disjoint", 1)[0] + assert GA7 in compare and "/pull/5" not in compare + + +# --- S6: branch update only on overlap or conflict ---------------------------------- + +class FilesOrderSpawner(tc.OrderSpawner): + """M3.6j's spawner, plus the changed-file read (`gh pr view --json files`).""" + + def __init__(self, files, picked=GA8): + super().__init__(picked) + self.files, self.reads = files, [] + + def pr_files(self, url): + self.reads.append(url) + return self.files.get(url) + + +def _merged_ahead(tmp_path, files, mergeable=""): + """#7 refused then merged after #8's worker began; #8 is green.""" + mind, brief, home, _ = tc._order_shift(tmp_path) + sp = FilesOrderSpawner(files) + tc._otick(brief, mind, home, sp, 1) + _verdict(home, brief, "named", result="refused", pr=GA7, + why="decision-taken label → human /prm") + tc._otick(brief, mind, home, sp, 2) + states = {GA7: ("MERGED", "2026-11-04T09:30:00Z")} + gh = tc._gh_states(states) + + def read(url): + out = gh(url) + if out is not None and url == GA8 and mergeable: + out = {**out, "mergeable": mergeable} + return out + r = orch.tick(brief, mind, home=home, now=NOW + _dt.timedelta(minutes=31), spawner=sp, + agents=Agents(), health=tc._health({}), pr_state=read) + return mind, brief, home, sp, r + + +def test_s6_a_pr_disjoint_from_every_pr_merged_ahead_is_closed_out_without_update(tmp_path): + files = {GA7: ["autogalaxy/a.py"], GA8: ["autogalaxy/b.py", "test_autogalaxy/test_b.py"]} + mind, brief, home, sp, r = _merged_ahead(tmp_path, files) + task, pr, kw = sp.closeouts[-1] + assert (task, pr) == ("picked", GA8) + assert "update_after" not in kw and kw["disjoint"] == [GA7] and kw["before"] == [GA7] + assert "after" not in kw + c = orch.read_counters(orch.slot_dir(brief, home)) + assert c["closeouts"][GA8]["state"] == "running" and c["closeouts"][GA8].get("kind") != "update" + assert c["pr_files"][GA8] == files[GA8] # cached for the shift + assert sorted(set(sp.reads)) == sorted(sp.reads) == sorted([GA7, GA8]) # once each + + +def test_s6_one_shared_file_still_gets_the_branch_update(tmp_path): + files = {GA7: ["autogalaxy/a.py", "autogalaxy/shared.py"], GA8: ["autogalaxy/shared.py"]} + mind, brief, home, sp, r = _merged_ahead(tmp_path, files) + assert sp.closeouts[-1] == ("picked", GA8, {"update_after": [GA7]}) + + +def test_s6_a_conflicting_pr_gets_the_update_even_with_disjoint_files(tmp_path): + files = {GA7: ["autogalaxy/a.py"], GA8: ["autogalaxy/b.py"]} + mind, brief, home, sp, r = _merged_ahead(tmp_path, files, mergeable="CONFLICTING") + assert sp.closeouts[-1] == ("picked", GA8, {"update_after": [GA7]}) + + +def test_s6_an_unreadable_file_list_fails_toward_the_update(tmp_path): + mind, brief, home, sp, r = _merged_ahead(tmp_path, {GA7: ["autogalaxy/a.py"]}) + assert sp.closeouts[-1] == ("picked", GA8, {"update_after": [GA7]}) + # Kept as unreadable (None), never read again (review round 1, finding 2). + assert orch.read_counters(orch.slot_dir(brief, home))["pr_files"][GA8] is None + + +@pytest.mark.parametrize("bad", ["none", "raise"]) +def test_s6_an_unreadable_file_list_is_read_once_a_shift(bad): + """Review round 1, finding 2: an earlier PR whose files cannot be read is + cached as unreadable (an overlap) and never read again for a later PR.""" + calls = [] + + def reader(url): + calls.append(url) + if url == GA7: + if bad == "raise": + raise RuntimeError("gh down") + return None + return ["autogalaxy/x.py"] + counters = {} + ga9 = GA8.replace("/8", "/9") + for later in (GA8, ga9): + need, disjoint = orch._overlap(counters, later, [GA7], None, reader, {}) + assert need == [GA7] and disjoint == [] + assert calls.count(GA7) == 1, calls + assert calls.count(GA8) == 1 and calls.count(ga9) == 1 + + +def test_gh_pr_files_and_mergeable_reads(): + def gh(out, rc=0): + return lambda argv, **kw: subprocess.CompletedProcess(argv, rc, out, "") + files = json.dumps({"files": [{"path": "a.py", "additions": 1}, {"path": "b/c.py"}]}) + assert orch.gh_pr_files(GA8, run=gh(files)) == ["a.py", "b/c.py"] + assert orch.gh_pr_files(GA8, run=gh("", rc=1)) is None + assert orch.gh_pr_files(GA8, run=gh("not json")) is None + full = json.dumps({"files": [{"path": f"f{i}.py"} for i in range(100)]}) + assert orch.gh_pr_files(GA8, run=gh(full)) is None # may be truncated + seen = [] + + def view(argv, **kw): + seen.append(argv) + return subprocess.CompletedProcess(argv, 0, json.dumps( + {"state": "OPEN", "headRefOid": "abc", "mergeable": "CONFLICTING"}), "") + assert orch.gh_pr_state(GA8, run=view)["mergeable"] == "CONFLICTING" + assert len(seen) == 1 and "mergeable" in seen[0][seen[0].index("--json") + 1] + + +# --- merge order unchanged ------------------------------------------------------------ + +def test_merge_order_a_later_pr_waits_while_the_earlier_closeout_waits_on_ci(tmp_path): + mind, brief, home, sp = tc._order_shift(tmp_path) + running = tc._health({GA7: "RUNNING", GA8: "RUNNING"}) + tc._otick(brief, mind, home, sp, 1, health=running) + assert [(task, pr) for task, pr, _ in sp.closeouts] == [("named", GA7)] + for minute in (2, 3, 4): + tc._otick(brief, mind, home, sp, minute, health=running) + c = orch.read_counters(orch.slot_dir(brief, home)) + assert c["closeouts"][GA7]["state"] == "running" + assert c["merge_waits"][GA8]["behind"] == [GA7] and GA8 not in c["closeouts"] + assert [pr for _, pr, _ in sp.closeouts] == [GA7] + + +# --- decision A: the session takes the slot, the reaper frees it --------------------- + +def _slot_take(brief, home, pr, task): + return orch._merge_slots.take(orch.slot_dir(brief, home), pr, "worker", task) + + +def test_a_a_full_cap_refuses_without_a_session(tmp_path): + mind, brief, home, sp = _shift(tmp_path, cap=1) + slot = orch.slot_dir(brief, home) + orch._merge_slots.publish(slot, 1, False) + assert _slot_take(brief, home, "https://github.com/o/r/pull/99", "other")[0] + tc._tick(brief, mind, home, sp, 1) + assert sp.closeouts == [] + c = orch.read_counters(slot) + assert c["closeouts"][PR1]["why"] == "merge-cap 1 reached this shift — left for your /prm" + + +def test_a_a_refused_closeout_frees_the_slot_its_session_took(tmp_path): + mind, brief, home, sp = _shift(tmp_path) + tc._tick(brief, mind, home, sp, 1) + assert _holders(brief, home) == {} + assert _slot_take(brief, home, PR1, "named")[0] and _slot_take(brief, home, PR2, "picked")[0] + _verdict(home, brief, "named", result="refused", pr=PR1, why="CI RED: check-failed") + _verdict(home, brief, "picked", result="merged", pr=PR2, gate="g", model="m") + r = tc._tick(brief, mind, home, sp, 2) + assert r["closeouts"]["refused"] == [PR1] and r["closeouts"]["merged"] == [PR2] + held = _holders(brief, home) + assert orch._merge_slots.pr_key(PR1) not in held # refused: freed + assert held[orch._merge_slots.pr_key(PR2)]["task"] == "picked" # merged: kept + + +def test_a_the_closeout_sessions_own_take_succeeds(tmp_path, monkeypatch, capsys): + 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": [GA7], "issues": []}, + "picked": {"prs": [GA8], "merged": [], "issues": []}}, + "closeouts": {GA8: {"task": "picked", "state": "running"}}})) + orch._merge_slots.publish(slot, 1, False) + env = orch.worker_env(slot / "leases", base={}) + for k in ("PYAUTO_SHIFT_WORKER", "PYAUTO_SHIFT_LEDGER_DIR"): + monkeypatch.setenv(k, env[k]) + monkeypatch.setattr(orch, "gh_pr_state", lambda u: {"state": "MERGED", "mergedAt": "", + "mergedBy": ""}) + assert merge_slot.main(["take", GA8, "--task", "picked"]) == 0, capsys.readouterr().out + assert orch._merge_slots.holders(slot)[orch._merge_slots.pr_key(GA8)]["task"] == "picked" + + +# --- ci-verdict --until --------------------------------------------------------------- + +def _verdicts(monkeypatch, words): + seq = list(words) + calls = [] + + def fake(ref, run=None, sleep=None): + calls.append(ref) + w = seq.pop(0) if len(seq) > 1 else seq[0] + return {"pr": "o/r#1", "sha": "abc", "verdict": w, "reasons": [], "counts": {}, + "skipped": [], "mergeable_state": "clean", "note": None} + monkeypatch.setattr(ci_verdict, "verdict_for", fake) + return calls + + +class Clock: + def __init__(self, start): + self.t, self.slept = start, [] + + def now(self): + return self.t + + def sleep(self, s): + self.slept.append(s) + self.t += _dt.timedelta(seconds=s) + + +def test_until_pending_then_green_exits_0(monkeypatch): + calls = _verdicts(monkeypatch, ["PENDING", "PENDING", "GREEN"]) + clock = Clock(NOW) + rc = ci_verdict.main([PR1, "--until", "2026-11-04T09:30:00Z"], sleep=clock.sleep, + now=clock.now) + assert rc == 0 and len(calls) == 3 and clock.slept == [30, 30] + + +def test_until_pending_through_the_deadline_exits_2(monkeypatch): + calls = _verdicts(monkeypatch, ["PENDING"]) + clock = Clock(NOW) + rc = ci_verdict.main([PR1, "--until", "2026-11-04T09:01:00Z"], sleep=clock.sleep, + now=clock.now) + # The deadline is re-checked after each sleep (review round 1, finding 4). + assert rc == 2 and clock.slept == [30, 30] and len(calls) == 2 + + +def test_until_one_call_polls_at_most_540_seconds(monkeypatch): + _verdicts(monkeypatch, ["PENDING"]) + clock = Clock(NOW) + rc = ci_verdict.main([PR1, "--until", "2026-11-04T10:00:00Z"], sleep=clock.sleep, + now=clock.now) + assert rc == 2 and sum(clock.slept) <= 540 and sum(clock.slept) >= 510 + + +def test_until_one_call_stays_within_540_seconds_when_reads_take_time(monkeypatch): + """Review round 1, finding 4: the bound is wall time from the call's + start, gh reads included, not the sum of the sleeps.""" + clock = Clock(NOW) + + def slow(ref, run=None, sleep=None): + clock.t += _dt.timedelta(seconds=20) # each read takes 20 s + return {"pr": "o/r#1", "sha": "abc", "verdict": "PENDING", "reasons": [], + "counts": {}, "skipped": [], "mergeable_state": "clean", "note": None} + monkeypatch.setattr(ci_verdict, "verdict_for", slow) + start = clock.t + rc = ci_verdict.main([PR1, "--until", "2026-11-04T10:00:00Z"], sleep=clock.sleep, + now=clock.now) + assert rc == 2 and (clock.t - start).total_seconds() <= 540 + + +def test_until_red_returns_at_once_and_a_bad_timestamp_is_usage(monkeypatch): + _verdicts(monkeypatch, ["RED"]) + clock = Clock(NOW) + assert ci_verdict.main([PR1, "--until", "2026-11-04T10:00:00Z"], sleep=clock.sleep, + now=clock.now) == 1 and clock.slept == [] + assert ci_verdict.main([PR1, "--until", "half past nine"], sleep=clock.sleep, + now=clock.now) == 64 + + +def test_pyauto_brain_passes_until_through(): + text = (BRAIN / "bin" / "pyauto-brain").read_text() + assert 'exec python3 "$BRAIN_HOME/bin/ci_verdict.py" "$@"' in text + assert "--until" in text + + +# --- the doctrine --------------------------------------------------------------------- + +def test_autonomy_records_s2_s5_s6_and_their_revert_conditions(): + text = (BRAIN / "AUTONOMY.md").read_text() + sec = text.split("## Shift speed — 2026-11-19", 1)[1].split("\n## ", 1)[0] + sec = " ".join(sec.split()) + for ruling in ("**S2,", "**S5,", "**S6,"): + assert ruling in sec, ruling + assert "one red sweep traced to an unattended merge" in sec + assert "one red `main` CI traced to two disjoint shift PRs" in sec + assert "30 minutes" in sec and "immediately before the merge" in sec + assert "(S2, S4 to S7)" not in sec + leg2 = text.split("2. **Smoke**", 1)[1].split("\n3. **Review**", 1)[0] + assert "S2" in leg2 and "M3.7d" in leg2 and "M3.7e" in leg2 + net = text.split("## The watcher's network surface — 2026-11-03", 1)[1].split("\n## ", 1)[0] + net = " ".join(net.split()) + assert "M3.7b" in net and "--json files" in net and "mergeable" in net + glance = text.split("### Unattended `glance` merges — 2026-11-03", 1)[1].split("\n### ", 1)[0] + assert "S5" in glance and "S6" in glance diff --git a/tests/test_closeout_merge_slots.py b/tests/test_closeout_merge_slots.py index d90ad55..a9bdd88 100644 --- a/tests/test_closeout_merge_slots.py +++ b/tests/test_closeout_merge_slots.py @@ -136,19 +136,22 @@ def test_take_is_atomic_across_processes(tmp_path): def test_watcher_closeout_and_worker_share_slots(tmp_path): - # A `glance` shift with merge-cap 1: the watcher starts a close-out on PR1, - # which takes the one slot; a worker's in-turn take of PR2 is refused. + # A `glance` shift with merge-cap 1: the watcher starts a close-out on PR1 + # without taking a slot (M3.7b, decision A); the session takes the one + # slot itself just before its merge, and a second take of PR2 is refused. mind, brief, home, sp = tc._shift(tmp_path, cap=1) slot = orch.slot_dir(brief, home) r = tc._tick(brief, mind, home, sp, 1) assert r["closeouts"]["started"] == [PR1], r["closeouts"] - assert _slot_cli(slot, "take", PR2, "--task", "picked").returncode == 1 - # The close-out session's own /prm take for its PR is the watcher's slot. + assert "0 of merge-cap 1" in _slot_cli(slot, "status").stdout # the watcher took none assert _slot_cli(slot, "take", PR1, "--task", "named").returncode == 0 - # A worker cannot free the watcher's slot. - _slot_cli(slot, "release", PR1, "--task", "named") + assert _slot_cli(slot, "take", PR1, "--task", "named").returncode == 0 # idempotent + assert _slot_cli(slot, "take", PR2, "--task", "picked").returncode == 1 + # Another task's release cannot free the close-out session's slot. + assert _slot_cli(slot, "release", PR1, "--task", "picked").returncode == 1 assert _slot_cli(slot, "take", PR2, "--task", "picked").returncode == 1 - # The close-out refuses: the watcher frees its slot, and the worker gets it. + # The close-out refuses: the watcher frees the slot its session took, and + # PR2's take gets it. tc._verdict(home, brief, "named", result="refused", pr=PR1, why="witness failed") tc._tick(brief, mind, home, sp, 2) assert orch.read_counters(slot)["closeouts"][PR1]["state"] == "refused" diff --git a/tests/test_dev_ship_gate.py b/tests/test_dev_ship_gate.py index 1ff5ec9..61c6ad3 100644 --- a/tests/test_dev_ship_gate.py +++ b/tests/test_dev_ship_gate.py @@ -181,7 +181,8 @@ def _closeout_heart_cmd(pr_url, tmp_path): import _orchestrator # noqa: PLC0415 text = _orchestrator.closeout_prompt("t", pr_url, "draft/x/t.md", tmp_path / "brief.md", tmp_path / "leases") - step = text.split("\n3. ", 1)[1].split("\n4. ", 1)[0] + # Heart is step 4 since M3.7b split label/tier (3) from Heart (4). + step = text.split("\n4. ", 1)[1].split("\n5. ", 1)[0] cmd = next((l.strip() for l in step.splitlines() if l.strip().startswith("bash -c")), "") return step, cmd diff --git a/tests/test_orchestrator_closeout.py b/tests/test_orchestrator_closeout.py index 5619f3f..1e59cd4 100644 --- a/tests/test_orchestrator_closeout.py +++ b/tests/test_orchestrator_closeout.py @@ -36,7 +36,7 @@ def __init__(self): super().__init__(done={"named": PR1 + "\n", "picked": PR2 + "\n"}, proofs={}) self.closeouts = [] - def spawn_closeout(self, task, pr_url, prompt_path, lease_dir): + def spawn_closeout(self, task, pr_url, prompt_path, lease_dir, **_kw): self.closeouts.append((task, pr_url)) return {"pid": 0, "agent_id": f"co{len(self.closeouts):06d}"} @@ -163,6 +163,11 @@ def gh(out, err="", rc=0): PR2: lambda u: _digest.pr_health(u, run=skipped_only)} mind, brief, home, sp = _shift(tmp_path, cap=2) _tick(brief, mind, home, sp, 1, health=lambda u: health[u](u)) + # M3.7b (S5): NO-CHECKS first waits UPDATE_CHECKS_GRACE_S from when the + # watcher first saw the PR — CI may not have registered yet. + assert sp.closeouts == [] + assert orch.read_counters(orch.slot_dir(brief, home))["closeouts"] == {} + _tick(brief, mind, home, sp, 12, health=lambda u: health[u](u)) assert sp.closeouts == [] c = orch.read_counters(orch.slot_dir(brief, home)) assert c["closeouts"][PR1]["state"] == "refused" @@ -170,14 +175,15 @@ def gh(out, err="", rc=0): assert c["closeouts"][PR2]["why"] == "CI NO-CHECKS — never merged unattended" -def test_red_ci_is_refused_and_pending_ci_waits(tmp_path): +def test_red_ci_is_refused_and_pending_ci_starts_at_pr_open(tmp_path): + """M3.7b (ruling S5): running CI no longer waits for the watcher — the + close-out starts at PR-open and waits for CI in its own turn.""" mind, brief, home, sp = _shift(tmp_path, cap=2) h = _health({PR1: "FAILED", PR2: "RUNNING"}) _tick(brief, mind, home, sp, 1, health=h) - assert sp.closeouts == [] + assert sp.closeouts == [("picked", PR2)] # started on RUNNING c = orch.read_counters(orch.slot_dir(brief, home)) assert c["closeouts"][PR1]["why"] == "CI FAILED — never merged unattended" - assert PR2 not in c["closeouts"] # waiting, not refused _tick(brief, mind, home, sp, 2, health=_health({PR1: "HEALTHY"})) assert sp.closeouts == [("picked", PR2)] # PR1's refusal is final @@ -363,8 +369,10 @@ def run(argv, **kw): "mergedBy": {"login": "someone"}, "headRefOid": "abc123"})) assert orch.gh_pr_state(PR1, run=run) == { "state": "MERGED", "mergedAt": "2026-11-04T09:00:00Z", "mergedBy": "someone", - "head": "abc123"} - assert seen == [["gh", "pr", "view", PR1, "--json", "state,mergedAt,mergedBy,headRefOid"]] + "head": "abc123", "mergeable": ""} + # `mergeable` is a field of the same call (S6, M3.7b), not a second read. + assert seen == [["gh", "pr", "view", PR1, "--json", + "state,mergedAt,mergedBy,headRefOid,mergeable"]] 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( @@ -535,7 +543,8 @@ def test_the_closeout_ceiling_counts_reservations_and_holds_on_unread_usage(tmp_ assert "1600 (committed) reached 1.5×" in orch.read_counters(slot)["closeouts"][PR1]["why"] mind, brief, home, sp = _shift(tmp_path / "unread", cap=2) - r = _tick(brief, mind, home, sp, 1, health=_health({PR2: "RUNNING"})) + # NO-CHECKS inside its grace waits (M3.7b: RUNNING would start it now). + r = _tick(brief, mind, home, sp, 1, health=_health({PR2: "NO-CHECKS"})) assert r["closeouts"]["started"] == [PR1] # PR1's close-out usage cannot be read (no session id): PR2 waits a tick. r = _tick(brief, mind, home, sp, 2) @@ -636,10 +645,13 @@ def test_683_a_later_pr_waits_behind_an_earlier_refused_one_no_slot_no_refusal(t assert "waiting" not in r["closeouts"] # an event only when it changes +UNTIL1 = {"ci_until": "2026-11-04T09:31:00Z"} # M3.7b: a tick-1 close-out's CI deadline + + @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 + (FIT8, {}, UNTIL1), # another repo + (GA8, {GA7: "CLOSED"}, {"before": [GA7], **UNTIL1}), # closed unmerged + (GA8, {GA7: ("MERGED", "2026-11-04T08:00:00Z")}, {"before": [GA7], **UNTIL1}), # before #8 began ]) def test_683_no_wait_on_another_repo_or_behind_a_merged_or_closed_pr(tmp_path, picked, states, kw): @@ -680,7 +692,9 @@ def test_683_once_the_earlier_pr_merged_after_it_began_the_branch_is_updated(tmp 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"})) + # CI has not registered on the new head yet (M3.7b: RUNNING would start + # the merge close-out at once, S5). + r = _otick(brief, mind, home, sp, 32, states, health=_health({GA8: "NO-CHECKS"})) return mind, brief, home, sp, r, states @@ -692,13 +706,18 @@ def test_683_an_updated_branch_holds_its_slot_and_waits_for_ci_on_the_new_head(t 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, 33, states, health=_health({GA8: "NO-CHECKS"})) _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 + # M3.7b (S5): CI running on the verified new head starts the merge + # close-out, which waits in-turn for a green `ci-verdict` on that head. + r = _otick(brief, mind, home, sp, 35, states, health=_health({GA8: "RUNNING"})) assert r["closeouts"]["started"] == [GA8] - assert sp.closeouts[-1] == ("picked", GA8, {"after": [GA7], "before": [GA7]}) + assert sp.closeouts[-1] == ("picked", GA8, {"after": [GA7], "before": [GA7], + "ci_until": "2026-11-04T10:05:00Z"}) + # The updated PR keeps the slot the watcher took before its update. + assert orch._merge_slots.pr_key(GA8) in _slots(brief, home) 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 diff --git a/tests/test_orchestrator_digest.py b/tests/test_orchestrator_digest.py index 933a577..25542e8 100644 --- a/tests/test_orchestrator_digest.py +++ b/tests/test_orchestrator_digest.py @@ -102,7 +102,7 @@ def spawn(self, task, prompt_path, lease_dir): (Path(lease_dir) / f"{task}.done").write_text(self.done.get(task, "")) return {"pid": 0, "session_id": None, "worktree": None} - def spawn_closeout(self, task, pr_url, prompt_path, lease_dir): + def spawn_closeout(self, task, pr_url, prompt_path, lease_dir, **_kw): # Phase 4b: a green glance PR gets a close-out; this one never reports. return {"pid": 0, "agent_id": "c0ffee00"} diff --git a/tests/test_orchestrator_steering.py b/tests/test_orchestrator_steering.py index 6984c93..21fca10 100644 --- a/tests/test_orchestrator_steering.py +++ b/tests/test_orchestrator_steering.py @@ -147,7 +147,11 @@ def test_the_status_comment_is_created_once_and_then_only_edited(tmp_path, monke (slot / "leases" / "t1.done").write_text("https://github.com/o/r/pull/9\n") r = _tick(brief, mind, home, 4, claude, gh, {"t1": "done"}) # a state change assert r["status"]["status"] == "edited" - assert "- **CI running** — [t1](https://github.com/o/r/pull/9)" in gh.status()[0]["body"] + # M3.7b (S5): a PR with CI running is judged for its close-out at once; + # this shift's merge-cap 0 refuses it (before S5 it showed "CI running"). + assert ("- **Needs you — not merged unattended** — [t1](https://github.com/o/r/pull/9)" + in gh.status()[0]["body"]) + assert "merge-cap 0 reached this shift" in gh.status()[0]["body"] r = _tick(brief, mind, home, 20, claude, gh) # the 10-minute refresh assert r["status"]["status"] == "edited" and "2h 10m left" in gh.status()[0]["body"] diff --git a/tests/test_public_names.py b/tests/test_public_names.py index f1e823b..245926a 100644 --- a/tests/test_public_names.py +++ b/tests/test_public_names.py @@ -574,7 +574,7 @@ def no_claude(argv, **kw): public_names=lambda url: why if url == tc.PR1 else "") class Gated(tc.Spawner): - def spawn_closeout(self, task, pr_url, prompt_path, lease_dir): + def spawn_closeout(self, task, pr_url, prompt_path, lease_dir, **_kw): self.closeouts.append((task, pr_url)) if pr_url != tc.PR1: return super().spawn_closeout(task, pr_url, prompt_path, lease_dir) diff --git a/tests/test_shift_smoke_split.py b/tests/test_shift_smoke_split.py index 9eafb27..a25e643 100644 --- a/tests/test_shift_smoke_split.py +++ b/tests/test_shift_smoke_split.py @@ -1,9 +1,8 @@ """The shift's smoke split (AUTONOMY.md leg 2, 2026-11-19, PyAutoHeart#352). -A shift worker runs a targeted smoke only; the full affected smoke, three -workspaces at a time, runs in the close-out before an unattended merge, and -not at all for a PR bound for the human's /prm (the close-out refuses those -before it reaches the smoke step). +A shift worker runs a targeted smoke only. Until ruling S2 (2026-11-19, +M3.7b) the full affected smoke ran in the close-out before an unattended +merge; it now runs nowhere before a merge, and the cloud sweep runs after. """ from __future__ import annotations @@ -68,23 +67,21 @@ def test_autonomy_records_the_notify_ruling(): assert "Shift workers no\nlonger merge in-turn" in agents -def test_the_closeout_runs_the_affected_parallel_smoke_before_the_merge(): +def test_the_closeout_runs_no_full_smoke_since_s2(): + """Ruling S2 (2026-11-19, M3.7b): the close-out no longer runs the full + affected smoke; the worker's targeted smoke is the pre-merge smoke and + the full sweep runs in the cloud after the merge. The witness step now + brings the task root to the PR head instead.""" text = _closeout() - smoke = _step(text, 5) - assert "--affected-by WidgetLib --jobs 3" in smoke - assert "resolve_heart" in smoke and '--root "$PWD"' in smoke - assert "headRefOid" in smoke and "--ff-only" in smoke - assert "smoke FAILED" in smoke and "/prm" in smoke - # The smoke comes after the refusal steps (tier, decision-taken, Heart, CI), - # so a PR bound for the human's /prm never reaches a full sweep... - assert text.index("decision-taken") < text.index("full affected smoke") - # ...and before the merge itself. - assert text.index("full affected smoke") < text.index("use the prm skill") - assert "/smoke …" in text # the verdict's gate field names it - - -def test_the_closeout_smoke_cannot_be_scoped_without_a_pr_repo(): - assert orch.smoke_command("") == "" + assert "--affected-by" not in text and "smoke FAILED" not in text + witness = _step(text, 1) + assert "headRefOid" in witness and "--ff-only" in witness + assert "no full affected smoke here (ruling S2)" in text + assert "/smoke" not in text.split("Last, write", 1)[1] # the verdict's gate field + assert not hasattr(orch, "smoke_command") and not hasattr(orch, "CLOSEOUT_SMOKE_JOBS") + + +def test_the_closeout_ci_wait_cannot_be_scoped_without_a_pr_repo(): assert "not a GitHub PR URL — refuse" in _step(_closeout("not-a-pr"), 5)