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
9 changes: 9 additions & 0 deletions agents/conductors/batch/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,15 @@ 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.

**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
`review-at:`. Before the start, a tick is idle (`not yet open: opens at
Expand Down
19 changes: 15 additions & 4 deletions agents/conductors/batch/_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET,
cap: int = DEFAULT_BACKPRESSURE_CAP, queue: list[str] | None = None,
awaiting_source: str = "given", carried: list[str] | None = None,
carried_from: str = "", brief: dict | None = None,
attended: bool = False) -> dict:
attended: bool = False, released: set[str] | None = None) -> dict:
"""Compose the next batch — a BatchDecision.

Every constraint states itself in `rejected`, because a planner that
Expand Down Expand Up @@ -511,7 +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"]))

members, spent, seen_epics, libs = [], 0, set(), set()
# `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 = released or set()
members, spent, seen_epics, libs = [], 0, set(), {}
for r in pool:
# One slice per epic counts only `Phase:` tasks (ruling R5, option a,
# 2026-11-17): a side task of the epic shares the shift with its phase.
Expand All @@ -527,7 +532,11 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET,
# repos are exempt — two docs changes in one shift cost nothing.
clash = next((x for x in r["repos"] if x in LIBRARY_REPOS and x in libs), None)
if clash:
rejected.append((r["path"], f"{clash} already claimed this shift"))
holder = libs[clash]
rejected.append((r["path"], f"{clash} held by {holder} — will start after "
f"{holder}'s PR merges"
if Path(r["path"]).name in named_names
else f"{clash} held by {holder} until its PR merges"))
continue
cost = 0 if r["consequence"] in CHEAP_TIERS else r["review_minutes"]
if spent + cost > effective_budget:
Expand All @@ -537,7 +546,9 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET,
spent += cost
if r["epic"] and has_phase(r):
seen_epics.add(r["epic"])
libs.update(x for x in r["repos"] if x in LIBRARY_REPOS)
if Path(r["path"]).stem not in released:
libs.update((x, Path(r["path"]).stem) for x in r["repos"]
if x in LIBRARY_REPOS and x not in libs)

other_lane = _lane_counts(
r for r in records
Expand Down
58 changes: 49 additions & 9 deletions agents/conductors/batch/_orchestrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -1569,8 +1569,30 @@ def claim_of(sections: dict[str, dict], task: str) -> tuple[str, dict] | None:
if Path(sec.get("prompt") or "").stem == task), None)


def released_picks(counters: dict) -> set[str]:
"""This shift's own picks that no longer hold their library repos
(PyAutoBrain#679): done or abandoned, and either every PR they opened has
merged, or they ended with no PR and no open question. Everything else
holds: a live lease, a park on a question or a person, a PR open or
refused (a judge PR awaiting /prm, a glance PR past `merge-cap:`), a
pending re-dispatch or an answered park waiting to restart."""
hold = {*(counters.get("parked") or []), *(counters.get("pending_redispatch") or []),
*(counters.get("inshift_pending") or {})}
out = set()
for task in {*(counters.get("done") or []), *(counters.get("abandoned") or [])}:
if task not in (counters.get("picks") or {}) or task in hold:
continue
o = (counters.get("outcomes") or {}).get(task)
o = o if isinstance(o, dict) else {}
prs, merged = o.get("prs") or [], set(o.get("merged") or [])
if (prs and all(u in merged for u in prs)) or (not prs and not o.get("questions")):
out.add(task)
return out


def on_origin(records: list[dict], mind: Path, own: set[str],
fetch=None, resumes: dict | None = None) -> tuple[list[dict], dict]:
fetch=None, resumes: dict | None = None, released: set[str] | None = None,
slot_name: str = "") -> tuple[list[dict], dict]:
"""`records` without the drafts Mind origin/main no longer holds as
unclaimed: a path not under its `draft/` (moved to `active/`, retired, or
never pushed — the writer's claim move would fail) or a task with a
Expand All @@ -1585,11 +1607,24 @@ def on_origin(records: list[dict], mind: Path, own: set[str],
its claim's `- session:` is `shift worker <slot> (<id>)` for a slot of
this home that picked it — a claim an interactive session owns, or one a
human took over, is the human's work and is left alone. Its own claim
never counts against its repos; every other claim on them does."""
never counts against its repos; every other claim on them does.

