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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions AUTONOMY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:` |
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 <pr-url>`, 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
Expand Down
14 changes: 8 additions & 6 deletions agents/conductors/batch/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -420,15 +420,17 @@ ends at PR-open (`worker_template.md`). Each tick, `_closeouts` first reaps
running close-outs — `<task>.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:<task> --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: <why>`). Same-model close-out: AUTONOMY
Expand Down
38 changes: 36 additions & 2 deletions agents/conductors/batch/_digest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -45,6 +46,13 @@
#: 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 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"
Expand Down Expand Up @@ -245,8 +253,12 @@ 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"]:
state = ("merged unattended (close-out, " + co.get("model", "?") + ")"
if co.get("state") == "merged" else "merged")
# Which path each merge took (R3, #661): a close-out, or the
# worker in-turn after taking a merge slot.
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":
Expand All @@ -259,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 ""."""
Expand Down Expand Up @@ -431,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"),
Expand Down Expand Up @@ -536,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]
Expand Down
205 changes: 205 additions & 0 deletions agents/conductors/batch/_merge_slots.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
"""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 <pr>` (`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.

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

import contextlib
import datetime as _dt
import fcntl
import json
import os
import re
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"


#: 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/<owner>/<repo>/pull/<n>` 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."""


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 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/<owner>/<repo>/pull/<n> URL "
"— left for your /prm")
with _locked(slot) as data:
held = data["slots"].get(key)
cap, used = data.get("cap"), len(data["slots"])
if held and task and held.get("task") == task:
return True, (f"{key} already holds a merge slot for task {task} "
f"(taken by {held.get('by', '?')})")
if held:
why = (f"{key} holds a merge slot for task {held.get('task') or '?'}, "
f"not {task or '(no task)'} — left for your /prm")
elif cap is None:
why = "no merge-cap published by the watcher — left for your /prm"
elif data.get("paused"):
why = "the shift is paused — left for your /prm"
elif used >= int(cap):
why = f"merge-cap {cap} reached this shift — left for your /prm"
else:
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 = "", *, 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
with _locked(slot) as data:
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()})
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 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]
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 ""
Loading
Loading