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
27 changes: 27 additions & 0 deletions AUTONOMY.md
Original file line number Diff line number Diff line change
Expand Up @@ -875,6 +875,29 @@ close-out may take the shift past its `token-budget:`, but its tokens count
against that budget and the digest shows them, and no new close-out starts
once the shift's spend reaches 1.5× the budget.

**Merge order and the branch update — 2026-11-19 (M3.6j, PyAutoBrain#683),
the human's rulings ("approved, all six yes").** A shift holds a library repo
for *starting* only while a worker on it is live; it holds it for *merging*
while an earlier PR of the shift on it is open. Six rulings:

- **(a)** an unattended branch-update session may push a merge from `main` to a
shift PR's branch (`gh pr update-branch`, never a rebase or force-push), then
must end; a later close-out merges only on CI green at the new head. The
watcher itself still pushes nothing;
- **(b)** the watcher may `gh pr view` the PRs a waiting PR waits behind every
tick, carried ones included;
- **(c)** an earlier PR blocks until GitHub says MERGED or CLOSED, whatever its
state in the shift (dropped, red, refused, abandoned);
- **(d)** a park on a question keeps holding its library's start;
- **(e)** a worker may proceed past a `worktree_check_conflict` hit that names
only a listed sibling PR's slug;
- **(f)** library repos only, and only PRs this shift knows (its outcomes and a
carried PR's `behind`).

A waiting PR is never refused for waiting and takes no merge slot; a conflict
on update, red CI on the new head or a third update refuses it for `/prm`.
Every guard of this section still applies to the merge close-out.

### One Mind writer per shift — 2026-11-03

During a shift, **only the orchestrator commits to PyAutoMind**, from its own
Expand Down Expand Up @@ -971,6 +994,10 @@ later tick, at most three tries in all; one that timed out may have landed and
is never retried. The watcher also reads `gh pr view --json
state,mergedAt,mergedBy` for the PRs its own workers named — the close-out's
merge truth (#603) and, once at `review-at:`, the digest's `merges` (#610).
Since 2026-11-19 (M3.6j, PyAutoBrain#683, ruling b) it also reads that state
every tick for each earlier PR a waiting PR of the shift waits behind, carried
ones included. The branch-update session it starts pushes a merge from `main`
(ruling a); the watcher itself still makes no write to a repository.
It also makes one read-only `gh api user` per shift, under the posting token,
to warn when it equals the mention login (#611) — as the App, one `GET /app`
with its JWT instead, naming it `<slug>[bot]` (#630).
Expand Down
58 changes: 50 additions & 8 deletions agents/conductors/batch/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,14 +306,23 @@ Until phase 3b it spawns only stub workers (`PYAUTO_ORCHESTRATOR_FAKE=1`); a rea
dispatch is refused. Doctrine: `AUTONOMY.md` "The watcher's network surface —
2026-11-03"; the exemption it runs under, `PyAutoMind/policy/shift_watcher.md`.

**A library slot frees at merge (2026-11-18, PyAutoBrain#679).** The plan
admits one task per library repo, because concurrent library PRs collide at
merge. A task this shift picked holds its library while it runs, while its PR
is open or refused, and while it is parked. Once it is done and every PR it
opened has merged (or it ended with no PR and no open question), the next tick
may start the next task on that library. The finished task stays in the plan,
so it is never re-dispatched. A claim it left in `active.md`, written by this
shift's own worker, no longer holds the repo either.
**A library is held while its worker runs; merges wait in PR order (M3.6j,
2026-11-19, PyAutoBrain#683).** The plan admits one *live* task per library
repo, so two workers never share one. Work does not collide; merges do. A task
this shift picked holds its library while its worker runs, while it is parked
(on a question or a person: ruling d), while a re-dispatch or an answered
restart is pending, and while its outcome carries an open question. Once its
worker has ended, the next tick may start the next task on that library, its
PR open, refused or merged alike (`released_picks`; first PyAutoBrain#679 freed
it only at merge, and one `/prm`-bound PR stalled the shift). A `/drop`ped task
with no live worker holds nothing. The finished task stays in the plan, so it
is never re-dispatched, and a claim its own shift worker left in `active.md`
holds nothing either. The next worker's prompt starts with `SIBLING_NOTE`,
naming this shift's open PRs on that library: branch from `main`, never stack;
end `obsolete` if a sibling already does the task; a `worktree_check_conflict`
hit naming only a listed sibling's slug is not a conflict (ruling e). The plan's
reason for a held task is `<repo> held by <task> — will start once <task>'s
worker ends` (named) or `<repo> held by <task> while its worker runs`.

**The open-brief gate is a window: `dispatched:` → `review-at:`.** A brief
that passes `batch brief --check` is open only from its `dispatched:` until its
Expand Down Expand Up @@ -533,6 +542,39 @@ writer. Every refusal is final for the shift and named in the digest
(`awaiting /prm — close-out refused: <why>`). Same-model close-out: AUTONOMY
"Stage-2 adversary amendment — 2026-11-04".

**Merge order and the branch update (M3.6j, PyAutoBrain#683).** Before CI is
read, a library PR waits behind every earlier PR this shift knows on the same
GitHub repo (its outcomes and a carried outcome's `behind`; library repos only,
ruling f) until GitHub says that PR is MERGED or CLOSED, whatever this shift
made of it (ruling c); an unreadable one blocks. Waiting is not a refusal: no
close-out, no merge slot, an entry in `counters["merge_waits"]` (rebuilt each
tick, one `gh pr view` per blocking PR per tick, ruling b) and a `waiting`
event when what it waits behind changes. A workspace PR waits while its own
task's library PR waits or is being closed out. Once nothing is ahead, a PR
whose branch was cut before an earlier PR merged (merged after its task's first
worker started; for a carried PR, any merged earlier PR) takes its merge slot
and gets one **branch-update session** (`closeout_update_template.md`, `claude
--bg --name shift-update:<task>`), after the public-name gate: it runs `gh pr
update-branch` (a merge commit from `main`; never a rebase or force-push,
ruling a), writes `updated` (new head), `current` or `refused` (`conflicts with
main after <A> merged → your /prm`) and ends. An `updated` or `current` PR
keeps its slot and is looked at again each tick: CI running, or NO-CHECKS
within `UPDATE_CHECKS_GRACE_S` (600 s), waits; red refuses (`CI <verdict> on
the updated head → your /prm`) and frees the slot; green starts the merge
close-out, whose step 4b checks every earlier PR is no longer OPEN and each
merged one is in the branch. A PR needing a third update refuses (`main kept
moving`, `UPDATE_LIMIT` 2). A waiting or updated PR at `review-at:` is not
refused; the next shift carries it with what it waited behind. The digest says
`waits behind <A> (<A's state>) — merge <A> first` and lists a per-library
"Merge order" block, ▶ on the PR that needs your /prm now. The in-turn path
keeps the same order: `merge-slot take` (`bin/merge_slot.py`) refuses a
`notify` worker's in-turn merge while an earlier shift PR on the same library
is open (`in_turn_merge_blockers`, the close-out's rule), so that PR ends at
PR-open and merges through the wait above. An `updated` PR's CI is read only
once GitHub shows the head the update made; a head that moved since refuses.
The spawn loop also refuses a task whose library a live, parked or
re-dispatch-pending task holds, whatever the plan's order made of it.

**Watching a shift live (`batch watch`, PyAutoBrain#575).** `batch watch
--record <brief> [--once] [--interval N]` (`_watch.py`) draws a running shift
in the terminal: SHADOW or LIVE, time left until `review-at:`, STOP and
Expand Down
20 changes: 12 additions & 8 deletions agents/conductors/batch/_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,10 +511,12 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET,
pool.sort(key=lambda r: (r["queue_rank"], priority_rank(r),
r["review_minutes"], r["path"]))

# `released` (PyAutoBrain#679): the watcher's own picks whose PRs have all
# merged, or that ended with no PR and no open question. They stay members
# (known, counted, never re-dispatched) but hold no library: a merged PR
# collides with nothing, so the next task on that library may start.
# `released` (M3.6j, PyAutoBrain#683; first #679): the watcher's own
# picks whose worker has ended (PR open or not) and that wait on no
# question, re-dispatch or restart. They stay members (known, counted,
# never re-dispatched) but hold no library: merges collide, starts do
# not, and the close-out merges a library's shift PRs in PR order (the
# merge-order wait), so the next task on that library may start.
released = released or set()
members, spent, seen_epics, libs = [], 0, set(), {}
for r in pool:
Expand All @@ -529,14 +531,16 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET,
# invalidates the others' test and smoke evidence. Only LIBRARY repos
# claim a shift: they are what the library-first gate serialises and
# what downstream suites are re-run against. Workspace, docs and organ
# repos are exempt — two docs changes in one shift cost nothing.
# repos are exempt — two docs changes in one shift cost nothing. A
# library is held while its worker runs, so two workers never share
# one; its PRs then merge in PR order at the close-out (M3.6j).
clash = next((x for x in r["repos"] if x in LIBRARY_REPOS and x in libs), None)
if clash:
holder = libs[clash]
rejected.append((r["path"], f"{clash} held by {holder} — will start after "
f"{holder}'s PR merges"
rejected.append((r["path"], f"{clash} held by {holder} — will start once "
f"{holder}'s worker ends"
if Path(r["path"]).name in named_names
else f"{clash} held by {holder} until its PR merges"))
else f"{clash} held by {holder} while its worker runs"))
continue
cost = 0 if r["consequence"] in CHEAP_TIERS else r["review_minutes"]
if spent + cost > effective_budget:
Expand Down
90 changes: 89 additions & 1 deletion agents/conductors/batch/_digest.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,16 +261,99 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False,
state = IN_TURN_MERGED if has_slot(counters, task, url) else IN_TURN_NO_SLOT
if co.get("state") == "merged" and co.get("cleanup"):
state += f" — worktree: {co['cleanup']}"
elif url in (counters.get("merge_waits") or {}):
state = wait_state(url, counters) # merge order (M3.6j, #683)
elif co.get("state") == "refused":
state = f"awaiting /prm — close-out refused: {co.get('why', '?')}"
elif co.get("state") == "running":
state = "close-out running"
state = UPDATING if co.get("kind") == "update" else "close-out running"
elif co.get("state") == "updated":
state = (f"{UPDATED} after {', '.join(map(pr_ref, co.get('after') or []))}, "
f"CI on new head {health(url)}")
elif co.get("state") == "current":
state = f"{CURRENT}, CI {health(url)}"
else:
state = health(url)
parts.append(f"{url} — {state}")
return "; ".join(parts), True


#: A PR's states in the merge order (M3.6j, PyAutoBrain#683).
UPDATING = "close-out updating the branch from main"
UPDATED = "branch updated from main"
CURRENT = "branch already up to date with main"
MERGE_ORDER_HEADING = "### Merge order"
_PR_REF_RE = re.compile(r"^https://github\.com/[^/\s]+/([^/\s]+)/pull/(\d+)")


def pr_ref(url: str) -> str:
"""`repo#n` for a GitHub PR URL; the URL itself otherwise."""
m = _PR_REF_RE.match(url or "")
return f"{m.group(1)}#{m.group(2)}" if m else (url or "?")


def _order_word(url: str, counters: dict) -> str:
"""What an earlier PR in the merge order is doing, in a few words."""
co = (counters.get("closeouts") or {}).get(url) or {}
if url in (counters.get("merge_waits") or {}):
return "itself waiting"
if co.get("state") == "refused":
return f"needs your /prm: {refusal_class(co.get('why') or '?')}"
if co.get("state") == "running":
return "close-out running"
if co.get("state") in ("updated", "current"):
return "branch updated, CI re-running"
return "open"


def wait_state(url: str, counters: dict) -> str:
"""A PR waiting in merge order: behind which PRs, what they are doing, and
which one to merge first (M3.6j, PyAutoBrain#683)."""
behind = ((counters.get("merge_waits") or {}).get(url) or {}).get("behind") or []
return ("waits behind " + ", ".join(f"{pr_ref(b)} ({_order_word(b, counters)})"
for b in behind)
+ f" — merge {pr_ref(behind[0]) if behind else '?'} first")


def merge_order_lines(counters: dict) -> list[str]:
"""The `### Merge order` block (M3.6j, PyAutoBrain#683): for each library
repo where a PR of this shift waits behind an earlier one, its open PRs
in PR-number order, ▶ on the one that needs your /prm now; and how many
branch updates conflicted with main. Empty when nothing waits."""
waits = counters.get("merge_waits") or {}
if not waits:
return []
merged = {u for o in (counters.get("outcomes") or {}).values() if isinstance(o, dict)
for u in o.get("merged") or []}
known = list(dict.fromkeys(
u for o in (counters.get("outcomes") or {}).values() if isinstance(o, dict)
for u in [*(o.get("prs") or []), *(o.get("behind") or [])]))

def repo(u):
key = _merge_slots.pr_key(u)
return key.rsplit("/pull/", 1)[0] if key else ""

def number(u):
key = _merge_slots.pr_key(u)
return int(key.rsplit("/", 1)[1]) if key else 0
repos = list(dict.fromkeys(repo(w) for w, info in waits.items()
if any(repo(b) == repo(w) for b in info.get("behind") or [])))
out = ["", MERGE_ORDER_HEADING]
for r in repos:
prs = sorted((u for u in known if repo(u) == r and u not in merged), key=number)
out.append(f"- **{r.rsplit('/', 1)[-1]}**, merged in this order:")
now = next((u for u in prs if u not in waits), None)
for u in prs:
word = wait_state(u, counters) if u in waits else _order_word(u, counters)
out.append(f" - {'▶ ' if u == now else ''}{u} — {word}")
conflicts = [u for u, co in (counters.get("closeouts") or {}).items()
if str(co.get("why") or "").startswith("conflicts with main")]
if conflicts:
out.append(f"- {len(conflicts)} branch update(s) conflicted with main — your /prm: "
+ ", ".join(map(pr_ref, conflicts)))
return out


def has_slot(counters: dict, task: str, url: str) -> bool:
"""Whether the shift's merge-slot file (as last synced into `counters`
as `slot_holders`) shows a slot for this PR held for this task."""
Expand Down Expand Up @@ -468,6 +551,10 @@ def label(task: str, pick: dict | None, url: str = "") -> str:
("awaiting /prm — close-out refused: CI RED", "CI failed — needs you"),
("awaiting /prm", "Needs you — not merged unattended"),
("close-out running", "Still running — close-out checking it"),
(UPDATING, "Still running — close-out updating the branch from main"),
("waits behind", "Waiting — merges after an earlier PR (your /prm first)"),
(UPDATED, "Branch updated from main — CI re-running"),
(CURRENT, "Branch up to date — awaiting its merge close-out"),
(STILL_OUT, "Still running at review time"),
("verdict posted", "Verdict posted"),
("PARKED-ON-ISSUE", "Needs you — question on the issue"),
Expand Down Expand Up @@ -593,6 +680,7 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None,
why=picks[t].get("why") or "NOT RECORDED", lease=held.get(t))
for t in backlog] or [NO_PICKS]
lines += backlog_gate_lines(counters)
lines += merge_order_lines(counters)

started = [t for t in named + backlog
if t in counters.get("outcomes", {}) or t in counters.get("parked", [])
Expand Down
23 changes: 20 additions & 3 deletions agents/conductors/batch/_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
KINDS = ("shift-open", "spawned", "redispatched", "crashed", "pr-opened", "finished",
"question", "parked", "ci", "closeout-started", "merged", "merged-outside",
"refused", "cap", "steer", "steer-unread", "impaired", "late", "digest",
"stopped", "shift-end", "login-expired")
"stopped", "shift-end", "login-expired", "waiting")
#: The kinds after which the stream has nothing more to follow.
FINAL_KINDS = ("shift-end", "stopped")

Expand Down Expand Up @@ -342,11 +342,28 @@ def _closeouts(b: _Batch, result: dict, counters: dict, info: dict) -> None:
f"{cls.removesuffix(' this shift')}: later green PRs wait for /prm.",
cls=cls)
continue
b.add("refused", f"refused:{pr}", f"Not merging {ref(pr)}: {cls}. Left for your /prm.",
# Merge order (M3.6j, #683): later PRs of the shift wait behind it.
later = sum(1 for w in (counters.get("merge_waits") or {}).values()
if pr in (w.get("behind") or []))
tail = f"; {later} later PR(s) wait behind it" if later else ""
b.add("refused", f"refused:{pr}",
f"Not merging {ref(pr)}: {cls}. Left for your /prm{tail}.",
task=co.get("task"), pr=pr, cls=cls)
for pr in events.get("waiting") or []:
w = (counters.get("merge_waits") or {}).get(pr) or {}
behind = w.get("behind") or []
b.add("waiting", f"waiting:{pr}:{','.join(behind)}",
f"{ref(pr)} waits behind {', '.join(map(ref, behind)) or '?'}: "
f"merge {ref(behind[0]) if behind else '?'} first.",
task=w.get("task"), pr=pr)
for pr in events.get("started") or []:
co = co_all.get(pr) or {}
b.add("closeout-started", f"closeout-started:{pr}", f"Close-out started on {ref(pr)}.",
if co.get("kind") == "update":
line = (f"Branch update started on {ref(pr)} (after "
f"{', '.join(map(ref, co.get('after') or [])) or '?'} merged).")
else:
line = f"Close-out started on {ref(pr)}."
b.add("closeout-started", f"closeout-started:{pr}:{co.get('started', '')}", line,
task=co.get("task"), pr=pr)


Expand Down
Loading
Loading