`released` (PyAutoBrain#679) are this shift's own picks that hold no
library any more (`released_picks`). A claim one of them left behind —
the close-out queues its `drop-section`, but a set-aside op, a failed push
or a close-out that skipped it leaves the section — holds nothing, when
its `- session:` is this shift's own worker (`slot_name`). Any other
claim still holds."""
claims = origin_claims(mind, fetch=fetch)
if claims is None:
return records, {}
resumes = resumes or {}
spent = set() # claim slugs of this shift's released picks
if released and slot_name and "error" not in claims:
for t in released:
c = claim_of(claims.get("sections") or {}, t)
if c and shift_worker_slot(c[1].get("session")) == slot_name:
spent.add(c[0])
kept, out = [], {}
for r in records:
task = task_id(r.get("path") or "")
Expand All @@ -1612,7 +1647,8 @@ def on_origin(records: list[dict], mind: Path, own: set[str],
"is not this home's shift worker's (session: "
f"{(sec.get('session') or 'none')[:60]}) — left to the human")
elif held := next(((repo, other) for other, sec2 in claims["sections"].items()
if other != slug and not coordinated_for(sec2, task)
if other != slug and other not in spent
and not coordinated_for(sec2, task)
for repo in sec2["repos"] if _repo_key(repo) in mine), None):
# Every other claim on the repo counts, not only the first
# (`claimed_repos` keeps one per repo): its own does not.
Expand All @@ -1625,21 +1661,23 @@ def on_origin(records: list[dict], mind: Path, own: set[str],
elif task in claims["active"]:
out[r["path"]] = "claimed in active.md on Mind origin/main"
elif held := _held_for(claims.get("sections") or {}, task,
r.get("declared_repos") or r.get("repos") or []):
r.get("declared_repos") or r.get("repos") or [],
ignore=spent):
out[r["path"]] = (f"repo {held[0]} claimed by `{held[1]}` in active.md on "
"Mind origin/main")
else:
kept.append(r)
return kept, out


def _held_for(sections: dict[str, dict], task: str, repos) -> tuple[str, str] | None:
def _held_for(sections: dict[str, dict], task: str, repos,
ignore=frozenset()) -> tuple[str, str] | None:
"""(repo as written, claiming slug) of the first claim on one of `repos`
that does not free it for `task` (R2: a coordination line frees a repo
only for the task it names), or None."""
only for the task it names), or None. A slug in `ignore` holds nothing."""
mine = {_repo_key(x) for x in repos}
return next(((repo, slug) for slug, sec in sections.items()
if not coordinated_for(sec, task)
if slug not in ignore and not coordinated_for(sec, task)
for repo in sec["repos"] if _repo_key(repo) in mine), None)


Expand Down Expand Up @@ -1883,17 +1921,19 @@ def plan() -> dict:
carried = {t for t, o in (counters.get("outcomes") or {}).items()
if isinstance(o, dict) and o.get("carried_from")}
recs = [r for r in recs if task_id(r["path"]) not in carried]
# A pick whose PRs have all merged frees its library (#679).
freed = released_picks(counters) - carried
recs, claimed = on_origin(recs, mind, set(counters["picks"]) - carried,
fetch=lambda: _fetch_once(mind, counters, now),
resumes=resumes)
resumes=resumes, released=freed, slot_name=slot.name)
planned["claimed"] = claimed
planned["resume"] = {t: v for t, v in resumes.items()
if any(task_id(r["path"]) == t for r in recs)}
# Unattended by construction: an absent Lane is excluded and an
# empty queue.md stops the backlog dip (M2.3, AUTONOMY.md "M2
# rulings — 2026-11-12"). Recorded each tick so the digest can say so.
planned["d"] = _batch.plan(recs, session_lane="local-dev", brief=brief,
queue=_batch.read_queue(mind))
queue=_batch.read_queue(mind), released=freed)
return planned["d"]

