From 585de63f356061c6743844fbdd9c385af491cfd0 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 17 Nov 2026 13:48:51 +0000 Subject: [PATCH 1/5] fix: in-shift merges take a merge-cap slot; R3 in AUTONOMY Shift 2026-11-16-pm read "2 merged of merge-cap 1": workers merged notify PRs in-turn without consulting the cap, and the watcher refused notify as "only glance merges unattended". Ruling R3 (2026-11-17): - _merge_slots.py: one file-locked merge-slot count per shift; the watcher publishes cap and pause each tick, fails closed. - pyauto-brain merge-slot take|release|status (bin/merge_slot.py): a worker's separate bare call before a bare gh pr merge. - watcher: notify PRs are closed out on glance terms; judge/undeclared go to /prm; close-outs take a slot just before spawn and release it on refusal; notify close-outs add no stage-2 row; /cap merges counts slots. - digest: an in-turn merge reads "merged in-turn by the worker (merge slot)". - sizing.merge_mode + pyauto-brain merge-mode: the one-line effective level and merge mode start_dev step 3 prints. - skills, worker and close-out templates, AUTONOMY.md R3 H3 + pointers. Refs #661. Co-Authored-By: Claude Opus 5.5 --- AUTONOMY.md | 16 +- agents/conductors/batch/AGENTS.md | 14 +- agents/conductors/batch/_digest.py | 7 +- agents/conductors/batch/_merge_slots.py | 163 +++++++++++++++++ agents/conductors/batch/_orchestrator.py | 87 ++++++--- agents/conductors/batch/closeout_template.md | 11 +- agents/conductors/batch/worker_template.md | 6 +- agents/faculties/sizing/_sizing.py | 39 ++++ bin/README.md | 9 + bin/merge_mode.py | 70 ++++++++ bin/merge_slot.py | 95 ++++++++++ bin/pyauto-brain | 15 ++ skills/prm/reference.md | 14 +- skills/ship_library/ship_library.md | 2 + skills/ship_workspace/ship_workspace.md | 2 + skills/start_dev/reference.md | 12 +- skills/start_dev/start_dev.md | 6 + tests/test_closeout_merge_slots.py | 180 +++++++++++++++++++ tests/test_orchestrator_closeout.py | 29 ++- tests/test_orchestrator_digest.py | 3 +- tests/test_orchestrator_merge_slots.py | 146 +++++++++++++++ tests/test_orchestrator_steering.py | 6 +- 22 files changed, 883 insertions(+), 49 deletions(-) create mode 100644 agents/conductors/batch/_merge_slots.py create mode 100644 bin/merge_mode.py create mode 100644 bin/merge_slot.py create mode 100644 tests/test_closeout_merge_slots.py create mode 100644 tests/test_orchestrator_merge_slots.py diff --git a/AUTONOMY.md b/AUTONOMY.md index 8aabb43b..85203865 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -29,7 +29,7 @@ Where the dev workflow stops for a human today: | Checkpoint | `safe` | `supervised` | `human-required` | |------------|--------|--------------|------------------| | Plan approval | write plan to the issue, proceed | write plan to the issue, proceed | present + wait | -| Ship PR sign-off | proceed through the autonomous-ship gate; end at PR-open | park (`awaiting-input`), question to the issue, continue elsewhere — except under an explicit `--auto` launch, where it resolves to decide-and-flag (below; 2026-09-07) | present + wait | +| Ship PR sign-off | proceed through the autonomous-ship gate; end at PR-open | park (`awaiting-input`), question to the issue, continue elsewhere — except under an explicit `--auto` launch, where it resolves to decide-and-flag (below; 2026-09-07) (a `notify` task merges in-turn under R3, "`notify` merges under `--auto` and inside a shift — 2026-11-17") | present + wait | | Heart YELLOW | park, unless the reason set was human-acknowledged at launch (see the autonomous-ship gate) | same as `safe` | present + wait | | Heart RED | stop, report | stop, report | stop, report — a live human may separately invoke the development override or corrective-PR exception below; neither is an autonomy level | | Merge / close | by declared `Consequence:` (2026-10-02 section) | by declared `Consequence:` | by declared `Consequence:` | @@ -258,7 +258,7 @@ checkpoint of an effective-`supervised` run.** The human's direction (2026-08-31): *"I dont really want these parked at ship judgements, ideally we send off a batch and then dont think about it again, the parked thing is an annoying middle ground which requires human time."* The argument: every -autonomous run already ends at PR-open with merge left to the human, so **the PR +autonomous run already ends at PR-open with merge left to the human (a `notify` task merges in-turn under R3, "`notify` merges under `--auto` and inside a shift — 2026-11-17"), so **the PR review IS the approval the `supervised` level exists to provide**. A mid-run park at ship sign-off is a redundant *second* checkpoint — it costs a GitHub-issue round-trip before a PR even exists, and then asks the human for the same @@ -538,6 +538,18 @@ It is not adopted here; it needs its own doctrine edit. auto-merge found to have bypassed one of the never-auto-merge rules retires this section and returns every merge to `/prm`. +### `notify` merges under `--auto` and inside a shift — 2026-11-17 (ruling R3) + +The human's ruling R3, 2026-11-17, from the review of shift 2026-11-16-pm. Two workers on the same `bug · safe · notify` header did opposite things: PyAutoBrain#654 stopped at decide-and-flag because the `bug` cap lowered it to `supervised`, and PyAutoBrain#655 merged in-turn. The shift then read "2 merged of merge-cap 1". + +- **A work-type cap does not stop a `notify` merge.** "Per-work-type caps" sets the effective level, and the level decides the checkpoints. Who merges is decided by the table above. A `notify` task whose cap lowered it to `supervised`, launched with `--auto` and with its `Witness:` held, merges in-turn on green. If the prompt declares no `Witness:`, it goes to `/prm`. A PR that took a decision under decide-and-flag carries `decision-taken` and is never auto-merged, as before. +- **Inside a shift, every merge counts against `merge-cap:`.** Before `gh pr merge`, a worker takes a merge slot with `pyauto-brain merge-slot take `, as its own bare call. If no slot is left, or the shift is paused, it does not merge and leaves the PR for `/prm`. The watcher's close-outs take slots from the same count. The digest says for each merge whether the worker merged it in-turn or a close-out did. +- **The watcher agrees with the worker.** It no longer refuses a `notify` PR as "only glance merges unattended". It closes out a `notify` PR a worker left open exactly as it closes out a `glance` one: Heart not RED, a merge slot free, the `Witness:` run by the close-out session, and nothing from "Never auto-merged". `judge`, an undeclared tier and `decision-taken` still go to `/prm`. +- **These are `notify` merges, not stage-2 rows.** They do not count toward the unattended `glance` sub-window. The 2026-11-16-pm overrun was two `notify` merges made in-turn, outside "Unattended `glance` merges — 2026-11-03", so it does not trigger that sub-rule's revert condition. +- Outside a shift, nothing changes. + +*Revert condition:* one in-shift merge past `merge-cap:` after this is built returns every in-shift `notify` merge to `/prm`. + ## The `glance` Shadow-window ruling — 2026-11-04 **`glance` is confirmed, narrowed.** Ruled by the human 2026-11-04 under the diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 4986f481..b4c84220 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -420,15 +420,17 @@ ends at PR-open (`worker_template.md`). Each tick, `_closeouts` first reaps running close-outs — `.closeout` (`merged` | `refused`, `why`, `gate`, `model`), or a session gone without one, which is recorded refused — then, for each PR a worker named, judges the guards it can see with its own reads: the -recorded tier is `glance`, `gh pr checks` is green — at least one completed -check, all green (pending waits a tick; red, none or unknown is refused), merges plus in-flight close-outs are under `merge-cap:`, the -shift is not shadow, `review-at:` is more than 20 minutes away, and spend is -under 1.5× `token-budget:` (#632; AUTONOMY.md "Close-out budget — 2026-11-14"). Then it starts **one** close-out session +recorded tier is `glance` or `notify` (ruling R3, 2026-11-17), `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`). That session is the independent leg: it runs the `Witness:` itself, reviews the diff adversarially, checks the `decision-taken` label and Heart, and only then -runs the `/prm` close-out — or refuses. A merge bumps `glance_auto_merges`, -marks the PR merged, and queues a `table-append` op that lands one row in +runs the `/prm` close-out — or refuses. 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 (`awaiting /prm — close-out refused: `). Same-model close-out: AUTONOMY diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index 16faef1f..a611de21 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -45,6 +45,9 @@ #: A worker whose lease is still held when the digest is built (#634, N1): it #: was dispatched and is not done; the late sweep reports how it ends. STILL_OUT = "still running at review time — the late sweep will report it" +#: A PR the worker merged in-turn — after taking a merge slot against the +#: shift's `merge-cap:` (AUTONOMY.md ruling R3, 2026-11-17, PyAutoBrain#661). +IN_TURN_MERGED = "merged in-turn by the worker (merge slot)" #: A killed worker whose re-dispatch never started (PyAutoBrain#637, item 2): #: never "not started" — its first worker ran. NOT_REDISPATCHED = "crashed — not re-dispatched" @@ -245,8 +248,10 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False, elif url in out.get("issues", []): state = "PARKED-ON-ISSUE" elif url in out["merged"]: + # Which path each merge took (R3, #661): a close-out, or the + # worker in-turn after taking a merge slot. state = ("merged unattended (close-out, " + co.get("model", "?") + ")" - if co.get("state") == "merged" else "merged") + if co.get("state") == "merged" else IN_TURN_MERGED) if co.get("state") == "merged" and co.get("cleanup"): state += f" — worktree: {co['cleanup']}" elif co.get("state") == "refused": diff --git a/agents/conductors/batch/_merge_slots.py b/agents/conductors/batch/_merge_slots.py new file mode 100644 index 00000000..c3ee768e --- /dev/null +++ b/agents/conductors/batch/_merge_slots.py @@ -0,0 +1,163 @@ +"""One merge-slot counter per shift (PyAutoBrain#661, ruling R3 of 2026-11-17). + +Inside a shift every merge counts against the brief's `merge-cap:`: a worker's +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. + +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 +through a temporary file and `os.replace`, so two takes can never both see the +last free slot. The watcher publishes the cap (and whether the shift is paused) +every tick. It fails closed: no published cap, or a paused shift, refuses. + +A take is idempotent per PR: a PR that already holds a slot is told yes again, +so a close-out session's own `/prm` take for the PR the watcher took a slot +for succeeds. A release frees a slot only for the caller that took it. +""" + +from __future__ import annotations + +import contextlib +import datetime as _dt +import fcntl +import json +import os +import tempfile +from pathlib import Path + +SLOTS_FILE = "merge_slots.json" +LOCK_FILE = "merge_slots.lock" +#: Who the watcher is, as a slot holder. +WATCHER = "watcher" + + +class MergeSlotError(RuntimeError): + """The slot file cannot be read or written: the caller cannot tell.""" + + +def _now() -> str: + return _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _empty() -> dict: + return {"cap": None, "paused": False, "published": "", "slots": {}, + "refusals": [], "released": []} + + +@contextlib.contextmanager +def _locked(slot: Path): + """The slot file's contents under the exclusive lock; a changed dict is + written back atomically on exit.""" + slot = Path(slot) + if not slot.is_dir(): + raise MergeSlotError(f"no shift slot directory at {slot}") + with open(slot / LOCK_FILE, "a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + data = _read(slot) + before = json.dumps(data, sort_keys=True) + yield data + if json.dumps(data, sort_keys=True) != before: + _write(slot, data) + finally: + fcntl.flock(lock.fileno(), fcntl.LOCK_UN) + + +def _read(slot: Path) -> dict: + path = Path(slot) / SLOTS_FILE + if not path.exists(): + return _empty() + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as e: + raise MergeSlotError(f"unreadable {path}: {e}") from e + if not isinstance(data, dict): + raise MergeSlotError(f"unreadable {path}: not a JSON object") + out = _empty() + out.update(data) + return out + + +def _write(slot: Path, data: dict) -> None: + fd, tmp = tempfile.mkstemp(prefix=".merge_slots.", dir=str(slot)) + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + json.dump(data, fh, indent=1, sort_keys=True) + fh.write("\n") + os.replace(tmp, Path(slot) / SLOTS_FILE) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(tmp) + raise + + +def publish(slot: Path, cap: int, paused: bool) -> None: + """The watcher's word on this tick's cap and pause, for every take.""" + with _locked(slot) as data: + data["cap"], data["paused"] = int(cap), bool(paused) + if not data.get("published"): + data["published"] = _now() + + +def take(slot: Path, pr: str, by: str, task: str = "") -> tuple[bool, str]: + """(taken, why). Idempotent per PR; every refusal is recorded.""" + with _locked(slot) as data: + held = data["slots"].get(pr) + if held: + return True, f"{pr} already holds a merge slot (taken by {held.get('by', '?')})" + cap, used = data.get("cap"), len(data["slots"]) + if 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: + data["slots"][pr] = {"by": by, "task": task, "at": _now()} + return True, f"merge slot {used + 1} of merge-cap {cap} taken for {pr}" + data["refusals"].append({"pr": pr, "by": by, "task": task, "why": why, "at": _now()}) + return False, why + + +def release(slot: Path, pr: str, by: str, why: str = "") -> bool: + """Free `pr`'s slot, only when `by` took it. True when one was freed.""" + with _locked(slot) as data: + held = data["slots"].get(pr) + if not held or held.get("by") != by: + return False + del data["slots"][pr] + data["released"].append({"pr": pr, "by": by, "task": held.get("task", ""), + "why": why, "at": _now()}) + return True + + +def state(slot: Path) -> dict: + """The whole file, read under the lock (the CLI's `status`).""" + with _locked(slot) as data: + return json.loads(json.dumps(data)) + + +def used(slot: Path) -> int: + """Slots held now — every merge taken this shift, in-turn or close-out. + 0 when there is no slot file yet.""" + if not (Path(slot) / SLOTS_FILE).exists(): + return 0 + return len(state(slot)["slots"]) + + +def why_unmerged(slot: Path, pr: str) -> str: + """The last refusal or release recorded for `pr`, else "".""" + if not (Path(slot) / SLOTS_FILE).exists(): + return "" + data = state(slot) + seen = [("refused", r) for r in data["refusals"] if r.get("pr") == pr] \ + + [("released", r) for r in data["released"] if r.get("pr") == pr] + if not seen: + return "" + kind, last = max(seen, key=lambda kr: kr[1].get("at") or "") + if kind == "released": + return f"slot released by {last.get('by', '?')}: {last.get('why') or 'no reason given'}" + return last.get("why") or "" diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 24036029..8f1c41dc 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -50,6 +50,7 @@ import _brief # noqa: E402 import _digest # noqa: E402 import _events # noqa: E402 +import _merge_slots # noqa: E402 — one merge-cap count per shift (R3, #661) import _mind_writer # noqa: E402 import _questions # noqa: E402 @@ -2430,11 +2431,17 @@ def _cmd_cap(slot: Path, counters: dict, arg: str, who: str, at: str, ctx: dict) "brief": ceiling} of = f"{ceiling}" if ceiling is not None else "none" if key == "merge-cap": - merged = int(counters.get("glance_auto_merges") or 0) - running = sum(1 for co in counters["closeouts"].values() if co.get("state") == "running") - tail = (": no new close-out starts." if merged + running >= n - else f": up to {n - merged - running} more may start.") - return f"merge-cap now {n} of this brief's {of} ({merged} merged so far){tail}" + # Every slot taken this shift — in-turn merges, close-outs merged and + # close-outs still running alike (R3, #661). + try: + taken = _merge_slots.used(slot) + except (_merge_slots.MergeSlotError, OSError): + taken = None + if taken is None: + return f"merge-cap now {n} of this brief's {of} (merge slots unreadable)." + tail = (": no new merge starts." if taken >= n + else f": up to {n - taken} more may merge.") + return f"merge-cap now {n} of this brief's {of} ({taken} merge slot(s) taken so far){tail}" if key == "max-workers": live = len(active_leases(slot)) return f"max-workers now {n} of {of}." + ( @@ -3148,6 +3155,14 @@ def _closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.dateti pr_state = pr_state or getattr(spawner, "pr_state", 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 + # (ruling R3, #661). A shadow or paused shift publishes a pause: a + # worker's take is refused and the PR waits for /prm. + try: + _merge_slots.publish(slot, _brief._nonneg_int(brief.get("merge-cap", {}).get("value", "")) + or 0, _brief.is_shadow(brief) or bool(counters.get("paused"))) + 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 _start_closeouts(slot, brief, counters, spawner, now, health, events, @@ -3262,17 +3277,21 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta # 10): the close-out removes them as /prm does, or says why not. co["cleanup"] = str((verdict or {}).get("cleanup") or "").strip()[:300] \ or CLEANUP_UNREPORTED - counters["glance_auto_merges"] += 1 out = counters["outcomes"].setdefault(co["task"], {"prs": [pr], "merged": []}) if pr not in out["merged"]: out["merged"].append(pr) - _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, { - "op": "table-append", "path": STAGE2_LOG, "heading": STAGE2_HEADING, - # One row per PR and shift, even if a crash between this queue - # and the counters write below reaps the close-out twice (#632). - "unique": f"| {co['task']} ({pr}) | {slot.name} |", - "row": stage2_row(now, co["task"], pr, slot.name, co["gate"], co["model"], - merged_by=(gh or {}).get("mergedBy") or "")}) + tier = co.get("tier") or counters["picks"].get(co["task"], {}).get("tier", "?") + if tier == "glance": + # Only a `glance` close-out is a stage-2 row and an unattended + # `glance` merge; a `notify` one (ruling R3, #661) is neither. + counters["glance_auto_merges"] += 1 + _mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, { + "op": "table-append", "path": STAGE2_LOG, "heading": STAGE2_HEADING, + # One row per PR and shift, even if a crash between this queue + # and the counters write below reaps the close-out twice (#632). + "unique": f"| {co['task']} ({pr}) | {slot.name} |", + "row": stage2_row(now, co["task"], pr, slot.name, co["gate"], co["model"], + merged_by=(gh or {}).get("mergedBy") or "")}) retire = queue_retire_op(counters, co["task"], pr, now) if retire: # The close-out queues this with its complete record; this is @@ -3296,6 +3315,13 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta why = "the close-out session ended without a verdict" 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 if late: co["late"] = _iso(now) if co.get("agent_id") in counters["usage"]: @@ -3310,7 +3336,6 @@ def _start_closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt. """Start one close-out per newly green PR, under the watcher's guards.""" lease_dir = slot / "leases" health = health or _digest.pr_health - cap = _brief._nonneg_int(brief.get("merge-cap", {}).get("value", "")) or 0 budget = _brief._nonneg_int(brief.get("token-budget", {}).get("value", "")) for task, out in counters["outcomes"].items(): for pr in out["prs"]: @@ -3322,9 +3347,12 @@ def _start_closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt. "why": "dropped by /drop — the human's /prm"} events["refused"].append(pr) continue - if tier != "glance": + if tier not in ("glance", "notify"): + # Ruling R3 (2026-11-17, #661): a `notify` PR a worker left + # open is closed out on the same terms as a `glance` one. counters["closeouts"][pr] = {"task": task, "state": "refused", - "why": f"tier {tier} — only glance merges unattended"} + "why": f"tier {tier} — never merged unattended " + "→ your /prm"} events["refused"].append(pr) continue verdict = health(pr) @@ -3335,14 +3363,6 @@ def _start_closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt. "why": f"CI {verdict} — never merged unattended"} events["refused"].append(pr) continue - in_flight = sum(1 for c in counters["closeouts"].values() if c["state"] == "running") - if counters["glance_auto_merges"] + in_flight >= cap: - # Final for this shift, like every refusal: the PR waits for a - # human `/prm`, and the digest says why. - counters["closeouts"][pr] = {"task": task, "state": "refused", - "why": f"merge-cap {cap} reached this shift"} - events["refused"].append(pr) - continue if review_at is not None \ and (review_at - now).total_seconds() < CLOSEOUT_CUTOFF_S: # A close-out runs ~10-20 min; one still out at review-at @@ -3372,14 +3392,31 @@ def _start_closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt. f"{CLOSEOUT_BUDGET_FACTOR}× token-budget {budget}"} events["refused"].append(pr) continue + # One merge-slot count for the shift (R3, #661): a worker's in-turn + # merge and a close-out take from it alike. Taken last, just + # before the spawn, so no other refusal holds a slot. + try: + taken, why = _merge_slots.take(slot, pr, _merge_slots.WATCHER, task) + except (_merge_slots.MergeSlotError, OSError) as e: + taken, why = False, f"merge slot cannot tell ({str(e)[:200]}) — left for your /prm" + if not taken: + # Final for this shift, like every refusal: the PR waits for a + # human `/prm`, and the digest says why. + counters["closeouts"][pr] = {"task": task, "state": "refused", "why": why} + events["refused"].append(pr) + continue prompt = counters["picks"].get(task, {}).get("prompt", "") - co = {"task": task, "state": "running", "started": _iso(now)} + co = {"task": task, "state": "running", "started": _iso(now), "tier": tier} try: co.update(spawner.spawn_closeout(task, pr, prompt, lease_dir)) except Exception as e: counters["closeouts"][pr] = {"task": task, "state": "refused", "why": f"the close-out could not start: {str(e)[:300]}"} events["refused"].append(pr) + try: + _merge_slots.release(slot, pr, _merge_slots.WATCHER, "the close-out could not start") + except (_merge_slots.MergeSlotError, OSError): + pass _write_counters(slot, counters) continue counters["closeouts"][pr] = co diff --git a/agents/conductors/batch/closeout_template.md b/agents/conductors/batch/closeout_template.md index c4d53433..93eababa 100644 --- a/agents/conductors/batch/closeout_template.md +++ b/agents/conductors/batch/closeout_template.md @@ -3,10 +3,11 @@ launched by writing a shift brief: {brief_path} The PR: {pr_url} -Its task: {task_path} (declared `Consequence: glance`) +Its task: {task_path} (declared `Consequence: glance` or `notify`) You are the **independent session** AUTONOMY.md "Unattended `glance` merges" -requires: you did not write this PR, and you trust nothing its author claimed. +requires (for a `notify` PR a worker left open, ruling R3 of 2026-11-17 closes +it out on the same terms): you did not write this PR, and you trust nothing its author claimed. Merge only if every check below passes; otherwise refuse. A refusal is a good outcome — the human merges by `/prm` at check-in. @@ -25,7 +26,7 @@ outcome — the human merges by `/prm` at check-in. 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 unless Heart's **scoped development-ship verdict** for the + `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): {heart_cmd} @@ -61,7 +62,9 @@ outcome — the human merges by `/prm` at check-in. {shift_ledger} queue-retire queue.md --text "{pr_url} → ()" Do **not** append the Shadow-window row: the watcher writes the stage-2 - row from your verdict. + row from your verdict for a `glance` PR, and none for a `notify` one. + The `/prm` merge slot take (reference.md "Tiered merge") succeeds for + this PR: the watcher took its slot before starting you. 7. 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 diff --git a/agents/conductors/batch/worker_template.md b/agents/conductors/batch/worker_template.md index a4dde44f..766caedb 100644 --- a/agents/conductors/batch/worker_template.md +++ b/agents/conductors/batch/worker_template.md @@ -48,7 +48,11 @@ The terms of this shift (AUTONOMY.md "Shift briefs and unattended `glance`"): - If the task is `Consequence: glance`, 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 merges, or refuses (AUTONOMY.md - "Unattended `glance` merges"). A `notify` task merges in-turn as usual. + "Unattended `glance` merges"). A `notify` task merges in-turn only after + `{brain_cli} merge-slot take ` exits 0, run as its own bare call just + before a bare `gh pr merge` (ruling R3, AUTONOMY.md "`notify` merges under + `--auto` and inside a shift — 2026-11-17"). If it refuses, do not merge: + list the PR in your `.done` without `merged`, and it is left for `/prm`. - Never commit to PyAutoMind yourself — a hook refuses it. Queue each Mind change with `{shift_ledger} append|write|move|remove|drop-section ...` (ops land in {ledger_dir}/) and the orchestrator commits them. This covers diff --git a/agents/faculties/sizing/_sizing.py b/agents/faculties/sizing/_sizing.py index eb478a5e..61c4e196 100755 --- a/agents/faculties/sizing/_sizing.py +++ b/agents/faculties/sizing/_sizing.py @@ -1097,6 +1097,45 @@ def effective_autonomy(p: dict, difficulty: str): return level, cap, declared +#: The merge modes `merge_mode` can return (AUTONOMY.md "Merge authority +#: follows Consequence — 2026-10-02" and its ruling R3 of 2026-11-17). +MERGE_HUMAN = "human /prm" +MERGE_ON_GREEN = "auto-merge on green" +MERGE_ON_GREEN_WITNESS = "auto-merge on green if the Witness passes" +#: Appended inside a shift: every merge first takes a slot against `merge-cap:`. +MERGE_SLOT_SUFFIX = " after a merge slot" + + +def merge_mode(p: dict, level: str, *, auto: bool = False, in_shift: bool = False) -> str: + """Who merges this task, in the words `start_dev` step 3 prints. + + The merge mode follows the DECLARED `Consequence:` alone (a tier the + sizing faculty would infer never carries merge authority): `judge` or no + header is a human `/prm`; `glance` auto-merges on green only if the + `Witness:` passes; `notify` auto-merges on green. The effective `level` + decides the checkpoints, not who merges — except, under ruling R3, that a + `notify` task whose work-type cap lowered its level, run under `--auto`, + merges only when it declares a `Witness:`, else it is a human `/prm`. A + shift is an `--auto` launch, and inside one the merge waits for a merge + slot (`pyauto-brain merge-slot take`). + """ + tier = p.get("declared_consequence") + witness = bool((p.get("witness") or "").strip()) + if tier == "notify": + declared = p.get("declared_autonomy") + lowered = bool(declared) and level != declared + if (auto or in_shift) and lowered and not witness: + return MERGE_HUMAN + mode = MERGE_ON_GREEN + elif tier == "glance": + if not witness: + return MERGE_HUMAN + mode = MERGE_ON_GREEN_WITNESS + else: + return MERGE_HUMAN + return mode + (MERGE_SLOT_SUFFIX if in_shift else "") + + def effective_difficulty(p: dict): """(level, score, factors, derived_level) — the DECLARED level wins. diff --git a/bin/README.md b/bin/README.md index 155cedad..1ec5a8a8 100644 --- a/bin/README.md +++ b/bin/README.md @@ -26,6 +26,15 @@ Executable tooling for the PyAuto organism. watcher refuses on 1 or 2 before any close-out session spawns, the close-out and the in-turn tiered merge stop on them too, and the review faculty lists the delta in its ReviewSurface. +- **`merge_slot.py`** — `pyauto-brain merge-slot take|release|status `: + inside a shift, one merge slot against the brief's `merge-cap:` + (PyAutoBrain#661; AUTONOMY.md ruling R3, 2026-11-17). A worker runs `take` + as its own bare call before a bare `gh pr merge`; the watcher's close-outs + take from the same file-locked count. Exit 0 taken (or not a shift) · 1 + refused · 2 cannot tell. +- **`merge_mode.py`** — `pyauto-brain merge-mode [--auto] + [--in-shift]`: prints `effective level: ; merge mode: `, the + line `start_dev` step 3 puts in the plan. Read-only. - **`lane_backfill.py`** — proposes a `Lane:` for every lane-less draft in the planner pool, from intake's own lane signals, as a table for a human to skim; `--apply [--from ]` writes the headers (commits nothing). diff --git a/bin/merge_mode.py b/bin/merge_mode.py new file mode 100644 index 00000000..374f239f --- /dev/null +++ b/bin/merge_mode.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""bin/merge_mode.py — one prompt's effective level and merge mode, one line +(PyAutoBrain#661). + + pyauto-brain merge-mode [--auto] [--in-shift] [--mind ] + +prints exactly + + effective level: ; merge mode: + +WHY. Shift 2026-11-16-pm: two workers on the same `bug · safe · notify` +header did opposite things — one stopped at decide-and-flag because the `bug` +cap lowered it to `supervised`, the other merged in-turn. `start_dev` step 3 +prints this line before work starts, so a worker and a reader see the same +answer. The level is `_sizing.effective_autonomy` (`min(header, cap)`); the +mode is `_sizing.merge_mode` (AUTONOMY.md "Merge authority follows +Consequence — 2026-10-02" and ruling R3 of 2026-11-17). Read-only. + +`--auto` is an explicit `--auto` launch; `--in-shift` a shift worker (a shift +is an `--auto` launch, and its merges first take a merge slot). +""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +SIZING = Path(__file__).resolve().parents[1] / "agents" / "faculties" / "sizing" +sys.path.insert(0, str(SIZING)) +import _sizing # noqa: E402 + + +def _mind_of(prompt: Path) -> Path: + """The Mind root the prompt sits in (the folder above its `draft/` or + `active/`), else the sibling checkout `pyauto-brain sizing` reads.""" + for parent in prompt.parents: + if parent.name in ("draft", "active"): + return parent.parent + return _sizing.BODY_MAP_PATH.parent + + +def line(prompt: Path, *, auto: bool = False, in_shift: bool = False, + mind: Path | None = None) -> str: + prompt = Path(prompt).resolve() + p = _sizing.parse_prompt(prompt, (mind or _mind_of(prompt)).resolve()) + difficulty = _sizing.effective_difficulty(p)[0] + level = _sizing.effective_autonomy(p, difficulty)[0] + mode = _sizing.merge_mode(p, level, auto=auto, in_shift=in_shift) + return f"effective level: {level}; merge mode: {mode}" + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(prog="pyauto-brain merge-mode", + description="One prompt's effective level and merge mode.") + ap.add_argument("prompt", help="path to a PyAutoMind prompt (.md)") + ap.add_argument("--auto", action="store_true", help="an explicit --auto launch") + ap.add_argument("--in-shift", action="store_true", dest="in_shift", + help="a shift worker: merges first take a merge slot") + ap.add_argument("--mind", type=Path, default=None, help="PyAutoMind root") + args = ap.parse_args(argv) + if not Path(args.prompt).is_file(): + print(f"merge-mode: no prompt file at {args.prompt}", file=sys.stderr) + return 2 + print(line(Path(args.prompt), auto=args.auto, in_shift=args.in_shift, mind=args.mind)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bin/merge_slot.py b/bin/merge_slot.py new file mode 100644 index 00000000..904438d3 --- /dev/null +++ b/bin/merge_slot.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""bin/merge_slot.py — take, release or show a shift's merge slot (PyAutoBrain#661). + + pyauto-brain merge-slot take + pyauto-brain merge-slot release [--why ] + pyauto-brain merge-slot status [] + +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 +`merge-cap:`. A worker runs `take` as its own bare call, then — only on exit 0 — +a bare `gh pr merge`. This never wraps the merge: the permission layer must +still see exactly one `gh pr merge` call. + +WHERE. A shift worker's environment carries `PYAUTO_SHIFT_WORKER=1` and +`PYAUTO_SHIFT_LEDGER_DIR` (`_orchestrator.worker_env`); the shift's slot +directory is that ledger directory's parent, and the counter is its +`merge_slots.json` (`agents/conductors/batch/_merge_slots.py`). + +EXIT. 0 = the slot is taken (or already held for this PR), or this is not a +shift, so nothing is counted; 1 = refused (no slot left, the shift is paused, +or no cap published) — do not merge, leave the PR for `/prm`; 2 = cannot tell +(the slot directory or its file cannot be read) — do not merge either. +`release` exits 0 when it freed this caller's slot, 1 when there was none to +free. `status` prints the count and exits 0. +""" + +from __future__ import annotations + +import argparse +import os +import sys +from pathlib import Path + +BATCH = Path(__file__).resolve().parents[1] / "agents" / "conductors" / "batch" +sys.path.insert(0, str(BATCH)) +import _merge_slots # noqa: E402 + +#: 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" + + +def _slot() -> Path | None: + """The shift slot directory, or None outside a shift.""" + ledger = os.environ.get("PYAUTO_SHIFT_LEDGER_DIR", "").strip() + if not os.environ.get("PYAUTO_SHIFT_WORKER") or not ledger: + return None + return Path(ledger).parent + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(prog="pyauto-brain merge-slot", + description="A shift's merge slot (AUTONOMY.md ruling R3).") + ap.add_argument("action", choices=("take", "release", "status")) + ap.add_argument("pr", nargs="?", default="", help="the PR URL") + ap.add_argument("--task", default="", help="the task slug, recorded with the slot") + ap.add_argument("--why", default="", help="release: why the slot is freed") + args = ap.parse_args(argv) + if args.action in ("take", "release") and not args.pr: + ap.error(f"{args.action} needs a PR URL") + + slot = _slot() + if slot is None: + print("not in a shift (no PYAUTO_SHIFT_WORKER / PYAUTO_SHIFT_LEDGER_DIR): " + "no merge slot is counted") + return 0 + task = args.task or os.environ.get("PYAUTO_SHIFT_TASK", "") + try: + if args.action == "take": + ok, why = _merge_slots.take(slot, args.pr, WORKER, task) + print(("taken: " if ok else "refused: ") + why) + return 0 if ok else 1 + if args.action == "release": + freed = _merge_slots.release(slot, args.pr, WORKER, args.why) + print(f"released {args.pr}" if freed + else f"no merge slot of yours held for {args.pr}") + return 0 if freed else 1 + data = _merge_slots.state(slot) + cap = data.get("cap") + line = (f"{len(data['slots'])} of merge-cap {cap if cap is not None else '(none published)'}" + + (" — paused" if data.get("paused") else "")) + print(line) + if args.pr: + held = data["slots"].get(args.pr) + print(f"{args.pr}: " + (f"held by {held.get('by', '?')}" if held + else _merge_slots.why_unmerged(slot, args.pr) + or "no slot, no refusal recorded")) + return 0 + except (_merge_slots.MergeSlotError, OSError) as e: + print(f"cannot tell: {e} — do not merge; leave the PR for /prm") + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bin/pyauto-brain b/bin/pyauto-brain index 796c57c2..c97e4808 100755 --- a/bin/pyauto-brain +++ b/bin/pyauto-brain @@ -47,6 +47,13 @@ # pyauto-brain public-names # | --repo --range a..b [--json] # (tool) read-only: does a change add or rename a public # library name? CLEAN/HIT/CANNOT-TELL (bin/public_names.py) +# pyauto-brain merge-slot take|release|status +# (tool) inside a shift, a merge slot against `merge-cap:` +# before a bare `gh pr merge` — 0 taken / not a shift, 1 refused, +# 2 cannot tell (bin/merge_slot.py; AUTONOMY.md ruling R3) +# pyauto-brain merge-mode [--auto] [--in-shift] +# (tool) read-only: `effective level: ; merge mode: +# ` for one prompt (bin/merge_mode.py; start_dev step 3) # pyauto-brain help [name] list agents or show one agent's docs # # Renamed from `pyauto-agent`; the former back-compat shim has been removed now @@ -172,6 +179,8 @@ EOF echo "Tools (read-only helpers the merge paths share):" echo " ci-verdict # [--json] — one PR's CI: GREEN, PENDING or RED, with reasons" echo " public-names # [--json] — a public library name added or renamed: a human /prm" + echo " merge-slot take|release|status — 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" echo echo "Run 'pyauto-brain help ' for that agent's full docs." } @@ -223,6 +232,12 @@ main() { if [[ "$sub" == "public-names" ]]; then exec python3 "$BRAIN_HOME/bin/public_names.py" "$@" fi + if [[ "$sub" == "merge-slot" ]]; then + exec python3 "$BRAIN_HOME/bin/merge_slot.py" "$@" + fi + if [[ "$sub" == "merge-mode" ]]; then + exec python3 "$BRAIN_HOME/bin/merge_mode.py" "$@" + fi local script="${AGENT_SCRIPT[$sub]:-}" if [[ -z "$script" || ! -f "$script" ]]; then echo "pyauto-brain: unknown agent '$sub'" >&2 diff --git a/skills/prm/reference.md b/skills/prm/reference.md index a3200adb..93ad11db 100644 --- a/skills/prm/reference.md +++ b/skills/prm/reference.md @@ -127,7 +127,7 @@ Since 2026-10-02 a PR may also reach this procedure **without** a human typing witnessed-`glance` task here after PR-open, under the merge authorization the approved plan (or `--auto` / batch launch) stated. The rule is [`../../AUTONOMY.md`](../../AUTONOMY.md) "Merge authority follows Consequence — -2026-10-02"; this procedure runs from step 2 exactly as written, with three +2026-10-02"; this procedure runs from step 2 exactly as written, with these differences: - **The wait (step 3).** One background `gh pr checks --watch`, capped @@ -150,6 +150,18 @@ differences: refuses: report its first line and stop; the human runs `/prm` (`AUTONOMY.md` "Public-name narrowing of `glance` — 2026-11-16"). A repo outside the five libraries prints CLEAN, exit 0. +- **R3 witness condition (step 4).** A `notify` task whose work-type cap + lowered its level (`bug · safe` runs `supervised`) merges under `--auto` + only with its `Witness:` held; with none declared, stop — the human runs + `/prm`. `pyauto-brain merge-mode --auto` says which (AUTONOMY.md + "`notify` merges under `--auto` and inside a shift — 2026-11-17"). +- **Inside a shift, a merge slot first.** When `PYAUTO_SHIFT_WORKER` is set, + run `pyauto-brain merge-slot take ` as its **own bare call** right + before the merge call. Exit 0 → merge. Exit 1 (no slot left under + `merge-cap:`, or the shift is paused) 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 succeeds: the watcher took + that slot. - **The merge call.** `gh pr merge --merge` as a **bare, unchained** Bash call (no `&&`, `;` or pipe); if the permission layer denies it, stop and report — never retry it another way. For `glance`, the close-out appends the diff --git a/skills/ship_library/ship_library.md b/skills/ship_library/ship_library.md index fcec2206..f1cacbf3 100644 --- a/skills/ship_library/ship_library.md +++ b/skills/ship_library/ship_library.md @@ -151,6 +151,8 @@ Who merges follows the prompt's **declared** `Consequence:` header — [`/prm`](../prm/prm.md) procedure from its step 2 — judge, merge, close-out — exactly as a human-typed `/prm` would. For `glance`, the close-out appends the Shadow-window row and the ledger ends with the post-merge summary. + Inside a shift the merge first takes a merge slot, and the R3 witness + condition applies (`/prm` reference.md "Tiered merge"). When step 5 routed the task to `/start_workspace` (options i / ii), merge the library PR but **run no close-out** — the task stays open as `library-shipped, workspace-pending`, and the close-out runs at the workspace diff --git a/skills/ship_workspace/ship_workspace.md b/skills/ship_workspace/ship_workspace.md index b0139e70..c4759dc3 100644 --- a/skills/ship_workspace/ship_workspace.md +++ b/skills/ship_workspace/ship_workspace.md @@ -113,6 +113,8 @@ Who merges follows the prompt's **declared** `Consequence:` header — exactly as a human-typed `/prm` would — the library-first gate included (a workspace PR whose library PR is not `MERGED` stops there). For `glance`, the close-out appends the Shadow-window row and the ledger ends with the post-merge summary. + Inside a shift the merge first takes a merge slot, and the R3 witness + condition applies (`/prm` reference.md "Tiered merge"). - **`judge`, no declared header**, a `decision-taken` PR, a Heart RED-override or corrective-PR-exception ship, a public name added or renamed (`pyauto-brain public-names` exit 1 or 2), or any red / pending-at-cap / conflicting / diff --git a/skills/start_dev/reference.md b/skills/start_dev/reference.md index d8041aee..14a3c9c9 100644 --- a/skills/start_dev/reference.md +++ b/skills/start_dev/reference.md @@ -240,7 +240,10 @@ Only when the human launches with an explicit `--auto` (never ambient — the activation rule in [`../../AUTONOMY.md`](../../AUTONOMY.md)): 1. Compute the **effective level** = min(prompt `Autonomy:` header, work-type - cap from the contract); missing header → `human-required`. + cap from the contract); missing header → `human-required`. Run + `pyauto-brain merge-mode --auto` (`--in-shift` too in a shift + worker) and put its one line, `effective level: ; merge mode: + `, on the issue with the plan. 2. **`safe`** → skip the Plan-Mode hold: write both plan levels into the issue (step 5 below) and proceed straight through steps 4–7 and into `start_library`/`start_workspace` and implementation. The plan the human @@ -249,7 +252,12 @@ activation rule in [`../../AUTONOMY.md`](../../AUTONOMY.md)): decide-and-flag ([`../../AUTONOMY.md`](../../AUTONOMY.md), "Decide-and-flag") — ship through the autonomous-ship gate, flag the decision in the PR body, and **end at PR-open** (a `decision-taken` PR is - never auto-merged, whatever its tier). Every + never auto-merged, whatever its tier). Label the PR `decision-taken` only + when a decision was actually taken. A `notify` task whose cap lowered it to + `supervised`, with its `Witness:` held and no decision taken, goes on to the + tiered merge (ruling R3, AUTONOMY.md "`notify` merges under `--auto` and + inside a shift — 2026-11-17"); with no `Witness:` declared it ends at + PR-open for `/prm`. Every *other* judgment gate — a scope/design fork the plan didn't settle, a second flagged decision, a hard blocker — still becomes a batched issue question with an `awaiting-input` park (the contract's "Checkpoint-and-continue" diff --git a/skills/start_dev/start_dev.md b/skills/start_dev/start_dev.md index 750ec0e9..9fc90666 100644 --- a/skills/start_dev/start_dev.md +++ b/skills/start_dev/start_dev.md @@ -103,6 +103,12 @@ Tier: glance — merge mode: auto-merge on green if the Witness passes, post-mer Tier: judge (or undeclared) — merge mode: human /prm ``` +Produce the mode with `pyauto-brain merge-mode ` (add `--auto` under +`--auto`, `--in-shift` in a shift worker). It prints one line, `effective +level: ; merge mode: `. Put that line in the plan before work +starts, so a worker and a reader see the same answer (ruling R3, AUTONOMY.md +"`notify` merges under `--auto` and inside a shift — 2026-11-17"). + **Approving the plan authorizes that merge mode**; a plan without the line authorizes no merge. An epic's approval chains auto-merged phases without re-asking, stopping at a `judge` phase, a failure, Heart RED or unnamed scope. diff --git a/tests/test_closeout_merge_slots.py b/tests/test_closeout_merge_slots.py new file mode 100644 index 00000000..b8b38f32 --- /dev/null +++ b/tests/test_closeout_merge_slots.py @@ -0,0 +1,180 @@ +"""M3.6e (PyAutoBrain#661): every in-shift merge takes a merge slot. + +Shift 2026-11-16-pm read "2 merged of merge-cap 1": two workers merged their +`notify` PRs in-turn without asking the watcher, whose `merge-cap:` counted +only its own close-outs. Ruling R3 (AUTONOMY.md, 2026-11-17): a worker takes a +slot with `pyauto-brain merge-slot take ` before its bare `gh pr merge`, +and the watcher's close-outs take from the same count. + +These tests drive the real CLI (`bin/pyauto-brain merge-slot`) with a fake +`gh` on PATH that logs its argv, so a merge that should not happen is seen. +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +from pathlib import Path + +BRAIN = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN / "tests")) +import test_orchestrator_closeout as tc # noqa: E402 — the 4b close-out fixtures +import test_orchestrator_digest as t # noqa: E402 — the 3d fixtures +from test_orchestrator_digest import orch # noqa: E402 +import _mind_writer as mw # noqa: E402 + +CLI = BRAIN / "bin" / "pyauto-brain" +PR1, PR2 = tc.PR1, tc.PR2 + + +def _fake_gh(tmp_path: Path) -> tuple[Path, Path]: + """A `gh` that logs one line of argv per call and succeeds.""" + bindir = tmp_path / "fakebin" + bindir.mkdir(exist_ok=True) + log = tmp_path / "gh.log" + gh = bindir / "gh" + gh.write_text(f'#!/usr/bin/env bash\necho "$*" >> "{log}"\n') + gh.chmod(0o755) + return bindir, log + + +def _shift_env(slot: Path, bindir: Path | None = None) -> dict: + """What `worker_env` gives a worker, as far as the merge slot reads it.""" + env = dict(os.environ) + env.pop("CLAUDE_CODE_REMOTE", None) + env.update({"PYAUTO_SHIFT_WORKER": "1", + "PYAUTO_SHIFT_LEDGER_DIR": str(slot / mw.LEDGER_DIR)}) + if bindir is not None: + env["PATH"] = f"{bindir}{os.pathsep}{env.get('PATH', '')}" + return env + + +def _slot_cli(slot: Path, *args) -> subprocess.CompletedProcess: + return subprocess.run([str(CLI), "merge-slot", *args], env=_shift_env(slot), + capture_output=True, text=True, timeout=60) + + +def _merges(log: Path) -> list[str]: + if not log.exists(): + return [] + return [ln for ln in log.read_text().splitlines() if ln.startswith("pr merge")] + + +class InTurnMerger(tc.Spawner): + """Workers that merge in-turn, as a `notify` worker does: a merge slot + first, as its own call, then a bare `gh pr merge` only if it was taken; + a refused worker lists its PR without `merged`.""" + + def __init__(self, bindir: Path, prs: dict[str, str]): + super().__init__() + self.bindir, self.prs = bindir, prs + + def spawn(self, task, prompt_path, lease_dir): + lease_dir = Path(lease_dir) + lease_dir.mkdir(parents=True, exist_ok=True) + pr = self.prs[task] + script = (f'if "{CLI}" merge-slot take "{pr}"; then\n' + f' gh pr merge "{pr}" --squash\n' + f' echo "merged {pr}" > "{lease_dir}/{task}.done"\n' + f'else\n' + f' echo "{pr}" > "{lease_dir}/{task}.done"\n' + f'fi\n') + subprocess.run(["bash", "-c", script], env=_shift_env(lease_dir.parent, self.bindir), + capture_output=True, text=True, timeout=60) + return {"pid": 0, "session_id": None, "worktree": None} + + +def test_merge_cap_1_refuses_second_in_turn_notify_merge(tmp_path): + bindir, log = _fake_gh(tmp_path) + mind = t._mind(tmp_path / "mind") + for name in ("named", "picked"): + f = mind / "draft" / "feature" / "pyautoheart" / f"{name}.md" + f.write_text(f.read_text().replace("Consequence: glance", "Consequence: notify")) + brief = tmp_path / "shift.md" + brief.write_text(t.BRIEF.format(issue=t.ISSUE, packet="")) # merge-cap: 1 + home = tmp_path / "home" + sp = InTurnMerger(bindir, {"named": PR1, "picked": PR2}) + r = orch.tick(brief, mind, home=home, now=t.NOW, spawner=sp, agents=tc.Agents(), + health=tc._health({})) + assert sorted(s["task"] for s in r["spawned"]) == ["named", "picked"], r + tc._tick(brief, mind, home, sp, 1) # reaps both workers; the watcher looks + slot = orch.slot_dir(brief, home) + c = orch.read_counters(slot) + + assert len(_merges(log)) == 1, _merges(log) # one merge, not two + merged = [task for task, o in c["outcomes"].items() if o.get("merged")] + assert len(merged) == 1 + left = PR2 if merged == ["named"] else PR1 + # The left PR is `notify`: the watcher no longer calls it "only glance", + # it is refused for the cap and left for the human's /prm. + co = c["closeouts"][left] + assert co["state"] == "refused", co + assert "merge-cap 1" in co["why"] and "/prm" in co["why"], co["why"] + assert sp.closeouts == [] # no session started + st = _slot_cli(slot, "status") + assert st.returncode == 0 and "1 of merge-cap 1" in st.stdout, st.stdout + + +def test_take_is_atomic_across_processes(tmp_path): + slot = tmp_path / "slot" + (slot / mw.LEDGER_DIR).mkdir(parents=True) + sys.path.insert(0, str(BRAIN / "agents" / "conductors" / "batch")) + import _merge_slots + _merge_slots.publish(slot, 3, False) + procs = [subprocess.Popen([str(CLI), "merge-slot", "take", f"https://github.com/o/r/pull/{i}"], + env=_shift_env(slot), stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True) + for i in range(10)] + codes = [p.wait(timeout=60) for p in procs] + assert sorted(codes) == [0, 0, 0] + [1] * 7, codes + assert _merge_slots.used(slot) == 3 + data = json.loads((slot / _merge_slots.SLOTS_FILE).read_text()) + assert len(data["slots"]) == 3 and len(data["refusals"]) == 7 + + +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. + 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).returncode == 1 + # The close-out session's own /prm take for its PR is the watcher's slot. + assert _slot_cli(slot, "take", PR1).returncode == 0 + # A worker cannot free the watcher's slot. + _slot_cli(slot, "release", PR1) + assert _slot_cli(slot, "take", PR2).returncode == 1 + # The close-out refuses: the watcher frees its slot, and the worker 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" + assert _slot_cli(slot, "take", PR2).returncode == 0 + st = _slot_cli(slot, "status", PR1) + assert "witness failed" in st.stdout or "released" in st.stdout, st.stdout + + +def test_outside_a_shift_the_take_is_a_no_op(tmp_path): + env = dict(os.environ) + for k in ("PYAUTO_SHIFT_WORKER", "PYAUTO_SHIFT_LEDGER_DIR", "CLAUDE_CODE_REMOTE"): + env.pop(k, None) + r = subprocess.run([str(CLI), "merge-slot", "take", PR1], env=env, + capture_output=True, text=True, timeout=60) + assert r.returncode == 0 and "not in a shift" in r.stdout + + +def test_no_published_cap_or_a_pause_fails_closed(tmp_path): + slot = tmp_path / "slot" + (slot / mw.LEDGER_DIR).mkdir(parents=True) + r = _slot_cli(slot, "take", PR1) + assert r.returncode == 1 and "no merge-cap" in r.stdout + sys.path.insert(0, str(BRAIN / "agents" / "conductors" / "batch")) + import _merge_slots + _merge_slots.publish(slot, 2, True) + r = _slot_cli(slot, "take", PR1) + assert r.returncode == 1 and "paused" in r.stdout + gone = tmp_path / "nowhere" + r = _slot_cli(gone, "take", PR1) + assert r.returncode == 2 diff --git a/tests/test_orchestrator_closeout.py b/tests/test_orchestrator_closeout.py index 52e0c420..5c53e3fb 100644 --- a/tests/test_orchestrator_closeout.py +++ b/tests/test_orchestrator_closeout.py @@ -115,16 +115,39 @@ def test_a_merged_verdict_counts_and_queues_one_stage2_row(tmp_path): # --- each guard failing on its own → nothing started, the reason digested ------- -def test_a_non_glance_task_is_never_closed_out(tmp_path): +def test_a_notify_pr_left_open_is_closed_out_like_glance(tmp_path): + """Ruling R3 (AUTONOMY.md, 2026-11-17, #661): the watcher closes out a + `notify` PR a worker left open on the same terms as a `glance` one — and + its merge is no stage-2 row and no unattended `glance` merge.""" mind, brief, home, sp = _shift(tmp_path, cap=2) slot = orch.slot_dir(brief, home) c = orch.read_counters(slot) c["picks"]["named"]["tier"] = "notify" orch._write_counters(slot, c) _tick(brief, mind, home, sp, 1) + assert ("named", PR1) in sp.closeouts + _verdict(home, brief, "named", result="merged", pr=PR1, gate="witness PASS", + model="claude-opus-5-5") + r = _tick(brief, mind, home, sp, 2) + assert r["closeouts"]["merged"] == [PR1] + c = orch.read_counters(slot) + assert c["outcomes"]["named"]["merged"] == [PR1] + assert c["glance_auto_merges"] == 0 + assert _stage2_rows(slot) == [] + + +@pytest.mark.parametrize("tier", ["judge", "?"]) +def test_a_judge_or_undeclared_task_is_never_closed_out(tier, tmp_path): + mind, brief, home, sp = _shift(tmp_path, cap=2) + slot = orch.slot_dir(brief, home) + c = orch.read_counters(slot) + c["picks"]["named"]["tier"] = tier + orch._write_counters(slot, c) + _tick(brief, mind, home, sp, 1) assert ("named", PR1) not in sp.closeouts co = orch.read_counters(slot)["closeouts"][PR1] - assert co["state"] == "refused" and "only glance merges unattended" in co["why"] + assert co["state"] == "refused" + assert "never merged unattended → your /prm" in co["why"], co["why"] def test_witness_343_a_pr_with_zero_completed_checks_is_refused_at_merge(tmp_path): @@ -165,7 +188,7 @@ def test_merge_cap_counts_merges_and_in_flight_closeouts(tmp_path): assert len(r["closeouts"]["started"]) == 1 and len(r["closeouts"]["refused"]) == 1 c = orch.read_counters(orch.slot_dir(brief, home)) refused = [co for co in c["closeouts"].values() if co["state"] == "refused"] - assert refused[0]["why"] == "merge-cap 1 reached this shift" + assert refused[0]["why"] == "merge-cap 1 reached this shift — left for your /prm" def test_merge_cap_zero_starts_nothing(tmp_path): diff --git a/tests/test_orchestrator_digest.py b/tests/test_orchestrator_digest.py index 90429fc2..a3938a81 100644 --- a/tests/test_orchestrator_digest.py +++ b/tests/test_orchestrator_digest.py @@ -177,7 +177,8 @@ def test_digest_separates_brief_work_from_backlog_picks_with_reasons(tmp_path): # Each task: the outcome in plain words and the title, linked to its PR # (never to a Mind path, which moves and 404s, #634); the detail below. assert ("- **Merged** — [named](https://github.com/o/r/pull/1)\n" - " `named` · glance · small · pyautoheart · merged") in work + " `named` · glance · small · pyautoheart · merged in-turn by the worker" + " (merge slot)") in work assert "- **Not started** — never\n `never` · not started" in work assert "blob/main" not in d # Green and glance: since phase 4b its close-out is running at review time. diff --git a/tests/test_orchestrator_merge_slots.py b/tests/test_orchestrator_merge_slots.py new file mode 100644 index 00000000..67c439cf --- /dev/null +++ b/tests/test_orchestrator_merge_slots.py @@ -0,0 +1,146 @@ +"""M3.6e (PyAutoBrain#661), ruling R3 (AUTONOMY.md, 2026-11-17). + +A `bug · safe · notify` task with a held `Witness:` merges in-turn under +`--auto`: the `bug` cap lowers its level to `supervised`, and the level +decides the checkpoints, not who merges. Inside a shift that merge takes a +merge slot, so the snapshot counts it against `merge-cap:`. `start_dev` prints +the effective level and merge mode in one line, from `pyauto-brain merge-mode`, +so a worker and a reader see the same answer. +""" + +from __future__ import annotations + +import subprocess +import sys +from pathlib import Path + +BRAIN = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN / "tests")) +import test_closeout_merge_slots as ms # noqa: E402 — fake gh, shift env +import test_orchestrator_closeout as tc # noqa: E402 +import test_orchestrator_digest as t # noqa: E402 +from test_orchestrator_digest import orch # noqa: E402 +import _watch # noqa: E402 + +CLI = BRAIN / "bin" / "pyauto-brain" +PR = "https://github.com/o/r/pull/7" + +BUG = """\ +# Fix the thing + +Type: bug +Target: PyAutoHeart +Repos: +- PyAutoHeart +Difficulty: small +Autonomy: {autonomy} +Priority: normal +Status: formalised +Consequence: {tier} +{witness}Review-minutes: 0 +Unattended: ready +Lane: any + +Body. +""" + +BRIEF = """\ +# Batch 2026-11-04 am +- dispatched: 2026-11-04T08:30Z +- review-at: 2026-11-04T11:30Z +- issue: {issue} +- brief: + - goals: + - 1. one bug + - tasks: + - draft/bug/pyautoheart/fix_thing.md + - backlog: none + - review-minutes: 45 + - lanes: any local-dev + - merge-cap: 1 + - token-budget: 100000 + - max-workers: 2 +""" + + +def _prompt(root: Path, autonomy="safe", tier="notify", witness=True) -> Path: + folder = root / "draft" / "bug" / "pyautoheart" + folder.mkdir(parents=True, exist_ok=True) + f = folder / "fix_thing.md" + f.write_text(BUG.format(autonomy=autonomy, tier=tier, + witness="Witness: `pytest -q tests/test_thing.py` passes\n" + if witness else "")) + return f + + +def _mode(prompt: Path, *flags) -> subprocess.CompletedProcess: + return subprocess.run([str(CLI), "merge-mode", str(prompt), *flags], + capture_output=True, text=True, timeout=60) + + +class AutoWorker(tc.Spawner): + """A shift worker under `--auto`: it asks `merge-mode` (in a shift), and + when that says auto-merge it takes a slot, then runs a bare merge.""" + + def __init__(self, bindir: Path, mind: Path): + super().__init__() + self.bindir, self.mind = bindir, mind + + def spawn(self, task, prompt_path, lease_dir): + lease_dir = Path(lease_dir) + lease_dir.mkdir(parents=True, exist_ok=True) + prompt_path = self.mind / prompt_path # the pick's Mind-relative path + script = (f'mode=$("{CLI}" merge-mode "{prompt_path}" --auto --in-shift)\n' + f'echo "$mode" > "{lease_dir}/{task}.mode"\n' + f'case "$mode" in *"merge mode: auto-merge on green"*)\n' + f' if "{CLI}" merge-slot take "{PR}"; then\n' + f' gh pr merge "{PR}" --squash\n' + f' echo "merged {PR}" > "{lease_dir}/{task}.done"; exit 0\n' + f' fi;;\n' + f'esac\n' + f'echo "{PR}" > "{lease_dir}/{task}.done"\n') + subprocess.run(["bash", "-c", script], env=ms._shift_env(lease_dir.parent, self.bindir), + capture_output=True, text=True, timeout=60) + return {"pid": 0, "session_id": None, "worktree": None} + + +def test_auto_safe_notify_bug_with_witness_merges_and_counts(tmp_path): + bindir, log = ms._fake_gh(tmp_path) + mind = tmp_path / "mind" + prompt = _prompt(mind) + (mind / "queue.md").write_text(t.QUEUE) + brief = tmp_path / "shift.md" + brief.write_text(BRIEF.format(issue=t.ISSUE)) + home = tmp_path / "home" + sp = AutoWorker(bindir, mind) + r = orch.tick(brief, mind, home=home, now=t.NOW, spawner=sp, agents=tc.Agents(), + health=tc._health({})) + assert [s["task"] for s in r["spawned"]] == ["fix_thing"], r + tc._tick(brief, mind, home, sp, 1) + slot = orch.slot_dir(brief, home) + # The line the worker read before it merged. + assert _mode(prompt, "--auto", "--in-shift").stdout == ( + "effective level: supervised; merge mode: auto-merge on green after a merge slot\n") + assert len(ms._merges(log)) == 1, ms._merges(log) + c = orch.read_counters(slot) + assert c["outcomes"]["fix_thing"]["merged"] == [PR] + assert "1 merged of merge-cap 1" in _watch.attach_summary(brief, slot) + st = ms._slot_cli(slot, "status") + assert "1 of merge-cap 1" in st.stdout, st.stdout + + +def test_merge_mode_prints_effective_level_line(tmp_path): + prompt = _prompt(tmp_path) + r = _mode(prompt, "--auto") + assert r.returncode == 0, r.stderr + assert r.stdout == "effective level: supervised; merge mode: auto-merge on green\n" + # R3: a cap-lowered `notify` task with no `Witness:` goes to /prm. + assert _mode(_prompt(tmp_path, witness=False), "--auto").stdout == ( + "effective level: supervised; merge mode: human /prm\n") + assert _mode(_prompt(tmp_path, tier="judge"), "--auto").stdout == ( + "effective level: supervised; merge mode: human /prm\n") + assert _mode(_prompt(tmp_path, tier="glance"), "--auto").stdout == ( + "effective level: supervised; merge mode: auto-merge on green if the Witness passes\n") + # start_dev step 3 produces its line from this command. + start_dev = (BRAIN / "skills" / "start_dev" / "start_dev.md").read_text() + assert "pyauto-brain merge-mode" in start_dev diff --git a/tests/test_orchestrator_steering.py b/tests/test_orchestrator_steering.py index 77c09fc3..6984c93f 100644 --- a/tests/test_orchestrator_steering.py +++ b/tests/test_orchestrator_steering.py @@ -563,11 +563,11 @@ def test_cap_merges_binds_the_close_out_gate_on_the_tick_that_reads_it(tmp_path, (slot / "leases" / "t1.done").write_text(pr + "\n") gh.add(LOGIN, "/cap merges 0", 2) r = _tick(brief, mind, home, 3, claude, gh, {"t1": "done"}, health="HEALTHY") - assert r["commands"][0]["ack"] == ("merge-cap now 0 of this brief's 2 (0 merged so far): " - "no new close-out starts.") + assert r["commands"][0]["ack"] == ("merge-cap now 0 of this brief's 2 (0 merge slot(s) " + "taken so far): no new merge starts.") c = orch.read_counters(slot) assert c["closeouts"][pr] == {"task": "t1", "state": "refused", - "why": "merge-cap 0 reached this shift"} + "why": "merge-cap 0 reached this shift — left for your /prm"} assert c["caps"]["merge-cap"] | {"at": "x"} == {"value": 0, "by": LOGIN, "at": "x", "was": 2, "brief": 2} assert "- merges: 0 of 0 (0 unattended)" in gh.status()[0]["body"] From 90cf4d5ab04daf408311d6899969199a82bc7d6e Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 17 Nov 2026 13:50:00 +0000 Subject: [PATCH 2/5] docs: a worker frees its merge slot when the merge call fails Refs PyAutoBrain#661 Co-Authored-By: Claude Opus 5.5 --- agents/conductors/batch/worker_template.md | 3 +++ skills/prm/reference.md | 3 +++ 2 files changed, 6 insertions(+) diff --git a/agents/conductors/batch/worker_template.md b/agents/conductors/batch/worker_template.md index 766caedb..24556151 100644 --- a/agents/conductors/batch/worker_template.md +++ b/agents/conductors/batch/worker_template.md @@ -53,6 +53,9 @@ The terms of this shift (AUTONOMY.md "Shift briefs and unattended `glance`"): before a bare `gh pr merge` (ruling R3, AUTONOMY.md "`notify` merges under `--auto` and inside a shift — 2026-11-17"). If it refuses, do not merge: list the PR in your `.done` without `merged`, and it is left for `/prm`. + If the take succeeded but `gh pr merge` then fails, free the slot with + `{brain_cli} merge-slot release --why "merge failed"` and list the PR + without `merged`. - Never commit to PyAutoMind yourself — a hook refuses it. Queue each Mind change with `{shift_ledger} append|write|move|remove|drop-section ...` (ops land in {ledger_dir}/) and the orchestrator commits them. This covers diff --git a/skills/prm/reference.md b/skills/prm/reference.md index 93ad11db..a2496807 100644 --- a/skills/prm/reference.md +++ b/skills/prm/reference.md @@ -162,6 +162,9 @@ differences: 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 succeeds: the watcher took that slot. + If the take succeeded and the merge call then fails, run + `pyauto-brain merge-slot release --why "merge failed"` so the + slot returns to the shift, then stop as above. - **The merge call.** `gh pr merge --merge` as a **bare, unchained** Bash call (no `&&`, `;` or pipe); if the permission layer denies it, stop and report — never retry it another way. For `glance`, the close-out appends the From 8d63c3519f631fc8495bfb713b92b4c71a4ae995 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 17 Nov 2026 14:22:40 +0000 Subject: [PATCH 3/5] fix: merge slots keyed by canonical PR URL and task; digest reads slot evidence Review findings on #661: - merge-slot take accepts only a https://github.com///pull/ URL (normalised; anything else exits 2) and requires --task in a shift; a held slot answers yes only to the same task (the worker, or the close-out of the task the watcher took it for). PR #12 of two repos no longer shares a slot. - digest labels an in-turn merge from the slot file: merge slot, or "merged in-turn with NO merge slot" (needs you, R3 revert evidence); /cap merges counts slots plus unslotted in-turn merges. - close-out refuses a notify task that declares no Witness:. - worker template and /prm pass --task; AUTONOMY R3 code span reads . Refs #661. Co-Authored-By: Claude Opus 5.5 --- AUTONOMY.md | 2 +- agents/conductors/batch/_digest.py | 33 ++++++++- agents/conductors/batch/_merge_slots.py | 66 ++++++++++++++---- agents/conductors/batch/_orchestrator.py | 17 +++-- agents/conductors/batch/closeout_template.md | 9 ++- agents/conductors/batch/worker_template.md | 6 +- bin/README.md | 2 +- bin/merge_slot.py | 40 ++++++++--- bin/pyauto-brain | 4 +- skills/prm/reference.md | 16 +++-- tests/test_batch_warmup_findings.py | 4 +- tests/test_closeout_merge_slots.py | 60 ++++++++++++++--- tests/test_orchestrator_digest.py | 8 ++- tests/test_orchestrator_merge_slots.py | 70 +++++++++++++++++++- 14 files changed, 276 insertions(+), 61 deletions(-) diff --git a/AUTONOMY.md b/AUTONOMY.md index 85203865..6442f8e6 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -543,7 +543,7 @@ section and returns every merge to `/prm`. The human's ruling R3, 2026-11-17, from the review of shift 2026-11-16-pm. Two workers on the same `bug · safe · notify` header did opposite things: PyAutoBrain#654 stopped at decide-and-flag because the `bug` cap lowered it to `supervised`, and PyAutoBrain#655 merged in-turn. The shift then read "2 merged of merge-cap 1". - **A work-type cap does not stop a `notify` merge.** "Per-work-type caps" sets the effective level, and the level decides the checkpoints. Who merges is decided by the table above. A `notify` task whose cap lowered it to `supervised`, launched with `--auto` and with its `Witness:` held, merges in-turn on green. If the prompt declares no `Witness:`, it goes to `/prm`. A PR that took a decision under decide-and-flag carries `decision-taken` and is never auto-merged, as before. -- **Inside a shift, every merge counts against `merge-cap:`.** Before `gh pr merge`, a worker takes a merge slot with `pyauto-brain merge-slot take `, as its own bare call. If no slot is left, or the shift is paused, it does not merge and leaves the PR for `/prm`. The watcher's close-outs take slots from the same count. The digest says for each merge whether the worker merged it in-turn or a close-out did. +- **Inside a shift, every merge counts against `merge-cap:`.** Before `gh pr merge`, a worker takes a merge slot with `pyauto-brain merge-slot take `, as its own bare call. If no slot is left, or the shift is paused, it does not merge and leaves the PR for `/prm`. The watcher's close-outs take slots from the same count. The digest says for each merge whether the worker merged it in-turn or a close-out did. - **The watcher agrees with the worker.** It no longer refuses a `notify` PR as "only glance merges unattended". It closes out a `notify` PR a worker left open exactly as it closes out a `glance` one: Heart not RED, a merge slot free, the `Witness:` run by the close-out session, and nothing from "Never auto-merged". `judge`, an undeclared tier and `decision-taken` still go to `/prm`. - **These are `notify` merges, not stage-2 rows.** They do not count toward the unattended `glance` sub-window. The 2026-11-16-pm overrun was two `notify` merges made in-turn, outside "Unattended `glance` merges — 2026-11-03", so it does not trigger that sub-rule's revert condition. - Outside a shift, nothing changes. diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index a611de21..011f3e94 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -22,6 +22,7 @@ from pathlib import Path import _brief # noqa: E402 +import _merge_slots # noqa: E402 — slot evidence for an in-turn merge (R3, #661) import _questions # noqa: E402 — the inbox line (M3.5, #645) # The one CI judgement (PyAutoBrain#628) lives in bin/, beside its CLI. @@ -48,6 +49,10 @@ #: A PR the worker merged in-turn — after taking a merge slot against the #: shift's `merge-cap:` (AUTONOMY.md ruling R3, 2026-11-17, PyAutoBrain#661). IN_TURN_MERGED = "merged in-turn by the worker (merge slot)" +#: A PR the worker reported merged in-turn with no merge slot held for its +#: task: past the shift's `merge-cap:` count, and the evidence ruling R3's +#: revert condition reads. +IN_TURN_NO_SLOT = "merged in-turn with NO merge slot — R3 revert-condition evidence" #: A killed worker whose re-dispatch never started (PyAutoBrain#637, item 2): #: never "not started" — its first worker ran. NOT_REDISPATCHED = "crashed — not re-dispatched" @@ -250,8 +255,10 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False, elif url in out["merged"]: # Which path each merge took (R3, #661): a close-out, or the # worker in-turn after taking a merge slot. - state = ("merged unattended (close-out, " + co.get("model", "?") + ")" - if co.get("state") == "merged" else IN_TURN_MERGED) + if co.get("state") == "merged": + state = "merged unattended (close-out, " + co.get("model", "?") + ")" + else: + state = IN_TURN_MERGED if has_slot(counters, task, url) else IN_TURN_NO_SLOT if co.get("state") == "merged" and co.get("cleanup"): state += f" — worktree: {co['cleanup']}" elif co.get("state") == "refused": @@ -264,6 +271,23 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False, return "; ".join(parts), True +def has_slot(counters: dict, task: str, url: str) -> bool: + """Whether the shift's merge-slot file (as last synced into `counters` + as `slot_holders`) shows a slot for this PR held for this task.""" + held = (counters.get("slot_holders") or {}).get(_merge_slots.pr_key(url) or url) + return bool(held) and held.get("task") == task + + +def no_slot_merges(counters: dict) -> list[str]: + """In-turn merges a worker reported with no merge slot for its task — + each one a merge `merge-cap:` did not count (R3, #661).""" + closeouts = counters.get("closeouts", {}) + return [url for task, o in counters.get("outcomes", {}).items() + for url in o.get("merged") or [] + if (closeouts.get(url) or {}).get("state") != "merged" + and not has_slot(counters, task, url)] + + def gate_why(task: str, counters: dict) -> str: """Why the watcher's last plan kept this task out — a claim or a held repo on Mind origin/main, or a park in an earlier shift (#637) — or "".""" @@ -436,6 +460,7 @@ def label(task: str, pick: dict | None, url: str = "") -> str: #: its `task_state`; the first match wins. The exact state stays on the #: entry's second line, so nothing is lost by the short form. _PLAIN = ( + (IN_TURN_NO_SLOT, "Merged with NO merge slot — needs you"), ("merged", "Merged"), ("awaiting /prm — close-out refused: CI FAILED", "CI failed — needs you"), ("awaiting /prm — close-out refused: CI RED", "CI failed — needs you"), @@ -541,6 +566,10 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None, watcher's Mind checkout, read locally for the prompt links (#634).""" tiers = tiers or {} health = health or pr_health + try: # the slot file is the merge evidence; fresh at build time + counters = {**counters, "slot_holders": _merge_slots.holders(slot)} + except (_merge_slots.MergeSlotError, OSError): + pass picks = counters.get("picks", {}) named = [Path(p).stem for p in _brief.tasks_of(brief)] backlog = [t for t in picks if t not in named] diff --git a/agents/conductors/batch/_merge_slots.py b/agents/conductors/batch/_merge_slots.py index c3ee768e..a23d8ca1 100644 --- a/agents/conductors/batch/_merge_slots.py +++ b/agents/conductors/batch/_merge_slots.py @@ -13,9 +13,12 @@ last free slot. The watcher publishes the cap (and whether the shift is paused) every tick. It fails closed: no published cap, or a paused shift, refuses. -A take is idempotent per PR: a PR that already holds a slot is told yes again, -so a close-out session's own `/prm` take for the PR the watcher took a slot -for succeeds. A release frees a slot only for the caller that took it. +Slots are keyed by the PR's canonical URL (`pr_key`): a bare number, or any +other string, is never a key, so PR #12 of two repos never shares a slot. A +take is idempotent per PR and task: a PR that already holds a slot is told yes +again only for the same task — the worker that took it, or the close-out +session for the task the watcher took it for (its own `/prm` take). Anyone +else is refused. A release frees a slot only for the caller that took it. """ from __future__ import annotations @@ -25,6 +28,7 @@ import fcntl import json import os +import re import tempfile from pathlib import Path @@ -34,6 +38,20 @@ WATCHER = "watcher" +#: A GitHub PR URL, with anything after the number (`/files`, `/`, `#…`, `?…`). +_PR_URL_RE = re.compile(r"^https://github\.com/([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+)/pull/(\d+)" + r"(?:[/?#].*)?$") + + +def pr_key(url: str) -> str | None: + """The canonical `https://github.com///pull/` for a PR URL + (owner and repo case-folded, as GitHub resolves them), else None.""" + m = _PR_URL_RE.match((url or "").strip()) + if not m: + return None + return f"https://github.com/{m.group(1).lower()}/{m.group(2).lower()}/pull/{int(m.group(3))}" + + class MergeSlotError(RuntimeError): """The slot file cannot be read or written: the caller cannot tell.""" @@ -103,33 +121,44 @@ def publish(slot: Path, cap: int, paused: bool) -> None: def take(slot: Path, pr: str, by: str, task: str = "") -> tuple[bool, str]: - """(taken, why). Idempotent per PR; every refusal is recorded.""" + """(taken, why). Idempotent per PR and task; every refusal is recorded.""" + 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") with _locked(slot) as data: - held = data["slots"].get(pr) - if held: - return True, f"{pr} already holds a merge slot (taken by {held.get('by', '?')})" + held = data["slots"].get(key) cap, used = data.get("cap"), len(data["slots"]) - if cap is None: + 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: - data["slots"][pr] = {"by": by, "task": task, "at": _now()} - return True, f"merge slot {used + 1} of merge-cap {cap} taken for {pr}" - data["refusals"].append({"pr": pr, "by": by, "task": task, "why": why, "at": _now()}) + 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 release(slot: Path, pr: str, by: str, why: str = "") -> bool: """Free `pr`'s slot, only when `by` took it. True when one was freed.""" + key = pr_key(pr) + if key is None: + return False with _locked(slot) as data: - held = data["slots"].get(pr) + held = data["slots"].get(key) if not held or held.get("by") != by: return False - del data["slots"][pr] - data["released"].append({"pr": pr, "by": by, "task": held.get("task", ""), + del data["slots"][key] + data["released"].append({"pr": key, "by": by, "task": held.get("task", ""), "why": why, "at": _now()}) return True @@ -148,10 +177,19 @@ def used(slot: Path) -> int: return len(state(slot)["slots"]) +def holders(slot: Path) -> dict: + """{canonical PR URL: {by, task}} for every slot held now; {} with no file.""" + if not (Path(slot) / SLOTS_FILE).exists(): + return {} + return {k: {"by": v.get("by", ""), "task": v.get("task", "")} + for k, v in state(slot)["slots"].items()} + + def why_unmerged(slot: Path, pr: str) -> str: """The last refusal or release recorded for `pr`, else "".""" if not (Path(slot) / SLOTS_FILE).exists(): return "" + pr = pr_key(pr) or pr data = state(slot) seen = [("refused", r) for r in data["refusals"] if r.get("pr") == pr] \ + [("released", r) for r in data["released"] if r.get("pr") == pr] diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 8f1c41dc..235d5a4a 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -2433,15 +2433,19 @@ def _cmd_cap(slot: Path, counters: dict, arg: str, who: str, at: str, ctx: dict) if key == "merge-cap": # Every slot taken this shift — in-turn merges, close-outs merged and # close-outs still running alike (R3, #661). + # An in-turn merge made with no slot is counted too (#661 review). try: taken = _merge_slots.used(slot) + unslotted = len(_digest.no_slot_merges( + {**counters, "slot_holders": _merge_slots.holders(slot)})) except (_merge_slots.MergeSlotError, OSError): - taken = None - if taken is None: return f"merge-cap now {n} of this brief's {of} (merge slots unreadable)." - tail = (": no new merge starts." if taken >= n - else f": up to {n - taken} more may merge.") - return f"merge-cap now {n} of this brief's {of} ({taken} merge slot(s) taken so far){tail}" + count = taken + unslotted + tail = (": no new merge starts." if count >= n + else f": up to {n - count} more may merge.") + extra = f", plus {unslotted} merged with no merge slot" if unslotted else "" + return (f"merge-cap now {n} of this brief's {of} ({taken} merge slot(s) taken so far" + f"{extra}){tail}") if key == "max-workers": live = len(active_leases(slot)) return f"max-workers now {n} of {of}." + ( @@ -3161,6 +3165,9 @@ def _closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.dateti try: _merge_slots.publish(slot, _brief._nonneg_int(brief.get("merge-cap", {}).get("value", "")) or 0, _brief.is_shadow(brief) or bool(counters.get("paused"))) + # Who holds which slot, for the live view and the digest's label of + # each in-turn merge (slot or NO slot). + counters["slot_holders"] = _merge_slots.holders(slot) 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"): diff --git a/agents/conductors/batch/closeout_template.md b/agents/conductors/batch/closeout_template.md index 93eababa..59192a0e 100644 --- a/agents/conductors/batch/closeout_template.md +++ b/agents/conductors/batch/closeout_template.md @@ -12,7 +12,9 @@ Merge only if every check below passes; otherwise refuse. A refusal is a good outcome — the human merges by `/prm` at check-in. 1. Read the task's `Witness:` header and **run it yourself** against the PR's - head. Record what decided it. + 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). 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 @@ -63,8 +65,9 @@ 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") succeeds for - this PR: the watcher took its slot before starting you. + 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. 7. 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 diff --git a/agents/conductors/batch/worker_template.md b/agents/conductors/batch/worker_template.md index 24556151..72afc26a 100644 --- a/agents/conductors/batch/worker_template.md +++ b/agents/conductors/batch/worker_template.md @@ -49,12 +49,14 @@ The terms of this shift (AUTONOMY.md "Shift briefs and unattended `glance`"): and do not merge. Once CI lands, the watcher starts an independent close-out session that runs the witness and merges, or refuses (AUTONOMY.md "Unattended `glance` merges"). A `notify` task merges in-turn only after - `{brain_cli} merge-slot take ` exits 0, run as its own bare call just + `{brain_cli} merge-slot take --task {task}` exits 0, run as its own + bare call just before a bare `gh pr merge` (ruling R3, AUTONOMY.md "`notify` merges under `--auto` and inside a shift — 2026-11-17"). If it refuses, do not merge: list the PR in your `.done` without `merged`, and it is left for `/prm`. If the take succeeded but `gh pr merge` then fails, free the slot with - `{brain_cli} merge-slot release --why "merge failed"` and list the PR + `{brain_cli} merge-slot release --task {task} --why "merge failed"` + and list the PR without `merged`. - Never commit to PyAutoMind yourself — a hook refuses it. Queue each Mind change with `{shift_ledger} append|write|move|remove|drop-section ...` diff --git a/bin/README.md b/bin/README.md index 1ec5a8a8..2504a9a3 100644 --- a/bin/README.md +++ b/bin/README.md @@ -26,7 +26,7 @@ Executable tooling for the PyAuto organism. watcher refuses on 1 or 2 before any close-out session spawns, the close-out and the in-turn tiered merge stop on them too, and the review faculty lists the delta in its ReviewSurface. -- **`merge_slot.py`** — `pyauto-brain merge-slot take|release|status `: +- **`merge_slot.py`** — `pyauto-brain merge-slot take|release|status --task `: inside a shift, one merge slot against the brief's `merge-cap:` (PyAutoBrain#661; AUTONOMY.md ruling R3, 2026-11-17). A worker runs `take` as its own bare call before a bare `gh pr merge`; the watcher's close-outs diff --git a/bin/merge_slot.py b/bin/merge_slot.py index 904438d3..68fa551a 100644 --- a/bin/merge_slot.py +++ b/bin/merge_slot.py @@ -1,9 +1,16 @@ #!/usr/bin/env python3 """bin/merge_slot.py — take, release or show a shift's merge slot (PyAutoBrain#661). - pyauto-brain merge-slot take - pyauto-brain merge-slot release [--why ] - pyauto-brain merge-slot status [] + pyauto-brain merge-slot take --task + pyauto-brain merge-slot release --task [--why ] + pyauto-brain merge-slot status [] + +`` is `https://github.com///pull/` (a trailing `/`, +`/files` or `#…` is dropped); anything else cannot be told apart from another +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. 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 @@ -16,10 +23,11 @@ directory is that ledger directory's parent, and the counter is its `merge_slots.json` (`agents/conductors/batch/_merge_slots.py`). -EXIT. 0 = the slot is taken (or already held for this PR), or this is not a -shift, so nothing is counted; 1 = refused (no slot left, the shift is paused, -or no cap published) — do not merge, leave the PR for `/prm`; 2 = cannot tell -(the slot directory or its file cannot be read) — do not merge either. +EXIT. 0 = the slot is taken (or already held for this PR and task), or this +is not a shift, so nothing is counted; 1 = refused (no slot left, the shift is +paused, no cap published, or the PR's slot is another task's) — do not merge, +leave the PR for `/prm`; 2 = cannot tell (not a PR URL, no task named, or the +slot directory or its file cannot be read) — do not merge either. `release` exits 0 when it freed this caller's slot, 1 when there was none to free. `status` prints the count and exits 0. """ @@ -58,6 +66,14 @@ def main(argv=None) -> int: args = ap.parse_args(argv) if args.action in ("take", "release") and not args.pr: ap.error(f"{args.action} needs a PR URL") + if args.pr and _merge_slots.pr_key(args.pr) is None: + if _slot() is None and args.action == "take": + print("not in a shift (no PYAUTO_SHIFT_WORKER / PYAUTO_SHIFT_LEDGER_DIR): " + "no merge slot is counted") + return 0 + print(f"cannot tell: {args.pr!r} is not a https://github.com///pull/ " + "URL — do not merge; leave the PR for /prm") + return 2 slot = _slot() if slot is None: @@ -65,6 +81,10 @@ def main(argv=None) -> int: "no merge slot is counted") return 0 task = args.task or os.environ.get("PYAUTO_SHIFT_TASK", "") + if args.action == "take" and not task: + print("cannot tell: a take in a shift names its task (--task ) — " + "do not merge; leave the PR for /prm") + return 2 try: if args.action == "take": ok, why = _merge_slots.take(slot, args.pr, WORKER, task) @@ -81,8 +101,10 @@ def main(argv=None) -> int: + (" — paused" if data.get("paused") else "")) print(line) if args.pr: - held = data["slots"].get(args.pr) - print(f"{args.pr}: " + (f"held by {held.get('by', '?')}" if held + key = _merge_slots.pr_key(args.pr) + held = data["slots"].get(key) + print(f"{key}: " + (f"held by {held.get('by', '?')} for task {held.get('task') or '?'}" + if held else _merge_slots.why_unmerged(slot, args.pr) or "no slot, no refusal recorded")) return 0 diff --git a/bin/pyauto-brain b/bin/pyauto-brain index c97e4808..188e32cb 100755 --- a/bin/pyauto-brain +++ b/bin/pyauto-brain @@ -47,7 +47,7 @@ # pyauto-brain public-names # | --repo --range a..b [--json] # (tool) read-only: does a change add or rename a public # library name? CLEAN/HIT/CANNOT-TELL (bin/public_names.py) -# pyauto-brain merge-slot take|release|status +# pyauto-brain merge-slot take|release|status [--task ] # (tool) inside a shift, a merge slot against `merge-cap:` # before a bare `gh pr merge` — 0 taken / not a shift, 1 refused, # 2 cannot tell (bin/merge_slot.py; AUTONOMY.md ruling R3) @@ -179,7 +179,7 @@ EOF echo "Tools (read-only helpers the merge paths share):" echo " ci-verdict # [--json] — one PR's CI: GREEN, PENDING or RED, with reasons" echo " public-names # [--json] — a public library name added or renamed: a human /prm" - echo " merge-slot take|release|status — inside a shift, a merge slot before a bare gh pr merge" + 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" echo echo "Run 'pyauto-brain help ' for that agent's full docs." diff --git a/skills/prm/reference.md b/skills/prm/reference.md index a2496807..6a19df86 100644 --- a/skills/prm/reference.md +++ b/skills/prm/reference.md @@ -156,14 +156,16 @@ differences: `/prm`. `pyauto-brain merge-mode --auto` says which (AUTONOMY.md "`notify` merges under `--auto` and inside a shift — 2026-11-17"). - **Inside a shift, a merge slot first.** When `PYAUTO_SHIFT_WORKER` is set, - run `pyauto-brain merge-slot take ` as its **own bare call** right - before the merge call. Exit 0 → merge. Exit 1 (no slot left under - `merge-cap:`, or the shift is paused) 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 succeeds: the watcher took - that slot. + run `pyauto-brain merge-slot take --task ` (the full + `https://github.com///pull/` URL and the task's slug) as + its **own bare call** right before the merge call. Exit 0 → merge. Exit 1 + (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. If the take succeeded and the merge call then fails, run - `pyauto-brain merge-slot release --why "merge failed"` so the + `pyauto-brain merge-slot release --task --why "merge failed"` so the slot returns to the shift, then stop as above. - **The merge call.** `gh pr merge --merge` as a **bare, unchained** Bash call (no `&&`, `;` or pipe); if the permission layer denies it, stop and diff --git a/tests/test_batch_warmup_findings.py b/tests/test_batch_warmup_findings.py index bd47ae84..ea080002 100644 --- a/tests/test_batch_warmup_findings.py +++ b/tests/test_batch_warmup_findings.py @@ -89,7 +89,9 @@ def test_titles_link_to_the_pr_else_the_work_issue_else_plain_and_mind_links_nev counters = {"picks": {"t1": {"title": "One", "prompt": "draft/bug/x/t1.md"}, "t2": {"title": "Two", "prompt": "draft/bug/x/t2.md"}, "t3": {"title": "Three", "prompt": "draft/bug/x/t3.md"}}, - "outcomes": {"t1": {"prs": [PR], "merged": [PR], "issues": []}}} + "outcomes": {"t1": {"prs": [PR], "merged": [PR], "issues": []}}, + # t1 merged in-turn on its merge slot (R3, #661). + "slot_holders": {PR: {"by": "worker", "task": "t1"}}} assert _digest.work_link("t1", counters, links) == PR assert _digest.work_link("t2", counters, links) == WORK_ISSUE # its claim's issue assert _digest.work_link("t3", counters, links) == "" # neither: plain diff --git a/tests/test_closeout_merge_slots.py b/tests/test_closeout_merge_slots.py index b8b38f32..efc6c55e 100644 --- a/tests/test_closeout_merge_slots.py +++ b/tests/test_closeout_merge_slots.py @@ -75,7 +75,7 @@ def spawn(self, task, prompt_path, lease_dir): lease_dir = Path(lease_dir) lease_dir.mkdir(parents=True, exist_ok=True) pr = self.prs[task] - script = (f'if "{CLI}" merge-slot take "{pr}"; then\n' + script = (f'if "{CLI}" merge-slot take "{pr}" --task "{task}"; then\n' f' gh pr merge "{pr}" --squash\n' f' echo "merged {pr}" > "{lease_dir}/{task}.done"\n' f'else\n' @@ -123,7 +123,8 @@ def test_take_is_atomic_across_processes(tmp_path): sys.path.insert(0, str(BRAIN / "agents" / "conductors" / "batch")) import _merge_slots _merge_slots.publish(slot, 3, False) - procs = [subprocess.Popen([str(CLI), "merge-slot", "take", f"https://github.com/o/r/pull/{i}"], + procs = [subprocess.Popen([str(CLI), "merge-slot", "take", f"https://github.com/o/r/pull/{i}", + "--task", f"t{i}"], env=_shift_env(slot), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) for i in range(10)] @@ -141,17 +142,17 @@ def test_watcher_closeout_and_worker_share_slots(tmp_path): 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).returncode == 1 + 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 _slot_cli(slot, "take", PR1).returncode == 0 + assert _slot_cli(slot, "take", PR1, "--task", "named").returncode == 0 # A worker cannot free the watcher's slot. - _slot_cli(slot, "release", PR1) - assert _slot_cli(slot, "take", PR2).returncode == 1 + _slot_cli(slot, "release", PR1, "--task", "named") + assert _slot_cli(slot, "take", PR2, "--task", "picked").returncode == 1 # The close-out refuses: the watcher frees its slot, and the worker 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" - assert _slot_cli(slot, "take", PR2).returncode == 0 + assert _slot_cli(slot, "take", PR2, "--task", "picked").returncode == 0 st = _slot_cli(slot, "status", PR1) assert "witness failed" in st.stdout or "released" in st.stdout, st.stdout @@ -168,13 +169,52 @@ def test_outside_a_shift_the_take_is_a_no_op(tmp_path): def test_no_published_cap_or_a_pause_fails_closed(tmp_path): slot = tmp_path / "slot" (slot / mw.LEDGER_DIR).mkdir(parents=True) - r = _slot_cli(slot, "take", PR1) + r = _slot_cli(slot, "take", PR1, "--task", "t") assert r.returncode == 1 and "no merge-cap" in r.stdout sys.path.insert(0, str(BRAIN / "agents" / "conductors" / "batch")) import _merge_slots _merge_slots.publish(slot, 2, True) - r = _slot_cli(slot, "take", PR1) + r = _slot_cli(slot, "take", PR1, "--task", "t") assert r.returncode == 1 and "paused" in r.stdout gone = tmp_path / "nowhere" - r = _slot_cli(gone, "take", PR1) + r = _slot_cli(gone, "take", PR1, "--task", "t") assert r.returncode == 2 + + +# --- review findings (M3.6e review, #661) ----------------------------------------- + +def _published(tmp_path, cap=1): + slot = tmp_path / "slot" + (slot / mw.LEDGER_DIR).mkdir(parents=True) + sys.path.insert(0, str(BRAIN / "agents" / "conductors" / "batch")) + import _merge_slots + _merge_slots.publish(slot, cap, False) + return slot, _merge_slots + + +def test_a_pr_number_shared_across_repos_never_shares_a_slot(tmp_path): + """Two workers on PR #12 of different repos, or of the same repo under + two tasks, never merge on one slot; a bare number cannot be told apart.""" + slot, _ = _published(tmp_path, cap=1) + a, b = "https://github.com/o/a/pull/12", "https://github.com/o/b/pull/12" + assert _slot_cli(slot, "take", a, "--task", "ta").returncode == 0 + assert _slot_cli(slot, "take", b, "--task", "tb").returncode == 1 # cap 1 used + assert _slot_cli(slot, "take", a, "--task", "tb").returncode == 1 # not tb's slot + r = _slot_cli(slot, "take", "12", "--task", "ta") + assert r.returncode == 2 and "pull" in r.stdout # not a PR URL + assert _slot_cli(slot, "take", a + "/files", "--task", "ta").returncode == 0 # same PR + + +def test_a_closeout_take_of_the_watchers_slot_is_normalised(tmp_path): + slot, ms = _published(tmp_path, cap=1) + ok, _ = ms.take(slot, PR1, ms.WATCHER, "named") + assert ok + assert _slot_cli(slot, "take", PR1 + "/", "--task", "named").returncode == 0 + assert _slot_cli(slot, "take", PR1 + "#issuecomment-1", "--task", "named").returncode == 0 + assert _slot_cli(slot, "take", PR1, "--task", "other").returncode == 1 + + +def test_a_worker_take_names_its_task(tmp_path): + slot, _ = _published(tmp_path, cap=2) + r = _slot_cli(slot, "take", PR1) + assert r.returncode == 2 and "--task" in r.stdout diff --git a/tests/test_orchestrator_digest.py b/tests/test_orchestrator_digest.py index a3938a81..c7f60212 100644 --- a/tests/test_orchestrator_digest.py +++ b/tests/test_orchestrator_digest.py @@ -176,9 +176,11 @@ def test_digest_separates_brief_work_from_backlog_picks_with_reasons(tmp_path): picks = d.split("### Backlog picks")[1].split("### Proof packets")[0] # Each task: the outcome in plain words and the title, linked to its PR # (never to a Mind path, which moves and 404s, #634); the detail below. - assert ("- **Merged** — [named](https://github.com/o/r/pull/1)\n" - " `named` · glance · small · pyautoheart · merged in-turn by the worker" - " (merge slot)") in work + # This fixture's worker wrote `merged` with no merge slot taken: the + # digest says so from the slot file (R3, #661 review). + assert ("- **Merged with NO merge slot — needs you** — [named](https://github.com/o/r/pull/1)\n" + " `named` · glance · small · pyautoheart · merged in-turn with NO merge slot" + " — R3 revert-condition evidence") in work assert "- **Not started** — never\n `never` · not started" in work assert "blob/main" not in d # Green and glance: since phase 4b its close-out is running at review time. diff --git a/tests/test_orchestrator_merge_slots.py b/tests/test_orchestrator_merge_slots.py index 67c439cf..280737b3 100644 --- a/tests/test_orchestrator_merge_slots.py +++ b/tests/test_orchestrator_merge_slots.py @@ -93,7 +93,7 @@ def spawn(self, task, prompt_path, lease_dir): script = (f'mode=$("{CLI}" merge-mode "{prompt_path}" --auto --in-shift)\n' f'echo "$mode" > "{lease_dir}/{task}.mode"\n' f'case "$mode" in *"merge mode: auto-merge on green"*)\n' - f' if "{CLI}" merge-slot take "{PR}"; then\n' + f' if "{CLI}" merge-slot take "{PR}" --task "{task}"; then\n' f' gh pr merge "{PR}" --squash\n' f' echo "merged {PR}" > "{lease_dir}/{task}.done"; exit 0\n' f' fi;;\n' @@ -144,3 +144,71 @@ def test_merge_mode_prints_effective_level_line(tmp_path): # start_dev step 3 produces its line from this command. start_dev = (BRAIN / "skills" / "start_dev" / "start_dev.md").read_text() assert "pyauto-brain merge-mode" in start_dev + + +# --- review findings (M3.6e review, #661) ----------------------------------------- + +class NoSlotWorker(tc.Spawner): + """A worker that merged in-turn without taking a merge slot — the + 2026-11-16-pm failure, and R3's revert-condition evidence.""" + + def __init__(self, bindir: Path): + super().__init__() + self.bindir = bindir + + def spawn(self, task, prompt_path, lease_dir): + lease_dir = Path(lease_dir) + lease_dir.mkdir(parents=True, exist_ok=True) + (lease_dir / f"{task}.done").write_text(f"merged {PR}\n") + return {"pid": 0, "session_id": None, "worktree": None} + + +def _bug_shift(tmp_path, sp_cls): + bindir, log = ms._fake_gh(tmp_path) + mind = tmp_path / "mind" + _prompt(mind) + (mind / "queue.md").write_text(t.QUEUE) + brief = tmp_path / "shift.md" + brief.write_text(BRIEF.format(issue=t.ISSUE)) + home = tmp_path / "home" + sp = sp_cls(bindir, mind) if sp_cls is AutoWorker else sp_cls(bindir) + orch.tick(brief, mind, home=home, now=t.NOW, spawner=sp, agents=tc.Agents(), + health=tc._health({})) + tc._tick(brief, mind, home, sp, 1) + return brief, orch.slot_dir(brief, home) + + +def _digest_of(brief, slot): + c = orch.read_counters(slot) + return orch._digest.build(orch._brief.parse(brief.read_text())["brief"], slot, c, + health=lambda u: "HEALTHY") + + +def test_an_in_turn_merge_with_its_slot_reads_merge_slot(tmp_path): + brief, slot = _bug_shift(tmp_path, AutoWorker) + d = _digest_of(brief, slot) + assert "merged in-turn by the worker (merge slot)" in d + assert "NO merge slot" not in d + + +def test_an_in_turn_merge_without_a_slot_is_flagged_and_counted(tmp_path): + brief, slot = _bug_shift(tmp_path, NoSlotWorker) + d = _digest_of(brief, slot) + assert "merged in-turn with NO merge slot" in d + assert "Merged with NO merge slot — needs you" in d + c = orch.read_counters(slot) + ack = orch._cmd_cap(slot, c, "merges 1", "someone", "2026-11-04T09:05Z", + {"brief": orch._brief.parse(brief.read_text())["brief"]}) + assert "1 merged with no merge slot" in ack and "no new merge starts" in ack, ack + + +def test_a_notify_closeout_refuses_without_a_witness(): + text = orch.closeout_prompt("t1", PR, "draft/bug/x/t1.md", Path("b.md"), Path("leases")) + assert "`notify` task that declares no `Witness:`" in text + assert "merge-slot take " + PR + " --task t1" in text + + +def test_the_worker_names_its_task_on_every_merge_slot_call(): + text = orch.worker_prompt("t1", "draft/bug/x/t1.md", Path("b.md"), Path("leases")) + assert "merge-slot take --task t1" in text + assert "merge-slot release --task t1" in text From 84974dfcef47feadda4853575b43c4ec4e54dec6 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 17 Nov 2026 14:33:13 +0000 Subject: [PATCH 4/5] fix: a merge-slot release frees only its own task's slot Every worker and close-out session holds as one class, so release now takes the task and frees a slot only when the holder's task matches; the CLI refuses another task's slot (exit 1, naming the holder) and a release with no task cannot tell (exit 2), as for take. Refs #661 (re-review). Co-Authored-By: Claude Opus 5.5 --- agents/conductors/batch/_merge_slots.py | 8 ++++++-- bin/merge_slot.py | 22 ++++++++++++++-------- tests/test_closeout_merge_slots.py | 13 +++++++++++++ 3 files changed, 33 insertions(+), 10 deletions(-) diff --git a/agents/conductors/batch/_merge_slots.py b/agents/conductors/batch/_merge_slots.py index a23d8ca1..0c298718 100644 --- a/agents/conductors/batch/_merge_slots.py +++ b/agents/conductors/batch/_merge_slots.py @@ -148,8 +148,10 @@ def take(slot: Path, pr: str, by: str, task: str = "") -> tuple[bool, str]: return False, why -def release(slot: Path, pr: str, by: str, why: str = "") -> bool: - """Free `pr`'s slot, only when `by` took it. True when one was freed.""" +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 + task. True when one was freed.""" key = pr_key(pr) if key is None: return False @@ -157,6 +159,8 @@ def release(slot: Path, pr: str, by: str, why: str = "") -> bool: held = data["slots"].get(key) if not held or held.get("by") != by: return False + if task is not None and held.get("task") != task: + return False del data["slots"][key] data["released"].append({"pr": key, "by": by, "task": held.get("task", ""), "why": why, "at": _now()}) diff --git a/bin/merge_slot.py b/bin/merge_slot.py index 68fa551a..4d923354 100644 --- a/bin/merge_slot.py +++ b/bin/merge_slot.py @@ -28,8 +28,9 @@ paused, no cap published, or the PR's slot is another task's) — do not merge, leave the PR for `/prm`; 2 = cannot tell (not a PR URL, no task named, or the slot directory or its file cannot be read) — do not merge either. -`release` exits 0 when it freed this caller's slot, 1 when there was none to -free. `status` prints the count and exits 0. +`release` (task required, as for `take`) exits 0 when it freed this task's +slot, 1 when there was none to free (the holder is named). `status` prints the +count and exits 0. """ from __future__ import annotations @@ -81,8 +82,8 @@ def main(argv=None) -> int: "no merge slot is counted") return 0 task = args.task or os.environ.get("PYAUTO_SHIFT_TASK", "") - if args.action == "take" and not task: - print("cannot tell: a take in a shift names its task (--task ) — " + if args.action in ("take", "release") and not task: + print(f"cannot tell: a {args.action} in a shift names its task (--task ) — " "do not merge; leave the PR for /prm") return 2 try: @@ -91,10 +92,15 @@ def main(argv=None) -> int: print(("taken: " if ok else "refused: ") + why) return 0 if ok else 1 if args.action == "release": - freed = _merge_slots.release(slot, args.pr, WORKER, args.why) - print(f"released {args.pr}" if freed - else f"no merge slot of yours held for {args.pr}") - return 0 if freed else 1 + freed = _merge_slots.release(slot, args.pr, WORKER, args.why, task=task) + if freed: + print(f"released {args.pr}") + return 0 + held = _merge_slots.state(slot)["slots"].get(_merge_slots.pr_key(args.pr)) + print(f"no merge slot of task {task} held for {args.pr}" + + (f" — it is held by {held.get('by', '?')} for task {held.get('task') or '?'}" + if held else "")) + return 1 data = _merge_slots.state(slot) cap = data.get("cap") line = (f"{len(data['slots'])} of merge-cap {cap if cap is not None else '(none published)'}" diff --git a/tests/test_closeout_merge_slots.py b/tests/test_closeout_merge_slots.py index efc6c55e..d90ad55a 100644 --- a/tests/test_closeout_merge_slots.py +++ b/tests/test_closeout_merge_slots.py @@ -218,3 +218,16 @@ def test_a_worker_take_names_its_task(tmp_path): slot, _ = _published(tmp_path, cap=2) r = _slot_cli(slot, "take", PR1) assert r.returncode == 2 and "--task" in r.stdout + + +def test_a_worker_release_names_and_matches_its_task(tmp_path): + """Every session holds as `worker`: a release frees only its own task's + slot, and one that names no task cannot tell (#661 re-review).""" + slot, _ = _published(tmp_path, cap=1) + assert _slot_cli(slot, "take", PR1, "--task", "a").returncode == 0 + r = _slot_cli(slot, "release", PR1, "--task", "b") + assert r.returncode == 1 and "task a" in r.stdout, r.stdout + assert _slot_cli(slot, "release", PR1).returncode == 2 + assert "1 of merge-cap 1" in _slot_cli(slot, "status").stdout + assert _slot_cli(slot, "release", PR1, "--task", "a").returncode == 0 + assert "0 of merge-cap 1" in _slot_cli(slot, "status").stdout From 44eacd8f6a50b90ba040ed5ceef4b383aba870db Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 17 Nov 2026 14:45:16 +0000 Subject: [PATCH 5/5] docs: move start_dev's tier + merge mode detail into reference.md start_dev (SKILL.md + start_dev.md) was 205 lines, over the 200-line skill budget CI checks. Step 3 keeps the instruction to run pyauto-brain merge-mode; the tier table and R3 note move to reference.md "Tier + merge mode line". Now 194 lines. Refs #661. Co-Authored-By: Claude Opus 5.5 --- skills/start_dev/reference.md | 18 ++++++++++++++++++ skills/start_dev/start_dev.md | 19 ++++--------------- 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/skills/start_dev/reference.md b/skills/start_dev/reference.md index 14a3c9c9..feecc0a3 100644 --- a/skills/start_dev/reference.md +++ b/skills/start_dev/reference.md @@ -77,6 +77,24 @@ Legacy check: if a target repo's **main checkout** is on a feature branch not referenced by any `worktree:` claim, warn (unregistered prior-session work) — ask whether to proceed; don't treat it as an automatic conflict. +## Tier + merge mode line + +`start_dev` step 3. The line follows the prompt's **declared** `Consequence:` +(never sizing-inferred), per [`../../AUTONOMY.md`](../../AUTONOMY.md) "Merge +authority follows Consequence — 2026-10-02": + +``` +Tier: notify — merge mode: auto-merge on green (in-turn wait, then /prm close-out) +Tier: glance — merge mode: auto-merge on green if the Witness passes, post-merge summary +Tier: judge (or undeclared) — merge mode: human /prm +``` + +Produce it with `pyauto-brain merge-mode ` (add `--auto` under +`--auto`, `--in-shift` in a shift worker). It prints one line, `effective +level: ; merge mode: `. Put that line in the plan before work +starts, so a worker and a reader see the same answer (ruling R3, AUTONOMY.md +"`notify` merges under `--auto` and inside a shift — 2026-11-17"). + ## Branch survey (the former /plan_branches) Run after the plan is approved (start_dev step 4): survey every repository the plan will touch, report branch state, and propose a single working branch name for the task. diff --git a/skills/start_dev/start_dev.md b/skills/start_dev/start_dev.md index 9fc90666..1cb706cd 100644 --- a/skills/start_dev/start_dev.md +++ b/skills/start_dev/start_dev.md @@ -93,21 +93,10 @@ Two levels: **high-level** (3–8 plain-English bullets, no code) and **detailed** (file paths, functions/classes, changes per step, trade-offs, testing) — enough for a fresh session to start from the issue alone. The high-level plan ends with one **tier + merge mode** line from the prompt's -**declared** `Consequence:` (never sizing-inferred), per -[`../../AUTONOMY.md`](../../AUTONOMY.md) "Merge authority follows Consequence — -2026-10-02": - -``` -Tier: notify — merge mode: auto-merge on green (in-turn wait, then /prm close-out) -Tier: glance — merge mode: auto-merge on green if the Witness passes, post-merge summary -Tier: judge (or undeclared) — merge mode: human /prm -``` - -Produce the mode with `pyauto-brain merge-mode ` (add `--auto` under -`--auto`, `--in-shift` in a shift worker). It prints one line, `effective -level: ; merge mode: `. Put that line in the plan before work -starts, so a worker and a reader see the same answer (ruling R3, AUTONOMY.md -"`notify` merges under `--auto` and inside a shift — 2026-11-17"). +**declared** `Consequence:` (never sizing-inferred): run +`pyauto-brain merge-mode ` (`--auto` under `--auto`, `--in-shift` in a +shift worker) and put its `effective level: ; merge mode: ` line +in the plan ([`reference.md`](reference.md) → "Tier + merge mode line"). **Approving the plan authorizes that merge mode**; a plan without the line authorizes no merge. An epic's approval chains auto-merged phases without