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
4 changes: 4 additions & 0 deletions AUTONOMY.md
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,10 @@ watcher may start sessions for work the brief covers. A watcher tick with **no
open brief dispatches nothing**, and a brief whose `review-at:` has passed is
not open.

**Human ruling 2026-11-16 (backlog reach, PyAutoBrain#637):** a `backlog:
scoped` dip takes `queue.md` first, then only `Difficulty: small` single-repo
backlog tasks; anything bigger must be queued by the human.

*Revert condition:* one dispatch found outside a brief's scope returns batching
to per-task `--auto` until the cause is found.

Expand Down
11 changes: 10 additions & 1 deletion agents/conductors/batch/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,16 @@ the plan inside the brief, the caps (`max-workers:`, default 2;
is checked against Mind `origin/main` (#632): a draft not under its `draft/` or
claimed in its `active.md` is excluded unless this shift picked it, read from the
local `origin/main` ref after one `git fetch` per shift through the one Mind
writer's own fetch (never a pull); an unreadable ref fails closed. State lives
writer's own fetch (never a pull); an unreadable ref fails closed. From
PyAutoBrain#637 the same read also skips a task whose declared repo (`Repos:`
header and target) a claim in that `active.md` holds, unless the claim records
`coordination:` or `conflict-override:`; a task an earlier shift in the same
home left parked on a question is not startable until a later shift finishes
it or a brief names it again; a dip never takes a Brain, Mind or Hands target;
a `backlog: scoped` dip beyond `queue.md` takes only small single-repo tasks
(ruling 2026-11-16); a re-dispatch goes first and may pass `max-sessions:` by
one; and a worker's token reservation is the larger of the even share and the
mean spend of finished workers in this and the last three shifts. State lives
under `$PYAUTO_ORCHESTRATOR_HOME` (default `.orchestrator` under the worktree
root), one directory per brief: `STOP`, `leases/`, `counters.json`, `tick.log`.
Until phase 3b it spawns only stub workers (`PYAUTO_ORCHESTRATOR_FAKE=1`); a real
Expand Down
64 changes: 63 additions & 1 deletion agents/conductors/batch/_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,22 @@ def lane_absent_why(r: dict) -> str:
return "lane absent — unattended picks fail closed; declare a Lane"


def declared_repos(p: dict) -> list[str]:
"""A parsed prompt's `Repos:` header and known target, normalised; its
survey `repos` when it declares neither."""
from _sizing import KNOWN_REPOS # noqa: E402
out = set()
block = re.search(r"^Repos:\n((?:- .+\n)+)", p.get("text") or "", re.M)
for ln in block.group(1).splitlines() if block else ():
r = normalise_repo(ln[1:].strip())
if r in KNOWN_REPOS:
out.add(r)
t = normalise_repo(p.get("target") or "")
if t in KNOWN_REPOS:
out.add(t)
return sorted(out) or list(p.get("repos") or [])


def grade(path: Path, mind: Path) -> dict:
"""Everything the planner needs about one prompt, from the faculty."""
p = parse_prompt(path, mind)
Expand All @@ -136,6 +152,11 @@ def grade(path: Path, mind: Path) -> dict:
# rulings — 2026-11-12"): `plan` excludes a lane-less draft from an
# unattended pick and reads it as `any` only when `attended=True`.
"lane": p.get("lane"), "lane_invalid": p.get("lane_invalid"),
"target": p.get("target") or "",
# What the prompt declares it will touch — its `Repos:` header and
# its target — not every repo its body mentions: the repo-claim gate
# (#637, item 4) reads these, so a passing `@repo` never skips a task.
"declared_repos": declared_repos(p),
"priority": p.get("priority") or "normal",
"blocked": bool(p.get("blocked_by")),
}
Expand Down Expand Up @@ -333,6 +354,37 @@ def pool_gate(r: dict, next_phase: dict[str, float]) -> str:
return ""


def self_organ_why(r: dict) -> str:
"""Why a shift never dips this draft, or "" (PyAutoBrain#637, item 7): it
targets an organ the shift runs on — its watcher, writer or release path
(`_brief.SELF_ORGANS`). By rule, not by a brief's `exclude:` list, so a
draft filed after the brief is written is kept out too. Read from the
target and every repo the draft names: a draft that names one is out."""
organs = {normalise_repo(o): o for o in _brief.SELF_ORGANS}
hit = sorted({organs[n] for x in {r.get("target") or "", *(r.get("repos") or [])}
if x and (n := normalise_repo(x)) in organs})
if not hit:
return ""
return (f"targets {', '.join(hit)} — a shift never changes its own watcher, "
"writer or release path")


def scoped_reach_why(r: dict) -> str:
"""Why `backlog: scoped` may not dip this unqueued draft, or "".

Human ruling 2026-11-16 (PyAutoBrain#637, item 6; AUTONOMY.md "Shift
briefs and unattended `glance`"): queue.md first, then only small
single-repo backlog tasks. Anything bigger is queued by the human."""
repos = r.get("repos") or []
small = r.get("difficulty") == _brief.SCOPED_REACH_DIFFICULTY
if small and len(repos) == 1:
return ""
size = r.get("difficulty") or "unsized"
return (f"not in queue.md and {size}, {len(repos)} repo(s) — beyond queue.md a "
"scoped dip takes only small single-repo tasks; the human queues "
"bigger work (ruling 2026-11-16)")


def planner_pool(records: list[dict]) -> list[dict]:
"""The records every session's planner would consider, before its lane
filters them — what a Lane backfill must cover."""
Expand Down Expand Up @@ -411,7 +463,9 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET,
# run, not which.
next_phase = next_phases(records)

pool, lane_absent = [], []
shift_dip = brief is not None and not attended
scoped_dip = shift_dip and brief.get("backlog", {}).get("value") == "scoped"
pool, lane_absent, reach = [], [], []
for r in records:
# A brief's named task is the human's own pick, not a backlog dip:
# neither M2.3 gate below applies to it (the brief's `lanes:` still does).
Expand All @@ -427,6 +481,12 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET,
elif queue_stop and backlog:
rejected.append((r["path"], "queue.md empty — no backlog dip "
"(named tasks only)"))
elif shift_dip and backlog and self_organ_why(r):
rejected.append((r["path"], self_organ_why(r)))
elif scoped_dip and backlog and queue_rank(r, queue) >= len(queue) \
and scoped_reach_why(r):
rejected.append((r["path"], scoped_reach_why(r)))
reach.append(r["path"])
else:
pool.append(r)

Expand Down Expand Up @@ -496,6 +556,8 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET,
# The two M2.3 gates, stated rather than buried in `rejected`.
"lane_absent": lane_absent,
"queue_stop": queue_stop,
# The 2026-11-16 backlog-reach ruling (#637, item 6), stated likewise.
"scoped_reach": reach,
}


Expand Down
56 changes: 51 additions & 5 deletions agents/conductors/batch/_brief.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@
WORKER_MODES = ("auto", "dontAsk", "acceptEdits")
DEFAULT_WORKER_MODE = "auto"
SCOPED_KEYS = ("epics", "tags", "tiers")
#: The organs a shift runs on: its watcher and planner (Brain), its one Mind
#: writer (Mind) and its release path (Hands). A shift never changes them, so
#: the planner never dips a draft that targets one (PyAutoBrain#637, item 7).
#: A brief's named task is the human's own pick and is not gated.
SELF_ORGANS = ("PyAutoBrain", "PyAutoMind", "PyAutoHands")
#: The one size `backlog: scoped` may dip beyond `queue.md` (human ruling
#: 2026-11-16, PyAutoBrain#637, item 6): small and single-repo only.
SCOPED_REACH_DIFFICULTY = "small"

_ITEM_RE = re.compile(r"^(\s*)-\s+(.*?)\s*$")
_KEY_RE = re.compile(r"^([a-z][a-z0-9-]*):\s*(.*)$")
Expand Down Expand Up @@ -181,6 +189,46 @@ def _previous_record(mind: Path, this: Path) -> Path | None:
return older[-1] if older else None


def _has_minutes(text: str) -> bool:
try:
return bool(parse(text)["top"].get("review-minutes-actual", {}).get("value"))
except BriefError:
return False


def origin_text(mind: Path, rel: str, ref: str = "origin/main") -> str | None:
"""`rel` as Mind's local `ref` holds it — a local, read-only `git show`,
never a fetch. None when `mind` is not a git checkout of its own or the
ref has no such file."""
import subprocess
try:
top = subprocess.run(["git", "-C", str(mind), "rev-parse", "--show-toplevel"],
capture_output=True, text=True, timeout=30)
if top.returncode != 0 or Path(top.stdout.strip()).resolve() != Path(mind).resolve():
return None
res = subprocess.run(["git", "-C", str(mind), "show", f"{ref}:{rel}"],
capture_output=True, text=True, timeout=30)
except (OSError, subprocess.SubprocessError):
return None
return res.stdout if res.returncode == 0 else None


def _measured(mind: Path, prev: Path) -> bool:
"""Whether the previous record carries `review-minutes-actual:` — in the
canonical working tree, or on Mind's local `origin/main` ref.

PyAutoBrain#637, item 5: the gate read only the working tree, which no
one pulls mid-shift. A check-in pushed from a linked worktree of the
canonical checkout (`prompt_sync_push`, the one Mind writer) moves the
local `origin/main` ref at once, whether or not the working tree is
fast-forwarded after it, so the next tick counts it. Nothing is fetched:
the watcher's network surface is unchanged."""
if _has_minutes(prev.read_text(encoding="utf-8", errors="replace")):
return True
text = origin_text(mind, f"batches/{prev.name}")
return bool(text) and _has_minutes(text)


def check(path: Path, mind: Path) -> dict:
"""Validate one brief. `errors` refuse it; `warnings` do not."""
errors: list[str] = []
Expand Down Expand Up @@ -289,11 +337,9 @@ def check(path: Path, mind: Path) -> dict:
# unmeasured. Only for a record that lives among the records.
if path.parent.resolve() == (mind / "batches").resolve():
prev = _previous_record(mind, path)
if prev is not None:
prev_top = parse(prev.read_text(encoding="utf-8", errors="replace"))["top"]
if not prev_top.get("review-minutes-actual", {}).get("value"):
errors.append(f"review-minutes-actual: missing on the previous "
f"record {prev.name} — measure it before a new brief")
if prev is not None and not _measured(mind, prev):
errors.append(f"review-minutes-actual: missing on the previous "
f"record {prev.name} — measure it before a new brief")

# The digest, once collect has appended one (phase 3d).
import _digest # noqa: E402 — deferred: _digest imports this module
Expand Down
56 changes: 51 additions & 5 deletions agents/conductors/batch/_digest.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,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 killed worker whose re-dispatch never started (PyAutoBrain#637, item 2):
#: never "not started" — its first worker ran.
NOT_REDISPATCHED = "crashed — not re-dispatched"
NO_PACKETS_SHADOW = "- none — shadow shift: nothing was dispatched"
#: A shadow digest's counters, in one line: every one is 0 by construction.
SHADOW_COUNTERS = "- all counters 0 — shadow shift, nothing dispatched"
Expand Down Expand Up @@ -219,9 +222,12 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False,
return _lease_state(lease, agents), True
if lease is not None:
return STILL_OUT, True
if live and task in counters.get("pending_redispatch", []):
return "crashed — awaiting re-dispatch", True
return "not started", False
if task in counters.get("pending_redispatch", []):
if live:
return "crashed — awaiting re-dispatch", True
return f"{NOT_REDISPATCHED}: {redispatch_why(task, counters)}", False
skipped = gate_why(task, counters)
return ("not started — skipped: " + skipped if skipped else "not started"), False
urls = urls_of(out)
if not urls and "obsolete" in out:
return ("obsolete (premise check): "
Expand All @@ -239,6 +245,8 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False,
elif url in out["merged"]:
state = ("merged unattended (close-out, " + co.get("model", "?") + ")"
if co.get("state") == "merged" else "merged")
if co.get("state") == "merged" and co.get("cleanup"):
state += f" — worktree: {co['cleanup']}"
elif co.get("state") == "refused":
state = f"awaiting /prm — close-out refused: {co.get('why', '?')}"
elif co.get("state") == "running":
Expand All @@ -249,6 +257,27 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False,
return "; ".join(parts), True


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 ""."""
gates = counters.get("backlog_gates") or {}
for key in ("origin", "parked"):
for path, why in (gates.get(key) or {}).items():
if Path(path).stem == task:
return why
return ""


def redispatch_why(task: str, counters: dict) -> str:
"""Why a crashed task's re-dispatch never started: the last refusal the
watcher recorded for it, else `review-at:` came first."""
last = max((r for r in counters.get("refusals", []) if r.get("task") == task),
key=lambda r: r.get("last") or r.get("at") or "", default=None)
if last:
return f"refused {last.get('why') or last.get('class') or '?'} (last {last.get('last') or last.get('at')})"
return "review-at came before a free session"


#: `claude agents` states for a session that has ended without succeeding. A
#: real worker in one of these with no `.done` is a crash at once — it can never
#: write one late, so it gets no grace (PyAutoBrain#592: three `failed` workers
Expand Down Expand Up @@ -416,6 +445,7 @@ def label(task: str, pick: dict | None, url: str = "") -> str:
("parked", "Needs you — blocked on a person"),
("blocked on a person", "Needs you — blocked on a person"),
("abandoned", "Abandoned — crashed twice"),
(NOT_REDISPATCHED, "Crashed — not re-dispatched"),
("crashed", "Crashed — waiting to be re-dispatched"),
("ended", "Crashed"),
("obsolete", "Obsolete — nothing to do"),
Expand Down Expand Up @@ -521,7 +551,8 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None,

started = [t for t in named + backlog
if t in counters.get("outcomes", {}) or t in counters.get("parked", [])
or t in counters.get("abandoned", [])]
or t in counters.get("abandoned", [])
or t in counters.get("pending_redispatch", [])]
lines += ["", "### Proof packets"]
lines += ["\n\n".join(_packet(t, slot, counters) for t in started)
or (NO_PACKETS_SHADOW if _brief.is_shadow(brief) else NO_PICKS)]
Expand Down Expand Up @@ -591,7 +622,8 @@ def backlog_gate_lines(counters: dict) -> list[str]:
"brief's named tasks only.")
origin = gates.get("origin") or {}
closed = {p: w for p, w in origin.items() if w.endswith("fail closed")}
claimed = sorted(p for p in origin if p not in closed)
repo_held = {p: w for p, w in origin.items() if w.startswith("repo ") and p not in closed}
claimed = sorted(p for p in origin if p not in closed and p not in repo_held)

def names(paths):
return (", ".join(f"`{Path(a).stem}`" for a in paths[:SUMMARY_NAMES])
Expand All @@ -604,6 +636,19 @@ def names(paths):
out.append(f"Mind origin/main could not be read: {len(closed)} draft(s) not picked "
f"(fail closed) — {next(iter(closed.values()))[5:]}: "
+ names(sorted(closed)))
if repo_held:
out.append(f"Repo claimed on Mind origin/main: {len(repo_held)} draft(s) skipped — "
+ "; ".join(f"`{Path(p).stem}` ({w.split(' in active.md')[0]})"
for p, w in sorted(repo_held.items())[:SUMMARY_NAMES]))
parked = gates.get("parked") or {}
if parked:
out.append(f"Parked on a question by an earlier shift: {len(parked)} draft(s) not "
"startable until answered (name one in a brief to start it again): "
+ names(sorted(parked)))
reach = gates.get("scoped_reach") or []
if reach:
out.append(f"Backlog reach (ruling 2026-11-16): {len(reach)} unqueued draft(s) not "
"dipped — beyond queue.md only small single-repo tasks: " + names(reach))
absent = gates.get("lane_absent") or []
if absent:
out.append(f"Lane absent: {len(absent)} draft(s) excluded — no valid `Lane:`, "
Expand Down Expand Up @@ -934,6 +979,7 @@ def validate(text: str) -> list[str]:
for item in _items(secs.get(sec, [])):
slug = _slug(item)
if slug and item.strip() != NO_PICKS and "not started" not in item \
and NOT_REDISPATCHED not in item \
and PROPOSED not in item and STILL_OUT not in item \
and f"#### {slug}" not in packets:
errs.append(f"digest: {slug} has no proof packet")
Expand Down
20 changes: 20 additions & 0 deletions agents/conductors/batch/_mind_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,8 @@ def validate_op(op: dict, lm) -> list[str]:
errs.append(f"{kind}: {p} is not a ledger path (scripts/ledger_merge.py)")
if kind in ("append", "write") and not isinstance(op.get("text"), str):
errs.append(f"{kind}: text is missing")
elif kind == "append" and op.get("path") == "active.md":
errs += pr_key_errors(op["text"])
if kind == "drop-section":
if not op.get("section"):
errs.append("drop-section: section is missing")
Expand Down Expand Up @@ -215,6 +217,24 @@ def validate_op(op: dict, lm) -> list[str]:
return errs


#: The PR keys of an `active.md` row (PyAutoMind REFERENCE.md "The PR keys"),
#: and the keys a worker wrote in their place (PyAutoBrain#637, item 9: a bare
#: `pr:` made `lifecycle.py check` drift and left /prm nothing to merge).
PR_KEYS = ("library-pr", "workspace-pr")
_LOOSE_PR_KEY_RE = re.compile(r"^-\s+((?:[a-z]+[-_])?prs?|pull-request|pr-url)\s*:", re.I | re.M)


def pr_key_errors(text: str) -> list[str]:
"""A refusal for every PR line in an `active.md` row whose key is not one
of `PR_KEYS` — `shift_ledger.py` refuses the op when it is queued, so
the worker fixes it, and the writer sets it aside if one slips through."""
bad = sorted({m.group(1) for m in _LOOSE_PR_KEY_RE.finditer(text or "")
if m.group(1).lower() not in PR_KEYS})
return [f"append: active.md key `{k}:` — a PR line uses `library-pr:` or "
"`workspace-pr:` (PyAutoMind REFERENCE.md \"The PR keys\"), one per PR"
for k in bad]


def apply_op(tree: Path, op: dict, lm, ctx: dict | None = None) -> str | None:
"""Apply one validated op inside `tree`; raises MindWriteError if it cannot,
ConflictError for a claim that is already on main but not this shift's own.
Expand Down
Loading
Loading