def known(task: str) -> bool:
Expand Down
4 changes: 2 additions & 2 deletions skills/batch/batch.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ Report, per task they named:
`autonomy human-required — would park at ship` (it cannot run unattended; it
would come back as a question — `supervised` no longer parks, AUTONOMY.md
"Decide-and-flag"), `Status: says the work is already done`, `epic <slug>
phase N is not next`, `<repo> already claimed this shift`, `would exceed the
budget`.
phase N is not next`, `<repo> held by <task> until its PR merges` (then the
next starts; PyAutoBrain#679), `would exceed the budget`.

If everything they named is rejected, **say so plainly and offer the planner's
own proposal instead** — never hand back a batch they did not ask for as though
Expand Down
119 changes: 119 additions & 0 deletions tests/test_batch_named_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -420,3 +420,122 @@ def test_review4_the_batch_conductor_is_refused_whatever_the_task_declares(tmp_p
errors, _, _ = _organ(tmp_path, "Edit `PyAutoMind/scripts` and `docs/x.md`.",
target="PyAutoMind")
assert errors


# --- PyAutoBrain#679: a shift's library slot frees once its task's PR has merged ------

PR1 = "https://github.com/example-org/autogalaxy/pull/7"
GALAXY = ("ag_bug_one", "ag_bug_two")


def _galaxy_shift(tmp_path: Path) -> tuple[Path, Path, Path]:
"""A brief naming two glance tasks on one library, first tick already run."""
mind, brief, home = _shift(tmp_path)
rels = []
for name in GALAXY:
rel = _write(mind, name, target="autogalaxy")
f = mind / rel
f.write_text(f.read_text().replace("Consequence: notify", "Consequence: glance"))
rels.append(rel)
brief.write_text(brief.read_text().replace(
" - draft/feature/x/none.md", "\n".join(f" - {r}" for r in rels)))
r = d._tick(brief, mind, home, NOW, d.FakeClaude())
assert [s["task"] for s in r["spawned"]] == ["ag_bug_one"], r
return mind, brief, home


def _end(brief: Path, home: Path, task: str, outcome: dict | None, *, how="done",
**extra) -> None:
"""The first task's worker has ended: its lease gone, its outcome recorded."""
slot = orch.slot_dir(brief, home)
(slot / "leases" / f"{task}.json").unlink()
c = orch.read_counters(slot)
c[how].append(task)
if outcome is not None:
c["outcomes"][task] = outcome
for k, v in extra.items():
c[k] = v
orch._write_counters(slot, c)


def test_679_1_the_second_task_on_a_library_waits_while_the_first_is_live(tmp_path):
mind, brief, home = _galaxy_shift(tmp_path)
r = d._tick(brief, mind, home, NOW, d.FakeClaude())
assert r["spawned"] == [], r
named = orch.read_counters(orch.slot_dir(brief, home))["backlog_gates"]["named"]
assert named == {"draft/feature/x/ag_bug_two.md":
"autogalaxy held by ag_bug_one — will start after ag_bug_one's PR "
"merges"}, named


def test_679_2_the_second_task_starts_once_every_pr_of_the_first_has_merged(tmp_path):
mind, brief, home = _galaxy_shift(tmp_path)
_end(brief, home, "ag_bug_one", {"prs": [PR1], "merged": [PR1], "issues": []})
r = d._tick(brief, mind, home, NOW, d.FakeClaude())
assert [s["task"] for s in r["spawned"]] == ["ag_bug_two"], r


@pytest.mark.parametrize("outcome, extra", [
({"prs": [PR1], "merged": [], "issues": []}, {}), # PR open
({"prs": [PR1], "merged": [], "issues": []}, # refused
{"closeouts": {PR1: {"task": "ag_bug_one", "state": "refused", "why": "red"}}}),
({"prs": [], "merged": [], "issues": [ISSUE], "questions": [ISSUE]}, {}), # question
({"prs": [PR1, PR1 + "0"], "merged": [PR1], "issues": []}, {}), # one of two
])
def test_679_3_an_open_or_refused_pr_or_a_question_still_holds(tmp_path, outcome, extra):
mind, brief, home = _galaxy_shift(tmp_path)
_end(brief, home, "ag_bug_one", outcome, **extra)
r = d._tick(brief, mind, home, NOW, d.FakeClaude())
assert r["spawned"] == [], r


def test_679_3_a_park_on_a_person_still_holds(tmp_path):
mind, brief, home = _galaxy_shift(tmp_path)
_end(brief, home, "ag_bug_one", None, how="parked")
r = d._tick(brief, mind, home, NOW, d.FakeClaude())
assert r["spawned"] == [], r


def test_679_4_an_abandoned_task_with_no_pr_frees_its_library(tmp_path):
mind, brief, home = _galaxy_shift(tmp_path)
_end(brief, home, "ag_bug_one", None, how="abandoned")
r = d._tick(brief, mind, home, NOW, d.FakeClaude())
assert [s["task"] for s in r["spawned"]] == ["ag_bug_two"], r


def test_679_5_a_released_picks_leftover_claim_does_not_hold_its_repo(tmp_path):
"""The close-out queues `drop-section active.md`, but a set-aside op or a
failed push leaves the claim on origin: only this shift's own worker's
claim on a released pick is passed over; any other claim still holds."""
if shutil.which("git") is None:
pytest.skip("needs git")
bare, mind = tmp_path / "mind.git", tmp_path / "mind"
_git(tmp_path, "init", "-q", "--bare", "-b", "main", str(bare))
_git(tmp_path, "clone", "-q", str(bare), str(mind))
first = _write(mind, "ag_bug_one", target="autogalaxy")
second = _write(mind, "ag_bug_two", target="autogalaxy")

def claim(session):
(mind / "active.md").write_text(
f"# Active\n\n## ag-bug-one\n- prompt: {first}\n- session: {session}\n"
"- repos:\n - autogalaxy: feature/ag-bug-one\n")
_git(mind, "add", "-A")
_git(mind, "-c", "user.name=T", "-c", "user.email=t@example.invalid", "commit",
"-q", "-m", "claim")
_git(mind, "push", "-q", "origin", "HEAD:main")
_git(mind, "fetch", "-q", "origin")

claim("shift worker 2026-11-18-pm (abc123)")
records = [_batch.grade(mind / second, mind)]
held = {second: "repo autogalaxy claimed by `ag-bug-one` in active.md on "
"Mind origin/main"}
assert orch.on_origin(records, mind, own={"ag_bug_one"}) == ([], held)
kept, out = orch.on_origin(records, mind, own={"ag_bug_one"}, released={"ag_bug_one"},
slot_name="2026-11-18-pm")
assert (kept, out) == (records, {})
# Another shift's worker, or a human who took the claim over: it holds.
assert orch.on_origin(records, mind, own={"ag_bug_one"}, released={"ag_bug_one"},
slot_name="2026-11-18-am") == ([], held)
claim("desktop session, human")
assert orch.on_origin(records, mind, own={"ag_bug_one"}, released={"ag_bug_one"},
slot_name="2026-11-18-pm") == ([], held)
11 changes: 10 additions & 1 deletion tests/test_batch_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,16 @@ def test_one_member_per_library_repo_per_shift():
d = _batch.plan([rec("a.md", repos=["autoarray"]),
rec("b.md", repos=["autoarray"])], budget=100)
assert paths(d) == ["a.md"]
assert "autoarray already claimed" in why(d, "b.md")
assert "autoarray held by a until its PR merges" in why(d, "b.md")


def test_a_released_member_holds_no_library():
"""PyAutoBrain#679: a pick whose PR merged collides with nothing at merge,
so the next task on its library is admitted; it stays a member."""
two = [rec("a.md", repos=["autoarray"]), rec("b.md", repos=["autoarray"])]
d = _batch.plan(two, budget=100, released={"a"})
assert paths(d) == ["a.md", "b.md"]
assert paths(_batch.plan(two, budget=100, released={"b"})) == ["a.md"]


def test_non_library_repos_do_not_claim_a_shift():
Expand Down
Loading